@zuplo/runtime 5.1982.0 → 5.1986.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.min.cjs CHANGED
@@ -74,5 +74,5 @@ Signature verification is impossible without access to the original signed mater
74
74
  `+d}):new xe(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
75
75
  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.
76
76
  `+l+`
77
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new xe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Pd,"validateComputedSignature");function Ed(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Ed,"parseHeader");function Id(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Id,"secureCompare");async function Td(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Do[s[u]];return a.join("")}i(Td,"computeHMACSignatureAsync");var Do=new Array(256);for(let t=0;t<Do.length;t++)Do[t]=t.toString(16).padStart(2,"0");function W(t,e,n="policy"){let r=`${n} '${e}'`;if(!je(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var dt=class extends ye{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ca(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return n.log.error("Error validating stripe webhook",s),v.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function la(t){return t!==null&&typeof t=="object"&&"id"in t&&ce(t.id)&&"type"in t&&ce(t.type)}i(la,"isStripeWebhookEvent");var xd={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new C(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new C(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new C(s)}return o}},Dn=xd;var Uo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",da="My API Key";async function pa({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,Uo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:da,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new C(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(pa,"createConsumer");async function ma({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,Uo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:da,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new C(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(ma,"createConsumerInvite");async function ga({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Uo);o.searchParams.set("with-api-key","true");let s=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new C(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ga,"deleteConsumer");async function fa({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!nt(d))throw new F("No Zuplo JWT token set.");let m=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new C(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(fa,"createSubscription");async function pt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!nt(o))throw new F("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new C(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(pt,"updateSubscription");async function mt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!nt(o))throw new F("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new C(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new C(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new C(c)}return u.data[0]}i(mt,"getSubscription");var G="Unable to process webhook event.",qe="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Un(t){return t.replaceAll("_","-")}i(Un,"stripeStatusToMeteringStatus");function Ho(t){return new Date(t*1e3).toISOString()}i(Ho,"unixTimestampToISOString");async function Zo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await pa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Dn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ma({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(t,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Un(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await fa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await ga({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(t,e,{title:G,detail:p.message})}return v.ok(t,e,{title:qe})}i(Zo,"onCustomerSubscriptionCreated");async function qo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});try{let a=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ue})}return v.ok(t,e,{title:qe})}i(qo,"onCustomerSubscriptionDeleted");async function $o(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Un(n.data.object.status);await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await Dn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==n.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==n.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==n.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:n.data.object.cancel_at?Ho(n.data.object.cancel_at):null,cancel_at_period_end:n.data.object.cancel_at_period_end,canceled_at:n.data.object.canceled_at?Ho(n.data.object.canceled_at):null,cancellation_details:n.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(t,e,{title:G,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ue})}i($o,"onCustomerSubscriptionUpdated");var Fo=class extends Wt{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new F("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!vd(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!la(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Zo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await $o(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qo(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),s=Es({inboundPolicies:[new dt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[oe,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function vd(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(vd,"isMetricsRegion");var ya=new WeakMap,ha={},Hn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ya.set(e,n)}};async function ba(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=rt(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ya.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new C(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ve(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=ha[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new $("amberflo-ingest-meter",10,async b=>{try{let T=n.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),ha[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(ba,"AmberfloMeteringInboundPolicy");async function Zn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(Zn,"sha256");var wa=new Map;async function ee(t,e){let n,r=wa.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await Zn(JSON.stringify({policyName:t,options:e}))}`,wa.set(t,n)),n}i(ee,"getPolicyCacheName");var Ra="key-metadata-cache-type";function Od(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Od,"getKeyValue");async function qn(t,e,n,r){if(!n.bucketName)if(ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?t:v.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Od(a,o);if(!u||u==="")return s("No key present");let c=await Sd(u),l=await ee(r,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ra&&z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new C(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:Ra,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(qn,"ApiKeyInboundPolicy");async function Sd(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Sd,"hashValue");var Pa=qn;var Dt=require("jose");var Ea=require("jose");var Bo=class{constructor(e,n,r){this.cache=n;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,n){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,n)}catch(r){if(r instanceof zo&&this.coolingDown()===!1)return await this.reload(),this.local(e,n);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(n=>{this.local=(0,Ea.createLocalJWKSet)(n),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(n=>{throw this.pendingFetch=void 0,n}),await this.pendingFetch}async fetchJwks(e,n,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},n));let c=await M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new gt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new gt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ia(t,e,n){let r=new Bo(t,e,n);return async(o,s)=>r.getKey(o,s)}i(Ia,"createRemoteJWKSet");var gt=class extends C{static{i(this,"JWKSError")}},zo=class extends gt{static{i(this,"JWKSNoMatchingKey")}},jo=class extends gt{static{i(this,"JWKSTimeout")}};var $n={},Cd=i((t,e)=>async(n,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!$n[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(t,r),u=new Y(a,e);$n[r.jwkUrl]=Ia(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else $n[r.jwkUrl]=(0,Dt.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,Dt.jwtVerify)(n,$n[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Ad=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,Dt.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),te=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Cd(r,e):Ad,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ta=i(async(t,e,n,r)=>te(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var xa=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>v.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.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 m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var _d=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ld(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ld,"digestMessage");var Nd=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Ld(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function va(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nd(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);_d.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(va,"CachingInboundPolicy");var Oa=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Sa=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ca=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Aa=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",te(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var _a=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return te(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var La=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ne.instance,s=St(n.policies,o?.routeData.policies);return to(s)(t,e)},"CompositeInboundPolicy");var Na=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return v.unauthorized(t,e,{detail:"No authorization header"});let s=kd(o);if(!s)return v.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function kd(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(kd,"getToken");var ka=i(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),te(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ma=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ft="__unknown__",Da=i(async(t,e,n,r)=>{let o={allow:{countries:yt(n.allow?.countries,"allow.countries",r),regionCodes:yt(n.allow?.regionCodes,"allow.regionCode",r),asns:yt(n.allow?.asns,"allow.asOrganization",r)},block:{countries:yt(n.block?.countries,"block.countries",r),regionCodes:yt(n.block?.regionCodes,"block.regionCode",r),asns:yt(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??ft,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ft,u=e.incomingRequestProperties.asn?.toString()??ft,c=o.ignoreUnknown&&s===ft,l=o.ignoreUnknown&&a===ft,d=o.ignoreUnknown&&u===ft,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ht(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?ht(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function ht(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(ht,"blockedResponse");function yt(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(yt,"toLowerStringArray");var Ua=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Za=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Vo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Vo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ha(a[u])}else return a.length>0?Ha(a[0]):Vo(r,t,e,"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");function Ha(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(Ha,"generateResponse");var Vo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return v.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Md="Incoming",Dd={logRequestBody:!0,logResponseBody:!0};function qa(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(qa,"headersToObject");function $a(){return new Date().toISOString()}i($a,"timestamp");var Go=new WeakMap,Ud={};function za(t,e){let n=Go.get(t);n||(n=Ud);let r=Object.assign({...n},e);Go.set(t,r)}i(za,"setMoesifContext");async function Fa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(Fa,"readBody");var Hd={},Wo;function Ba(){if(!Wo)throw new C("Invalid State - no _lastLogger");return Wo}i(Ba,"getLastLogger");function Zd(t){let e=Hd[t];return e||(e=new $("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ba().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Ba().error({status:o.status,body:await o.text()})})),e}i(Zd,"getDispatcher");async function ja(t,e,n,r){Wo=e.log;let o=$a(),s=Object.assign(Dd,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Fa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Zd(s.applicationId),d=t.headers.get("true-client-ip"),p=Go.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:qa(t.headers)},g=s.logResponseBody?await Fa(u,e):void 0,I={time:$a(),status:u.status,headers:qa(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Md};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(ja,"MoesifInboundPolicy");async function Va(t,e,n,r){let o=z.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Va,"loadSubscription");async function Ga(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=z.getLogger(t);try{let c=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(Ga,"consumeSubcriptionQuotas");var qd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Fn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(Fn,"validateMeters");function Wa(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Ge(t),r=[];for(let o of n)qd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(Wa,"parseAllowedSubscriptionStatuses");function Ja(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(Ja,"compareMeters");var Bn=class extends ye{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,Et)}static setMeters(e,n){Fn(n,"setMeters"),ge.set(e,Gt,n)}async handler(e,n){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=rt(this.options.meterOnStatusCodes),s=ge.get(n,Gt),a={...this.options.meters,...s};Fn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Wa(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,T,_)=>{let h=ge.get(_,Et);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=ge.get(_,Gt),H={...this.options.meters,...O};if(Fn(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=Ja(h.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await Ga(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Va(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:v.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ge.set(n,Et,p));let m=ge.get(n,Et);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),v.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return v.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var Ka=i(async(t,e,n,r)=>te(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Ya=require("jose");var Jo,Qa=i(async(t,e,n,r)=>{if(!Jo)try{Jo=await(0,Ya.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return te(t,e,{issuer:n.authUrl,secret:Jo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ru=Ae(Ne());var eu=Ae(Ne());var zn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ko=class extends zn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Yo=class extends zn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function $d(t,e){if(hs(t))throw new Ko(e)}i($d,"throwIfUndefinedOrNull");function Ut(t,e){if($d(t,e),!ce(t))throw new Yo(e,"string")}i(Ut,"throwIfNotString");var jn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ut(e,"redisClientUrl"),Ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Ut(e,"url");let s=await M.fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"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 F("Redis client failed with 401: Unauthorized"):new F(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Vn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new F("The in-memory redis client only supports /rate-limit calls")}};var Fd=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Wn=i(async t=>({key:`ip-${Fd(t)}`}),"getIP"),Jn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Kn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Gn;function Yn(t,e){let n;if(Gn)return Gn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Vn,Gn=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ce(o))throw new F(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new F(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=jn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new F(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Gn=n,n}i(Yn,"getRedisClient");async function Qn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(Qn,"getCountAndUpdateExpiry");function Xn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new C(c)}return u},"outerFunction")}i(Xn,"wrapUserFunction");var er="Retry-After";var Xa=(0,eu.debug)("zuplo:policies:RateLimitInboundPolicy"),tu=i(async(t,e,n,r)=>{let o=z.getLogger(e),s=i((f,R)=>{let S={};return(!f||f==="retry-after")&&(S[er]=R.toString()),v.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Xn(n,r),user:Jn,ip:Wn,all:Kn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=Yn(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,n),_=new Y(T,e),h=Qn(b,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),Xa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){Xa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),t},"AsyncRateLimitInboundPolicy");var nu=(0,ru.debug)("zuplo:policies:RateLimitInboundPolicy"),Bd="strict",Qo=i(async(t,e,n,r)=>{if((n.mode??Bd)==="async")return tu(t,e,n,r);let s=Date.now(),a=z.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new F(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[er]=d.toString()),v.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Xn(n,r),user:Jn,ip:Wn,all:Kn}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",T=Yn(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await Qn(h,I,T,a,e.requestId);return P.count>g?(nu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;nu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Xo;function ou(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(ou,"headersToNameValuePairs");function zd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(zd,"queryToNameValueParis");function jd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(jd,"parseIntOrUndefined");var iu={};async function su(t,e,n,r){let o=new Date,s=Date.now();return Xo||(Xo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ve(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ve(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Xo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ou(t.headers),queryString:zd(t.query)},response:{status:a.status,statusText:a.statusText,headers:ou(a.headers),content:{size:jd(t.headers.get("content-length"))}}}]}}},d=iu[n.apiKey];if(!d){let p=n.apiKey;d=new $("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),iu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(su,"ReadmeMetricsInboundPolicy");var au=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var uu=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var cu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var lu=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),pu=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?du():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?du():t},"RequestSizeLimitInboundPolicy");function mu(t,e,n){return`_${$e(t+"_"+e+"_"+n)}`}i(mu,"getRawOperationDataIdentifierName");function tr(t,e,n,r){return`_${$e(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(tr,"getIdForParameterSchema");function nr(t,e,n){return`_${$e(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${$e(n.toLowerCase())}`}i(nr,"getIdForRequestBodySchema");function gu(t,e){return`_${$e(t)}__${$e(e)}`}i(gu,"getIdForRefSchema");function $e(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i($e,"sanitizedIdentifierName");var bt=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),wt=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=tr(n,r,o,c.name),p=ne.instance.schemaValidator[d],m=p(e[c.name]),g=ei(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),be=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),we=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),Re=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),ei=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function fu(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=v.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(we(n.validateBody)&&be(t,n.logLevel??"info",I,[r],g),Re(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=v.badRequest(e,t,{detail:g});return we(n.validateBody)&&be(t,n.logLevel??"info",g,[r],[g]),Re(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=nr(t.route.path,e.method,o),u=ne.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,t,{detail:g});return we(n.validateBody)&&be(t,n.logLevel??"info",g,[r],[g]),Re(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=ei(l),m=v.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(we(n.validateBody)&&be(t,n.logLevel??"info",d,[r],p),Re(n.validateBody))return m}i(fu,"handleBodyValidation");function hu(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=bt(t),s=wt(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(we(n.validateHeaders)&&be(t,n.logLevel??"info",a,s.invalidValues,s.errors),Re(n.validateHeaders))return u}}i(hu,"handleHeadersValidation");function yu(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=bt(t),o=wt(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(we(n.validatePathParameters)&&be(t,n.logLevel??"info",s,o.invalidValues,o.errors),Re(n.validatePathParameters))return a}}i(yu,"handlePathParameterValidation");function bu(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=bt(t),o=wt(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(we(n.validateQueryParameters)&&be(t,n.logLevel??"info",s,o.invalidValues,o.errors),Re(n.validateQueryParameters))return a}}i(bu,"handleQueryParameterValidation");var ti=i(async(t,e,n)=>{let r=bu(e,t,n);if(r!==void 0||(r=yu(e,t,n),r!==void 0)||(r=hu(e,t,n),r!==void 0))return r;let o=await fu(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),wu=ti;var Ru=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return v.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Pu=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Eu=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Iu=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Tu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var xu=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Vd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),vu=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Vd(n.sleepInMs),t},"SleepInboundPolicy");var Ou=i(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await te(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new F("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new C(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Su=i(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Y(o,e),a=await s.get(r);if(!a){let u=await Gd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Gd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new C("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new C("Response returned from Azure AD is not in the expected format.")}i(Gd,"getAccessToken");var Cu="https://accounts.google.com/o/oauth2/token",ni,Au=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),ni||(ni=await le.init(n.serviceAccountJson));let o={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 ee(r,n),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Ie({serviceAccount:ni,audience:Cu,payload:o}),l=await pn(Cu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new C("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Wd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Jd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],ri,_u=i(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Jd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}ri||(ri=await le.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new C("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new C(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ve(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new C(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Y(a,e),c={uid:s,claims:o},l=await Zn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ie({serviceAccount:ri,audience:Wd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await Ls(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new C("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var oi,Lu=i(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),oi||(oi=await le.init(n.serviceAccountJson));let o=await Ie({serviceAccount:oi,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Nu="https://www.googleapis.com/oauth2/v4/token",ii,ku=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),ii||(ii=await le.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=Ge(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await ee(r,n),a;n.useMemoryCacheOnly?a=new Ke(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Ie({serviceAccount:ii,audience:Nu,payload:o}),l=await pn(Nu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new C("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new C("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Mu=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return v.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new F("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Zu=Ae(Hu());var rr=class extends Se{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?rt(e.parseOnStatusCodes):void 0,this.parser=new Zu.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new C(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var or=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new F(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var ir=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new $(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),En().waitUntil(this.#e.waitUntilFlushed())}};var sr=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new Ht(r)),await new Ht(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new Ht(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},Ht=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){En().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var ai=["sha-1","sha-256","sha-384","sha-512"],ar=class{static{i(this,"BaseCryptoBeta")}};var ur=class extends ar{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!ai.includes(e.toLowerCase()))throw new C(`Algorithm ${e} is not supported. Try using ${ai.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var cr=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var lr=class extends cr{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new jt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
77
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new xe(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(Pd,"validateComputedSignature");function Ed(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Ed,"parseHeader");function Id(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Id,"secureCompare");async function Td(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Do[s[u]];return a.join("")}i(Td,"computeHMACSignatureAsync");var Do=new Array(256);for(let t=0;t<Do.length;t++)Do[t]=t.toString(16).padStart(2,"0");function W(t,e,n="policy"){let r=`${n} '${e}'`;if(!je(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var dt=class extends ye{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ca(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return n.log.error("Error validating stripe webhook",s),v.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function la(t){return t!==null&&typeof t=="object"&&"id"in t&&ce(t.id)&&"type"in t&&ce(t.type)}i(la,"isStripeWebhookEvent");var xd={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new C(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new C(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new C(s)}return o}},Dn=xd;var Uo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",da="My API Key";async function pa({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,Uo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:da,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new C(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(pa,"createConsumer");async function ma({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,Uo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:da,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new C(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(ma,"createConsumerInvite");async function ga({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Uo);o.searchParams.set("with-api-key","true");let s=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new C(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ga,"deleteConsumer");async function fa({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!nt(d))throw new F("No Zuplo JWT token set.");let m=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new C(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(fa,"createSubscription");async function pt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!nt(o))throw new F("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new C(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(pt,"updateSubscription");async function mt({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!nt(o))throw new F("No Zuplo JWT token set.");let a=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new C(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new C(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new C(c)}return u.data[0]}i(mt,"getSubscription");var G="Unable to process webhook event.",qe="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Un(t){return t.replaceAll("_","-")}i(Un,"stripeStatusToMeteringStatus");function Ho(t){return new Date(t*1e3).toISOString()}i(Ho,"unixTimestampToISOString");async function Zo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await pa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Dn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ma({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(t,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Un(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await fa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await ga({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(t,e,{title:G,detail:p.message})}return v.ok(t,e,{title:qe})}i(Zo,"onCustomerSubscriptionCreated");async function qo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});try{let a=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ue})}return v.ok(t,e,{title:qe})}i(qo,"onCustomerSubscriptionDeleted");async function $o(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=Un(n.data.object.status);await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await Dn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==n.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==n.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==n.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${n.id}'.`);let u=await mt({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:n.data.object.cancel_at?Ho(n.data.object.cancel_at):null,cancel_at_period_end:n.data.object.cancel_at_period_end,canceled_at:n.data.object.canceled_at?Ho(n.data.object.canceled_at):null,cancellation_details:n.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:qe})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(t,e,{title:G,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ue})}i($o,"onCustomerSubscriptionUpdated");var Fo=class extends Wt{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new F("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!vd(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!la(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await Zo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await $o(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await qo(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),s=Es({inboundPolicies:[new dt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[oe,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function vd(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(vd,"isMetricsRegion");var ya=new WeakMap,ha={},Hn=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){ya.set(e,n)}};async function ba(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=rt(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ya.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new C(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ve(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=ha[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new $("amberflo-ingest-meter",10,async b=>{try{let T=n.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),ha[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(ba,"AmberfloMeteringInboundPolicy");async function Zn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(Zn,"sha256");var wa=new Map;async function ee(t,e){let n,r=wa.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await Zn(JSON.stringify({policyName:t,options:e}))}`,wa.set(t,n)),n}i(ee,"getPolicyCacheName");var Ra="key-metadata-cache-type";function Od(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Od,"getKeyValue");async function qn(t,e,n,r){if(!n.bucketName)if(ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ie.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?t:v.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Od(a,o);if(!u||u==="")return s("No key present");let c=await Sd(u),l=await ee(r,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==Ra&&z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await ae({retryDelayMs:5,retries:2,logger:z.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new C(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:Ra,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(qn,"ApiKeyInboundPolicy");async function Sd(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Sd,"hashValue");var Pa=qn;var Dt=require("jose");var Ea=require("jose");var Bo=class{constructor(e,n,r){this.cache=n;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,n){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,n)}catch(r){if(r instanceof zo&&this.coolingDown()===!1)return await this.reload(),this.local(e,n);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(n=>{this.local=(0,Ea.createLocalJWKSet)(n),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(n=>{throw this.pendingFetch=void 0,n}),await this.pendingFetch}async fetchJwks(e,n,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},n));let c=await M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new gt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new gt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ia(t,e,n){let r=new Bo(t,e,n);return async(o,s)=>r.getKey(o,s)}i(Ia,"createRemoteJWKSet");var gt=class extends C{static{i(this,"JWKSError")}},zo=class extends gt{static{i(this,"JWKSNoMatchingKey")}},jo=class extends gt{static{i(this,"JWKSTimeout")}};var $n={},Cd=i((t,e)=>async(n,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!$n[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(t,r),u=new Y(a,e);$n[r.jwkUrl]=Ia(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else $n[r.jwkUrl]=(0,Dt.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,Dt.jwtVerify)(n,$n[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Ad=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await(0,Dt.jwtVerify)(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),te=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Cd(r,e):Ad,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var Ta=i(async(t,e,n,r)=>te(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var xa=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>v.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.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 m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var _d=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Ld(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Ld,"digestMessage");var Nd=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Ld(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function va(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Nd(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);_d.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(va,"CachingInboundPolicy");var Oa=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Sa=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Ca=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var Aa=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",te(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var _a=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return te(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var La=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ne.instance,s=St(n.policies,o?.routeData.policies);return to(s)(t,e)},"CompositeInboundPolicy");var Na=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return v.unauthorized(t,e,{detail:"No authorization header"});let s=kd(o);if(!s)return v.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function kd(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(kd,"getToken");var ka=i(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),te(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ma=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ft="__unknown__",Da=i(async(t,e,n,r)=>{let o={allow:{countries:yt(n.allow?.countries,"allow.countries",r),regionCodes:yt(n.allow?.regionCodes,"allow.regionCode",r),asns:yt(n.allow?.asns,"allow.asOrganization",r)},block:{countries:yt(n.block?.countries,"block.countries",r),regionCodes:yt(n.block?.regionCodes,"block.regionCode",r),asns:yt(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??ft,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ft,u=e.incomingRequestProperties.asn?.toString()??ft,c=o.ignoreUnknown&&s===ft,l=o.ignoreUnknown&&a===ft,d=o.ignoreUnknown&&u===ft,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return ht(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?ht(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function ht(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(ht,"blockedResponse");function yt(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(yt,"toLowerStringArray");var Ua=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var Za=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Vo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Vo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ha(a[u])}else return a.length>0?Ha(a[0]):Vo(r,t,e,"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");function Ha(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(Ha,"generateResponse");var Vo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return v.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var Md="Incoming",Dd={logRequestBody:!0,logResponseBody:!0};function qa(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(qa,"headersToObject");function $a(){return new Date().toISOString()}i($a,"timestamp");var Go=new WeakMap,Ud={};function za(t,e){let n=Go.get(t);n||(n=Ud);let r=Object.assign({...n},e);Go.set(t,r)}i(za,"setMoesifContext");async function Fa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(Fa,"readBody");var Hd={},Wo;function Ba(){if(!Wo)throw new C("Invalid State - no _lastLogger");return Wo}i(Ba,"getLastLogger");function Zd(t){let e=Hd[t];return e||(e=new $("moesif-inbound",100,async n=>{let r=JSON.stringify(n);Ba().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||Ba().error({status:o.status,body:await o.text()})})),e}i(Zd,"getDispatcher");async function ja(t,e,n,r){Wo=e.log;let o=$a(),s=Object.assign(Dd,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await Fa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Zd(s.applicationId),d=t.headers.get("true-client-ip"),p=Go.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:qa(t.headers)},g=s.logResponseBody?await Fa(u,e):void 0,I={time:$a(),status:u.status,headers:qa(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Md};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(ja,"MoesifInboundPolicy");async function Va(t,e,n,r){let o=z.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Va,"loadSubscription");async function Ga(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=z.getLogger(t);try{let c=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(Ga,"consumeSubcriptionQuotas");var qd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Fn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(Fn,"validateMeters");function Wa(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=Ge(t),r=[];for(let o of n)qd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(Wa,"parseAllowedSubscriptionStatuses");function Ja(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(Ja,"compareMeters");var Bn=class extends ye{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return ge.get(e,Et)}static setMeters(e,n){Fn(n,"setMeters"),ge.set(e,Gt,n)}async handler(e,n){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=rt(this.options.meterOnStatusCodes),s=ge.get(n,Gt),a={...this.options.meters,...s};Fn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Wa(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,T,_)=>{let h=ge.get(_,Et);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=ge.get(_,Gt),H={...this.options.meters,...O};if(Fn(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=Ja(h.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await Ga(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ie.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ie.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Va(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:v.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),ge.set(n,Et,p));let m=ge.get(n,Et);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),v.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return v.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var Ka=i(async(t,e,n,r)=>te(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");var Ya=require("jose");var Jo,Qa=i(async(t,e,n,r)=>{if(!Jo)try{Jo=await(0,Ya.importSPKI)(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return te(t,e,{issuer:n.authUrl,secret:Jo,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ru=Ae(Ne());var eu=Ae(Ne());var zn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Ko=class extends zn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Yo=class extends zn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function $d(t,e){if(hs(t))throw new Ko(e)}i($d,"throwIfUndefinedOrNull");function Ut(t,e){if($d(t,e),!ce(t))throw new Yo(e,"string")}i(Ut,"throwIfNotString");var jn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Ut(e,"redisClientUrl"),Ut(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Ut(e,"url");let s=await M.fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"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 F("Rate limiting service failed with 401: Unauthorized"):new F(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Vn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Ut(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new F("The in-memory redis client only supports /rate-limit calls")}};var Fd=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),Wn=i(async t=>({key:`ip-${Fd(t)}`}),"getIP"),Jn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),Kn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Gn;function Yn(t,e){let n;if(Gn)return Gn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Vn,Gn=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ce(o))throw new F(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new F(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=jn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new F(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return Gn=n,n}i(Yn,"getRedisClient");async function Qn(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(Qn,"getCountAndUpdateExpiry");function Xn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new C(c)}return u},"outerFunction")}i(Xn,"wrapUserFunction");var er="Retry-After";var Xa=(0,eu.debug)("zuplo:policies:RateLimitInboundPolicy"),tu=i(async(t,e,n,r)=>{let o=z.getLogger(e),s=i((f,R)=>{let S={};return(!f||f==="retry-after")&&(S[er]=R.toString()),v.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Xn(n,r),user:Jn,ip:Wn,all:Kn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=Yn(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,n),_=new Y(T,e),h=Qn(b,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),Xa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){Xa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),t},"AsyncRateLimitInboundPolicy");var nu=(0,ru.debug)("zuplo:policies:RateLimitInboundPolicy"),Bd="strict",Qo=i(async(t,e,n,r)=>{if((n.mode??Bd)==="async")return tu(t,e,n,r);let s=Date.now(),a=z.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new F(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[er]=d.toString()),v.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Xn(n,r),user:Jn,ip:Wn,all:Kn}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",T=Yn(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await Qn(h,I,T,a,e.requestId);return P.count>g?(nu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;nu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Xo;function ou(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(ou,"headersToNameValuePairs");function zd(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(zd,"queryToNameValueParis");function jd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(jd,"parseIntOrUndefined");var iu={};async function su(t,e,n,r){let o=new Date,s=Date.now();return Xo||(Xo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?Ve(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?Ve(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Xo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:ou(t.headers),queryString:zd(t.query)},response:{status:a.status,statusText:a.statusText,headers:ou(a.headers),content:{size:jd(t.headers.get("content-length"))}}}]}}},d=iu[n.apiKey];if(!d){let p=n.apiKey;d=new $("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),iu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(su,"ReadmeMetricsInboundPolicy");var au=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var uu=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var cu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var lu=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),pu=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?du():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?du():t},"RequestSizeLimitInboundPolicy");function mu(t,e,n){return`_${$e(t+"_"+e+"_"+n)}`}i(mu,"getRawOperationDataIdentifierName");function tr(t,e,n,r){return`_${$e(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(tr,"getIdForParameterSchema");function nr(t,e,n){return`_${$e(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${$e(n.toLowerCase())}`}i(nr,"getIdForRequestBodySchema");function gu(t,e){return`_${$e(t)}__${$e(e)}`}i(gu,"getIdForRefSchema");function $e(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i($e,"sanitizedIdentifierName");var bt=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),wt=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=tr(n,r,o,c.name),p=ne.instance.schemaValidator[d],m=p(e[c.name]),g=ei(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),be=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),we=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),Re=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),ei=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function fu(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=v.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(we(n.validateBody)&&be(t,n.logLevel??"info",I,[r],g),Re(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=v.badRequest(e,t,{detail:g});return we(n.validateBody)&&be(t,n.logLevel??"info",g,[r],[g]),Re(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=nr(t.route.path,e.method,o),u=ne.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,t,{detail:g});return we(n.validateBody)&&be(t,n.logLevel??"info",g,[r],[g]),Re(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=ei(l),m=v.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(we(n.validateBody)&&be(t,n.logLevel??"info",d,[r],p),Re(n.validateBody))return m}i(fu,"handleBodyValidation");function hu(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=bt(t),s=wt(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(we(n.validateHeaders)&&be(t,n.logLevel??"info",a,s.invalidValues,s.errors),Re(n.validateHeaders))return u}}i(hu,"handleHeadersValidation");function yu(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=bt(t),o=wt(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(we(n.validatePathParameters)&&be(t,n.logLevel??"info",s,o.invalidValues,o.errors),Re(n.validatePathParameters))return a}}i(yu,"handlePathParameterValidation");function bu(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=bt(t),o=wt(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(we(n.validateQueryParameters)&&be(t,n.logLevel??"info",s,o.invalidValues,o.errors),Re(n.validateQueryParameters))return a}}i(bu,"handleQueryParameterValidation");var ti=i(async(t,e,n)=>{let r=bu(e,t,n);if(r!==void 0||(r=yu(e,t,n),r!==void 0)||(r=hu(e,t,n),r!==void 0))return r;let o=await fu(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),wu=ti;var Ru=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return v.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Pu=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Eu=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Iu=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Tu=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var xu=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var Vd=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),vu=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Vd(n.sleepInMs),t},"SleepInboundPolicy");var Ou=i(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await te(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new F("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new C(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Su=i(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Y(o,e),a=await s.get(r);if(!a){let u=await Gd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function Gd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ae({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new C("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new C("Response returned from Azure AD is not in the expected format.")}i(Gd,"getAccessToken");var Cu="https://accounts.google.com/o/oauth2/token",ni,Au=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),ni||(ni=await le.init(n.serviceAccountJson));let o={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 ee(r,n),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Ie({serviceAccount:ni,audience:Cu,payload:o}),l=await pn(Cu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new C("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Wd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Jd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],ri,_u=i(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Jd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}ri||(ri=await le.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new C("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new C(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=Ve(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new C(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Y(a,e),c={uid:s,claims:o},l=await Zn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ie({serviceAccount:ri,audience:Wd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await Ls(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new C("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var oi,Lu=i(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),oi||(oi=await le.init(n.serviceAccountJson));let o=await Ie({serviceAccount:oi,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Nu="https://www.googleapis.com/oauth2/v4/token",ii,ku=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),ii||(ii=await le.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=Ge(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await ee(r,n),a;n.useMemoryCacheOnly?a=new Ke(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Ie({serviceAccount:ii,audience:Nu,payload:o}),l=await pn(Nu,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new C("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new C("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Mu=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return v.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new F("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Zu=Ae(Hu());var rr=class extends Se{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?rt(e.parseOnStatusCodes):void 0,this.parser=new Zu.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new C(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var or=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new F(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var ir=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new $(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),En().waitUntil(this.#e.waitUntilFlushed())}};var sr=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new Ht(r)),await new Ht(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new Ht(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},Ht=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){En().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var ai=["sha-1","sha-256","sha-384","sha-512"],ar=class{static{i(this,"BaseCryptoBeta")}};var ur=class extends ar{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!ai.includes(e.toLowerCase()))throw new C(`Algorithm ${e} is not supported. Try using ${ai.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var cr=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var lr=class extends cr{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new jt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};
78
78
  /*! For license information please see index.min.cjs.LEGAL.txt */
package/index.min.js CHANGED
@@ -75,5 +75,5 @@ Signature verification is impossible without access to the original signed mater
75
75
  `+d}):new Te(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
76
76
  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.
77
77
  `+l+`
78
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Te(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(_l,"validateComputedSignature");function Ll(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Ll,"parseHeader");function Nl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Nl,"secureCompare");async function kl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Po[s[u]];return a.join("")}i(kl,"computeHMACSignatureAsync");var Po=new Array(256);for(let t=0;t<Po.length;t++)Po[t]=t.toString(16).padStart(2,"0");function W(t,e,n="policy"){let r=`${n} '${e}'`;if(!Be(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var _t=class extends Pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Js(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return n.log.error("Error validating stripe webhook",s),v.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Ks(t){return t!==null&&typeof t=="object"&&"id"in t&&ce(t.id)&&"type"in t&&ce(t.type)}i(Ks,"isStripeWebhookEvent");var Ml={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new A(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new A(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new A(s)}return o}},gn=Ml;var Eo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ys="My API Key";async function Qs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,Eo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ys,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await se({retryDelayMs:5,retries:2,logger:z.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(Qs,"createConsumer");async function Xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,Eo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ys,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await se({retryDelayMs:5,retries:2,logger:z.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Xs,"createConsumerInvite");async function ea({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Eo);o.searchParams.set("with-api-key","true");let s=await se({retryDelayMs:5,retries:2,logger:z.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new A(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ea,"deleteConsumer");async function ta({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!Ye(d))throw new $("No Zuplo JWT token set.");let m=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new A(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(ta,"createSubscription");async function rt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ye(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new A(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(rt,"updateSubscription");async function ot({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ye(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}return u.data[0]}i(ot,"getSubscription");var G="Unable to process webhook event.",He="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function fn(t){return t.replaceAll("_","-")}i(fn,"stripeStatusToMeteringStatus");function Io(t){return new Date(t*1e3).toISOString()}i(Io,"unixTimestampToISOString");async function To(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await Qs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await gn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(t,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=fn(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await ta({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await ea({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(t,e,{title:G,detail:p.message})}return v.ok(t,e,{title:He})}i(To,"onCustomerSubscriptionCreated");async function xo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});try{let a=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ue})}return v.ok(t,e,{title:He})}i(xo,"onCustomerSubscriptionDeleted");async function vo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=fn(n.data.object.status);await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await gn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==n.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==n.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==n.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:n.data.object.cancel_at?Io(n.data.object.cancel_at):null,cancel_at_period_end:n.data.object.cancel_at_period_end,canceled_at:n.data.object.canceled_at?Io(n.data.object.canceled_at):null,cancellation_details:n.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(t,e,{title:G,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ue})}i(vo,"onCustomerSubscriptionUpdated");var na=class extends zt{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Dl(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!Ks(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await To(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await vo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await xo(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),s=hs({inboundPolicies:[new _t({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[re,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Dl(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(Dl,"isMetricsRegion");var oa=new WeakMap,ra={},Oo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){oa.set(e,n)}};async function Ul(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Qe(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=oa.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new A(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ze(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=ra[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async b=>{try{let T=n.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),ra[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(Ul,"AmberfloMeteringInboundPolicy");async function hn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(hn,"sha256");var ia=new Map;async function ee(t,e){let n,r=ia.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await hn(JSON.stringify({policyName:t,options:e}))}`,ia.set(t,n)),n}i(ee,"getPolicyCacheName");var sa="key-metadata-cache-type";function Hl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Hl,"getKeyValue");async function So(t,e,n,r){if(!n.bucketName)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?t:v.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Hl(a,o);if(!u||u==="")return s("No key present");let c=await Zl(u),l=await ee(r,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==sa&&z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await se({retryDelayMs:5,retries:2,logger:z.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:sa,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(So,"ApiKeyInboundPolicy");async function Zl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Zl,"hashValue");var ql=So;import{createRemoteJWKSet as Fl,jwtVerify as ua}from"jose";import{createLocalJWKSet as $l}from"jose";var Co=class{constructor(e,n,r){this.cache=n;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,n){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,n)}catch(r){if(r instanceof Ao&&this.coolingDown()===!1)return await this.reload(),this.local(e,n);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(n=>{this.local=$l(n),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(n=>{throw this.pendingFetch=void 0,n}),await this.pendingFetch}async fetchJwks(e,n,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},n));let c=await M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new _o("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new it("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new it("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function aa(t,e,n){let r=new Co(t,e,n);return async(o,s)=>r.getKey(o,s)}i(aa,"createRemoteJWKSet");var it=class extends A{static{i(this,"JWKSError")}},Ao=class extends it{static{i(this,"JWKSNoMatchingKey")}},_o=class extends it{static{i(this,"JWKSTimeout")}};var yn={},Bl=i((t,e)=>async(n,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!yn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(t,r),u=new Y(a,e);yn[r.jwkUrl]=aa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else yn[r.jwkUrl]=Fl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ua(n,yn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),zl=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await ua(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Bl(r,e):zl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var jl=i(async(t,e,n,r)=>oe(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Vl=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>v.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.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 m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Gl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Wl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Wl,"digestMessage");var Jl=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Wl(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Kl(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Jl(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);Gl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Kl,"CachingInboundPolicy");var Yl=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ql=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Xl=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var ed=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",oe(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var td=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return oe(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var nd=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,s=Pt(n.policies,o?.routeData.policies);return Cr(s)(t,e)},"CompositeInboundPolicy");var rd=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return v.unauthorized(t,e,{detail:"No authorization header"});let s=od(o);if(!s)return v.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function od(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(od,"getToken");var id=i(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var sd=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var st="__unknown__",ad=i(async(t,e,n,r)=>{let o={allow:{countries:ut(n.allow?.countries,"allow.countries",r),regionCodes:ut(n.allow?.regionCodes,"allow.regionCode",r),asns:ut(n.allow?.asns,"allow.asOrganization",r)},block:{countries:ut(n.block?.countries,"block.countries",r),regionCodes:ut(n.block?.regionCodes,"block.regionCode",r),asns:ut(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??st,a=e.incomingRequestProperties.regionCode?.toLowerCase()??st,u=e.incomingRequestProperties.asn?.toString()??st,c=o.ignoreUnknown&&s===st,l=o.ignoreUnknown&&a===st,d=o.ignoreUnknown&&u===st,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return at(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?at(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function at(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(at,"blockedResponse");function ut(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(ut,"toLowerStringArray");var ud=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var cd=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Lo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ca(a[u])}else return a.length>0?ca(a[0]):Lo(r,t,e,"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");function ca(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(ca,"generateResponse");var Lo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return v.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var ld="Incoming",dd={logRequestBody:!0,logResponseBody:!0};function la(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(la,"headersToObject");function da(){return new Date().toISOString()}i(da,"timestamp");var No=new WeakMap,pd={};function md(t,e){let n=No.get(t);n||(n=pd);let r=Object.assign({...n},e);No.set(t,r)}i(md,"setMoesifContext");async function pa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(pa,"readBody");var gd={},ko;function ma(){if(!ko)throw new A("Invalid State - no _lastLogger");return ko}i(ma,"getLastLogger");function fd(t){let e=gd[t];return e||(e=new F("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ma().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ma().error({status:o.status,body:await o.text()})})),e}i(fd,"getDispatcher");async function hd(t,e,n,r){ko=e.log;let o=da(),s=Object.assign(dd,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await pa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=fd(s.applicationId),d=t.headers.get("true-client-ip"),p=No.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:la(t.headers)},g=s.logResponseBody?await pa(u,e):void 0,I={time:da(),status:u.status,headers:la(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ld};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(hd,"MoesifInboundPolicy");async function ga(t,e,n,r){let o=z.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(ga,"loadSubscription");async function fa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=z.getLogger(t);try{let c=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(fa,"consumeSubcriptionQuotas");var yd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function bn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(bn,"validateMeters");function ha(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=je(t),r=[];for(let o of n)yd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(ha,"parseAllowedSubscriptionStatuses");function ya(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(ya,"compareMeters");var Mo=class extends Pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,mt)}static setMeters(e,n){bn(n,"setMeters"),he.set(e,Ft,n)}async handler(e,n){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Qe(this.options.meterOnStatusCodes),s=he.get(n,Ft),a={...this.options.meters,...s};bn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ha(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,T,_)=>{let h=he.get(_,mt);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=he.get(_,Ft),H={...this.options.meters,...O};if(bn(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=ya(h.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await fa(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ga(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:v.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(n,mt,p));let m=he.get(n,mt);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),v.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return v.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var bd=i(async(t,e,n,r)=>oe(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as wd}from"jose";var Do,Rd=i(async(t,e,n,r)=>{if(!Do)try{Do=await wd(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(t,e,{issuer:n.authUrl,secret:Do,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ea=Ce(Le());var wa=Ce(Le());var wn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Uo=class extends wn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ho=class extends wn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Pd(t,e){if(us(t))throw new Uo(e)}i(Pd,"throwIfUndefinedOrNull");function Lt(t,e){if(Pd(t,e),!ce(t))throw new Ho(e,"string")}i(Lt,"throwIfNotString");var Rn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Lt(e,"redisClientUrl"),Lt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Lt(e,"url");let s=await M.fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"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 $("Redis client failed with 401: Unauthorized"):new $(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Pn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Lt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var Ed=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),In=i(async t=>({key:`ip-${Ed(t)}`}),"getIP"),Tn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),xn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),En;function vn(t,e){let n;if(En)return En;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Pn,En=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ce(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Rn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return En=n,n}i(vn,"getRedisClient");async function On(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(On,"getCountAndUpdateExpiry");function Sn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(Sn,"wrapUserFunction");var Cn="Retry-After";var ba=(0,wa.debug)("zuplo:policies:RateLimitInboundPolicy"),Ra=i(async(t,e,n,r)=>{let o=z.getLogger(e),s=i((f,R)=>{let S={};return(!f||f==="retry-after")&&(S[Cn]=R.toString()),v.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Sn(n,r),user:Tn,ip:In,all:xn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=vn(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,n),_=new Y(T,e),h=On(b,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),ba(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){ba(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),t},"AsyncRateLimitInboundPolicy");var Pa=(0,Ea.debug)("zuplo:policies:RateLimitInboundPolicy"),Id="strict",Ia=i(async(t,e,n,r)=>{if((n.mode??Id)==="async")return Ra(t,e,n,r);let s=Date.now(),a=z.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Cn]=d.toString()),v.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Sn(n,r),user:Tn,ip:In,all:xn}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",T=vn(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await On(h,I,T,a,e.requestId);return P.count>g?(Pa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;Pa(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Zo;function Ta(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(Ta,"headersToNameValuePairs");function Td(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(Td,"queryToNameValueParis");function xd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(xd,"parseIntOrUndefined");var xa={};async function vd(t,e,n,r){let o=new Date,s=Date.now();return Zo||(Zo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Zo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ta(t.headers),queryString:Td(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ta(a.headers),content:{size:xd(t.headers.get("content-length"))}}}]}}},d=xa[n.apiKey];if(!d){let p=n.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),xa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(vd,"ReadmeMetricsInboundPolicy");var Od=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Sd=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Cd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ad=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var va=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_d=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?va():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?va():t},"RequestSizeLimitInboundPolicy");function Ld(t,e,n){return`_${Ge(t+"_"+e+"_"+n)}`}i(Ld,"getRawOperationDataIdentifierName");function qo(t,e,n,r){return`_${Ge(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(qo,"getIdForParameterSchema");function $o(t,e,n){return`_${Ge(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ge(n.toLowerCase())}`}i($o,"getIdForRequestBodySchema");function Nd(t,e){return`_${Ge(t)}__${Ge(e)}`}i(Nd,"getIdForRefSchema");function Ge(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(Ge,"sanitizedIdentifierName");var ct=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),lt=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=qo(n,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=Fo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),ye=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),be=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),we=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Fo=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Oa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=v.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(be(n.validateBody)&&ye(t,n.logLevel??"info",I,[r],g),we(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=v.badRequest(e,t,{detail:g});return be(n.validateBody)&&ye(t,n.logLevel??"info",g,[r],[g]),we(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=$o(t.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,t,{detail:g});return be(n.validateBody)&&ye(t,n.logLevel??"info",g,[r],[g]),we(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Fo(l),m=v.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(be(n.validateBody)&&ye(t,n.logLevel??"info",d,[r],p),we(n.validateBody))return m}i(Oa,"handleBodyValidation");function Sa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ct(t),s=lt(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(be(n.validateHeaders)&&ye(t,n.logLevel??"info",a,s.invalidValues,s.errors),we(n.validateHeaders))return u}}i(Sa,"handleHeadersValidation");function Ca(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=ct(t),o=lt(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(n.validatePathParameters)&&ye(t,n.logLevel??"info",s,o.invalidValues,o.errors),we(n.validatePathParameters))return a}}i(Ca,"handlePathParameterValidation");function Aa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=ct(t),o=lt(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(n.validateQueryParameters)&&ye(t,n.logLevel??"info",s,o.invalidValues,o.errors),we(n.validateQueryParameters))return a}}i(Aa,"handleQueryParameterValidation");var _a=i(async(t,e,n)=>{let r=Aa(e,t,n);if(r!==void 0||(r=Ca(e,t,n),r!==void 0)||(r=Sa(e,t,n),r!==void 0))return r;let o=await Oa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),kd=_a;var Md=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return v.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Dd=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Ud=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Hd=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Zd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var qd=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var $d=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Fd=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await $d(n.sleepInMs),t},"SleepInboundPolicy");var Bd=i(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await oe(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var zd=i(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Y(o,e),a=await s.get(r);if(!a){let u=await jd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function jd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await se({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}i(jd,"getAccessToken");var La="https://accounts.google.com/o/oauth2/token",Bo,Vd=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),Bo||(Bo=await le.init(n.serviceAccountJson));let o={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 ee(r,n),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Ee({serviceAccount:Bo,audience:La,payload:o}),l=await tn(La,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Gd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Wd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],zo,Jd=i(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Wd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}zo||(zo=await le.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new A(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Y(a,e),c={uid:s,claims:o},l=await hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ee({serviceAccount:zo,audience:Gd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await vs(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var jo,Kd=i(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),jo||(jo=await le.init(n.serviceAccountJson));let o=await Ee({serviceAccount:jo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Na="https://www.googleapis.com/oauth2/v4/token",Vo,Yd=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vo||(Vo=await le.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=je(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await ee(r,n),a;n.useMemoryCacheOnly?a=new Je(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Ee({serviceAccount:Vo,audience:Na,payload:o}),l=await tn(Na,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Qd=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return v.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ua=Ce(Da());var Wo=class extends Me{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Qe(e.parseOnStatusCodes):void 0,this.parser=new Ua.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Jo=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Ko=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new F(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),ln().waitUntil(this.#e.waitUntilFlushed())}};var Yo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new Nt(r)),await new Nt(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new Nt(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},Nt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){ln().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var Qo=["sha-1","sha-256","sha-384","sha-512"],An=class{static{i(this,"BaseCryptoBeta")}};var Xo=class extends An{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!Qo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Qo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var _n=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var ei=class extends _n{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new qt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{so as AWSLoggingPlugin,Ul as AmberfloMeteringInboundPolicy,Oo as AmberfloMeteringPolicy,ql as ApiAuthKeyInboundPolicy,So as ApiKeyInboundPolicy,yo as AuditLogDataStaxProvider,bo as AuditLogPlugin,jl as Auth0JwtInboundPolicy,rl as AwsLambdaHandlerExtensions,Ko as BackgroundDispatcher,Yo as BackgroundLoader,Vl as BasicAuthInboundPolicy,Ia as BasicRateLimitInboundPolicy,F as BatchDispatch,Kl as CachingInboundPolicy,Yl as ChangeMethodInboundPolicy,Ql as ClearHeadersInboundPolicy,Xl as ClearHeadersOutboundPolicy,ed as ClerkJwtInboundPolicy,td as CognitoJwtInboundPolicy,nd as CompositeInboundPolicy,y as ConfigurationError,pr as ContentTypes,he as ContextData,Xo as CryptoBeta,rd as CurityPhantomTokenInboundPolicy,Hr as DataDogLoggingPlugin,co as DataDogMetricsPlugin,Yr as DynaTraceLoggingPlugin,go as DynatraceMetricsPlugin,id as FirebaseJwtInboundPolicy,sd as FormDataToJsonInboundPolicy,ad as GeoFilterInboundPolicy,Nr as GoogleCloudLoggingPlugin,Br as Handler,v as HttpProblems,fr as HttpStatusCode,Pe as InboundPolicy,ud as JWTScopeValidationInboundPolicy,ei as KeyValueStore,Xr as LokiLoggingPlugin,St as LookupResult,Y as MemoryZoneReadThroughCache,cd as MockApiInboundPolicy,hd as MoesifInboundPolicy,Mo as MonetizationInboundPolicy,bd as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,Me as OutboundPolicy,Fe as ProblemResponseFormatter,Rd as PropelAuthJwtInboundPolicy,Ia as RateLimitInboundPolicy,vd as ReadmeMetricsInboundPolicy,Od as RemoveHeadersInboundPolicy,Sd as RemoveHeadersOutboundPolicy,Cd as RemoveQueryParamsInboundPolicy,Ad as ReplaceStringOutboundPolicy,_d as RequestSizeLimitInboundPolicy,_a as RequestValidationInboundPolicy,Md as RequireOriginInboundPolicy,yt as ResponseSendingEvent,bt as ResponseSentEvent,Ct as Router,A as RuntimeError,Bt as SYSTEM_LOGGER,kd as SchemaBasedRequestValidation,fe as SemanticAttributes,Jo as ServiceProviderImpl,Dd as SetBodyInboundPolicy,Ud as SetHeadersInboundPolicy,Hd as SetHeadersOutboundPolicy,Zd as SetQueryParamsInboundPolicy,qd as SetStatusOutboundPolicy,Fd as SleepInboundPolicy,na as StripeMonetizationPlugin,_t as StripeWebhookVerificationInboundPolicy,no as SumoLogicLoggingPlugin,Bd as SupabaseJwtInboundPolicy,Oe as SystemRouteName,gt as TelemetryPlugin,zd as UpstreamAzureAdServiceAuthInboundPolicy,Vd as UpstreamFirebaseAdminAuthInboundPolicy,Jd as UpstreamFirebaseUserAuthInboundPolicy,Kd as UpstreamGcpJwtInboundPolicy,Yd as UpstreamGcpServiceAuthInboundPolicy,oo as VMWareLogInsightLoggingPlugin,Qd as ValidateJsonSchemaInbound,Wo as XmlToJsonOutboundPolicy,pt as ZoneCache,j as ZuploRequest,ol as awsLambdaHandler,ae as environment,qo as getIdForParameterSchema,Nd as getIdForRefSchema,$o as getIdForRequestBodySchema,Ld as getRawOperationDataIdentifierName,hr as httpStatuses,pl as openApiSpecHandler,gl as redirectHandler,Ge as sanitizedIdentifierName,mr as serialize,md as setMoesifContext,hl as urlForwardHandler,bl as urlRewriteHandler,wl as webSocketHandler,Rl as webSocketPipelineHandler};
78
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-n.timestamp;if(o>0&&p>o)throw new Te(e,t,{message:"Timestamp outside the tolerance zone"});return!0}i(_l,"validateComputedSignature");function Ll(t,e){return typeof t!="string"?null:t.split(",").reduce((n,r)=>{let o=r.split("=");return o[0]==="t"&&(n.timestamp=parseInt(o[1],10)),o[0]===e&&n.signatures.push(o[1]),n},{timestamp:-1,signatures:[]})}i(Ll,"parseHeader");function Nl(t,e){if(t.length!==e.length)return!1;let n=t.length,r=0;for(let o=0;o<n;++o)r|=t.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Nl,"secureCompare");async function kl(t,e){let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,n.encode(t)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Po[s[u]];return a.join("")}i(kl,"computeHMACSignatureAsync");var Po=new Array(256);for(let t=0;t<Po.length;t++)Po[t]=t.toString(16).padStart(2,"0");function W(t,e,n="policy"){let r=`${n} '${e}'`;if(!Be(t))throw new y(`Options on ${r} is expected to be an object. Received the type '${typeof t}'.`);let o=i((u,c,l)=>{let d=t[u];if(!(l&&d===void 0)){if(d===void 0)throw new y(`Value of '${String(u)}' on ${r} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(c==="array"&&Array.isArray(d))throw new y(`Value of '${String(u)}' on ${r} must be an array. Received type ${typeof d}.`);if(typeof d!==c)throw new y(`Value of '${String(u)}' on ${r} must be of type ${c}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new y(`Value of '${String(u)}' on ${r} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new y(`Value of '${String(u)}' on ${r} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=i((u,c)=>(o(u,c,!0),{optional:s,required:a}),"optional"),a=i((u,c)=>(o(u,c,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}i(W,"optionValidator");var _t=class extends Pe{static{i(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,n){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Js(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return n.log.error("Error validating stripe webhook",s),v.badRequest(e,n,{title:"Webhook Error",detail:s})}return e}};function Ks(t){return t!==null&&typeof t=="object"&&"id"in t&&ce(t.id)&&"type"in t&&ce(t.type)}i(Ks,"isStripeWebhookEvent");var Ml={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw n.error(s,o),new A(s)}return o},getCustomer:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw n.error(s,o),new A(s)}return o},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:n})=>{let r=await M.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw n.error(s,o),new A(s)}return o}},gn=Ml;var Eo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ys="My API Key";async function Qs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${t}/consumers`,Eo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ys,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await se({retryDelayMs:5,retries:2,logger:z.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let g="Error creating API Key Consumer";throw a.log.error(g,m),new A(g)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:n}),l}i(Qs,"createConsumer");async function Xs({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${t}/consumers`,Eo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ys,tags:{subscriptionExternalId:e,planExternalIds:[n]},metadata:{stripeSubscriptionId:e,stripeProductId:n,stripeCustomerId:r},managers:[o]},d=await se({retryDelayMs:5,retries:2,logger:z.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw s.log.error(m,p),new A(m)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:n}),c}i(Xs,"createConsumerInvite");async function ea({apiKeyBucketName:t,consumerId:e,context:n}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${t}/consumers/${e}`,Eo);o.searchParams.set("with-api-key","true");let s=await se({retryDelayMs:5,retries:2,logger:z.getLogger(n)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw n.log.error(u,a),new A(u)}return n.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(ea,"deleteConsumer");async function ta({context:t,stripeSubscriptionId:e,stripeProductId:n,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c}){let l={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[n],customerKey:r,customerExternalId:a,metadata:c},{authApiJWT:d,meteringServiceUrl:p}=w.instance;if(!Ye(d))throw new $("No Zuplo JWT token set.");let m=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${p}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!m.ok){let g=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,b="";try{I=await m.json(),b=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:m.status,detail:m.statusText}}throw t.log.error(g,I),new A(`${g} ${b}`)}t.log.info("Successfully created monetization subscription.",l)}i(ta,"createSubscription");async function rt({context:t,meteringSubscriptionId:e,meteringBucketId:n,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ye(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(u,c),new A(`${u} ${l}`)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(rt,"updateSubscription");async function ot({context:t,stripeSubscriptionId:e,stripeCustomerId:n,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=w.instance;if(!Ye(o))throw new $("No Zuplo JWT token set.");let a=await se({retryDelayMs:5,retries:2,logger:z.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw t.log.error(c,l),new A(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}if(u.data[0].customerExternalId!==n){let c=`Subscription was not found for Stripe customer '${n}' and the event was ignored by Zuplo.`;throw t.log.error(c),new A(c)}return u.data[0]}i(ot,"getSubscription");var G="Unable to process webhook event.",He="Successfully processed webhook event",ue="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function fn(t){return t.replaceAll("_","-")}i(fn,"stripeStatusToMeteringStatus");function Io(t){return new Date(t*1e3).toISOString()}i(Io,"unixTimestampToISOString");async function To(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${n.id}' to have a plan data.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=n.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});let u=s.product,c,l,d;if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_email&&n.data.object.metadata.zuplo_created_by_sub)l=n.data.object.metadata.zuplo_created_by_email,d=n.data.object.metadata.zuplo_created_by_sub,c=await Qs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await gn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!c)return v.internalServerError(t,e,{title:G,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=fn(n.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}}),await ta({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m})}catch(p){return await ea({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.internalServerError(t,e,{title:G,detail:p.message})}return v.ok(t,e,{title:He})}i(To,"onCustomerSubscriptionCreated");async function xo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to have '.data.object.id' be the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});try{let a=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await rt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+ue})}return v.ok(t,e,{title:He})}i(xo,"onCustomerSubscriptionDeleted");async function vo(t,e,n,r){let o=n.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${n.id}' to include '.data.object.id' as the subscription ID.`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=n.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${n.id}'`),v.badRequest(t,e,{title:G,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(n.data.object.metadata&&n.data.object.metadata.zuplo_created_by_deploymentName&&n.data.object.metadata.zuplo_created_by_deploymentName!==w.instance.deploymentName)return e.log.warn(`Subscription event '${n.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.badRequest(t,e,{title:G,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${n.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue});if(n.data.previous_attributes){let a=n.data.previous_attributes;if(a.status&&a.status!==n.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=fn(n.data.object.status);await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}if(a.plan&&a.plan.product!==n.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=n.data.object.plan.product,d=(await gn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${n.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==n.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==n.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==n.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${n.id}'.`);let u=await ot({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:n.data.object.cancel_at?Io(n.data.object.cancel_at):null,cancel_at_period_end:n.data.object.cancel_at_period_end,canceled_at:n.data.object.canceled_at?Io(n.data.object.canceled_at):null,cancellation_details:n.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await rt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.internalServerError(t,e,{title:G,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+ue})}return v.ok(t,e,{title:He})}}return e.log.warn(`This update event '${n.id}' is not supported by Stripe monetization plugin webhook.`),v.badRequest(t,e,{title:G,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+ue})}i(vo,"onCustomerSubscriptionUpdated");var na=class extends zt{constructor(n){super();this.options=n}static{i(this,"StripeMonetizationPlugin")}registerRoutes(n,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)d=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new $("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!Dl(m))throw new y(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let g=await c.json();if(!Ks(g))return v.badRequest(c,l,{title:G,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+ue});switch(l.log.info(`Received Stripe webhook event of type '${g.type}' with ID '${g.id}'.`),g.type){case"customer.subscription.created":return await To(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await vo(c,l,g,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await xo(c,l,g,{meteringBucketId:d});default:return v.badRequest(c,l,{title:G,detail:`Event '${g.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+ue})}},"stripeWebhookHandler"),s=hs({inboundPolicies:[new _t({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Q({processors:[re,s],handler:o,gateway:r}),u=new K({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});n.addRoute(u,a.execute)}};function Dl(t){return t!==null&&typeof t=="string"&&["us-central1","us-east1","europe-west4"].includes(t)}i(Dl,"isMetricsRegion");var oa=new WeakMap,ra={},Oo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,n){oa.set(e,n)}};async function Ul(t,e,n,r){if(!n.statusCodes)throw new y(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Qe(n.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=oa.get(e),u=n.customerId;if(n.customerIdPropertyPath){if(!t.user)throw new A(`Unable to apply customerIdPropertyPath '${n.customerIdPropertyPath}' as request.user is 'undefined'.`);u=ze(t.user,n.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??n.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??n.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(n.dimensions??{},a?.dimensions)},m=ra[n.apiKey];if(!m){let g=n.apiKey,I=t.headers.get("zm-test-id")??"";m=new F("amberflo-ingest-meter",10,async b=>{try{let T=n.url??"https://app.amberflo.io/ingest",_=await M.fetch(T,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":g,"zm-test-id":I}});_.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${_.status}: ${await _.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${T.message}`),T}}),ra[g]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}i(Ul,"AmberfloMeteringInboundPolicy");async function hn(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(hn,"sha256");var ia=new Map;async function ee(t,e){let n,r=ia.get(t);return r!==void 0?n=r:(n=`zuplo-policy-${await hn(JSON.stringify({policyName:t,options:e}))}`,ia.set(t,n)),n}i(ee,"getPolicyCacheName");var sa="key-metadata-cache-type";function Hl(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}i(Hl,"getKeyValue");async function So(t,e,n,r){if(!n.bucketName)if(ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)n.bucketName=ae.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new y(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:n.authHeader??"authorization",authScheme:n.authScheme??"Bearer",bucketName:n.bucketName,cacheTtlSeconds:n.cacheTtlSeconds??60,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:n.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new y(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(T=>o.allowUnauthenticatedRequests?t:v.unauthorized(t,e,{detail:T}),"unauthorizedResponse"),a=t.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=Hl(a,o);if(!u||u==="")return s("No key present");let c=await Zl(u),l=await ee(r,o),d=new Y(l,e),p=await d.get(c);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==sa&&z.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let m={key:u},g=await se({retryDelayMs:5,retries:2,logger:z.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.instance.systemUserAgent},body:JSON.stringify(m)});if(g.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(g.status!==200){try{let T=await g.text(),_=JSON.parse(T);e.log.error("Unexpected response from key service",_)}catch{e.log.error("Invalid response from key service")}throw new A(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${g.status}`)}let I=await g.json(),b={isValid:!0,typeId:sa,user:{sub:I.name,data:I.metadata}};return t.user=b.user,d.put(c,b,o.cacheTtlSeconds),t}i(So,"ApiKeyInboundPolicy");async function Zl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Zl,"hashValue");var ql=So;import{createRemoteJWKSet as Fl,jwtVerify as ua}from"jose";import{createLocalJWKSet as $l}from"jose";var Co=class{constructor(e,n,r){this.cache=n;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,n){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,n)}catch(r){if(r instanceof Ao&&this.coolingDown()===!1)return await this.reload(),this.local(e,n);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(n=>{this.local=$l(n),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(n=>{throw this.pendingFetch=void 0,n}),await this.pendingFetch}async fetchJwks(e,n,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},n));let c=await M.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new _o("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new it("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new it("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function aa(t,e,n){let r=new Co(t,e,n);return async(o,s)=>r.getKey(o,s)}i(aa,"createRemoteJWKSet");var it=class extends A{static{i(this,"JWKSError")}},Ao=class extends it{static{i(this,"JWKSNoMatchingKey")}},_o=class extends it{static{i(this,"JWKSTimeout")}};var yn={},Bl=i((t,e)=>async(n,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new y("Invalid State - jwkUrl not set");if(!yn[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ee(t,r),u=new Y(a,e);yn[r.jwkUrl]=aa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else yn[r.jwkUrl]=Fl(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ua(n,yn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),zl=i(async(t,e)=>{let n;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);n=new Uint8Array(s)}else n=e.secret;let{payload:r}=await ua(t,n,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),oe=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization"),s="bearer ",a=i(m=>v.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!n.jwkUrl&&!n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(n.jwkUrl&&n.secret)throw new y(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=n.jwkUrl?Bl(r,e):zl,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let m=o.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await u(m,n)}catch(g){let I=new URL(t.url);return"code"in g&&g.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${I.pathname} `,g):e.log.warn(`Invalid token on: ${t.method} ${I.pathname}`,g),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return n.allowUnauthenticatedRequests===!0?t:l;let d=n.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var jl=i(async(t,e,n,r)=>oe(t,e,{issuer:`https://${n.auth0Domain}/`,audience:n.audience,jwkUrl:`https://${n.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Vl=i(async(t,e,n)=>{let r=t.headers.get("Authorization"),o="basic ",s=i(l=>v.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.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 m=d.substring(0,p),g=d.substring(p+1),I=n.accounts.find(b=>b.username===m&&b.password===g);return I||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return n.allowUnauthenticatedRequests?t:u;let c=u.username;return t.user={sub:c,data:u.data},t},"BasicAuthInboundPolicy");var Gl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Wl(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Wl,"digestMessage");var Jl=i(async(t,e)=>{let n=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of t.headers.entries())n.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Wl(JSON.stringify(r)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",t.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":t.method})},"createCacheKeyRequest");async function Kl(t,e,n,r){let o=await ee(r,n),s=await caches.open(o),a=n?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Jl(t,n),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=n.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let m=n?.expirationSecondsTtl??60,g=new Response(p.body,p);Gl.forEach(I=>g.headers.delete(I)),g.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(s.put(u,g))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),t)}i(Kl,"CachingInboundPolicy");var Yl=i(async(t,e,n,r)=>{if(!n.method)throw new y(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new j(t,{method:n.method})},"ChangeMethodInboundPolicy");var Ql=i(async(t,e,n)=>{let r=[...n.exclude??[]],o=new Headers;return r.forEach(a=>{let u=t.headers.get(a);u&&o.set(a,u)}),new j(t,{headers:o})},"ClearHeadersInboundPolicy");var Xl=i(async(t,e,n,r)=>{let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=t.headers.get(u);c&&s.set(u,c)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");var ed=i(async(t,e,n,r)=>{let o=new URL(n.frontendApiUrl.startsWith("https://")||n.frontendApiUrl.startsWith("http://")?n.frontendApiUrl:`https://${n.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",oe(t,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var td=i(async(t,e,n,r)=>{if(!n.userPoolId)throw new y("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!n.region)throw new y("region must be set in the options for CognitoJwtInboundPolicy");return oe(t,e,{issuer:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}`,jwkUrl:`https://cognito-idp.${n.region}.amazonaws.com/${n.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var nd=i(async(t,e,n,r)=>{if(!n.policies||n.policies.length===0)throw new y(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=te.instance,s=Pt(n.policies,o?.routeData.policies);return Cr(s)(t,e)},"CompositeInboundPolicy");var rd=i(async(t,e,n,r)=>{let o=t.headers.get("Authorization");if(!o)return v.unauthorized(t,e,{detail:"No authorization header"});let s=od(o);if(!s)return v.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await ee(r,n),u=new Y(a,e),c=await u.get(s);if(!c){let l=await M.fetch(n.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${n.clientId}:${n.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)c=d,u.put(s,c,n.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${c}`),t},"CurityPhantomTokenInboundPolicy");function od(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}i(od,"getToken");var id=i(async(t,e,n,r)=>(W(n,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),oe(t,e,{issuer:`https://securetoken.google.com/${n.projectId}`,audience:n.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var sd=i(async(t,e,n)=>{let r="application/x-www-form-urlencoded",o="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return n&&n.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(n&&n.optionalHoneypotName&&a.get(n.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(t.headers);return c.set("content-type","application/json"),c.delete("content-length"),new j(t,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var st="__unknown__",ad=i(async(t,e,n,r)=>{let o={allow:{countries:ut(n.allow?.countries,"allow.countries",r),regionCodes:ut(n.allow?.regionCodes,"allow.regionCode",r),asns:ut(n.allow?.asns,"allow.asOrganization",r)},block:{countries:ut(n.block?.countries,"block.countries",r),regionCodes:ut(n.block?.regionCodes,"block.regionCode",r),asns:ut(n.block?.asns,"block.asOrganization",r)},ignoreUnknown:n.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??st,a=e.incomingRequestProperties.regionCode?.toLowerCase()??st,u=e.incomingRequestProperties.asn?.toString()??st,c=o.ignoreUnknown&&s===st,l=o.ignoreUnknown&&a===st,d=o.ignoreUnknown&&u===st,p=o.allow.countries,m=o.allow.regionCodes,g=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||m.length>0&&!m.includes(a)&&!l||g.length>0&&!g.includes(u)&&!d)return at(t,e,r,s,a,u);let I=o.block.countries,b=o.block.regionCodes,T=o.block.asns;return I.length>0&&I.includes(s)&&!c||b.length>0&&b.includes(a)&&!l||T.length>0&&T.includes(u)&&!d?at(t,e,r,s,a,u):t},"GeoFilterInboundPolicy");function at(t,e,n,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${n}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),v.forbidden(t,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(at,"blockedResponse");function ut(t,e,n){if(typeof t=="string")return t.split(",").map(r=>r.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(r=>r.trim().toLowerCase());throw new y(`Invalid '${e}' for GeoFilterInboundPolicy '${n}': '${t}', must be a string or string[]`)}i(ut,"toLowerStringArray");var ud=i(async(t,e,n)=>{let r=t.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,n.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${n.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");var cd=i(async(t,e,n,r)=>{let o=e.route.raw().responses;if(!o)return Lo(r,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Lo(r,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:u,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(u=>!(n.responsePrefixFilter&&!u.responseName.startsWith(n.responsePrefixFilter)||n.contentType&&u.contentName!==n.contentType||n.exampleName&&u.exampleName!==n.exampleName)),n.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return ca(a[u])}else return a.length>0?ca(a[0]):Lo(r,t,e,"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");function ca(t){let e=JSON.stringify(t.exampleValue,null,2),n=new Headers;switch(n.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:n});case"2XX":return new Response(e,{status:200,headers:n});case"3XX":return new Response(e,{status:300,headers:n});case"4XX":return new Response(e,{status:400,headers:n});case"5XX":case"default":return new Response(e,{status:500,headers:n});default:return new Response(e,{status:Number(t.responseName),headers:n})}}i(ca,"generateResponse");var Lo=i((t,e,n,r)=>{let o=`Error in policy: ${t} - On route ${e.method} ${n.route.path}. ${r}`;return v.internalServerError(e,n,{detail:o})},"getProblemDetailResponse");var ld="Incoming",dd={logRequestBody:!0,logResponseBody:!0};function la(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}i(la,"headersToObject");function da(){return new Date().toISOString()}i(da,"timestamp");var No=new WeakMap,pd={};function md(t,e){let n=No.get(t);n||(n=pd);let r=Object.assign({...n},e);No.set(t,r)}i(md,"setMoesifContext");async function pa(t,e){let n=t.headers.get("content-type");if(n&&n.indexOf("json")!==0)try{return await t.clone().json()}catch(o){e.log.error(o)}let r=await t.clone().text();return e.log.debug({textBody:r}),r}i(pa,"readBody");var gd={},ko;function ma(){if(!ko)throw new A("Invalid State - no _lastLogger");return ko}i(ma,"getLastLogger");function fd(t){let e=gd[t];return e||(e=new F("moesif-inbound",100,async n=>{let r=JSON.stringify(n);ma().debug("posting",r);let o=await M.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:r});o.ok||ma().error({status:o.status,body:await o.text()})})),e}i(fd,"getDispatcher");async function hd(t,e,n,r){ko=e.log;let o=da(),s=Object.assign(dd,n);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await pa(t,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=fd(s.applicationId),d=t.headers.get("true-client-ip"),p=No.get(e)??{},m={time:o,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:la(t.headers)},g=s.logResponseBody?await pa(u,e):void 0,I={time:da(),status:u.status,headers:la(u.headers),body:g},b={request:m,response:I,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:ld};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}i(hd,"MoesifInboundPolicy");async function ga(t,e,n,r){let o=z.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=w.instance,u;try{let l=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${n}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(ga,"loadSubscription");async function fa(t,e,n,r,o){let{authApiJWT:s,meteringServiceUrl:a}=w.instance,u=z.getLogger(t);try{let c=await M.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){t.log.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${n}' - Error updating subscription quota.`,c)}}i(fa,"consumeSubcriptionQuotas");var yd=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function bn(t,e){try{let n=[];for(let r in t)typeof t[r]!="number"&&!(Number.isInteger(t[r])&&/^-?\d+$/.test(t[r].toString()))&&n.push(r);if(n.length>0)throw new y(n.length>1?`The values found in these properties are not integers : ${n.join(", ")}`:`The value in property '${n[0]}' is not an integer`)}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${n.message}`):n}}i(bn,"validateMeters");function ha(t,e){if(t)try{if(t.length===0)throw new y("Must set valid subscription statuses");let n=je(t),r=[];for(let o of n)yd.has(o)||r.push(o);if(r.length>0)throw new y(`Found the following invalid statuses: ${r.join(", ")}`);return t}catch(n){throw n instanceof y?new y(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${n.message}`):n}else return["active","incomplete","trialing"]}i(ha,"parseAllowedSubscriptionStatuses");function ya(t,e){let n={},r={};for(let o in e)t.hasOwnProperty(o)?n[o]=e[o]:r[o]=e[o];return{metersInSubscription:n,metersNotInSubscription:r}}i(ya,"compareMeters");var Mo=class extends Pe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,mt)}static setMeters(e,n){bn(n,"setMeters"),he.set(e,Ft,n)}async handler(e,n){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Qe(this.options.meterOnStatusCodes),s=he.get(n,Ft),a={...this.options.meters,...s};bn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=ha(this.options.allowedSubscriptionStatuses,this.policyName);n.addResponseSendingFinalHook(async(b,T,_)=>{let h=he.get(_,mt);if((this.options.allowRequestsWithoutSubscription??!1)&&!h){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=he.get(_,Ft),H={...this.options.meters,...O};if(bn(H,this.policyName),o.includes(b.status)&&h&&H){_.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${h.id}' with meters '${JSON.stringify(H)} on response status '${b.status}'`);let{metersInSubscription:f,metersNotInSubscription:R}=ya(h.meters,H);if(R&&Object.keys(R).length>0){let S=Object.keys(R);_.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${S}'`)}await fa(_,h.id,this.policyName,this.options.bucketId,f)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,n,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(ae.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=ae.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new y(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await ga(n,d,this.policyName,this.options.bucketId);if(!p)return n.log.warn("No valid subscription found"),u?e:v.unauthorized(e,n,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return n.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,n,{detail:"No valid subscription found"});c.includes(p.status)&&(n.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(n,mt,p));let m=he.get(n,mt);if(!m)return u?e:(n.log.warn("Subscription is not available for user"),v.paymentRequired(e,n,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return n.log.error(`Quota is not set up for subscription '${m.id}'`),v.tooManyRequests(e,n,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let I=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(I.length>0)return n.log.warn(`The following policy meters are not present in the subscription: ${I.join(", ")}`),v.tooManyRequests(e,n,{detail:`The following policy meters are not present in the subscription: ${I.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return v.tooManyRequests(e,n,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};var bd=i(async(t,e,n,r)=>oe(t,e,{issuer:n.issuerUrl,audience:n.audience,jwkUrl:`${n.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as wd}from"jose";var Do,Rd=i(async(t,e,n,r)=>{if(!Do)try{Do=await wd(n.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return oe(t,e,{issuer:n.authUrl,secret:Do,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ea=Ce(Le());var wa=Ce(Le());var wn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},Uo=class extends wn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Ho=class extends wn{static{i(this,"ArgumentTypeError")}constructor(e,n){super(`The argument '${e}' must be of type '${n}'.`)}};function Pd(t,e){if(us(t))throw new Uo(e)}i(Pd,"throwIfUndefinedOrNull");function Lt(t,e){if(Pd(t,e),!ce(t))throw new Ho(e,"string")}i(Lt,"throwIfNotString");var Rn=class t{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,n,r,o){this.redisClientUrl=e,this.clientAuthToken=n,this.deploymentName=r,this.userAgent=o}static initialize(e,n,r,o){return Lt(e,"redisClientUrl"),Lt(n,"clientAuthToken"),t.instance||(t.instance=new t(e,n,r,o)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:n,method:r,requestId:o}){Lt(e,"url");let s=await M.fetch(`${this.redisClientUrl}${e}`,{method:r,body:n,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"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 $("Rate limiting service failed with 401: Unauthorized"):new $(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Pn=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:n,method:r}){if(Lt(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(n),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new $("The in-memory redis client only supports /rate-limit calls")}};var Ed=i(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let n=t.headers.get("x-forwarded-for");return n?n.split(",")[0]:"127.0.0.1"},"getRealIP"),In=i(async t=>({key:`ip-${Ed(t)}`}),"getIP"),Tn=i(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),xn=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),En;function vn(t,e){let n;if(En)return En;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),n=new Pn,En=n,n;let{authApiJWT:r,redisURL:o}=w.instance;if(!ce(o))throw new $(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!ce(r))throw new $(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(o&&(n=Rn.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!n||!n.isEnabled())throw new $(`RateLimitInboundPolicy '${t}' - no redis ('${n}') or redis.isEnabled ('${n?.isEnabled}) is false`);return En=n,n}i(vn,"getRedisClient");async function On(t,e,n,r,o){let s=Math.floor(e*60);return await n.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:o})}i(On,"getCountAndUpdateExpiry");function Sn(t,e){let n;if(t.rateLimitBy==="function"){if(!t.identifier)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new y(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(n=t.identifier.module[t.identifier.export],!n||typeof n!="function")throw new y(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return i(async(o,s,a)=>{let u=await n(o,s,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw s.log.error(c),new A(c)}return u},"outerFunction")}i(Sn,"wrapUserFunction");var Cn="Retry-After";var ba=(0,wa.debug)("zuplo:policies:RateLimitInboundPolicy"),Ra=i(async(t,e,n,r)=>{let o=z.getLogger(e),s=i((f,R)=>{let S={};return(!f||f==="retry-after")&&(S[Cn]=R.toString()),v.tooManyRequests(t,e,void 0,S)},"rateLimited"),u={function:Sn(n,r),user:Tn,ip:In,all:xn}[n.rateLimitBy],c=await u(t,e,r),l=c.key,d=c.requestsAllowed??n.requestsAllowed,p=c.timeWindowMinutes??n.timeWindowMinutes,m=n.headerMode??"retry-after",g=vn(r,o),b=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,T=await ee(r,n),_=new Y(T,e),h=On(b,p,g,o,e.requestId),P;i(async()=>{let f=await h;if(f.count>d){let R=Date.now()+f.ttlSeconds*1e3;_.put(b,R,f.ttlSeconds),ba(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${b}' (async mode)`),P=s(m,f.ttlSeconds)}},"asyncCheck")();let H=await _.get(b);if(H!==void 0&&H>Date.now()){ba(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${b}' (async mode)`);let f=Math.round((H-Date.now())/1e3);return s(m,f)}return e.addResponseSendingHook(async f=>P??f),t},"AsyncRateLimitInboundPolicy");var Pa=(0,Ea.debug)("zuplo:policies:RateLimitInboundPolicy"),Id="strict",Ia=i(async(t,e,n,r)=>{if((n.mode??Id)==="async")return Ra(t,e,n,r);let s=Date.now(),a=z.getLogger(e),u=i((l,d)=>{if(n.throwOnFailure)throw new $(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Cn]=d.toString()),v.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:Sn(n,r),user:Tn,ip:In,all:xn}[n.rateLimitBy],p=await d(t,e,r),m=p.key,g=p.requestsAllowed??n.requestsAllowed,I=p.timeWindowMinutes??n.timeWindowMinutes,b=n.headerMode??"retry-after",T=vn(r,a),h=`bucket/${w.instance.build.BUILD_ID}/${r}/${m}`,P=await On(h,I,T,a,e.requestId);return P.count>g?(Pa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${h}' (strict mode)`),c(b,P.ttlSeconds)):t}catch(l){return u(l.message,l),t}finally{let l=Date.now()-s;Pa(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Zo;function Ta(t){let e=[];for(let[n,r]of t)e.push({name:n,value:r});return e}i(Ta,"headersToNameValuePairs");function Td(t){let e=[];return Object.entries(t).forEach(([n,r])=>{e.push({name:n,value:r})}),e}i(Td,"queryToNameValueParis");function xd(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}i(xd,"parseIntOrUndefined");var xa={};async function vd(t,e,n,r){let o=new Date,s=Date.now();return Zo||(Zo={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=n.userLabelPropertyPath&&t.user?ze(t.user,n.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,c=n.userEmailPropertyPath&&t.user?ze(t.user,n.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:n.development!==void 0?n.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:t.user?.sub??"anonymous"},request:{log:{creator:Zo,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:t.method,url:n.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:Ta(t.headers),queryString:Td(t.query)},response:{status:a.status,statusText:a.statusText,headers:Ta(a.headers),content:{size:xd(t.headers.get("content-length"))}}}]}}},d=xa[n.apiKey];if(!d){let p=n.apiKey;d=new F("readme-metering-inbound-policy",10,async m=>{try{let g=n.url??"https://metrics.readme.io/request",I=await M.fetch(g,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});I.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${I.status}: '${await I.text()}'`)}catch(g){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${g.message}'`),g}}),xa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),t}i(vd,"ReadmeMetricsInboundPolicy");var Od=i(async(t,e,n,r)=>{let o=n?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return o.forEach(u=>{s.delete(u)}),new j(t,{headers:s})},"RemoveHeadersInboundPolicy");var Sd=i(async(t,e,n,r,o)=>{let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new y(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(c=>{a.delete(c)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");var Cd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length===0)throw new y(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return o.forEach(u=>{s.searchParams.delete(u)}),new j(s.toString(),t)},"RemoveQueryParamsInboundPolicy");var Ad=i(async(t,e,n,r)=>{let o=await t.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");var va=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),_d=i(async(t,e,n)=>{let r=n.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let o=t.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>n.maxSizeInBytes?va():s&&r?t:(await t.clone().text()).length>n.maxSizeInBytes?va():t},"RequestSizeLimitInboundPolicy");function Ld(t,e,n){return`_${Ge(t+"_"+e+"_"+n)}`}i(Ld,"getRawOperationDataIdentifierName");function qo(t,e,n,r){return`_${Ge(t.toLowerCase())}_`+e.toLowerCase()+"_"+n.toLowerCase()+`_${r.toLowerCase()}`}i(qo,"getIdForParameterSchema");function $o(t,e,n){return`_${Ge(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Ge(n.toLowerCase())}`}i($o,"getIdForRequestBodySchema");function Nd(t,e){return`_${Ge(t)}__${Ge(e)}`}i(Nd,"getIdForRefSchema");function Ge(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(t.charAt(n)):e.push("_")}return e.join("")}i(Ge,"sanitizedIdentifierName");var ct=i(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),lt=i((t,e,n,r,o)=>{let s=[],a=!0,u=[];return t.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=qo(n,r,o,c.name),p=te.instance.schemaValidator[d],m=p(e[c.name]),g=Fo(p.errors);m||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${g.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),ye=i((t,e,n,r,o)=>{r?t.log[e](n,r,o):t.log[e](n,o)},"logErrors"),be=i(t=>t==="log-only"||t==="reject-and-log","shouldLog"),we=i(t=>t==="reject-only"||t==="reject-and-log","shouldReject"),Fo=i(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Oa(t,e,n){if(!n.validateBody||n.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(g){let I=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=v.badRequest(e,t,{detail:`${I}, see errors property for more details`,errors:`${g}`});if(be(n.validateBody)&&ye(t,n.logLevel??"info",I,[r],g),we(n.validateBody))return b}if(!e.headers.get("Content-Type")){let g=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,I=v.badRequest(e,t,{detail:g});return be(n.validateBody)&&ye(t,n.logLevel??"info",g,[r],[g]),we(n.validateBody)?I:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=$o(t.route.path,e.method,o),u=te.instance.schemaValidator[a];if(!u){let g=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,t,{detail:g});return be(n.validateBody)&&ye(t,n.logLevel??"info",g,[r],[g]),we(n.validateBody)?I:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Fo(l),m=v.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if(be(n.validateBody)&&ye(t,n.logLevel??"info",d,[r],p),we(n.validateBody))return m}i(Oa,"handleBodyValidation");function Sa(t,e,n){if(!n.validateHeaders||n.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ct(t),s=lt(o.filter(a=>a.location==="header"),r,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=v.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if(be(n.validateHeaders)&&ye(t,n.logLevel??"info",a,s.invalidValues,s.errors),we(n.validateHeaders))return u}}i(Sa,"handleHeadersValidation");function Ca(t,e,n){if(!n.validatePathParameters||n.validatePathParameters==="none")return;let r=ct(t),o=lt(r.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(n.validatePathParameters)&&ye(t,n.logLevel??"info",s,o.invalidValues,o.errors),we(n.validatePathParameters))return a}}i(Ca,"handlePathParameterValidation");function Aa(t,e,n){if(!n.validateQueryParameters||n.validateQueryParameters==="none")return;let r=ct(t),o=lt(r.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=v.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:o.errors});if(be(n.validateQueryParameters)&&ye(t,n.logLevel??"info",s,o.invalidValues,o.errors),we(n.validateQueryParameters))return a}}i(Aa,"handleQueryParameterValidation");var _a=i(async(t,e,n)=>{let r=Aa(e,t,n);if(r!==void 0||(r=Ca(e,t,n),r!==void 0)||(r=Sa(e,t,n),r!==void 0))return r;let o=await Oa(e,t,n);return o!==void 0?o:t},"RequestValidationInboundPolicy"),kd=_a;var Md=i(async(t,e,n,r)=>{if(n.origins===void 0||n.origins.length===0)throw new y(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof n.origins=="string"?n.origins.split(","):n.origins;o=o.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!o.includes(s)){let a=n.failureDetail??"Forbidden";return v.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");var Dd=i(async(t,e,n)=>new j(t,{body:n.body}),"SetBodyInboundPolicy");var Ud=i(async(t,e,n,r)=>{let o=n.headers;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new j(t,{headers:s})},"SetHeadersInboundPolicy");var Hd=i(async(t,e,n,r,o)=>{let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new y(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new y(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");var Zd=i(async(t,e,n,r)=>{let o=n.params;if(!o||!Array.isArray(o)||o.length==0)throw new y(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new y(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new j(s.toString(),t)},"SetQueryParamsInboundPolicy");var qd=i(async(t,e,n,r,o)=>{if(!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(t.body,{headers:t.headers,status:r.status,statusText:r.statusText??t.statusText})},"SetStatusOutboundPolicy");var $d=i(async t=>new Promise(n=>{setTimeout(n,t)}),"sleep"),Fd=i(async(t,e,n,r)=>{if(!n||n.sleepInMs===void 0||isNaN(n.sleepInMs))throw new y(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await $d(n.sleepInMs),t},"SleepInboundPolicy");var Bd=i(async(t,e,n,r)=>{W(n,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:n.secret,allowUnauthenticatedRequests:n.allowUnauthenticatedRequests??!1},s=await oe(t,e,o,r);if(s instanceof Response)return s;if(!(s instanceof j))throw new $("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=n.requiredClaims;if(!a)return s;let u=t.user?.data.app_metadata;if(!u)throw new A(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?v.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var zd=i(async(t,e,n,r)=>{W(n,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ee(r,n),s=new Y(o,e),a=await s.get(r);if(!a){let u=await jd(n,e);s.put(r,u.access_token,u.expires_in-(n.expirationOffsetSeconds??300)),a=u.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");async function jd(t,e){let n=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await se({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:n});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new A("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new A("Response returned from Azure AD is not in the expected format.")}i(jd,"getAccessToken");var La="https://accounts.google.com/o/oauth2/token",Bo,Vd=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string"),Bo||(Bo=await le.init(n.serviceAccountJson));let o={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 ee(r,n),a=new Y(s,e),u=await a.get(r);if(!u){let c=await Ee({serviceAccount:Bo,audience:La,payload:o}),l=await tn(La,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new A("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");var Gd="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Wd=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],zo,Jd=i(async(t,e,n,r)=>{if(W(n,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!n.userId&&!n.userIdPropertyPath)throw new y(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof n.developerClaims<"u"){for(let p in n.developerClaims)if(Object.prototype.hasOwnProperty.call(n.developerClaims,p)){if(Wd.indexOf(p)!==-1)throw new y(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=n.developerClaims[p]}}zo||(zo=await le.init(n.serviceAccountJson));let s=n.userId;if(!s&&!n.userIdPropertyPath){if(!t.user)throw new A("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(n.userIdPropertyPath){if(!t.user)throw new A(`Unable to apply userIdPropertyPath '${n.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=ze(t.user,n.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new A(`Unable to determine user from for the policy ${r}`);let a=await ee(r,n),u=new Y(a,e),c={uid:s,claims:o},l=await hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Ee({serviceAccount:zo,audience:Gd,payload:c}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${n.webApiKey}`,g=await vs(m,p,{retries:n.tokenRetries??3,retryDelayMs:10});if(!g.idToken)throw new A("Invalid token response from Firebase");d=g.idToken,u.put(l,d,(g.expiresIn?parseInt(g.expiresIn):3600)-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");var jo,Kd=i(async(t,e,n,r)=>{W(n,r).required("audience","string").required("serviceAccountJson","string"),jo||(jo=await le.init(n.serviceAccountJson));let o=await Ee({serviceAccount:jo,audience:n.audience});return t.headers.set("Authorization",`Bearer ${o}`),t},"UpstreamGcpJwtInboundPolicy");var Na="https://www.googleapis.com/oauth2/v4/token",Vo,Yd=i(async(t,e,n,r)=>{W(n,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Vo||(Vo=await le.init(n.serviceAccountJson));let o={};if(n.scopes&&n.audience)throw new y("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(n.scopes)try{let c=je(n.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof y?new y(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}n.audience&&(o.target_audience=`${n.audience}`);let s=await ee(r,n),a;n.useMemoryCacheOnly?a=new Je(s):a=new Y(s,e);let u=await a.get(r);if(!u){let c=await Ee({serviceAccount:Vo,audience:Na,payload:o}),l=await tn(Na,c,{retries:n.tokenRetries??3,retryDelayMs:10});if(n.audience){if(!l.id_token)throw new A("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new A("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(n.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${u}`),t},"UpstreamGcpServiceAuthInboundPolicy");var Qd=i(async(t,e,n)=>{let r=t.clone(),o;try{o=await r.json()}catch{return v.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(n.validator(o))return t;let{errors:a}=n.validator;if(!a)throw new $("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return v.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Ua=Ce(Da());var Wo=class extends Me{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,n){super(e,n),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Qe(e.parseOnStatusCodes):void 0,this.parser=new Ua.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,n,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new A(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Jo=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var Ko=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,n){if(!n||n.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new F(n.name??"",n.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),ln().waitUntil(this.#e.waitUntilFlushed())}};var Yo=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r=new Map;constructor(e,n){this.#t=e,this.#n=n*1e3}#o(e){let n=this.#e.get(e);n&&(n.expiry=new Date(Date.now()+this.#n))}#i(e){return e.expiry<=new Date}async get(e){let n=this.#e.get(e);return n&&!this.#i(n)?(this.#s(e),n.data):this.#a(e)}async#s(e){let n=this.#r.get(e);if(n!==void 0)return n.wrap();let r=this.#a(e);return this.#r.set(e,new Nt(r)),await new Nt(r).wrap(),this.#r.delete(e),r}async#a(e){let n=this.#r.get(e);if(n===void 0){let r=this.#t(e);n=new Nt(r),this.#o(e);let o=await n.wrap();this.#e.set(e,{data:o,expiry:new Date(Date.now()+this.#n)})}return n.wrap()}},Nt=class{static{i(this,"WrappedPromise")}#e;#t=[];#n;#r;constructor(e){ln().waitUntil(e),this.#e=e,this.#e.then(r=>{this.#t.forEach(o=>o.resolve(r)),this.#n=r}).catch(r=>{this.#t.forEach(o=>o.reject(r)),this.#r=r})}async wrap(){if(this.#r)throw this.#r;if(this.#n)return this.#n;let e=this;return new Promise((r,o)=>{e.#t.push({resolve:r,reject:o})})}};var Qo=["sha-1","sha-256","sha-384","sha-512"],An=class{static{i(this,"BaseCryptoBeta")}};var Xo=class extends An{static{i(this,"WorkerCryptoBeta")}async digest(e,n){if(!Qo.includes(e.toLowerCase()))throw new A(`Algorithm ${e} is not supported. Try using ${Qo.join(", ")}`);let r=new TextEncoder().encode(n),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var _n=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var ei=class extends _n{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=w.instance.runtime.ZUPLO_KV;if(!n)throw new qt("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,n,r){if(typeof e!="string")throw new y("value must be of type string");return this.#e.put(e,n,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,n){return this.#e.get(e,{type:"text",cacheTtl:n?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{so as AWSLoggingPlugin,Ul as AmberfloMeteringInboundPolicy,Oo as AmberfloMeteringPolicy,ql as ApiAuthKeyInboundPolicy,So as ApiKeyInboundPolicy,yo as AuditLogDataStaxProvider,bo as AuditLogPlugin,jl as Auth0JwtInboundPolicy,rl as AwsLambdaHandlerExtensions,Ko as BackgroundDispatcher,Yo as BackgroundLoader,Vl as BasicAuthInboundPolicy,Ia as BasicRateLimitInboundPolicy,F as BatchDispatch,Kl as CachingInboundPolicy,Yl as ChangeMethodInboundPolicy,Ql as ClearHeadersInboundPolicy,Xl as ClearHeadersOutboundPolicy,ed as ClerkJwtInboundPolicy,td as CognitoJwtInboundPolicy,nd as CompositeInboundPolicy,y as ConfigurationError,pr as ContentTypes,he as ContextData,Xo as CryptoBeta,rd as CurityPhantomTokenInboundPolicy,Hr as DataDogLoggingPlugin,co as DataDogMetricsPlugin,Yr as DynaTraceLoggingPlugin,go as DynatraceMetricsPlugin,id as FirebaseJwtInboundPolicy,sd as FormDataToJsonInboundPolicy,ad as GeoFilterInboundPolicy,Nr as GoogleCloudLoggingPlugin,Br as Handler,v as HttpProblems,fr as HttpStatusCode,Pe as InboundPolicy,ud as JWTScopeValidationInboundPolicy,ei as KeyValueStore,Xr as LokiLoggingPlugin,St as LookupResult,Y as MemoryZoneReadThroughCache,cd as MockApiInboundPolicy,hd as MoesifInboundPolicy,Mo as MonetizationInboundPolicy,bd as OktaJwtInboundPolicy,oe as OpenIdJwtInboundPolicy,Me as OutboundPolicy,Fe as ProblemResponseFormatter,Rd as PropelAuthJwtInboundPolicy,Ia as RateLimitInboundPolicy,vd as ReadmeMetricsInboundPolicy,Od as RemoveHeadersInboundPolicy,Sd as RemoveHeadersOutboundPolicy,Cd as RemoveQueryParamsInboundPolicy,Ad as ReplaceStringOutboundPolicy,_d as RequestSizeLimitInboundPolicy,_a as RequestValidationInboundPolicy,Md as RequireOriginInboundPolicy,yt as ResponseSendingEvent,bt as ResponseSentEvent,Ct as Router,A as RuntimeError,Bt as SYSTEM_LOGGER,kd as SchemaBasedRequestValidation,fe as SemanticAttributes,Jo as ServiceProviderImpl,Dd as SetBodyInboundPolicy,Ud as SetHeadersInboundPolicy,Hd as SetHeadersOutboundPolicy,Zd as SetQueryParamsInboundPolicy,qd as SetStatusOutboundPolicy,Fd as SleepInboundPolicy,na as StripeMonetizationPlugin,_t as StripeWebhookVerificationInboundPolicy,no as SumoLogicLoggingPlugin,Bd as SupabaseJwtInboundPolicy,Oe as SystemRouteName,gt as TelemetryPlugin,zd as UpstreamAzureAdServiceAuthInboundPolicy,Vd as UpstreamFirebaseAdminAuthInboundPolicy,Jd as UpstreamFirebaseUserAuthInboundPolicy,Kd as UpstreamGcpJwtInboundPolicy,Yd as UpstreamGcpServiceAuthInboundPolicy,oo as VMWareLogInsightLoggingPlugin,Qd as ValidateJsonSchemaInbound,Wo as XmlToJsonOutboundPolicy,pt as ZoneCache,j as ZuploRequest,ol as awsLambdaHandler,ae as environment,qo as getIdForParameterSchema,Nd as getIdForRefSchema,$o as getIdForRequestBodySchema,Ld as getRawOperationDataIdentifierName,hr as httpStatuses,pl as openApiSpecHandler,gl as redirectHandler,Ge as sanitizedIdentifierName,mr as serialize,md as setMoesifContext,hl as urlForwardHandler,bl as urlRewriteHandler,wl as webSocketHandler,Rl as webSocketPipelineHandler};
79
79
  /*! For license information please see index.min.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
- "version": "5.1982.0",
3
+ "version": "5.1986.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {