@zuplo/runtime 5.2189.0 → 5.2191.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/out/cjs/index.js +8 -8
- package/out/esm/index.js +1 -1
- package/out/types/index.d.ts +78 -3
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -58,7 +58,7 @@ Signature verification is impossible without access to the original signed mater
|
|
|
58
58
|
`+d}):new Ne(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
59
59
|
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.
|
|
60
60
|
`+l+`
|
|
61
|
-
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ne(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(Gu,"validateComputedSignature");function Wu(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(Wu,"parseHeader");function Ku(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Ku,"secureCompare");async function Ju(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=go[i[u]];return a.join("")}s(Ju,"computeHMACSignatureAsync");var go=new Array(256);for(let n=0;n<go.length;n++)go[n]=n.toString(16).padStart(2,"0");var Ft=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){te(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 ws(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="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 t.log.error("Error validating stripe webhook",i),v.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Rs(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}s(Rs,"isStripeWebhookEvent");var Yu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new U(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new U(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new U(i)}return o}},In=Yu;var fo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ps="My API Key";async function Is({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,fo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ps,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,g),new U(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Is,"createConsumer");async function Es({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,fo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ps,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(i)},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 g="Error creating API Key Consumer";throw i.log.error(g,p),new U(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Es,"createConsumerInvite");async function xs({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,fo);o.searchParams.set("with-api-key","true");let i=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new U(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(xs,"deleteConsumer");async function vs({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:g}=y.instance;if(!ot(p))throw new K("No Zuplo JWT token set.");let h=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${g}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let C=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,O="";try{R=await h.json(),O=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(C,R),new U(`${C} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}s(vs,"createSubscription");async function mt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.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 n.log.error(u,c),new U(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(mt,"updateSubscription");async function gt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.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 n.log.error(c,l),new U(`${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 n.log.error(c),new U(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new U(c)}return u.data[0]}s(gt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Be="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function En(n){return n.replaceAll("_","-")}s(En,"stripeStatusToMeteringStatus");function et(n){return new Date(n*1e3).toISOString()}s(et,"unixTimestampToISOString");async function ho(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),v.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await In.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.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Es({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),v.ok(n,e,{title:re,detail:p.message})}if(!c)return v.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=En(t.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:et(t.data.object.trial_end),trialStartDate:et(t.data.object.trial_start)}),await vs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g,trial:h})}catch(p){return await xs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.ok(n,e,{title:re,detail:p.message})}return v.ok(n,e,{title:Be})}s(ho,"onCustomerSubscriptionCreated");async function yo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await mt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}s(yo,"onCustomerSubscriptionDeleted");async function bo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=En(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=et(t.data.object.trial_end)),await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await In.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.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 '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?et(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?et(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.ok(n,e,{title:re,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."+Pe})}s(bo,"onCustomerSubscriptionUpdated");var Ts=class extends zt{constructor(t){super();this.options=t;f("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(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(be.ZUPLO_METERING_SERVICE_BUCKET_ID)d=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.primaryDataRegion??"us-central1";if(!Xu(g))throw new m(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Rs(h))return v.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await ho(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await bo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await yo(c,l,h,{meteringBucketId:d});default:return v.ok(c,l,{title:re,detail:`Event '${h.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.`+Pe})}},"stripeWebhookHandler"),i=Hi({inboundPolicies:[new Ft({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});te(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new ce({processors:[fe,i],handler:o,gateway:r}),u=new ie({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Xu(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(Xu,"isMetricsRegion");var Os=new WeakMap,Ss={},wo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Os.set(e,t)}};async function Qu(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=it(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new U(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ye(n.user,t.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??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.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(t.dimensions??{},a?.dimensions)},g=Ss[t.apiKey];if(!g){let h=t.apiKey,C=n.headers.get("zm-test-id")??"";g=new J("amberflo-ingest-meter",10,async R=>{try{let O=t.url??"https://app.amberflo.io/ingest",M=await $.fetch(O,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":C}});M.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${M.status}: ${await M.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),Ss[h]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}s(Qu,"AmberfloMeteringInboundPolicy");async function xn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(xn,"sha256");var Cs=new Map;async function de(n,e,t){let r,o=`${n}-${e}`,i=Cs.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await xn(JSON.stringify({policyName:n,options:t}))}`,Cs.set(n,r)),r}s(de,"getPolicyCacheName");var As="key-metadata-cache-type";function ec(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(ec,"getKeyValue");async function Ro(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(O=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:O}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=ec(a,o);if(!u||u==="")return i("No key present");let c=await tc(u),l=await de(r,void 0,o),d=new ue(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==As&&Y.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},h=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(g)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(h.status!==200){try{let O=await h.text(),M=JSON.parse(O);e.log.error("Unexpected response from key service",M)}catch{e.log.error("Invalid response from key service")}throw new U(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let C=await h.json(),R={isValid:!0,typeId:As,user:{sub:C.name,data:C.metadata}};return n.user=R.user,d.put(c,R,o.cacheTtlSeconds),n}s(Ro,"ApiKeyInboundPolicy");async function tc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(tc,"hashValue");var nc=Ro;import{createRemoteJWKSet as oc,jwtVerify as ks}from"jose";import{createLocalJWKSet as rc}from"jose";var Po=class{constructor(e,t,r){this.cache=t;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{s(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,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Io&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);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",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=rc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await $.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Eo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ft("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 ft("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ls(n,e,t){let r=new Po(n,e,t);return async(o,i)=>r.getKey(o,i)}s(Ls,"createRemoteJWKSet");var ft=class extends U{static{s(this,"JWKSError")}},Io=class extends ft{static{s(this,"JWKSNoMatchingKey")}},Eo=class extends ft{static{s(this,"JWKSTimeout")}};var vn={},ic=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await de(n,void 0,r),u=new ue(a,e);vn[r.jwkUrl]=Ls(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else vn[r.jwkUrl]=oc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ks(t,vn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),sc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await ks(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=s(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(g=>v.unauthorized(n,e,{detail:g}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ic(r,e):sc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(i.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,t)}catch(h){let C=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${C.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${C.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ac=s(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var xo=class n extends pe{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setXacmlAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Ko(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:v.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:v.unauthorized(e,t);let o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.scheme",Value:o.protocol}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),v.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var uc=s(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>v.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),h=d.substring(p+1),C=t.accounts.find(R=>R.username===g&&R.password===h);return C||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Tn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Tn,"extractDateElements");function _s(n,e){return new Date(n,e+1,0).getDate()}s(_s,"getDaysInMonth");function vo(n,e){return n<=e?e-n:6-n+e+1}s(vo,"getDaysBetweenWeekdays");var Sn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=_s(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(g=>g>=d)??this.weekdays[0]:this.reversed.weekdays.find(g=>g<=d)??this.reversed.weekdays[0];if(p!==void 0){let g=e==="next"?vo(d,p):vo(p,d);l=e==="next"?o+g:o-g,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Tn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("next",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Tn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("prev",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Tn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var cc={min:0,max:59},lc={min:0,max:59},dc={min:0,max:23},pc={min:1,max:31},mc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},gc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},fc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function tt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{tt(d,e).forEach(g=>t.add(g))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(tt,"parseElement");function To(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=fc[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Sn({seconds:tt(t,cc),minutes:tt(r,lc),hours:tt(o,dc),days:tt(i,pc),months:new Set(Array.from(tt(a,mc)).map(c=>c-1)),weekdays:new Set(Array.from(tt(u,gc)).map(c=>c%7))})}s(To,"parseCronExpression");var So=class extends pe{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),te(e,t).optional("problem","object"),e.problem&&te(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[To(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>To(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=v.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return v.format(i,e,t)}return e}};var hc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function yc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"digestMessage");var bc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await yc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function wc(n,e,t,r){f("policy.inbound.caching");let o=await de(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await bc(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let g=t?.expirationSecondsTtl??60,h=new Response(p.body,p);hc.forEach(C=>h.headers.delete(C)),h.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(wc,"CachingInboundPolicy");var Rc=s(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Pc=s(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Ic=s(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Ec=s(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var xc=s(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return ye(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var vc=s(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=me.instance,i=At(t.policies,o?.routeData.policies);return br(i)(n,e)},"CompositeInboundPolicy");var Tc=s(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let i=Sc(o);if(!i)return v.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await de(r,void 0,t),u=new ue(a,e),c=await u.get(i);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Sc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Sc,"getToken");var Oc=s(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Cc=s(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ht="__unknown__",Ac=s(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:bt(t.allow?.countries,"allow.countries",r),regionCodes:bt(t.allow?.regionCodes,"allow.regionCode",r),asns:bt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:bt(t.block?.countries,"block.countries",r),regionCodes:bt(t.block?.regionCodes,"block.regionCode",r),asns:bt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ht,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ht,u=e.incomingRequestProperties.asn?.toString()??ht,c=o.ignoreUnknown&&i===ht,l=o.ignoreUnknown&&a===ht,d=o.ignoreUnknown&&u===ht,p=o.allow.countries,g=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return yt(n,e,r,i,a,u);let C=o.block.countries,R=o.block.regionCodes,O=o.block.asns;return C.length>0&&C.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?yt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function yt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(yt,"blockedResponse");function bt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(bt,"toLowerStringArray");var Lc=s(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var kc=s(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Oo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Oo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ns(a[u])}else return a.length>0?Ns(a[0]):Oo(r,n,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 Ns(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(Ns,"generateResponse");var Oo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var _c="Incoming",Nc={logRequestBody:!0,logResponseBody:!0};function Ds(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Ds,"headersToObject");function Ms(){return new Date().toISOString()}s(Ms,"timestamp");var Co=new WeakMap,Dc={};function Mc(n,e){let t=Co.get(n);t||(t=Dc);let r=Object.assign({...t},e);Co.set(n,r)}s(Mc,"setMoesifContext");async function Hs(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(Hs,"readBody");var Hc={},Ao;function Us(){if(!Ao)throw new U("Invalid State - no _lastLogger");return Ao}s(Us,"getLastLogger");function Uc(n){let e=Hc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Us().debug("posting",r);let o=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Us().error({status:o.status,body:await o.text()})})),e}s(Uc,"getDispatcher");async function Zc(n,e,t,r){f("policy.inbound.moesif-analytics"),Ao=e.log;let o=Ms(),i=Object.assign(Nc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Uc(i.applicationId),d=n.headers.get("true-client-ip"),p=Co.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ds(n.headers)},h=i.logResponseBody?await Hs(u,e):void 0,C={time:Ms(),status:u.status,headers:Ds(u.headers),body:h},R={request:g,response:C,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_c};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}s(Zc,"MoesifInboundPolicy");async function Zs(n,e,t,r){let o=Y.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - 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]}s(Zs,"loadSubscription");async function qs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,u=Y.getLogger(n);try{let c=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(qs,"consumeSubcriptionQuotas");var qc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function On(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(On,"validateMeters");function Fs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Xe(n),r=[];for(let o of t)qc.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Fs,"parseAllowedSubscriptionStatuses");function $s(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s($s,"compareMeters");var Lo=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,It)}static setMeters(e,t){On(t,"setMeters"),he.set(e,jt,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){te(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=it(this.options.meterOnStatusCodes),i=he.get(t,jt),a={...this.options.meters,...i};On(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Fs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,O,M)=>{let k=he.get(M,It);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){M.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=he.get(M,jt),F={...this.options.meters,...Z};if(On(F,this.policyName),o.includes(R.status)&&k&&F){M.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(F)} on response status '${R.status}'`);let{metersInSubscription:E,metersNotInSubscription:D}=$s(k.meters,F);if(D&&Object.keys(D).length>0){let V=Object.keys(D);M.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await qs(M,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Zs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:v.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(t,It,p));let g=he.get(t,It);if(!g)return u?e:(t.log.warn("Subscription is not available for user"),v.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let C=Object.keys(a).filter(R=>!Object.keys(g.meters).includes(R));if(C.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${C.join(", ")}`),v.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${C.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(g.meters[R].available<=0&&!r)return v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var Fc=s(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");import{importSPKI as $c}from"jose";var ko,jc=s(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!ko)try{ko=await $c(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:ko,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Gs=ze(Ve());var Bs=ze(Ve());var js=(0,Bs.debug)("zuplo:policies:RateLimitInboundPolicy"),zs=s(async(n,e,t,r)=>{let o=Y.getLogger(e),i=s((F,E)=>{let D={};return(!F||F==="retry-after")&&(D[pt]=E.toString()),v.tooManyRequests(n,e,void 0,D)},"rateLimited"),u=await lt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",g=dt(r,o),C=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,R=await de(r,void 0,t),O=new ue(R,e),M=Pn(C,d,g,e.requestId),k;s(async()=>{let F=await M;if(F.count>l){let E=Date.now()+F.ttlSeconds*1e3;O.put(C,E,F.ttlSeconds),js(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${C}' (async mode)`),k=i(p,F.ttlSeconds)}},"asyncCheck")();let Z=await O.get(C);if(Z!==void 0&&Z>Date.now()){js(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${C}' (async mode)`);let F=Math.round((Z-Date.now())/1e3);return i(p,F)}return e.addResponseSendingHook(async F=>k??F),n},"AsyncRateLimitInboundPolicy");var Vs=(0,Gs.debug)("zuplo:policies:RateLimitInboundPolicy"),Bc="strict",Ws=s(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Bc)==="async")return zs(n,e,t,r);let i=Date.now(),a=Y.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[pt]=d.toString()),v.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await lt(r,t)(n,e,r),p=d.key,g=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,C=t.headerMode??"retry-after",R=dt(r,a),M=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${p}`,k=await Pn(M,h,R,e.requestId);return k.count>g?(Vs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${M}' (strict mode)`),c(C,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;Vs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _o;function Ks(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Ks,"headersToNameValuePairs");function zc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(zc,"queryToNameValueParis");function Vc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Vc,"parseIntOrUndefined");var Js={};async function Gc(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return _o||(_o={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ye(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ye(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:_o,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ks(n.headers),queryString:zc(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ks(a.headers),content:{size:Vc(n.headers.get("content-length"))}}}]}}},d=Js[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async g=>{try{let h=t.url??"https://metrics.readme.io/request",C=await $.fetch(h,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});C.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${C.status}: '${await C.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Js[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Gc,"ReadmeMetricsInboundPolicy");var Wc=s(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new ee(n,{headers:i})},"RemoveHeadersInboundPolicy");var Kc=s(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Jc=s(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new ee(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var Yc=s(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ys=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Xc=s(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?Ys():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ys():n},"RequestSizeLimitInboundPolicy");var wt=s(n=>{let e=n.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"),Rt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=_n(t,r,o,c.name),p=me.instance.schemaValidator[d],g=p(e[c.name]),h=No(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ce=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ae=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),No=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Xs(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let C=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=v.badRequest(e,n,{detail:`${C}, see errors property for more details`,errors:`${h}`});if(Ce(t.validateBody)&&Oe(n,t.logLevel??"info",C,[r],h),Ae(t.validateBody))return R}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,C=v.badRequest(e,n,{detail:h});return Ce(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?C:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Nn(n.route.path,e.method,o),u=me.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,C=v.badRequest(e,n,{detail:h});return Ce(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?C:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=No(l),g=v.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ce(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Ae(t.validateBody))return g}s(Xs,"handleBodyValidation");function Qs(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=wt(n),i=Rt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ce(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ae(t.validateHeaders))return u}}s(Qs,"handleHeadersValidation");function ea(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ce(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validatePathParameters))return a}}s(ea,"handlePathParameterValidation");function ta(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ce(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validateQueryParameters))return a}}s(ta,"handleQueryParameterValidation");var na=s(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ta(e,n,t);if(r!==void 0||(r=ea(e,n,t),r!==void 0)||(r=Qs(e,n,t),r!==void 0))return r;let o=await Xs(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Qc=na;var el=s(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var tl=s(async(n,e,t)=>(f("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var nl=s(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new ee(n,{headers:i})},"SetHeadersInboundPolicy");var rl=s(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ol=s(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new ee(i.toString(),n)},"SetQueryParamsInboundPolicy");var il=s(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!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(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var sl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),al=s(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await sl(t.sleepInMs),n},"SleepInboundPolicy");var ul=s(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await ye(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ee))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new U(`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(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var cl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await de(r,void 0,t),i=new ue(o,e),a=await i.get(r);if(!a){let u=await ll(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ll(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Re({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new U("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 U("Response returned from Azure AD is not in the expected format.")}s(ll,"getAccessToken");var ra="https://accounts.google.com/o/oauth2/token",Do,dl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Do||(Do=await Ee.init(t.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(" ")},i=await de(r,void 0,t),a=new ue(i,e),u=await a.get(r);if(!u){let c=await ke({serviceAccount:Do,audience:ra,payload:o}),l=await on(ra,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new U("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",ml=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mo,gl=s(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),te(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(ml.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Mo||(Mo=await Ee.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new U("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new U(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ye(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new U(`Unable to determine user from for the policy ${r}`);let a=await de(r,void 0,t),u=new ue(a,e),c={uid:i,claims:o},l=await xn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ke({serviceAccount:Mo,audience:pl,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Gi(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new U("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ho,fl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ho||(Ho=await Ee.init(t.serviceAccountJson));let o=await ke({serviceAccount:Ho,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var oa="https://www.googleapis.com/oauth2/v4/token",Uo,hl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Uo||(Uo=await Ee.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=Xe(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await de(r,void 0,t),a;t.useMemoryCacheOnly?a=new nt(i):a=new ue(i,e);let u=await a.get(r);if(!u){let c=await ke({serviceAccount:Uo,audience:oa,payload:o}),l=await on(oa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new U("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new U("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var yl=s(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return v.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new K("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(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((R,O)=>e(R,"name",{value:O,configurable:!0}),"__name"),o=s((R,O)=>s(function(){return O||(0,R[t(R)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,j){return j},attributeValueProcessor:function(k,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,j,Z){return k}},M=r(function(k){return Object.assign({},O,k)},"buildOptions");R.buildOptions=M,R.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var O=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",M=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+M+"]*",j=new RegExp("^"+k+"$"),Z=r(function(E,D){let V=[],G=D.exec(E);for(;G;){let T=[];T.startIndex=D.lastIndex-G[0].length;let x=G.length;for(let H=0;H<x;H++)T.push(G[H]);V.push(T),G=D.exec(E)}return V},"getAllMatches"),F=r(function(E){let D=j.exec(E);return!(D===null||typeof D>"u")},"isName");R.isExist=function(E){return typeof E<"u"},R.isEmptyObject=function(E){return Object.keys(E).length===0},R.merge=function(E,D,V){if(D){let G=Object.keys(D),T=G.length;for(let x=0;x<T;x++)V==="strict"?E[G[x]]=[D[G[x]]]:E[G[x]]=D[G[x]]}},R.getValue=function(E){return R.isExist(E)?E:""},R.isName=F,R.getAllMatches=Z,R.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,O){"use strict";var M=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};O.exports=M}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,O){var M=a();function k(T,x){let H={};if(T[x+3]==="O"&&T[x+4]==="C"&&T[x+5]==="T"&&T[x+6]==="Y"&&T[x+7]==="P"&&T[x+8]==="E"){x=x+9;let se=1,W=!1,X=!1,ve="";for(;x<T.length;x++)if(T[x]==="<"&&!X){if(W&&F(T,x))x+=7,[entityName,val,x]=j(T,x+1),val.indexOf("&")===-1&&(H[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(W&&E(T,x))x+=8;else if(W&&D(T,x))x+=8;else if(W&&V(T,x))x+=9;else if(Z)X=!0;else throw new Error("Invalid DOCTYPE");se++,ve=""}else if(T[x]===">"){if(X?T[x-1]==="-"&&T[x-2]==="-"&&(X=!1,se--):se--,se===0)break}else T[x]==="["?W=!0:ve+=T[x];if(se!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}s(k,"readDocType"),r(k,"readDocType");function j(T,x){let H="";for(;x<T.length&&T[x]!=="'"&&T[x]!=='"';x++)H+=T[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let se=T[x++],W="";for(;x<T.length&&T[x]!==se;x++)W+=T[x];return[H,W,x]}s(j,"readEntityExp"),r(j,"readEntityExp");function Z(T,x){return T[x+1]==="!"&&T[x+2]==="-"&&T[x+3]==="-"}s(Z,"isComment"),r(Z,"isComment");function F(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="N"&&T[x+4]==="T"&&T[x+5]==="I"&&T[x+6]==="T"&&T[x+7]==="Y"}s(F,"isEntity"),r(F,"isEntity");function E(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="L"&&T[x+4]==="E"&&T[x+5]==="M"&&T[x+6]==="E"&&T[x+7]==="N"&&T[x+8]==="T"}s(E,"isElement"),r(E,"isElement");function D(T,x){return T[x+1]==="!"&&T[x+2]==="A"&&T[x+3]==="T"&&T[x+4]==="T"&&T[x+5]==="L"&&T[x+6]==="I"&&T[x+7]==="S"&&T[x+8]==="T"}s(D,"isAttlist"),r(D,"isAttlist");function V(T,x){return T[x+1]==="!"&&T[x+2]==="N"&&T[x+3]==="O"&&T[x+4]==="T"&&T[x+5]==="A"&&T[x+6]==="T"&&T[x+7]==="I"&&T[x+8]==="O"&&T[x+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(T){if(M.isName(T))return T;throw new Error(`Invalid entity name ${T}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(R,O){var M=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(E,D={}){if(D=Object.assign({},j,D),!E||typeof E!="string")return E;let V=E.trim();if(D.skipLike!==void 0&&D.skipLike.test(V))return E;if(D.hex&&M.test(V))return Number.parseInt(V,16);{let G=k.exec(V);if(G){let T=G[1],x=G[2],H=F(G[3]),se=G[4]||G[6];if(!D.leadingZeros&&x.length>0&&T&&V[2]!==".")return E;if(!D.leadingZeros&&x.length>0&&!T&&V[1]!==".")return E;{let W=Number(V),X=""+W;return X.search(/[eE]/)!==-1||se?D.eNotation?W:E:V.indexOf(".")!==-1?X==="0"&&H===""||X===H||T&&X==="-"+H?W:E:x?H===X||T+H===X?W:E:V===X||V===T+X?W:E}}else return E}}s(Z,"toNumber"),r(Z,"toNumber");function F(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s(F,"trimZeros"),r(F,"trimZeros"),O.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,O){"use strict";var M=a(),k=u(),j=c(),Z=l(),F=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=V,this.buildAttributesMap=T,this.isItStopNode=X,this.replaceEntitiesValue=se,this.readStopNodeData=z,this.saveTextToParentTag=W,this.addChild=H}};function E(P){let I=Object.keys(P);for(let A=0;A<I.length;A++){let B=I[A];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function D(P,I,A,B,L,_,Q){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){Q||(P=this.replaceEntitiesValue(P));let q=this.options.tagValueProcessor(I,P,A,L,_);return q==null?P:typeof q!=typeof P||q!==P?q:this.options.trimValues?ae(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?ae(P,this.options.parseTagValue,this.options.numberParseOptions):P}}s(D,"parseTextData"),r(D,"parseTextData");function V(P){if(this.options.removeNSPrefix){let I=P.split(":"),A=P.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(P=A+I[1])}return P}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function T(P,I,A){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=M.getAllMatches(P,G),L=B.length,_={};for(let Q=0;Q<L;Q++){let q=this.resolveNameSpace(B[Q][1]),N=B[Q][4],oe=this.options.attributeNamePrefix+q;if(q.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let ne=this.options.attributeValueProcessor(q,N,I);ne==null?_[oe]=N:typeof ne!=typeof N||ne!==N?_[oe]=ne:_[oe]=ae(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[oe]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let Q={};return Q[this.options.attributesGroupName]=_,Q}return _}}s(T,"buildAttributesMap"),r(T,"buildAttributesMap");var x=r(function(P){P=P.replace(/\r\n?/g,`
|
|
61
|
+
`+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ne(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(Gu,"validateComputedSignature");function Wu(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s(Wu,"parseHeader");function Ku(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Ku,"secureCompare");async function Ju(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=go[i[u]];return a.join("")}s(Ju,"computeHMACSignatureAsync");var go=new Array(256);for(let n=0;n<go.length;n++)go[n]=n.toString(16).padStart(2,"0");var Ft=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){te(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 ws(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="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 t.log.error("Error validating stripe webhook",i),v.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Rs(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}s(Rs,"isStripeWebhookEvent");var Yu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new U(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new U(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new U(i)}return o}},In=Yu;var fo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ps="My API Key";async function Is({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,fo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ps,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,g),new U(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Is,"createConsumer");async function Es({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,fo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ps,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(i)},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 g="Error creating API Key Consumer";throw i.log.error(g,p),new U(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Es,"createConsumerInvite");async function xs({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,fo);o.searchParams.set("with-api-key","true");let i=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new U(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(xs,"deleteConsumer");async function vs({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:g}=y.instance;if(!ot(p))throw new K("No Zuplo JWT token set.");let h=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${g}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let C=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,O="";try{R=await h.json(),O=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(C,R),new U(`${C} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}s(vs,"createSubscription");async function mt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.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 n.log.error(u,c),new U(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(mt,"updateSubscription");async function gt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.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 n.log.error(c,l),new U(`${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 n.log.error(c),new U(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new U(c)}return u.data[0]}s(gt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Be="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function En(n){return n.replaceAll("_","-")}s(En,"stripeStatusToMeteringStatus");function et(n){return new Date(n*1e3).toISOString()}s(et,"unixTimestampToISOString");async function ho(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),v.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});let u=i.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await Is({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await In.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.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Es({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),v.ok(n,e,{title:re,detail:p.message})}if(!c)return v.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=En(t.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:et(t.data.object.trial_end),trialStartDate:et(t.data.object.trial_start)}),await vs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g,trial:h})}catch(p){return await xs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.ok(n,e,{title:re,detail:p.message})}return v.ok(n,e,{title:Be})}s(ho,"onCustomerSubscriptionCreated");async function yo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});try{let a=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await mt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}s(yo,"onCustomerSubscriptionDeleted");async function bo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),v.ok(n,e,{title:re,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),v.ok(n,e,{title:re,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Pe});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=En(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=et(t.data.object.trial_end)),await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await In.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.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 '${t.id}'.`);let u=await gt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?et(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?et(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await mt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return v.ok(n,e,{title:re,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. `+Pe})}return v.ok(n,e,{title:Be})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.ok(n,e,{title:re,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."+Pe})}s(bo,"onCustomerSubscriptionUpdated");var Ts=class extends zt{constructor(t){super();this.options=t;f("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(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(be.ZUPLO_METERING_SERVICE_BUCKET_ID)d=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.primaryDataRegion??"us-central1";if(!Xu(g))throw new m(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Rs(h))return v.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await ho(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await bo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await yo(c,l,h,{meteringBucketId:d});default:return v.ok(c,l,{title:re,detail:`Event '${h.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.`+Pe})}},"stripeWebhookHandler"),i=Hi({inboundPolicies:[new Ft({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});te(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new ce({processors:[fe,i],handler:o,gateway:r}),u=new ie({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Xu(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(Xu,"isMetricsRegion");var Os=new WeakMap,Ss={},wo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Os.set(e,t)}};async function Qu(n,e,t,r){if(f("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=it(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new U(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ye(n.user,t.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??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.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(t.dimensions??{},a?.dimensions)},g=Ss[t.apiKey];if(!g){let h=t.apiKey,C=n.headers.get("zm-test-id")??"";g=new J("amberflo-ingest-meter",10,async R=>{try{let O=t.url??"https://app.amberflo.io/ingest",M=await $.fetch(O,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":C}});M.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${M.status}: ${await M.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),Ss[h]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}s(Qu,"AmberfloMeteringInboundPolicy");async function xn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(xn,"sha256");var Cs=new Map;async function de(n,e,t){let r,o=`${n}-${e}`,i=Cs.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await xn(JSON.stringify({policyName:n,options:t}))}`,Cs.set(n,r)),r}s(de,"getPolicyCacheName");var As="key-metadata-cache-type";function ec(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(ec,"getKeyValue");async function Ro(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(O=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:O}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let u=ec(a,o);if(!u||u==="")return i("No key present");let c=await tc(u),l=await de(r,void 0,o),d=new ue(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==As&&Y.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},h=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(g)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(h.status!==200){try{let O=await h.text(),M=JSON.parse(O);e.log.error("Unexpected response from key service",M)}catch{e.log.error("Invalid response from key service")}throw new U(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let C=await h.json(),R={isValid:!0,typeId:As,user:{sub:C.name,data:C.metadata}};return n.user=R.user,d.put(c,R,o.cacheTtlSeconds),n}s(Ro,"ApiKeyInboundPolicy");async function tc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(tc,"hashValue");var nc=Ro;import{createRemoteJWKSet as oc,jwtVerify as ks}from"jose";import{createLocalJWKSet as rc}from"jose";var Po=class{constructor(e,t,r){this.cache=t;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{s(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,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Io&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);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",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=rc(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await $.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Eo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new ft("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 ft("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ls(n,e,t){let r=new Po(n,e,t);return async(o,i)=>r.getKey(o,i)}s(Ls,"createRemoteJWKSet");var ft=class extends U{static{s(this,"JWKSError")}},Io=class extends ft{static{s(this,"JWKSNoMatchingKey")}},Eo=class extends ft{static{s(this,"JWKSTimeout")}};var vn={},ic=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!vn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await de(n,void 0,r),u=new ue(a,e);vn[r.jwkUrl]=Ls(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else vn[r.jwkUrl]=oc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await ks(t,vn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),sc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await ks(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=s(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(g=>v.unauthorized(n,e,{detail:g}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ic(r,e):sc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(i.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,t)}catch(h){let C=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${C.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${C.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ac=s(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var xo=class n extends pe{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Ko(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:v.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),v.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var uc=s(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>v.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let g=d.substring(0,p),h=d.substring(p+1),C=t.accounts.find(R=>R.username===g&&R.password===h);return C||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Tn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Tn,"extractDateElements");function _s(n,e){return new Date(n,e+1,0).getDate()}s(_s,"getDaysInMonth");function vo(n,e){return n<=e?e-n:6-n+e+1}s(vo,"getDaysBetweenWeekdays");var Sn=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=_s(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(g=>g>=d)??this.weekdays[0]:this.reversed.weekdays.find(g=>g<=d)??this.reversed.weekdays[0];if(p!==void 0){let g=e==="next"?vo(d,p):vo(p,d);l=e==="next"?o+g:o-g,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Tn(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("next",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=Tn(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("prev",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:u}=Tn(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var cc={min:0,max:59},lc={min:0,max:59},dc={min:0,max:23},pc={min:1,max:31},mc={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},gc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},fc={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function tt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{tt(d,e).forEach(g=>t.add(g))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(tt,"parseElement");function To(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=fc[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Sn({seconds:tt(t,cc),minutes:tt(r,lc),hours:tt(o,dc),days:tt(i,pc),months:new Set(Array.from(tt(a,mc)).map(c=>c-1)),weekdays:new Set(Array.from(tt(u,gc)).map(c=>c%7))})}s(To,"parseCronExpression");var So=class extends pe{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),te(e,t).optional("problem","object"),e.problem&&te(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[To(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>To(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=v.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return v.format(i,e,t)}return e}};var hc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function yc(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(yc,"digestMessage");var bc=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await yc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function wc(n,e,t,r){f("policy.inbound.caching");let o=await de(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await bc(n,t),c=await i.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let g=t?.expirationSecondsTtl??60,h=new Response(p.body,p);hc.forEach(C=>h.headers.delete(C)),h.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(wc,"CachingInboundPolicy");var Rc=s(async(n,e,t,r)=>{if(f("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var Pc=s(async(n,e,t)=>{f("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ee(n,{headers:o})},"ClearHeadersInboundPolicy");var Ic=s(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Ec=s(async(n,e,t,r)=>{f("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var xc=s(async(n,e,t,r)=>{if(f("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return ye(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var vc=s(async(n,e,t,r)=>{if(f("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=me.instance,i=At(t.policies,o?.routeData.policies);return br(i)(n,e)},"CompositeInboundPolicy");var Tc=s(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let i=Sc(o);if(!i)return v.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await de(r,void 0,t),u=new ue(a,e),c=await u.get(i);if(!c){let l=await $.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Sc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Sc,"getToken");var Oc=s(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Cc=s(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.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(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ht="__unknown__",Ac=s(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:bt(t.allow?.countries,"allow.countries",r),regionCodes:bt(t.allow?.regionCodes,"allow.regionCode",r),asns:bt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:bt(t.block?.countries,"block.countries",r),regionCodes:bt(t.block?.regionCodes,"block.regionCode",r),asns:bt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ht,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ht,u=e.incomingRequestProperties.asn?.toString()??ht,c=o.ignoreUnknown&&i===ht,l=o.ignoreUnknown&&a===ht,d=o.ignoreUnknown&&u===ht,p=o.allow.countries,g=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return yt(n,e,r,i,a,u);let C=o.block.countries,R=o.block.regionCodes,O=o.block.asns;return C.length>0&&C.includes(i)&&!c||R.length>0&&R.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?yt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function yt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(yt,"blockedResponse");function bt(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(bt,"toLowerStringArray");var Lc=s(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var kc=s(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Oo(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return Oo(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ns(a[u])}else return a.length>0?Ns(a[0]):Oo(r,n,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 Ns(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(Ns,"generateResponse");var Oo=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var _c="Incoming",Nc={logRequestBody:!0,logResponseBody:!0};function Ds(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Ds,"headersToObject");function Ms(){return new Date().toISOString()}s(Ms,"timestamp");var Co=new WeakMap,Dc={};function Mc(n,e){let t=Co.get(n);t||(t=Dc);let r=Object.assign({...t},e);Co.set(n,r)}s(Mc,"setMoesifContext");async function Hs(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(Hs,"readBody");var Hc={},Ao;function Us(){if(!Ao)throw new U("Invalid State - no _lastLogger");return Ao}s(Us,"getLastLogger");function Uc(n){let e=Hc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Us().debug("posting",r);let o=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Us().error({status:o.status,body:await o.text()})})),e}s(Uc,"getDispatcher");async function Zc(n,e,t,r){f("policy.inbound.moesif-analytics"),Ao=e.log;let o=Ms(),i=Object.assign(Nc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Uc(i.applicationId),d=n.headers.get("true-client-ip"),p=Co.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ds(n.headers)},h=i.logResponseBody?await Hs(u,e):void 0,C={time:Ms(),status:u.status,headers:Ds(u.headers),body:h},R={request:g,response:C,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_c};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}s(Zc,"MoesifInboundPolicy");async function Zs(n,e,t,r){let o=Y.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - 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]}s(Zs,"loadSubscription");async function qs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,u=Y.getLogger(n);try{let c=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.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.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(qs,"consumeSubcriptionQuotas");var qc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function On(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(On,"validateMeters");function Fs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Xe(n),r=[];for(let o of t)qc.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Fs,"parseAllowedSubscriptionStatuses");function $s(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s($s,"compareMeters");var Lo=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,It)}static setMeters(e,t){On(t,"setMeters"),he.set(e,jt,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){te(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=it(this.options.meterOnStatusCodes),i=he.get(t,jt),a={...this.options.meters,...i};On(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Fs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,O,M)=>{let k=he.get(M,It);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){M.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=he.get(M,jt),F={...this.options.meters,...Z};if(On(F,this.policyName),o.includes(R.status)&&k&&F){M.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(F)} on response status '${R.status}'`);let{metersInSubscription:E,metersNotInSubscription:D}=$s(k.meters,F);if(D&&Object.keys(D).length>0){let V=Object.keys(D);M.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await qs(M,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Zs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:v.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),v.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(t,It,p));let g=he.get(t,It);if(!g)return u?e:(t.log.warn("Subscription is not available for user"),v.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let C=Object.keys(a).filter(R=>!Object.keys(g.meters).includes(R));if(C.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${C.join(", ")}`),v.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${C.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(g.meters[R].available<=0&&!r)return v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var Fc=s(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");import{importSPKI as $c}from"jose";var ko,jc=s(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!ko)try{ko=await $c(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:ko,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Gs=ze(Ve());var Bs=ze(Ve());var js=(0,Bs.debug)("zuplo:policies:RateLimitInboundPolicy"),zs=s(async(n,e,t,r)=>{let o=Y.getLogger(e),i=s((F,E)=>{let D={};return(!F||F==="retry-after")&&(D[pt]=E.toString()),v.tooManyRequests(n,e,void 0,D)},"rateLimited"),u=await lt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",g=dt(r,o),C=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,R=await de(r,void 0,t),O=new ue(R,e),M=Pn(C,d,g,e.requestId),k;s(async()=>{let F=await M;if(F.count>l){let E=Date.now()+F.ttlSeconds*1e3;O.put(C,E,F.ttlSeconds),js(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${C}' (async mode)`),k=i(p,F.ttlSeconds)}},"asyncCheck")();let Z=await O.get(C);if(Z!==void 0&&Z>Date.now()){js(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${C}' (async mode)`);let F=Math.round((Z-Date.now())/1e3);return i(p,F)}return e.addResponseSendingHook(async F=>k??F),n},"AsyncRateLimitInboundPolicy");var Vs=(0,Gs.debug)("zuplo:policies:RateLimitInboundPolicy"),Bc="strict",Ws=s(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Bc)==="async")return zs(n,e,t,r);let i=Date.now(),a=Y.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[pt]=d.toString()),v.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await lt(r,t)(n,e,r),p=d.key,g=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,C=t.headerMode??"retry-after",R=dt(r,a),M=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${p}`,k=await Pn(M,h,R,e.requestId);return k.count>g?(Vs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${M}' (strict mode)`),c(C,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;Vs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _o;function Ks(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Ks,"headersToNameValuePairs");function zc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(zc,"queryToNameValueParis");function Vc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Vc,"parseIntOrUndefined");var Js={};async function Gc(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return _o||(_o={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ye(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ye(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:_o,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ks(n.headers),queryString:zc(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ks(a.headers),content:{size:Vc(n.headers.get("content-length"))}}}]}}},d=Js[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async g=>{try{let h=t.url??"https://metrics.readme.io/request",C=await $.fetch(h,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});C.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${C.status}: '${await C.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),Js[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Gc,"ReadmeMetricsInboundPolicy");var Wc=s(async(n,e,t,r)=>{f("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new ee(n,{headers:i})},"RemoveHeadersInboundPolicy");var Kc=s(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Jc=s(async(n,e,t,r)=>{f("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new ee(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var Yc=s(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ys=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Xc=s(async(n,e,t)=>{f("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?Ys():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ys():n},"RequestSizeLimitInboundPolicy");var wt=s(n=>{let e=n.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"),Rt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=_n(t,r,o,c.name),p=me.instance.schemaValidator[d],g=p(e[c.name]),h=No(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ce=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ae=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),No=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Xs(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let C=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=v.badRequest(e,n,{detail:`${C}, see errors property for more details`,errors:`${h}`});if(Ce(t.validateBody)&&Oe(n,t.logLevel??"info",C,[r],h),Ae(t.validateBody))return R}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,C=v.badRequest(e,n,{detail:h});return Ce(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?C:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Nn(n.route.path,e.method,o),u=me.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,C=v.badRequest(e,n,{detail:h});return Ce(t.validateBody)&&Oe(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?C:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=No(l),g=v.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ce(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Ae(t.validateBody))return g}s(Xs,"handleBodyValidation");function Qs(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=wt(n),i=Rt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ce(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ae(t.validateHeaders))return u}}s(Qs,"handleHeadersValidation");function ea(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ce(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validatePathParameters))return a}}s(ea,"handlePathParameterValidation");function ta(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ce(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validateQueryParameters))return a}}s(ta,"handleQueryParameterValidation");var na=s(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ta(e,n,t);if(r!==void 0||(r=ea(e,n,t),r!==void 0)||(r=Qs(e,n,t),r!==void 0))return r;let o=await Xs(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Qc=na;var el=s(async(n,e,t,r)=>{if(f("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var tl=s(async(n,e,t)=>(f("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var nl=s(async(n,e,t,r)=>{f("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new ee(n,{headers:i})},"SetHeadersInboundPolicy");var rl=s(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`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(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ol=s(async(n,e,t,r)=>{f("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new ee(i.toString(),n)},"SetQueryParamsInboundPolicy");var il=s(async(n,e,t,r,o)=>{if(f("policy.outbound.set-status"),!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(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var sl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),al=s(async(n,e,t,r)=>{if(f("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await sl(t.sleepInMs),n},"SleepInboundPolicy");var ul=s(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await ye(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ee))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new U(`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(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var cl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await de(r,void 0,t),i=new ue(o,e),a=await i.get(r);if(!a){let u=await ll(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ll(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Re({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new U("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 U("Response returned from Azure AD is not in the expected format.")}s(ll,"getAccessToken");var ra="https://accounts.google.com/o/oauth2/token",Do,dl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Do||(Do=await Ee.init(t.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(" ")},i=await de(r,void 0,t),a=new ue(i,e),u=await a.get(r);if(!u){let c=await ke({serviceAccount:Do,audience:ra,payload:o}),l=await on(ra,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new U("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",ml=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mo,gl=s(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),te(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(ml.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Mo||(Mo=await Ee.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new U("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new U(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ye(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new U(`Unable to determine user from for the policy ${r}`);let a=await de(r,void 0,t),u=new ue(a,e),c={uid:i,claims:o},l=await xn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ke({serviceAccount:Mo,audience:pl,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Gi(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new U("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ho,fl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ho||(Ho=await Ee.init(t.serviceAccountJson));let o=await ke({serviceAccount:Ho,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var oa="https://www.googleapis.com/oauth2/v4/token",Uo,hl=s(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Uo||(Uo=await Ee.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=Xe(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await de(r,void 0,t),a;t.useMemoryCacheOnly?a=new nt(i):a=new ue(i,e);let u=await a.get(r);if(!u){let c=await ke({serviceAccount:Uo,audience:oa,payload:o}),l=await on(oa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new U("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new U("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var yl=s(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return v.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new K("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(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((R,O)=>e(R,"name",{value:O,configurable:!0}),"__name"),o=s((R,O)=>s(function(){return O||(0,R[t(R)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var O={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(k,j){return j},attributeValueProcessor:function(k,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,j,Z){return k}},M=r(function(k){return Object.assign({},O,k)},"buildOptions");R.buildOptions=M,R.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var O=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",M=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+M+"]*",j=new RegExp("^"+k+"$"),Z=r(function(E,D){let V=[],G=D.exec(E);for(;G;){let T=[];T.startIndex=D.lastIndex-G[0].length;let x=G.length;for(let H=0;H<x;H++)T.push(G[H]);V.push(T),G=D.exec(E)}return V},"getAllMatches"),F=r(function(E){let D=j.exec(E);return!(D===null||typeof D>"u")},"isName");R.isExist=function(E){return typeof E<"u"},R.isEmptyObject=function(E){return Object.keys(E).length===0},R.merge=function(E,D,V){if(D){let G=Object.keys(D),T=G.length;for(let x=0;x<T;x++)V==="strict"?E[G[x]]=[D[G[x]]]:E[G[x]]=D[G[x]]}},R.getValue=function(E){return R.isExist(E)?E:""},R.isName=F,R.getAllMatches=Z,R.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,O){"use strict";var M=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};O.exports=M}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,O){var M=a();function k(T,x){let H={};if(T[x+3]==="O"&&T[x+4]==="C"&&T[x+5]==="T"&&T[x+6]==="Y"&&T[x+7]==="P"&&T[x+8]==="E"){x=x+9;let se=1,W=!1,X=!1,ve="";for(;x<T.length;x++)if(T[x]==="<"&&!X){if(W&&F(T,x))x+=7,[entityName,val,x]=j(T,x+1),val.indexOf("&")===-1&&(H[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(W&&E(T,x))x+=8;else if(W&&D(T,x))x+=8;else if(W&&V(T,x))x+=9;else if(Z)X=!0;else throw new Error("Invalid DOCTYPE");se++,ve=""}else if(T[x]===">"){if(X?T[x-1]==="-"&&T[x-2]==="-"&&(X=!1,se--):se--,se===0)break}else T[x]==="["?W=!0:ve+=T[x];if(se!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}s(k,"readDocType"),r(k,"readDocType");function j(T,x){let H="";for(;x<T.length&&T[x]!=="'"&&T[x]!=='"';x++)H+=T[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let se=T[x++],W="";for(;x<T.length&&T[x]!==se;x++)W+=T[x];return[H,W,x]}s(j,"readEntityExp"),r(j,"readEntityExp");function Z(T,x){return T[x+1]==="!"&&T[x+2]==="-"&&T[x+3]==="-"}s(Z,"isComment"),r(Z,"isComment");function F(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="N"&&T[x+4]==="T"&&T[x+5]==="I"&&T[x+6]==="T"&&T[x+7]==="Y"}s(F,"isEntity"),r(F,"isEntity");function E(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="L"&&T[x+4]==="E"&&T[x+5]==="M"&&T[x+6]==="E"&&T[x+7]==="N"&&T[x+8]==="T"}s(E,"isElement"),r(E,"isElement");function D(T,x){return T[x+1]==="!"&&T[x+2]==="A"&&T[x+3]==="T"&&T[x+4]==="T"&&T[x+5]==="L"&&T[x+6]==="I"&&T[x+7]==="S"&&T[x+8]==="T"}s(D,"isAttlist"),r(D,"isAttlist");function V(T,x){return T[x+1]==="!"&&T[x+2]==="N"&&T[x+3]==="O"&&T[x+4]==="T"&&T[x+5]==="A"&&T[x+6]==="T"&&T[x+7]==="I"&&T[x+8]==="O"&&T[x+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(T){if(M.isName(T))return T;throw new Error(`Invalid entity name ${T}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(R,O){var M=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(E,D={}){if(D=Object.assign({},j,D),!E||typeof E!="string")return E;let V=E.trim();if(D.skipLike!==void 0&&D.skipLike.test(V))return E;if(D.hex&&M.test(V))return Number.parseInt(V,16);{let G=k.exec(V);if(G){let T=G[1],x=G[2],H=F(G[3]),se=G[4]||G[6];if(!D.leadingZeros&&x.length>0&&T&&V[2]!==".")return E;if(!D.leadingZeros&&x.length>0&&!T&&V[1]!==".")return E;{let W=Number(V),X=""+W;return X.search(/[eE]/)!==-1||se?D.eNotation?W:E:V.indexOf(".")!==-1?X==="0"&&H===""||X===H||T&&X==="-"+H?W:E:x?H===X||T+H===X?W:E:V===X||V===T+X?W:E}}else return E}}s(Z,"toNumber"),r(Z,"toNumber");function F(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s(F,"trimZeros"),r(F,"trimZeros"),O.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,O){"use strict";var M=a(),k=u(),j=c(),Z=l(),F=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=V,this.buildAttributesMap=T,this.isItStopNode=X,this.replaceEntitiesValue=se,this.readStopNodeData=z,this.saveTextToParentTag=W,this.addChild=H}};function E(P){let I=Object.keys(P);for(let A=0;A<I.length;A++){let B=I[A];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function D(P,I,A,B,L,_,Q){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){Q||(P=this.replaceEntitiesValue(P));let q=this.options.tagValueProcessor(I,P,A,L,_);return q==null?P:typeof q!=typeof P||q!==P?q:this.options.trimValues?ae(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?ae(P,this.options.parseTagValue,this.options.numberParseOptions):P}}s(D,"parseTextData"),r(D,"parseTextData");function V(P){if(this.options.removeNSPrefix){let I=P.split(":"),A=P.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(P=A+I[1])}return P}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function T(P,I,A){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=M.getAllMatches(P,G),L=B.length,_={};for(let Q=0;Q<L;Q++){let q=this.resolveNameSpace(B[Q][1]),N=B[Q][4],oe=this.options.attributeNamePrefix+q;if(q.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let ne=this.options.attributeValueProcessor(q,N,I);ne==null?_[oe]=N:typeof ne!=typeof N||ne!==N?_[oe]=ne:_[oe]=ae(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[oe]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let Q={};return Q[this.options.attributesGroupName]=_,Q}return _}}s(T,"buildAttributesMap"),r(T,"buildAttributesMap");var x=r(function(P){P=P.replace(/\r\n?/g,`
|
|
62
62
|
`);let I=new k("!xml"),A=I,B="",L="";for(let _=0;_<P.length;_++)if(P[_]==="<")if(P[_+1]==="/"){let q=b(P,">",_,"Closing Tag is not closed."),N=P.substring(_+2,q).trim();if(this.options.removeNSPrefix){let Se=N.indexOf(":");Se!==-1&&(N=N.substr(Se+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),A&&(B=this.saveTextToParentTag(B,A,L));let oe=L.substring(L.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let ne=0;oe&&this.options.unpairedTags.indexOf(oe)!==-1?(ne=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=L.lastIndexOf("."),L=L.substring(0,ne),A=this.tagsNodeStack.pop(),B="",_=q}else if(P[_+1]==="?"){let q=S(P,_,!1,"?>");if(!q)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,A,L),!(this.options.ignoreDeclaration&&q.tagName==="?xml"||this.options.ignorePiTags)){let N=new k(q.tagName);N.add(this.options.textNodeName,""),q.tagName!==q.tagExp&&q.attrExpPresent&&(N[":@"]=this.buildAttributesMap(q.tagExp,L,q.tagName)),this.addChild(A,N,L)}_=q.closeIndex+1}else if(P.substr(_+1,3)==="!--"){let q=b(P,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=P.substring(_+4,q-2);B=this.saveTextToParentTag(B,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=q}else if(P.substr(_+1,2)==="!D"){let q=j(P,_);this.docTypeEntities=q.entities,_=q.i}else if(P.substr(_+1,2)==="!["){let q=b(P,"]]>",_,"CDATA is not closed.")-2,N=P.substring(_+9,q);B=this.saveTextToParentTag(B,A,L);let oe=this.parseTextData(N,A.tagname,L,!0,!1,!0,!0);oe==null&&(oe=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):A.add(this.options.textNodeName,oe),_=q+2}else{let q=S(P,_,this.options.removeNSPrefix),N=q.tagName,oe=q.rawTagName,ne=q.tagExp,Se=q.attrExpPresent,Vo=q.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),A&&B&&A.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,A,L,!1));let Go=A;if(Go&&this.options.unpairedTags.indexOf(Go.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),N!==I.tagname&&(L+=L?"."+N:N),this.isItStopNode(this.options.stopNodes,L,N)){let Te="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)_=q.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=q.closeIndex;else{let kn=this.readStopNodeData(P,oe,Vo+1);if(!kn)throw new Error(`Unexpected end of ${oe}`);_=kn.i,Te=kn.tagContent}let Ln=new k(N);N!==ne&&Se&&(Ln[":@"]=this.buildAttributesMap(ne,L,N)),Te&&(Te=this.parseTextData(Te,N,L,!0,Se,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Ln.add(this.options.textNodeName,Te),this.addChild(A,Ln,L)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),L=L.substr(0,L.length-1),ne=N):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let Te=new k(N);N!==ne&&Se&&(Te[":@"]=this.buildAttributesMap(ne,L,N)),this.addChild(A,Te,L),L=L.substr(0,L.lastIndexOf("."))}else{let Te=new k(N);this.tagsNodeStack.push(A),N!==ne&&Se&&(Te[":@"]=this.buildAttributesMap(ne,L,N)),this.addChild(A,Te,L),A=Te}B="",_=Vo}}else B+=P[_];return I.child},"parseXml");function H(P,I,A){let B=this.options.updateTag(I.tagname,A,I[":@"]);B===!1||(typeof B=="string"&&(I.tagname=B),P.addChild(I))}s(H,"addChild"),r(H,"addChild");var se=r(function(P){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];P=P.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];P=P.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];P=P.replace(A.regex,A.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function W(P,I,A,B){return P&&(B===void 0&&(B=Object.keys(I.child).length===0),P=this.parseTextData(P,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&I.add(this.options.textNodeName,P),P=""),P}s(W,"saveTextToParentTag"),r(W,"saveTextToParentTag");function X(P,I,A){let B="*."+A;for(let L in P){let _=P[L];if(B===_||I===_)return!0}return!1}s(X,"isItStopNode"),r(X,"isItStopNode");function ve(P,I,A=">"){let B,L="";for(let _=I;_<P.length;_++){let Q=P[_];if(B)Q===B&&(B="");else if(Q==='"'||Q==="'")B=Q;else if(Q===A[0])if(A[1]){if(P[_+1]===A[1])return{data:L,index:_}}else return{data:L,index:_};else Q===" "&&(Q=" ");L+=Q}}s(ve,"tagExpWithClosingIndex"),r(ve,"tagExpWithClosingIndex");function b(P,I,A,B){let L=P.indexOf(I,A);if(L===-1)throw new Error(B);return L+I.length-1}s(b,"findClosingIndex"),r(b,"findClosingIndex");function S(P,I,A,B=">"){let L=ve(P,I+1,B);if(!L)return;let _=L.data,Q=L.index,q=_.search(/\s/),N=_,oe=!0;q!==-1&&(N=_.substring(0,q),_=_.substring(q+1).trimStart());let ne=N;if(A){let Se=N.indexOf(":");Se!==-1&&(N=N.substr(Se+1),oe=N!==L.data.substr(Se+1))}return{tagName:N,tagExp:_,closeIndex:Q,attrExpPresent:oe,rawTagName:ne}}s(S,"readTagExp"),r(S,"readTagExp");function z(P,I,A){let B=A,L=1;for(;A<P.length;A++)if(P[A]==="<")if(P[A+1]==="/"){let _=b(P,">",A,`${I} is not closed`);if(P.substring(A+2,_).trim()===I&&(L--,L===0))return{tagContent:P.substring(B,A),i:_};A=_}else if(P[A+1]==="?")A=b(P,"?>",A+1,"StopNode is not closed.");else if(P.substr(A+1,3)==="!--")A=b(P,"-->",A+3,"StopNode is not closed.");else if(P.substr(A+1,2)==="![")A=b(P,"]]>",A,"StopNode is not closed.")-2;else{let _=S(P,A,">");_&&((_&&_.tagName)===I&&_.tagExp[_.tagExp.length-1]!=="/"&&L++,A=_.closeIndex)}}s(z,"readStopNodeData"),r(z,"readStopNodeData");function ae(P,I,A){if(I&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:Z(P,A)}else return M.isExist(P)?P:""}s(ae,"parseValue"),r(ae,"parseValue"),O.exports=F}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function O(F,E){return M(F,E)}s(O,"prettify"),r(O,"prettify");function M(F,E,D){let V,G={};for(let T=0;T<F.length;T++){let x=F[T],H=k(x),se="";if(D===void 0?se=H:se=D+"."+H,H===E.textNodeName)V===void 0?V=x[H]:V+=""+x[H];else{if(H===void 0)continue;if(x[H]){let W=M(x[H],E,se),X=Z(W,E);x[":@"]?j(W,x[":@"],se,E):Object.keys(W).length===1&&W[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?W=W[E.textNodeName]:Object.keys(W).length===0&&(E.alwaysCreateTextNode?W[E.textNodeName]="":W=""),G[H]!==void 0&&G.hasOwnProperty(H)?(Array.isArray(G[H])||(G[H]=[G[H]]),G[H].push(W)):E.isArray(H,se,X)?G[H]=[W]:G[H]=W}}}return typeof V=="string"?V.length>0&&(G[E.textNodeName]=V):V!==void 0&&(G[E.textNodeName]=V),G}s(M,"compress"),r(M,"compress");function k(F){let E=Object.keys(F);for(let D=0;D<E.length;D++){let V=E[D];if(V!==":@")return V}}s(k,"propName"),r(k,"propName");function j(F,E,D,V){if(E){let G=Object.keys(E),T=G.length;for(let x=0;x<T;x++){let H=G[x];V.isArray(H,D+"."+H,!0,!0)?F[H]=[E[H]]:F[H]=E[H]}}}s(j,"assignAttributes"),r(j,"assignAttributes");function Z(F,E){let{textNodeName:D}=E,V=Object.keys(F).length;return!!(V===0||V===1&&(F[D]||typeof F[D]=="boolean"||F[D]===0))}s(Z,"isLeafTag"),r(Z,"isLeafTag"),R.prettify=O}}),g=o({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var O=a(),M={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,S){S=Object.assign({},M,S);let z=[],ae=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=Z(b,I);continue}else{let B=!1;b[I]==="/"&&(B=!0,I++);let L="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
|
|
63
63
|
`&&b[I]!=="\r";I++)L+=b[I];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),I--),!W(L)){let q;return L.trim().length===0?q="Invalid space after '<'.":q="Tag '"+L+"' is an invalid name.",H("InvalidTag",q,X(b,I))}let _=D(b,I);if(_===!1)return H("InvalidAttr","Attributes for '"+L+"' have open quote.",X(b,I));let Q=_.value;if(I=_.index,Q[Q.length-1]==="/"){let q=I-Q.length;Q=Q.substring(0,Q.length-1);let N=G(Q,S);if(N===!0)ae=!0;else return H(N.err.code,N.err.msg,X(b,q+N.err.line))}else if(B)if(_.tagClosed){if(Q.trim().length>0)return H("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",X(b,A));{let q=z.pop();if(L!==q.tagName){let N=X(b,q.tagStartPos);return H("InvalidTag","Expected closing tag '"+q.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+L+"'.",X(b,A))}z.length==0&&(P=!0)}}else return H("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",X(b,I));else{let q=G(Q,S);if(q!==!0)return H(q.err.code,q.err.msg,X(b,I-Q.length+q.err.line));if(P===!0)return H("InvalidXml","Multiple possible root nodes found.",X(b,I));S.unpairedTags.indexOf(L)!==-1||z.push({tagName:L,tagStartPos:A}),ae=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=Z(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let q=x(b,I);if(q==-1)return H("InvalidChar","char '&' is not expected.",X(b,I));I=q}else if(P===!0&&!k(b[I]))return H("InvalidXml","Extra text at the end",X(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return H("InvalidChar","char '"+b[I]+"' is not expected.",X(b,I))}if(ae){if(z.length==1)return H("InvalidTag","Unclosed tag '"+z[0].tagName+"'.",X(b,z[0].tagStartPos));if(z.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(z.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
|
|
64
64
|
`||b==="\r"}s(k,"isWhiteSpace"),r(k,"isWhiteSpace");function j(b,S){let z=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let ae=b.substr(z,S-z);if(S>5&&ae==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",X(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}s(j,"readPI"),r(j,"readPI");function Z(b,S){if(b.length>S+5&&b[S+1]==="-"&&b[S+2]==="-"){for(S+=3;S<b.length;S++)if(b[S]==="-"&&b[S+1]==="-"&&b[S+2]===">"){S+=2;break}}else if(b.length>S+8&&b[S+1]==="D"&&b[S+2]==="O"&&b[S+3]==="C"&&b[S+4]==="T"&&b[S+5]==="Y"&&b[S+6]==="P"&&b[S+7]==="E"){let z=1;for(S+=8;S<b.length;S++)if(b[S]==="<")z++;else if(b[S]===">"&&(z--,z===0))break}else if(b.length>S+9&&b[S+1]==="["&&b[S+2]==="C"&&b[S+3]==="D"&&b[S+4]==="A"&&b[S+5]==="T"&&b[S+6]==="A"&&b[S+7]==="["){for(S+=8;S<b.length;S++)if(b[S]==="]"&&b[S+1]==="]"&&b[S+2]===">"){S+=2;break}}return S}s(Z,"readCommentAndCDATA"),r(Z,"readCommentAndCDATA");var F='"',E="'";function D(b,S){let z="",ae="",P=!1;for(;S<b.length;S++){if(b[S]===F||b[S]===E)ae===""?ae=b[S]:ae!==b[S]||(ae="");else if(b[S]===">"&&ae===""){P=!0;break}z+=b[S]}return ae!==""?!1:{value:z,index:S,tagClosed:P}}s(D,"readAttributeStr"),r(D,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(b,S){let z=O.getAllMatches(b,V),ae={};for(let P=0;P<z.length;P++){if(z[P][1].length===0)return H("InvalidAttr","Attribute '"+z[P][2]+"' has no space in starting.",ve(z[P]));if(z[P][3]!==void 0&&z[P][4]===void 0)return H("InvalidAttr","Attribute '"+z[P][2]+"' is without value.",ve(z[P]));if(z[P][3]===void 0&&!S.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+z[P][2]+"' is not allowed.",ve(z[P]));let I=z[P][2];if(!se(I))return H("InvalidAttr","Attribute '"+I+"' is an invalid name.",ve(z[P]));if(!ae.hasOwnProperty(I))ae[I]=1;else return H("InvalidAttr","Attribute '"+I+"' is repeated.",ve(z[P]))}return!0}s(G,"validateAttributeString"),r(G,"validateAttributeString");function T(b,S){let z=/\d/;for(b[S]==="x"&&(S++,z=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(z))break}return-1}s(T,"validateNumberAmpersand"),r(T,"validateNumberAmpersand");function x(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,T(b,S);let z=0;for(;S<b.length;S++,z++)if(!(b[S].match(/\w/)&&z<20)){if(b[S]===";")break;return-1}return S}s(x,"validateAmpersand"),r(x,"validateAmpersand");function H(b,S,z){return{err:{code:b,msg:S,line:z.line||z,col:z.col}}}s(H,"getErrorObject"),r(H,"getErrorObject");function se(b){return O.isName(b)}s(se,"validateAttrName"),r(se,"validateAttrName");function W(b){return O.isName(b)}s(W,"validateTagName"),r(W,"validateTagName");function X(b,S){let z=b.substring(0,S).split(/\r?\n/);return{line:z.length,col:z[z.length-1].length+1}}s(X,"getLineNumberForPosition"),r(X,"getLineNumberForPosition");function ve(b){return b.startIndex+b[1].length}s(ve,"getPositionFromMatch"),r(ve,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,O){var{buildOptions:M}=i(),k=d(),{prettify:j}=p(),Z=g(),F=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=M(E)}parse(E,D){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(D){D===!0&&(D={});let T=Z.validate(E,D);if(T!==!0)throw Error(`${T.err.msg}:${T.err.line}:${T.err.col}`)}let V=new k(this.options);V.addExternalEntities(this.externalEntities);let G=V.parseXml(E);return this.options.preserveOrder||G===void 0?G:j(G,this.options)}addEntity(E,D){if(D.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(D==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=D}};O.exports=F}});let C=h();return new C(n)},"getXmlParser");var Zo=class extends Fe{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),te(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?it(e.parseOnStatusCodes):void 0,this.parser=ia({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,t,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 U(c)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var qo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new K(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Fo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new J(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),mn().waitUntil(this.#e.waitUntilFlushed())}};var sa=10,aa=3e4,$o=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=aa,this.#r=sa}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:aa,this.#r=sa}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await bl(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);mn().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new Error(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function bl(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(bl,"waitUntilTrue");var jo=["sha-1","sha-256","sha-384","sha-512"],Cn=class{static{s(this,"BaseCryptoBeta")}};var Bo=class extends Cn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!jo.includes(e.toLowerCase()))throw new U(`Algorithm ${e} is not supported. Try using ${jo.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var An=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var zo=class extends An{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=y.instance.runtime.ZUPLO_KV;if(!t)throw new Wo("The Key Value Store feature is not enabled for this project.");this.#e=t,f("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{Qr as AWSLoggingPlugin,Qu as AmberfloMeteringInboundPolicy,wo as AmberfloMeteringPolicy,nc as ApiAuthKeyInboundPolicy,Ro as ApiKeyInboundPolicy,co as AuditLogDataStaxProvider,lo as AuditLogPlugin,ac as Auth0JwtInboundPolicy,pu as AwsLambdaHandlerExtensions,xo as AxiomaticsAuthZInboundPolicy,Fo as BackgroundDispatcher,$o as BackgroundLoader,uc as BasicAuthInboundPolicy,Ws as BasicRateLimitInboundPolicy,J as BatchDispatch,So as BrownoutInboundPolicy,wc as CachingInboundPolicy,Rc as ChangeMethodInboundPolicy,Pc as ClearHeadersInboundPolicy,Ic as ClearHeadersOutboundPolicy,Ec as ClerkJwtInboundPolicy,xc as CognitoJwtInboundPolicy,jr as ComplexRateLimitInboundPolicy,vc as CompositeInboundPolicy,m as ConfigurationError,nr as ContentTypes,he as ContextData,Bo as CryptoBeta,Tc as CurityPhantomTokenInboundPolicy,Sr as DataDogLoggingPlugin,no as DataDogMetricsPlugin,Br as DynaTraceLoggingPlugin,so as DynatraceMetricsPlugin,Oc as FirebaseJwtInboundPolicy,Cc as FormDataToJsonInboundPolicy,Ac as GeoFilterInboundPolicy,Ir as GoogleCloudLoggingPlugin,kr as Handler,v as HttpProblems,Kt as HttpStatusCode,pe as InboundPolicy,Lc as JWTScopeValidationInboundPolicy,zo as KeyValueStore,Vr as LokiLoggingPlugin,Ht as LookupResult,ue as MemoryZoneReadThroughCache,kc as MockApiInboundPolicy,Zc as MoesifInboundPolicy,Lo as MonetizationInboundPolicy,Fc as OktaJwtInboundPolicy,ye as OpenIdJwtInboundPolicy,Fe as OutboundPolicy,Ke as ProblemResponseFormatter,jc as PropelAuthJwtInboundPolicy,Ws as RateLimitInboundPolicy,Gc as ReadmeMetricsInboundPolicy,Wc as RemoveHeadersInboundPolicy,Kc as RemoveHeadersOutboundPolicy,Jc as RemoveQueryParamsInboundPolicy,Yc as ReplaceStringOutboundPolicy,Xc as RequestSizeLimitInboundPolicy,na as RequestValidationInboundPolicy,el as RequireOriginInboundPolicy,Tt as ResponseSendingEvent,St as ResponseSentEvent,Ut as Router,U as RuntimeError,Bt as SYSTEM_LOGGER,Qc as SchemaBasedRequestValidation,Le as SemanticAttributes,qo as ServiceProviderImpl,tl as SetBodyInboundPolicy,nl as SetHeadersInboundPolicy,rl as SetHeadersOutboundPolicy,ol as SetQueryParamsInboundPolicy,il as SetStatusOutboundPolicy,al as SleepInboundPolicy,Ts as StripeMonetizationPlugin,Ft as StripeWebhookVerificationInboundPolicy,Kr as SumoLogicLoggingPlugin,ul as SupabaseJwtInboundPolicy,Ue as SystemRouteName,Et as TelemetryPlugin,cl as UpstreamAzureAdServiceAuthInboundPolicy,dl as UpstreamFirebaseAdminAuthInboundPolicy,gl as UpstreamFirebaseUserAuthInboundPolicy,fl as UpstreamGcpJwtInboundPolicy,hl as UpstreamGcpServiceAuthInboundPolicy,Yr as VMWareLogInsightLoggingPlugin,yl as ValidateJsonSchemaInbound,Zo as XmlToJsonOutboundPolicy,Pt as ZoneCache,ee as ZuploRequest,mu as awsLambdaHandler,be as environment,_n as getIdForParameterSchema,ca as getIdForRefSchema,Nn as getIdForRequestBodySchema,ua as getRawOperationDataIdentifierName,or as httpStatuses,Pu as openApiSpecHandler,Eu as redirectHandler,la as sanitizedIdentifierName,rr as serialize,Mc as setMoesifContext,f as trackFeature,vu as urlForwardHandler,Su as urlRewriteHandler,Ou as webSocketHandler,Cu as webSocketPipelineHandler};
|