@zuplo/runtime 5.2296.0 → 5.2299.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 CHANGED
@@ -68,7 +68,7 @@ Signature verification is impossible without access to the original signed mater
68
68
  `+d}):new He(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
69
69
  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.
70
70
  `+l+`
71
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(rp,"validateComputedSignature");function op(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:[]})}i(op,"parseHeader");function ip(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}i(ip,"secureCompare");async function sp(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ai[s[u]];return a.join("")}i(sp,"computeHMACSignatureAsync");var ai=new Array(256);for(let n=0;n<ai.length;n++)ai[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(te,"optionValidator");var Ot=class extends ge{static{i(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 Ma(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Da(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Da,"isStripeWebhookEvent");var ap={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new _(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new _(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new _(s)}return o}},ir=ap;var ui="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ua="My API Key";async function Ha({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,ui);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ua,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new _(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ha,"createConsumer");async function Za({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,ui);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ua,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new _(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Za,"createConsumerInvite");async function qa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ui);o.searchParams.set("with-api-key","true");let s=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(qa,"deleteConsumer");async function Fa({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,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:h}=g.instance;if(!yt(p))throw new Y("No Zuplo JWT token set.");let y=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,C="";try{P=await y.json(),C=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,P),new _(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Fa,"createSubscription");async function vt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(vt,"updateSubscription");async function Ct({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 _(`${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 _(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 _(c)}return u.data[0]}i(Ct,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Qe="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function sr(n){return n.replaceAll("_","-")}i(sr,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ci(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:se,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}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});let u=s.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 Ha({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ir.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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Za({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}`),x.ok(n,e,{title:se,detail:p.message})}if(!c)return x.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=sr(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;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")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Fa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await qa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:se,detail:p.message})}return x.ok(n,e,{title:Qe})}i(ci,"onCustomerSubscriptionCreated");async function li(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});try{let a=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await vt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}i(li,"onCustomerSubscriptionDeleted");async function di(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=sr(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ir.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.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 vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:se,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."+xe})}i(di,"onCustomerSubscriptionUpdated");var pi=class extends bn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!up(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Da(y))return x.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await ci(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await di(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await li(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:se,detail:`Event '${y.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.`+xe})}},"stripeWebhookHandler"),s=Gs({inboundPolicies:[new Ot({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 me({processors:[Pe,s],handler:o,gateway:r}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function up(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(up,"isMetricsRegion");var ja=new WeakMap,$a={},ar=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ja.set(e,t)}};async function Ba(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=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ja.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=st(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)},h=$a[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async P=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),$a[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Ba,"AmberfloMeteringInboundPolicy");async function ur(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("")}i(ur,"sha256");var za=new Map;async function pe(n,e,t){let r,o=`${n}-${e}`,s=za.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ur(JSON.stringify({policyName:n,options:t}))}`,za.set(n,r)),r}i(pe,"getPolicyCacheName");var Va="key-metadata-cache-type";function cp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(cp,"getKeyValue");async function cr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Ee.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 s=i(C=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=cp(a,o);if(!u||u==="")return s("No key present");let c=await lp(u),l=await pe(r,void 0,o),d=new ae(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!==Va&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),H=JSON.parse(C);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),P={isValid:!0,typeId:Va,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(cr,"ApiKeyInboundPolicy");async function lp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(lp,"hashValue");var Ga=cr;var on=require("jose");var Wa=require("jose");var mi=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof gi&&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",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,Wa.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new fi("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new St("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 St("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ka(n,e,t){let r=new mi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ka,"createRemoteJWKSet");var St=class extends _{static{i(this,"JWKSError")}},gi=class extends St{static{i(this,"JWKSNoMatchingKey")}},fi=class extends St{static{i(this,"JWKSTimeout")}};var lr={},dp=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!lr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await pe(n,void 0,r),u=new ae(a,e);lr[r.jwkUrl]=Ka(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else lr[r.jwkUrl]=(0,on.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,on.jwtVerify)(t,lr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),pp=i(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 s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,on.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),be=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>x.unauthorized(n,e,{detail:h}),"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?dp(r,e):pp,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),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 Ja=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),be(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var dr=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var pr=class n extends ge{static{i(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 dr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"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(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);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),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.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 Ya=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(P=>P.username===h&&P.password===y);return A||await s("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 mr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(mr,"extractDateElements");function Xa(n,e){return new Date(n,e+1,0).getDate()}i(Xa,"getDaysInMonth");function hi(n,e){return n<=e?e-n:6-n+e+1}i(hi,"getDaysBetweenWeekdays");var gr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,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(!s||s.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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=Xa(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?hi(d,p):hi(p,d);l=e==="next"?o+h:o-h,(l>s||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=mr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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=mr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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:s,month:a,weekday:u}=mr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var mp={min:0,max:59},gp={min:0,max:59},fp={min:0,max:23},hp={min:1,max:31},yp={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"}},bp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},wp={"@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 lt(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=>{lt(d,e).forEach(h=>t.add(h))}),t;let o=i(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"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[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}i(lt,"parseElement");function yi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=wp[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],s=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 gr({seconds:lt(t,mp),minutes:lt(r,gp),hours:lt(o,fp),days:lt(s,hp),months:new Set(Array.from(lt(a,yp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,bp)).map(c=>c%7))})}i(yi,"parseCronExpression");var fr=class extends ge{static{i(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=[yi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>yi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.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 x.format(s,e,t)}return e}};var Rp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Pp,"digestMessage");var Ep=i(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 Pp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Qa(n,e,t,r){f("policy.inbound.caching");let o=await pe(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ep(n,t),c=await s.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 h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Rp.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Qa,"CachingInboundPolicy");var eu=i(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 oe(n,{method:t.method})},"ChangeMethodInboundPolicy");var tu=i(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 oe(n,{headers:o})},"ClearHeadersInboundPolicy");var nu=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var ru=i(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}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",be(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ou=i(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 be(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 uu=Be(Ze());var hr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},bi=class extends hr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},wi=class extends hr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Ip(n,e){if(Fs(n))throw new bi(e)}i(Ip,"throwIfUndefinedOrNull");function sn(n,e){if(Ip(n,e),!Te(n))throw new wi(e,"string")}i(sn,"throwIfNotString");var yr=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return sn(e,"redisClientUrl"),sn(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){sn(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},br=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(sn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Y("The in-memory rate limit client does not support this request")}};var xp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function At(n,e){return{function:Cp(e,"RateLimitInboundPolicy",n),user:Op,ip:Tp,all:vp}[e.rateLimitBy??"ip"]}i(At,"getRateLimitByFunctions");var Tp=i(async n=>({key:`ip-${xp(n)}`}),"getIP"),Op=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),vp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),wr;function _t(n,e){let t;if(wr)return wr;if(!g.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new br,wr=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=yr.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return wr=t,t}i(_t,"getRedisClient");async function Rr(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Rr,"getCountAndUpdateExpiry");async function iu(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(iu,"multiCount");async function su(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(su,"multiIncrement");function Cp(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new _(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new _(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new _(l)}return c},"outerFunction")}i(Cp,"wrapUserFunction");var Lt="Retry-After";var au=(0,uu.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),Ri=Symbol("complex-rate-limit-counters"),Pr=class n extends ge{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=fe.get(e,Ri)??{};Object.assign(r,t),fe.set(e,Ri,t)}static getIncrements(e){return fe.get(e,Ri)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=_t(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Lt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await At(this.policyName,this.options)(e,t,this.policyName),d=g.instance.isTestMode||g.instance.isWorkingCopy?g.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);au(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let H=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:h,increment:C[B]??0})),N=su(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let y=Object.entries(p).map(([C,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:h,limit:H})),A=await iu(y,s,t.requestId);return Sp(A,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;au(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Sp(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Sp,"findOverLimits");var cu=i(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=we.instance,s=Jt(t.policies,o?.routeData.policies);return Co(s)(n,e)},"CompositeInboundPolicy");var lu=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Ap(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await pe(r,void 0,t),u=new ae(a,e),c=await u.get(s);if(!c){let l=await F.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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Ap(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Ap,"getToken");var du=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),be(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 pu=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",mu=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Mt(t.allow?.countries,"allow.countries",r),regionCodes:Mt(t.allow?.regionCodes,"allow.regionCode",r),asns:Mt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Mt(t.block?.countries,"block.countries",r),regionCodes:Mt(t.block?.regionCodes,"block.regionCode",r),asns:Mt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??kt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kt,u=e.incomingRequestProperties.asn?.toString()??kt,c=o.ignoreUnknown&&s===kt,l=o.ignoreUnknown&&a===kt,d=o.ignoreUnknown&&u===kt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Nt(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?Nt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Nt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Nt,"blockedResponse");function Mt(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[]`)}i(Mt,"toLowerStringArray");var gu=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var hu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Pi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Pi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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 fu(a[u])}else return a.length>0?fu(a[0]):Pi(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 fu(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})}}i(fu,"generateResponse");var Pi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var _p="Incoming",Lp={logRequestBody:!0,logResponseBody:!0};function yu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(yu,"headersToObject");function bu(){return new Date().toISOString()}i(bu,"timestamp");var Ei=new WeakMap,kp={};function Pu(n,e){let t=Ei.get(n);t||(t=kp);let r=Object.assign({...t},e);Ei.set(n,r)}i(Pu,"setMoesifContext");async function wu(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}i(wu,"readBody");var Np={},Ii;function Ru(){if(!Ii)throw new _("Invalid State - no _lastLogger");return Ii}i(Ru,"getLastLogger");function Mp(n){let e=Np[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ru().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ru().error({status:o.status,body:await o.text()})})),e}i(Mp,"getDispatcher");async function Eu(n,e,t,r){f("policy.inbound.moesif-analytics"),Ii=e.log;let o=bu(),s=Object.assign(Lp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await wu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Mp(s.applicationId),d=n.headers.get("true-client-ip"),p=Ei.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:yu(n.headers)},y=s.logResponseBody?await wu(u,e):void 0,A={time:bu(),status:u.status,headers:yu(u.headers),body:y},P={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_p};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Eu,"MoesifInboundPolicy");async function Iu(n,e,t,r){let o=ee.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"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]}i(Iu,"loadSubscription");async function xu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ee.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(xu,"consumeSubcriptionQuotas");var Dp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Er(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}}i(Er,"validateMeters");function Tu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)Dp.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"]}i(Tu,"parseAllowedSubscriptionStatuses");function Ou(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}}i(Ou,"compareMeters");var Ir=class extends ge{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,jt)}static setMeters(e,t){Er(t,"setMeters"),fe.set(e,yn,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=bt(this.options.meterOnStatusCodes),s=fe.get(t,yn),a={...this.options.meters,...s};Er(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Tu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,C,H)=>{let N=fe.get(H,jt);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=fe.get(H,yn),j={...this.options.meters,...q};if(Er(j,this.policyName),o.includes(P.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=Ou(N.meters,j);if(U&&Object.keys(U).length>0){let G=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await xu(H,N.id,this.policyName,this.options.bucketId,I)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Iu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.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.`),x.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`),fe.set(t,jt,p));let h=fe.get(t,jt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function vu(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await ye({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Error getting token from identity provider.",s)}catch{}throw new _("Error getting token from identity provider.")}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 _("Response returned from identity provider is not in the expected format.")}i(vu,"getClientCredentialsAccessToken");var Dt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},xr=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",g.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Dt("unknown",`Unknown error. Status: ${c.status}`):new Dt(l.code,l.message)}return c.json()}};function an(n,e,t){!n[e]&&t&&(n[e]=t)}i(an,"setHeaderIfNotSet");var Cu="X-OpenFGA-Client-Method",Su="X-OpenFGA-Client-Bulk-Request-Id",un=class extends xr{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return an(r,Cu,"BatchCheck"),an(r,Su,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Dt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(an(c,Cu,"ListRelations"),an(c,Su,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Au=Symbol("openfga-authz-context-data"),Ut=class extends ge{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];fe.set(e,Au,r)}constructor(e,t){if(super(e,t),te(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")te(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")te(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")te(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new un({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await pe(this.policyName,void 0,this.options);this.cache=new ae(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=fe.get(t,Au);if(!o||o.length===0)throw new _(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?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 OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new Y(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await vu({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new _("Invalid state for credentials method is not valid. This should not happen.")}};var _u=["us1","eu1","au1"],Tr=class extends Ut{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!_u.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${_u.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientId,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var Lu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),be(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Or=class extends Ut{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};var ku=require("jose");var xi,Nu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!xi)try{xi=await(0,ku.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return be(n,e,{issuer:t.authUrl,secret:xi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Zu=Be(Ze());var Du=Be(Ze());var Mu=(0,Du.debug)("zuplo:policies:RateLimitInboundPolicy"),Uu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Lt]=I.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await At(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=_t(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,P=await pe(r,void 0,t),C=new ae(P,e),H=Rr(A,d,h,e.requestId),N;i(async()=>{let j=await H;if(j.count>l){let I=Date.now()+j.ttlSeconds*1e3;C.put(A,I,j.ttlSeconds),Mu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),N=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await C.get(A);if(q!==void 0&&q>Date.now()){Mu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>N??j),n},"AsyncRateLimitInboundPolicy");var Hu=(0,Zu.debug)("zuplo:policies:RateLimitInboundPolicy"),Up="strict",Ti=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Up)==="async")return Uu(n,e,t,r);let s=Date.now(),a=ee.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Lt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await At(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=_t(r,a),H=`rate-limit${g.instance.isTestMode||g.instance.isWorkingCopy?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Rr(H,y,P,e.requestId);return N.count>h?(Hu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(A,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Hu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Oi;function qu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(qu,"headersToNameValuePairs");function Hp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Hp,"queryToNameValueParis");function Zp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Zp,"parseIntOrUndefined");var Fu={};async function $u(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return Oi||(Oi={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Oi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:qu(n.headers),queryString:Hp(n.query)},response:{status:a.status,statusText:a.statusText,headers:qu(a.headers),content:{size:Zp(n.headers.get("content-length"))}}}]}}},d=Fu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",A=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Fu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i($u,"ReadmeMetricsInboundPolicy");var ju=i(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 s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new oe(n,{headers:s})},"RemoveHeadersInboundPolicy");var Bu=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.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 s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var zu=i(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 s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new oe(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Vu=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Gu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Wu=i(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"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Gu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Gu():n},"RequestSizeLimitInboundPolicy");function Ku(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Ku,"getRawOperationDataIdentifierName");function vr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(vr,"getIdForParameterSchema");function Cr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Cr,"getIdForRequestBodySchema");function Ju(n,e){return`_${et(n)}__${et(e)}`}i(Ju,"getIdForRefSchema");function et(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(et,"sanitizedIdentifierName");var Ht=i(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"),Zt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=vr(t,r,o,c.name),p=we.instance.schemaValidator[d],h=p(e[c.name]),y=vi(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),vi=i(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 Yu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",A,[r],y),Ne(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Cr(n.route.path,e.method,o),u=we.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=vi(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return h}i(Yu,"handleBodyValidation");function Xu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ht(n),s=Zt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Xu,"handleHeadersValidation");function Qu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ht(n),o=Zt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Qu,"handlePathParameterValidation");function ec(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ht(n),o=Zt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(ec,"handleQueryParameterValidation");var Ci=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ec(e,n,t);if(r!==void 0||(r=Qu(e,n,t),r!==void 0)||(r=Xu(e,n,t),r!==void 0))return r;let o=await Yu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),tc=Ci;var nc=i(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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var rc=i(async(n,e,t)=>(f("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var oc=i(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 s=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;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new oe(n,{headers:s})},"SetHeadersInboundPolicy");var ic=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.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 sc=i(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 s=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;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new oe(s.toString(),n)},"SetQueryParamsInboundPolicy");var ac=i(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 qp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),uc=i(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 qp(t.sleepInMs),n},"SleepInboundPolicy");var cc=i(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},s=await be(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof oe))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new _(`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?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var lc=i(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 pe(r,void 0,t),s=new ae(o,e),a=await s.get(r);if(!a){let u=await Fp(t,e);s.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 Fp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ye({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new _("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 _("Response returned from Azure AD is not in the expected format.")}i(Fp,"getAccessToken");var dc="https://accounts.google.com/o/oauth2/token",Si,pc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Si||(Si=await Oe.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(" ")},s=await pe(r,void 0,t),a=new ae(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Si,audience:dc,payload:o}),l=await Mn(dc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("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 $p="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",jp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ai,mc=i(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(jp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ai||(Ai=await Oe.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new _("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new _(`Unable to determine user from for the policy ${r}`);let a=await pe(r,void 0,t),u=new ae(a,e),c={uid:s,claims:o},l=await ur(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ai,audience:$p,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await ra(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new _("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var _i,gc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),_i||(_i=await Oe.init(t.serviceAccountJson));let o=await De({serviceAccount:_i,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var fc="https://www.googleapis.com/oauth2/v4/token",Li,hc=i(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"),Li||(Li=await Oe.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=at(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 s=await pe(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new ae(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Li,audience:fc,payload:o}),l=await Mn(fc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("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 yc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.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 Y("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var bc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,C)=>e(P,"name",{value:C,configurable:!0}),"__name"),o=i((P,C)=>i(function(){return C||(0,P[t(P)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,B){return B},attributeValueProcessor:function(N,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,B,q){return N}},H=r(function(N){return Object.assign({},C,N)},"buildOptions");P.buildOptions=H,P.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var C=":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",H=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+H+"]*",B=new RegExp("^"+N+"$"),q=r(function(I,U){let G=[],W=U.exec(I);for(;W;){let v=[];v.startIndex=U.lastIndex-W[0].length;let T=W.length;for(let Z=0;Z<T;Z++)v.push(W[Z]);G.push(v),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");P.isExist=function(I){return typeof I<"u"},P.isEmptyObject=function(I){return Object.keys(I).length===0},P.merge=function(I,U,G){if(U){let W=Object.keys(U),v=W.length;for(let T=0;T<v;T++)G==="strict"?I[W[T]]=[U[W[T]]]:I[W[T]]=U[W[T]]}},P.getValue=function(I){return P.isExist(I)?I:""},P.isName=j,P.getAllMatches=q,P.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,C){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,B){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:B})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,C){var H=a();function N(v,T){let Z={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let le=1,X=!1,ne=!1,Ce="";for(;T<v.length;T++)if(v[T]==="<"&&!ne){if(X&&j(v,T))T+=7,[entityName,val,T]=B(v,T+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(v,T))T+=8;else if(X&&U(v,T))T+=8;else if(X&&G(v,T))T+=9;else if(q)ne=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(v[T]===">"){if(ne?v[T-1]==="-"&&v[T-2]==="-"&&(ne=!1,le--):le--,le===0)break}else v[T]==="["?X=!0:Ce+=v[T];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:T}}i(N,"readDocType"),r(N,"readDocType");function B(v,T){let Z="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)Z+=v[T];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=v[T++],X="";for(;T<v.length&&v[T]!==le;T++)X+=v[T];return[Z,X,T]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(P,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(I,U={}){if(U=Object.assign({},B,U),!I||typeof I!="string")return I;let G=I.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return I;if(U.hex&&H.test(G))return Number.parseInt(G,16);{let W=N.exec(G);if(W){let v=W[1],T=W[2],Z=j(W[3]),le=W[4]||W[6];if(!U.leadingZeros&&T.length>0&&v&&G[2]!==".")return I;if(!U.leadingZeros&&T.length>0&&!v&&G[1]!==".")return I;{let X=Number(G),ne=""+X;return ne.search(/[eE]/)!==-1||le?U.eNotation?X:I:G.indexOf(".")!==-1?ne==="0"&&Z===""||ne===Z||v&&ne==="-"+Z?X:I:T?Z===ne||v+Z===ne?X:I:G===ne||G===v+ne?X:I}}else return I}}i(q,"toNumber"),r(q,"toNumber");function j(I){return I&&I.indexOf(".")!==-1&&(I=I.replace(/0+$/,""),I==="."?I="0":I[0]==="."?I="0"+I:I[I.length-1]==="."&&(I=I.substr(0,I.length-1))),I}i(j,"trimZeros"),r(j,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,C){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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:(E,L)=>String.fromCharCode(Number.parseInt(L,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,L)=>String.fromCharCode(Number.parseInt(L,16))}},this.addExternalEntities=I,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=v,this.isItStopNode=ne,this.replaceEntitiesValue=le,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(R){let E=Object.keys(R);for(let L=0;L<E.length;L++){let z=E[L];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(R,E,L,z,k,M,re){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){re||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(E,R,L,k,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?de(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?de(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function G(R){if(this.options.removeNSPrefix){let E=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(R=L+E[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,E,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,W),k=z.length,M={};for(let re=0;re<k;re++){let $=this.resolveNameSpace(z[re][1]),D=z[re][4],ue=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,E);ie==null?M[ue]=D:typeof ie!=typeof D||ie!==D?M[ue]=ie:M[ue]=de(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ue]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=M,re}return M}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
71
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new He(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(rp,"validateComputedSignature");function op(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:[]})}i(op,"parseHeader");function ip(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}i(ip,"secureCompare");async function sp(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)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=ai[s[u]];return a.join("")}i(sp,"computeHMACSignatureAsync");var ai=new Array(256);for(let n=0;n<ai.length;n++)ai[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!it(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],h=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${h}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${h}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${h}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${h}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${h}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(te,"optionValidator");var Ot=class extends ge{static{i(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 Ma(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),x.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function Da(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Da,"isStripeWebhookEvent");var ap={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new _(s)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new _(s)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new _(s)}return o}},ir=ap;var ui="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ua="My API Key";async function Ha({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=g.instance,c=new URL(`/v1/buckets/${n}/consumers`,ui);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ua,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,h),new _(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Ha,"createConsumer");async function Za({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,ui);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ua,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let h="Error creating API Key Consumer";throw s.log.error(h,p),new _(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Za,"createConsumerInvite");async function qa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,ui);o.searchParams.set("with-api-key","true");let s=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(qa,"deleteConsumer");async function Fa({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,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:h}=g.instance;if(!yt(p))throw new Y("No Zuplo JWT token set.");let y=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${h}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let A=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,C="";try{P=await y.json(),C=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,P),new _(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Fa,"createSubscription");async function vt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(vt,"updateSubscription");async function Ct({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=g.instance;if(!yt(o))throw new Y("No Zuplo JWT token set.");let a=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(n)},`${s}/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 _(`${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 _(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 _(c)}return u.data[0]}i(Ct,"getSubscription");var se="Skipping since we're unable to process the webhook event.",Qe="Successfully processed the webhook event",xe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function sr(n){return n.replaceAll("_","-")}i(sr,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ci(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),x.ok(n,e,{title:se,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}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});let u=s.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 Ha({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ir.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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Za({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}`),x.ok(n,e,{title:se,detail:p.message})}if(!c)return x.ok(n,e,{title:se,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=sr(t.data.object.status),h;l&&d&&(h={subscriber:{sub:d,email:l}});let y;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")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ct(t.data.object.trial_end),trialStartDate:ct(t.data.object.trial_start)}),await Fa({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:h,trial:y})}catch(p){return await qa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:se,detail:p.message})}return x.ok(n,e,{title:Qe})}i(ci,"onCustomerSubscriptionCreated");async function li(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});try{let a=await Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await vt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}i(li,"onCustomerSubscriptionDeleted");async function di(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.`),x.ok(n,e,{title:se,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),x.ok(n,e,{title:se,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!==g.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}'.`),x.ok(n,e,{title:se,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.`+xe});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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=sr(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ct(t.data.object.trial_end)),await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ir.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(h=>h.proration&&h.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 vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}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 Ct({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ct(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ct(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await vt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:se,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. `+xe})}return x.ok(n,e,{title:Qe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:se,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."+xe})}i(di,"onCustomerSubscriptionUpdated");var pi=class extends bn{constructor(t){super();this.options=t;f("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!g.instance.build.ACCOUNT_NAME)throw new Y("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let h=this.options.primaryDataRegion??"us-central1";if(!up(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Da(y))return x.ok(c,l,{title:se,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+xe});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await ci(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await di(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await li(c,l,y,{meteringBucketId:d});default:return x.ok(c,l,{title:se,detail:`Event '${y.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.`+xe})}},"stripeWebhookHandler"),s=Gs({inboundPolicies:[new Ot({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 me({processors:[Pe,s],handler:o,gateway:r}),u=new ce({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function up(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(up,"isMetricsRegion");var ja=new WeakMap,$a={},ar=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){ja.set(e,t)}};async function Ba(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=bt(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=ja.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=st(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)},h=$a[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async P=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":A}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(C){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${C.message}`),C}}),$a[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i(Ba,"AmberfloMeteringInboundPolicy");async function ur(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("")}i(ur,"sha256");var za=new Map;async function pe(n,e,t){let r,o=`${n}-${e}`,s=za.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ur(JSON.stringify({policyName:n,options:t}))}`,za.set(n,r)),r}i(pe,"getPolicyCacheName");var Va="key-metadata-cache-type";function cp(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(cp,"getKeyValue");async function cr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Ee.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Ee.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 s=i(C=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:C}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=cp(a,o);if(!u||u==="")return s("No key present");let c=await lp(u),l=await pe(r,void 0,o),d=new ae(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!==Va&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await ye({retryDelayMs:5,retries:2,logger:ee.getLogger(e)},`${g.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":g.instance.deploymentName??"unknown","User-Agent":g.instance.systemUserAgent},body:JSON.stringify(h)});if(y.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(y.status!==200){try{let C=await y.text(),H=JSON.parse(C);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),P={isValid:!0,typeId:Va,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}i(cr,"ApiKeyInboundPolicy");async function lp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(lp,"hashValue");var Ga=cr;var on=require("jose");var Wa=require("jose");var mi=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{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof gi&&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",g.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=(0,Wa.createLocalJWKSet)(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 s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await F.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new fi("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new St("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 St("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ka(n,e,t){let r=new mi(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ka,"createRemoteJWKSet");var St=class extends _{static{i(this,"JWKSError")}},gi=class extends St{static{i(this,"JWKSNoMatchingKey")}},fi=class extends St{static{i(this,"JWKSTimeout")}};var lr={},dp=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!lr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await pe(n,void 0,r),u=new ae(a,e);lr[r.jwkUrl]=Ka(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else lr[r.jwkUrl]=(0,on.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,on.jwtVerify)(t,lr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),pp=i(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 s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await(0,on.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),be=i(async(n,e,t,r)=>{f("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),s="bearer ",a=i(h=>x.unauthorized(n,e,{detail:h}),"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?dp(r,e):pp,l=await i(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let h=o.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await u(h,t)}catch(y){let A=new URL(n.url);return"code"in y&&y.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,y):e.log.warn(`Invalid token on: ${n.method} ${A.pathname}`,y),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 Ja=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),be(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var dr=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await F.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var pr=class n extends ge{static{i(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 dr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"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(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);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),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.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 Ya=i(async(n,e,t)=>{f("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let h=d.substring(0,p),y=d.substring(p+1),A=t.accounts.find(P=>P.username===h&&P.password===y);return A||await s("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 mr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(mr,"extractDateElements");function Xa(n,e){return new Date(n,e+1,0).getDate()}i(Xa,"getDaysInMonth");function hi(n,e){return n<=e?e-n:6-n+e+1}i(hi,"getDaysBetweenWeekdays");var gr=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,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(!s||s.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(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((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 s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};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 s=Xa(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(h=>h>=d)??this.weekdays[0]:this.reversed.weekdays.find(h=>h<=d)??this.reversed.weekdays[0];if(p!==void 0){let h=e==="next"?hi(d,p):hi(p,d);l=e==="next"?o+h:o-h,(l>s||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=mr(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("next",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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=mr(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;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 h=this.findAllowedTime("prev",t);if(h!==void 0)return new Date(u,c,d,h.hour,h.minute,h.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 s=0;s<e;s++)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:s,month:a,weekday:u}=mr(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(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var mp={min:0,max:59},gp={min:0,max:59},fp={min:0,max:23},hp={min:1,max:31},yp={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"}},bp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},wp={"@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 lt(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=>{lt(d,e).forEach(h=>t.add(h))}),t;let o=i(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"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[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}i(lt,"parseElement");function yi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=wp[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],s=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 gr({seconds:lt(t,mp),minutes:lt(r,gp),hours:lt(o,fp),days:lt(s,hp),months:new Set(Array.from(lt(a,yp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,bp)).map(c=>c%7))})}i(yi,"parseCronExpression");var fr=class extends ge{static{i(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=[yi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>yi(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=x.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 x.format(s,e,t)}return e}};var Rp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Pp(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Pp,"digestMessage");var Ep=i(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 Pp(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.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=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Qa(n,e,t,r){f("policy.inbound.caching");let o=await pe(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ep(n,t),c=await s.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 h=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Rp.forEach(A=>y.headers.delete(A)),y.headers.set("cache-control",`s-maxage=${h}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Qa,"CachingInboundPolicy");var eu=i(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 oe(n,{method:t.method})},"ChangeMethodInboundPolicy");var tu=i(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 oe(n,{headers:o})},"ClearHeadersInboundPolicy");var nu=i(async(n,e,t,r)=>{f("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var ru=i(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}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",be(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var ou=i(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 be(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 uu=Be(Ze());var hr=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},bi=class extends hr{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},wi=class extends hr{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Ip(n,e){if(Fs(n))throw new bi(e)}i(Ip,"throwIfUndefinedOrNull");function sn(n,e){if(Ip(n,e),!Te(n))throw new wi(e,"string")}i(sn,"throwIfNotString");var yr=class n{static{i(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return sn(e,"redisClientUrl"),sn(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){sn(e,"url");let s=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Y("Rate limiting service failed with 401: Unauthorized"):new Y(`Rate limiting service failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},br=class{static{i(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(sn(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:s,key:a}=JSON.parse(t),u=Date.now()+s*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Y("The in-memory rate limit client does not support this request")}};var xp=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function At(n,e){return{function:Cp(e,"RateLimitInboundPolicy",n),user:Op,ip:Tp,all:vp}[e.rateLimitBy??"ip"]}i(At,"getRateLimitByFunctions");var Tp=i(async n=>({key:`ip-${xp(n)}`}),"getIP"),Op=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),vp=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),wr;function _t(n,e){let t;if(wr)return wr;if(!g.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new br,wr=t,t;let{authApiJWT:r,redisURL:o}=g.instance;if(!Te(o))throw new Y(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Te(r))throw new Y(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=yr.initialize(o,r,g.instance.deploymentName??"unknown",g.instance.systemUserAgent)),!t||!t.isEnabled())throw new Y(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return wr=t,t}i(_t,"getRedisClient");async function Rr(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}i(Rr,"getCountAndUpdateExpiry");async function iu(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(iu,"multiCount");async function su(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}i(su,"multiIncrement");function Cp(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new _(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new _(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new _(l)}return c},"outerFunction")}i(Cp,"wrapUserFunction");var Lt="Retry-After";var au=(0,uu.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),Ri=Symbol("complex-rate-limit-counters"),Pr=class n extends ge{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=fe.get(e,Ri)??{};Object.assign(r,t),fe.set(e,Ri,t)}static getIncrements(e){return fe.get(e,Ri)??{}}constructor(e,t){super(e,t),f("policy.inbound.complex-rate-limit-inbound"),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ee.getLogger(t),s=_t(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new Y(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[Lt]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await At(this.policyName,this.options)(e,t,this.policyName),d=g.instance.isTestMode||g.instance.isWorkingCopy?g.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),h=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let C=n.getIncrements(t);au(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(C)}`);let H=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:h,increment:C[B]??0})),N=su(H,s,t.requestId);t.waitUntil(N),await N}catch(C){t.log.error(C)}});let y=Object.entries(p).map(([C,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${C}`,ttlSeconds:h,limit:H})),A=await iu(y,s,t.requestId);return Sp(A,y).length>0?u(this.options.headerMode??"retry-after",h):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;au(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function Sp(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(Sp,"findOverLimits");var cu=i(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=we.instance,s=Jt(t.policies,o?.routeData.policies);return Co(s)(n,e)},"CompositeInboundPolicy");var lu=i(async(n,e,t,r)=>{f("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let s=Ap(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await pe(r,void 0,t),u=new ae(a,e),c=await u.get(s);if(!c){let l=await F.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="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Ap(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Ap,"getToken");var du=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),be(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 pu=i(async(n,e,t)=>{f("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))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 oe(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",mu=i(async(n,e,t,r)=>{f("policy.inbound.geo-filter");let o={allow:{countries:Mt(t.allow?.countries,"allow.countries",r),regionCodes:Mt(t.allow?.regionCodes,"allow.regionCode",r),asns:Mt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Mt(t.block?.countries,"block.countries",r),regionCodes:Mt(t.block?.regionCodes,"block.regionCode",r),asns:Mt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??kt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kt,u=e.incomingRequestProperties.asn?.toString()??kt,c=o.ignoreUnknown&&s===kt,l=o.ignoreUnknown&&a===kt,d=o.ignoreUnknown&&u===kt,p=o.allow.countries,h=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||h.length>0&&!h.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Nt(n,e,r,s,a,u);let A=o.block.countries,P=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||P.length>0&&P.includes(a)&&!l||C.length>0&&C.includes(u)&&!d?Nt(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Nt(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Nt,"blockedResponse");function Mt(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[]`)}i(Mt,"toLowerStringArray");var gu=i(async(n,e,t)=>{f("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var hu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Pi(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return Pi(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(h=>{a.push({responseName:u,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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 fu(a[u])}else return a.length>0?fu(a[0]):Pi(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 fu(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})}}i(fu,"generateResponse");var Pi=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var _p="Incoming",Lp={logRequestBody:!0,logResponseBody:!0};function yu(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(yu,"headersToObject");function bu(){return new Date().toISOString()}i(bu,"timestamp");var Ei=new WeakMap,kp={};function Pu(n,e){let t=Ei.get(n);t||(t=kp);let r=Object.assign({...t},e);Ei.set(n,r)}i(Pu,"setMoesifContext");async function wu(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}i(wu,"readBody");var Np={},Ii;function Ru(){if(!Ii)throw new _("Invalid State - no _lastLogger");return Ii}i(Ru,"getLastLogger");function Mp(n){let e=Np[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ru().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ru().error({status:o.status,body:await o.text()})})),e}i(Mp,"getDispatcher");async function Eu(n,e,t,r){f("policy.inbound.moesif-analytics"),Ii=e.log;let o=bu(),s=Object.assign(Lp,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await wu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Mp(s.applicationId),d=n.headers.get("true-client-ip"),p=Ei.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:yu(n.headers)},y=s.logResponseBody?await wu(u,e):void 0,A={time:bu(),status:u.status,headers:yu(u.headers),body:y},P={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_p};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}i(Eu,"MoesifInboundPolicy");async function Iu(n,e,t,r){let o=ee.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=g.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"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]}i(Iu,"loadSubscription");async function xu(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=g.instance,u=ee.getLogger(n);try{let c=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"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)}}i(xu,"consumeSubcriptionQuotas");var Dp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Er(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}}i(Er,"validateMeters");function Tu(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=at(n),r=[];for(let o of t)Dp.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"]}i(Tu,"parseAllowedSubscriptionStatuses");function Ou(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}}i(Ou,"compareMeters");var Ir=class extends ge{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,jt)}static setMeters(e,t){Er(t,"setMeters"),fe.set(e,yn,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=bt(this.options.meterOnStatusCodes),s=fe.get(t,yn),a={...this.options.meters,...s};Er(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Tu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,C,H)=>{let N=fe.get(H,jt);if((this.options.allowRequestsWithoutSubscription??!1)&&!N){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=fe.get(H,yn),j={...this.options.meters,...q};if(Er(j,this.policyName),o.includes(P.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${P.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=Ou(N.meters,j);if(U&&Object.keys(U).length>0){let G=Object.keys(U);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${G}'`)}await xu(H,N.id,this.policyName,this.options.bucketId,I)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Ee.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Ee.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Iu(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.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.`),x.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`),fe.set(t,jt,p));let h=fe.get(t,jt);if(!h)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return t.log.error(`Quota is not set up for subscription '${h.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(h.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(h.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};async function vu(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await ye({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Error getting token from identity provider.",s)}catch{}throw new _("Error getting token from identity provider.")}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 _("Response returned from identity provider is not in the expected format.")}i(vu,"getClientCredentialsAccessToken");var Dt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},xr=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new Error("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",g.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new Dt("unknown",`Unknown error. Status: ${c.status}`):new Dt(l.code,l.message)}return c.json()}};function an(n,e,t){!n[e]&&t&&(n[e]=t)}i(an,"setHeaderIfNotSet");var Cu="X-OpenFGA-Client-Method",Su="X-OpenFGA-Client-Bulk-Request-Id",un=class extends xr{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return an(r,Cu,"BatchCheck"),an(r,Su,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof Dt)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(an(c,Cu,"ListRelations"),an(c,Su,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Au=Symbol("openfga-authz-context-data"),Ut=class extends ge{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];fe.set(e,Au,r)}constructor(e,t){if(super(e,t),te(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")te(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")te(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")te(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new un({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await pe(this.policyName,void 0,this.options);this.cache=new ae(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=fe.get(t,Au);if(!o||o.length===0)throw new _(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?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 OpenFGA service`,a),x.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new Y(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await vu({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new _("Invalid state for credentials method is not valid. This should not happen.")}};var _u=["us1","eu1","au1"],Tr=class extends Ut{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!_u.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${_u.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),f("policy.inbound.oktafga-authz")}};var Lu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),be(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Or=class extends Ut{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.openfga-authz")}};var ku=require("jose");var xi,Nu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!xi)try{xi=await(0,ku.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return be(n,e,{issuer:t.authUrl,secret:xi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Zu=Be(Ze());var Du=Be(Ze());var Mu=(0,Du.debug)("zuplo:policies:RateLimitInboundPolicy"),Uu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Lt]=I.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await At(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=_t(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,P=await pe(r,void 0,t),C=new ae(P,e),H=Rr(A,d,h,e.requestId),N;i(async()=>{let j=await H;if(j.count>l){let I=Date.now()+j.ttlSeconds*1e3;C.put(A,I,j.ttlSeconds),Mu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${A}' (async mode)`),N=s(p,j.ttlSeconds)}},"asyncCheck")();let q=await C.get(A);if(q!==void 0&&q>Date.now()){Mu(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${A}' (async mode)`);let j=Math.round((q-Date.now())/1e3);return s(p,j)}return e.addResponseSendingHook(async j=>N??j),n},"AsyncRateLimitInboundPolicy");var Hu=(0,Zu.debug)("zuplo:policies:RateLimitInboundPolicy"),Up="strict",Ti=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Up)==="async")return Uu(n,e,t,r);let s=Date.now(),a=ee.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new Y(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Lt]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await At(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",P=_t(r,a),H=`rate-limit${g.instance.isTestMode||g.instance.isWorkingCopy?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Rr(H,y,P,e.requestId);return N.count>h?(Hu(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(A,N.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Hu(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var Oi;function qu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(qu,"headersToNameValuePairs");function Hp(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Hp,"queryToNameValueParis");function Zp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Zp,"parseIntOrUndefined");var Fu={};async function $u(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return Oi||(Oi={name:"zuplo",version:g.instance.build.ZUPLO_VERSION,comment:`zuplo/${g.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?st(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?st(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:g.instance.isWorkingCopy||g.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:Oi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:qu(n.headers),queryString:Hp(n.query)},response:{status:a.status,statusText:a.statusText,headers:qu(a.headers),content:{size:Zp(n.headers.get("content-length"))}}}]}}},d=Fu[t.apiKey];if(!d){let p=t.apiKey;d=new Q("readme-metering-inbound-policy",10,async h=>{try{let y=t.url??"https://metrics.readme.io/request",A=await F.fetch(y,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Fu[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i($u,"ReadmeMetricsInboundPolicy");var ju=i(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 s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new oe(n,{headers:s})},"RemoveHeadersInboundPolicy");var Bu=i(async(n,e,t,r,o)=>{f("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.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 s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var zu=i(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 s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new oe(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Vu=i(async(n,e,t,r)=>{f("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Gu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Wu=i(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"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?Gu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Gu():n},"RequestSizeLimitInboundPolicy");function Ku(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Ku,"getRawOperationDataIdentifierName");function vr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(vr,"getIdForParameterSchema");function Cr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Cr,"getIdForRequestBodySchema");function Ju(n,e){return`_${et(n)}__${et(e)}`}i(Ju,"getIdForRefSchema");function et(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)||r>="A".charCodeAt(0)&&r<="Z".charCodeAt(0)||r>="a".charCodeAt(0)&&r<="z".charCodeAt(0)?e.push(n.charAt(t)):e.push("_")}return e.join("")}i(et,"sanitizedIdentifierName");var Ht=i(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"),Zt=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=vr(t,r,o,c.name),p=we.instance.schemaValidator[d],h=p(e[c.name]),y=vi(p.errors);h||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Le=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ne=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),vi=i(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 Yu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let A=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${A}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",A,[r],y),Ne(t.validateBody))return P}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Cr(n.route.path,e.method,o),u=we.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,A=x.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Le(n,t.logLevel??"info",y,[r],[y]),Ne(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=vi(l),h=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Le(n,t.logLevel??"info",d,[r],p),Ne(t.validateBody))return h}i(Yu,"handleBodyValidation");function Xu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Ht(n),s=Zt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Le(n,t.logLevel??"info",a,s.invalidValues,s.errors),Ne(t.validateHeaders))return u}}i(Xu,"handleHeadersValidation");function Qu(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Ht(n),o=Zt(r.filter(s=>s.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validatePathParameters))return a}}i(Qu,"handlePathParameterValidation");function ec(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Ht(n),o=Zt(r.filter(s=>s.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Le(n,t.logLevel??"info",s,o.invalidValues,o.errors),Ne(t.validateQueryParameters))return a}}i(ec,"handleQueryParameterValidation");var Ci=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ec(e,n,t);if(r!==void 0||(r=Qu(e,n,t),r!==void 0)||(r=Xu(e,n,t),r!==void 0))return r;let o=await Yu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),tc=Ci;var nc=i(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 s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var rc=i(async(n,e,t)=>(f("policy.inbound.set-body"),new oe(n,{body:t.body})),"SetBodyInboundPolicy");var oc=i(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 s=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;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new oe(n,{headers:s})},"SetHeadersInboundPolicy");var ic=i(async(n,e,t,r,o)=>{f("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.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 sc=i(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 s=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;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new oe(s.toString(),n)},"SetQueryParamsInboundPolicy");var ac=i(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 qp=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),uc=i(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 qp(t.sleepInMs),n},"SleepInboundPolicy");var cc=i(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},s=await be(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof oe))throw new Y("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new _(`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?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var lc=i(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 pe(r,void 0,t),s=new ae(o,e),a=await s.get(r);if(!a){let u=await Fp(t,e);s.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 Fp(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ye({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 s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new _("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 _("Response returned from Azure AD is not in the expected format.")}i(Fp,"getAccessToken");var dc="https://accounts.google.com/o/oauth2/token",Si,pc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Si||(Si=await Oe.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(" ")},s=await pe(r,void 0,t),a=new ae(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Si,audience:dc,payload:o}),l=await Mn(dc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("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 $p="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",jp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ai,mc=i(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(jp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ai||(Ai=await Oe.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new _("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=st(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new _(`Unable to determine user from for the policy ${r}`);let a=await pe(r,void 0,t),u=new ae(a,e),c={uid:s,claims:o},l=await ur(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ai,audience:$p,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await ra(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new _("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var _i,gc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),_i||(_i=await Oe.init(t.serviceAccountJson));let o=await De({serviceAccount:_i,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var fc="https://www.googleapis.com/oauth2/v4/token",Li,hc=i(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"),Li||(Li=await Oe.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=at(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 s=await pe(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new ae(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Li,audience:fc,payload:o}),l=await Mn(fc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("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 yc=i(async(n,e,t)=>{f("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.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 Y("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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var bc=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((P,C)=>e(P,"name",{value:C,configurable:!0}),"__name"),o=i((P,C)=>i(function(){return C||(0,P[t(P)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var C={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(N,B){return B},attributeValueProcessor:function(N,B){return B},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(N,B,q){return N}},H=r(function(N){return Object.assign({},C,N)},"buildOptions");P.buildOptions=H,P.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var C=":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",H=C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",N="["+C+"]["+H+"]*",B=new RegExp("^"+N+"$"),q=r(function(I,U){let G=[],W=U.exec(I);for(;W;){let v=[];v.startIndex=U.lastIndex-W[0].length;let T=W.length;for(let Z=0;Z<T;Z++)v.push(W[Z]);G.push(v),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");P.isExist=function(I){return typeof I<"u"},P.isEmptyObject=function(I){return Object.keys(I).length===0},P.merge=function(I,U,G){if(U){let W=Object.keys(U),v=W.length;for(let T=0;T<v;T++)G==="strict"?I[W[T]]=[U[W[T]]]:I[W[T]]=U[W[T]]}},P.getValue=function(I){return P.isExist(I)?I:""},P.isName=j,P.getAllMatches=q,P.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,C){"use strict";var H=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(N){this.tagname=N,this.child=[],this[":@"]={}}add(N,B){N==="__proto__"&&(N="#__proto__"),this.child.push({[N]:B})}addChild(N){N.tagname==="__proto__"&&(N.tagname="#__proto__"),N[":@"]&&Object.keys(N[":@"]).length>0?this.child.push({[N.tagname]:N.child,":@":N[":@"]}):this.child.push({[N.tagname]:N.child})}};C.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,C){var H=a();function N(v,T){let Z={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let le=1,X=!1,ne=!1,Ce="";for(;T<v.length;T++)if(v[T]==="<"&&!ne){if(X&&j(v,T))T+=7,[entityName,val,T]=B(v,T+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(v,T))T+=8;else if(X&&U(v,T))T+=8;else if(X&&G(v,T))T+=9;else if(q)ne=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(v[T]===">"){if(ne?v[T-1]==="-"&&v[T-2]==="-"&&(ne=!1,le--):le--,le===0)break}else v[T]==="["?X=!0:Ce+=v[T];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:T}}i(N,"readDocType"),r(N,"readDocType");function B(v,T){let Z="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)Z+=v[T];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=v[T++],X="";for(;T<v.length&&v[T]!==le;T++)X+=v[T];return[Z,X,T]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(P,C){var H=/^[-+]?0x[a-fA-F0-9]+$/,N=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function q(I,U={}){if(U=Object.assign({},B,U),!I||typeof I!="string")return I;let G=I.trim();if(U.skipLike!==void 0&&U.skipLike.test(G))return I;if(U.hex&&H.test(G))return Number.parseInt(G,16);{let W=N.exec(G);if(W){let v=W[1],T=W[2],Z=j(W[3]),le=W[4]||W[6];if(!U.leadingZeros&&T.length>0&&v&&G[2]!==".")return I;if(!U.leadingZeros&&T.length>0&&!v&&G[1]!==".")return I;{let X=Number(G),ne=""+X;return ne.search(/[eE]/)!==-1||le?U.eNotation?X:I:G.indexOf(".")!==-1?ne==="0"&&Z===""||ne===Z||v&&ne==="-"+Z?X:I:T?Z===ne||v+Z===ne?X:I:G===ne||G===v+ne?X:I}}else return I}}i(q,"toNumber"),r(q,"toNumber");function j(I){return I&&I.indexOf(".")!==-1&&(I=I.replace(/0+$/,""),I==="."?I="0":I[0]==="."?I="0"+I:I[I.length-1]==="."&&(I=I.substr(0,I.length-1))),I}i(j,"trimZeros"),r(j,"trimZeros"),C.exports=q}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,C){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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:(E,L)=>String.fromCharCode(Number.parseInt(L,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,L)=>String.fromCharCode(Number.parseInt(L,16))}},this.addExternalEntities=I,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=v,this.isItStopNode=ne,this.replaceEntitiesValue=le,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(R){let E=Object.keys(R);for(let L=0;L<E.length;L++){let z=E[L];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(R,E,L,z,k,M,re){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){re||(R=this.replaceEntitiesValue(R));let $=this.options.tagValueProcessor(E,R,L,k,M);return $==null?R:typeof $!=typeof R||$!==R?$:this.options.trimValues?de(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?de(R,this.options.parseTagValue,this.options.numberParseOptions):R}}i(U,"parseTextData"),r(U,"parseTextData");function G(R){if(this.options.removeNSPrefix){let E=R.split(":"),L=R.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(R=L+E[1])}return R}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,E,L){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,W),k=z.length,M={};for(let re=0;re<k;re++){let $=this.resolveNameSpace(z[re][1]),D=z[re][4],ue=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ue=this.options.transformAttributeName(ue)),ue==="__proto__"&&(ue="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,E);ie==null?M[ue]=D:typeof ie!=typeof D||ie!==D?M[ue]=ie:M[ue]=de(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ue]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let re={};return re[this.options.attributesGroupName]=M,re}return M}}i(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
72
72
  `);let E=new N("!xml"),L=E,z="",k="";for(let M=0;M<R.length;M++)if(R[M]==="<")if(R[M+1]==="/"){let $=b(R,">",M,"Closing Tag is not closed."),D=R.substring(M+2,$).trim();if(this.options.removeNSPrefix){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),L&&(z=this.saveTextToParentTag(z,L,k));let ue=k.substring(k.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ie=0;ue&&this.options.unpairedTags.indexOf(ue)!==-1?(ie=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=k.lastIndexOf("."),k=k.substring(0,ie),L=this.tagsNodeStack.pop(),z="",M=$}else if(R[M+1]==="?"){let $=S(R,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,L,k),!(this.options.ignoreDeclaration&&$.tagName==="?xml"||this.options.ignorePiTags)){let D=new N($.tagName);D.add(this.options.textNodeName,""),$.tagName!==$.tagExp&&$.attrExpPresent&&(D[":@"]=this.buildAttributesMap($.tagExp,k,$.tagName)),this.addChild(L,D,k)}M=$.closeIndex+1}else if(R.substr(M+1,3)==="!--"){let $=b(R,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(M+4,$-2);z=this.saveTextToParentTag(z,L,k),L.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}M=$}else if(R.substr(M+1,2)==="!D"){let $=B(R,M);this.docTypeEntities=$.entities,M=$.i}else if(R.substr(M+1,2)==="!["){let $=b(R,"]]>",M,"CDATA is not closed.")-2,D=R.substring(M+9,$);z=this.saveTextToParentTag(z,L,k);let ue=this.parseTextData(D,L.tagname,k,!0,!1,!0,!0);ue==null&&(ue=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):L.add(this.options.textNodeName,ue),M=$+2}else{let $=S(R,M,this.options.removeNSPrefix),D=$.tagName,ue=$.rawTagName,ie=$.tagExp,Ae=$.attrExpPresent,Ni=$.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),L&&z&&L.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,L,k,!1));let Mi=L;if(Mi&&this.options.unpairedTags.indexOf(Mi.tagname)!==-1&&(L=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),D!==E.tagname&&(k+=k?"."+D:D),this.isItStopNode(this.options.stopNodes,k,D)){let Se="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)M=$.closeIndex;else{let Hr=this.readStopNodeData(R,ue,Ni+1);if(!Hr)throw new Error(`Unexpected end of ${ue}`);M=Hr.i,Se=Hr.tagContent}let Ur=new N(D);D!==ie&&Ae&&(Ur[":@"]=this.buildAttributesMap(ie,k,D)),Se&&(Se=this.parseTextData(Se,D,k,!0,Ae,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Ur.add(this.options.textNodeName,Se),this.addChild(L,Ur,k)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),k=k.substr(0,k.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let Se=new N(D);D!==ie&&Ae&&(Se[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(L,Se,k),k=k.substr(0,k.lastIndexOf("."))}else{let Se=new N(D);this.tagsNodeStack.push(L),D!==ie&&Ae&&(Se[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(L,Se,k),L=Se}z="",M=Ni}}else z+=R[M];return E.child},"parseXml");function Z(R,E,L){let z=this.options.updateTag(E.tagname,L,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),R.addChild(E))}i(Z,"addChild"),r(Z,"addChild");var le=r(function(R){if(this.options.processEntities){for(let E in this.docTypeEntities){let L=this.docTypeEntities[E];R=R.replace(L.regx,L.val)}for(let E in this.lastEntities){let L=this.lastEntities[E];R=R.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let L=this.htmlEntities[E];R=R.replace(L.regex,L.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function X(R,E,L,z){return R&&(z===void 0&&(z=Object.keys(E.child).length===0),R=this.parseTextData(R,E.tagname,L,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&E.add(this.options.textNodeName,R),R=""),R}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function ne(R,E,L){let z="*."+L;for(let k in R){let M=R[k];if(z===M||E===M)return!0}return!1}i(ne,"isItStopNode"),r(ne,"isItStopNode");function Ce(R,E,L=">"){let z,k="";for(let M=E;M<R.length;M++){let re=R[M];if(z)re===z&&(z="");else if(re==='"'||re==="'")z=re;else if(re===L[0])if(L[1]){if(R[M+1]===L[1])return{data:k,index:M}}else return{data:k,index:M};else re===" "&&(re=" ");k+=re}}i(Ce,"tagExpWithClosingIndex"),r(Ce,"tagExpWithClosingIndex");function b(R,E,L,z){let k=R.indexOf(E,L);if(k===-1)throw new Error(z);return k+E.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function S(R,E,L,z=">"){let k=Ce(R,E+1,z);if(!k)return;let M=k.data,re=k.index,$=M.search(/\s/),D=M,ue=!0;$!==-1&&(D=M.substring(0,$),M=M.substring($+1).trimStart());let ie=D;if(L){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1),ue=D!==k.data.substr(Ae+1))}return{tagName:D,tagExp:M,closeIndex:re,attrExpPresent:ue,rawTagName:ie}}i(S,"readTagExp"),r(S,"readTagExp");function V(R,E,L){let z=L,k=1;for(;L<R.length;L++)if(R[L]==="<")if(R[L+1]==="/"){let M=b(R,">",L,`${E} is not closed`);if(R.substring(L+2,M).trim()===E&&(k--,k===0))return{tagContent:R.substring(z,L),i:M};L=M}else if(R[L+1]==="?")L=b(R,"?>",L+1,"StopNode is not closed.");else if(R.substr(L+1,3)==="!--")L=b(R,"-->",L+3,"StopNode is not closed.");else if(R.substr(L+1,2)==="![")L=b(R,"]]>",L,"StopNode is not closed.")-2;else{let M=S(R,L,">");M&&((M&&M.tagName)===E&&M.tagExp[M.tagExp.length-1]!=="/"&&k++,L=M.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function de(R,E,L){if(E&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:q(R,L)}else return H.isExist(R)?R:""}i(de,"parseValue"),r(de,"parseValue"),C.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function C(j,I){return H(j,I)}i(C,"prettify"),r(C,"prettify");function H(j,I,U){let G,W={};for(let v=0;v<j.length;v++){let T=j[v],Z=N(T),le="";if(U===void 0?le=Z:le=U+"."+Z,Z===I.textNodeName)G===void 0?G=T[Z]:G+=""+T[Z];else{if(Z===void 0)continue;if(T[Z]){let X=H(T[Z],I,le),ne=q(X,I);T[":@"]?B(X,T[":@"],le,I):Object.keys(X).length===1&&X[I.textNodeName]!==void 0&&!I.alwaysCreateTextNode?X=X[I.textNodeName]:Object.keys(X).length===0&&(I.alwaysCreateTextNode?X[I.textNodeName]="":X=""),W[Z]!==void 0&&W.hasOwnProperty(Z)?(Array.isArray(W[Z])||(W[Z]=[W[Z]]),W[Z].push(X)):I.isArray(Z,le,ne)?W[Z]=[X]:W[Z]=X}}}return typeof G=="string"?G.length>0&&(W[I.textNodeName]=G):G!==void 0&&(W[I.textNodeName]=G),W}i(H,"compress"),r(H,"compress");function N(j){let I=Object.keys(j);for(let U=0;U<I.length;U++){let G=I[U];if(G!==":@")return G}}i(N,"propName"),r(N,"propName");function B(j,I,U,G){if(I){let W=Object.keys(I),v=W.length;for(let T=0;T<v;T++){let Z=W[T];G.isArray(Z,U+"."+Z,!0,!0)?j[Z]=[I[Z]]:j[Z]=I[Z]}}}i(B,"assignAttributes"),r(B,"assignAttributes");function q(j,I){let{textNodeName:U}=I,G=Object.keys(j).length;return!!(G===0||G===1&&(j[U]||typeof j[U]=="boolean"||j[U]===0))}i(q,"isLeafTag"),r(q,"isLeafTag"),P.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,S){S=Object.assign({},H,S);let V=[],de=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let E=0;E<b.length;E++)if(b[E]==="<"&&b[E+1]==="?"){if(E+=2,E=B(b,E),E.err)return E}else if(b[E]==="<"){let L=E;if(E++,b[E]==="!"){E=q(b,E);continue}else{let z=!1;b[E]==="/"&&(z=!0,E++);let k="";for(;E<b.length&&b[E]!==">"&&b[E]!==" "&&b[E]!==" "&&b[E]!==`
73
73
  `&&b[E]!=="\r";E++)k+=b[E];if(k=k.trim(),k[k.length-1]==="/"&&(k=k.substring(0,k.length-1),E--),!X(k)){let $;return k.trim().length===0?$="Invalid space after '<'.":$="Tag '"+k+"' is an invalid name.",Z("InvalidTag",$,ne(b,E))}let M=U(b,E);if(M===!1)return Z("InvalidAttr","Attributes for '"+k+"' have open quote.",ne(b,E));let re=M.value;if(E=M.index,re[re.length-1]==="/"){let $=E-re.length;re=re.substring(0,re.length-1);let D=W(re,S);if(D===!0)de=!0;else return Z(D.err.code,D.err.msg,ne(b,$+D.err.line))}else if(z)if(M.tagClosed){if(re.trim().length>0)return Z("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",ne(b,L));{let $=V.pop();if(k!==$.tagName){let D=ne(b,$.tagStartPos);return Z("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+k+"'.",ne(b,L))}V.length==0&&(R=!0)}}else return Z("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",ne(b,E));else{let $=W(re,S);if($!==!0)return Z($.err.code,$.err.msg,ne(b,E-re.length+$.err.line));if(R===!0)return Z("InvalidXml","Multiple possible root nodes found.",ne(b,E));S.unpairedTags.indexOf(k)!==-1||V.push({tagName:k,tagStartPos:L}),de=!0}for(E++;E<b.length;E++)if(b[E]==="<")if(b[E+1]==="!"){E++,E=q(b,E);continue}else if(b[E+1]==="?"){if(E=B(b,++E),E.err)return E}else break;else if(b[E]==="&"){let $=T(b,E);if($==-1)return Z("InvalidChar","char '&' is not expected.",ne(b,E));E=$}else if(R===!0&&!N(b[E]))return Z("InvalidXml","Extra text at the end",ne(b,E));b[E]==="<"&&E--}}else{if(N(b[E]))continue;return Z("InvalidChar","char '"+b[E]+"' is not expected.",ne(b,E))}if(de){if(V.length==1)return Z("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",ne(b,V[0].tagStartPos));if(V.length>0)return Z("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Z("InvalidXml","Start tag expected.",1);return!0};function N(b){return b===" "||b===" "||b===`
74
74
  `||b==="\r"}i(N,"isWhiteSpace"),r(N,"isWhiteSpace");function B(b,S){let V=S;for(;S<b.length;S++)if(b[S]=="?"||b[S]==" "){let de=b.substr(V,S-V);if(S>5&&de==="xml")return Z("InvalidXml","XML declaration allowed only at the start of the document.",ne(b,S));if(b[S]=="?"&&b[S+1]==">"){S++;break}else continue}return S}i(B,"readPI"),r(B,"readPI");function q(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 V=1;for(S+=8;S<b.length;S++)if(b[S]==="<")V++;else if(b[S]===">"&&(V--,V===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}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',I="'";function U(b,S){let V="",de="",R=!1;for(;S<b.length;S++){if(b[S]===j||b[S]===I)de===""?de=b[S]:de!==b[S]||(de="");else if(b[S]===">"&&de===""){R=!0;break}V+=b[S]}return de!==""?!1:{value:V,index:S,tagClosed:R}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,S){let V=C.getAllMatches(b,G),de={};for(let R=0;R<V.length;R++){if(V[R][1].length===0)return Z("InvalidAttr","Attribute '"+V[R][2]+"' has no space in starting.",Ce(V[R]));if(V[R][3]!==void 0&&V[R][4]===void 0)return Z("InvalidAttr","Attribute '"+V[R][2]+"' is without value.",Ce(V[R]));if(V[R][3]===void 0&&!S.allowBooleanAttributes)return Z("InvalidAttr","boolean attribute '"+V[R][2]+"' is not allowed.",Ce(V[R]));let E=V[R][2];if(!le(E))return Z("InvalidAttr","Attribute '"+E+"' is an invalid name.",Ce(V[R]));if(!de.hasOwnProperty(E))de[E]=1;else return Z("InvalidAttr","Attribute '"+E+"' is repeated.",Ce(V[R]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function v(b,S){let V=/\d/;for(b[S]==="x"&&(S++,V=/[\da-fA-F]/);S<b.length;S++){if(b[S]===";")return S;if(!b[S].match(V))break}return-1}i(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function T(b,S){if(S++,b[S]===";")return-1;if(b[S]==="#")return S++,v(b,S);let V=0;for(;S<b.length;S++,V++)if(!(b[S].match(/\w/)&&V<20)){if(b[S]===";")break;return-1}return S}i(T,"validateAmpersand"),r(T,"validateAmpersand");function Z(b,S,V){return{err:{code:b,msg:S,line:V.line||V,col:V.col}}}i(Z,"getErrorObject"),r(Z,"getErrorObject");function le(b){return C.isName(b)}i(le,"validateAttrName"),r(le,"validateAttrName");function X(b){return C.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function ne(b,S){let V=b.substring(0,S).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(ne,"getLineNumberForPosition"),r(ne,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),r(Ce,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,C){var{buildOptions:H}=s(),N=d(),{prettify:B}=p(),q=h(),j=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(I){this.externalEntities={},this.options=H(I)}parse(I,U){if(typeof I!="string")if(I.toString)I=I.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let v=q.validate(I,U);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let G=new N(this.options);G.addExternalEntities(this.externalEntities);let W=G.parseXml(I);return this.options.preserveOrder||W===void 0?W:B(W,this.options)}addEntity(I,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(I.indexOf("&")!==-1||I.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[I]=U}};C.exports=j}});let A=y();return new A(n)},"getXmlParser");var Sr=class extends $e{static{i(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?bt(e.parseOnStatusCodes):void 0,this.parser=bc({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 _(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ar=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new Y(`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 _r=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new Q(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),zn().waitUntil(this.#e.waitUntilFlushed())}};var wc=10,Rc=3e4,Lr=class{static{i(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=Rc,this.#r=wc}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Rc,this.#r=wc}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 Bp(()=>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);zn().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 Bp(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)}}i(Bp,"waitUntilTrue");var ki=["sha-1","sha-256","sha-384","sha-512"],kr=class{static{i(this,"BaseCryptoBeta")}};var Nr=class extends kr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!ki.includes(e.toLowerCase()))throw new _(`Algorithm ${e} is not supported. Try using ${ki.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 Mr=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Dr=class extends Mr{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new fn("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)}};