@zuplo/runtime 5.2187.0 → 5.2188.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 +1 -1
- package/out/cjs/policies/axiomatics-authz-inbound/exports.js +1 -1
- package/out/esm/{chunk-M2WV76HS.js → chunk-LPFDZM3G.js} +2 -2
- package/out/esm/index.js +1 -1
- package/out/esm/policies/axiomatics-authz-inbound/exports.js +1 -1
- package/package.json +1 -1
- /package/out/esm/{chunk-M2WV76HS.js.LEGAL.txt → chunk-LPFDZM3G.js.LEGAL.txt} +0 -0
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(Qd,"validateComputedSignature");function ep(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(ep,"parseHeader");function tp(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(tp,"secureCompare");async function np(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]=ri[s[u]];return a.join("")}i(np,"computeHMACSignatureAsync");var ri=new Array(256);for(let n=0;n<ri.length;n++)ri[n]=n.toString(16).padStart(2,"0");var Ct=class extends fe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){oe(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 ka(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 Na(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Na,"isStripeWebhookEvent");var rp={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 L(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 L(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 L(s)}return o}},ar=rp;var oi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ma="My API Key";async function Da({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`,oi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ma,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ie({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 L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Da,"createConsumer");async function Ua({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,oi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ma,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ie({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 L(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ua,"createConsumerInvite");async function Ha({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oi);o.searchParams.set("with-api-key","true");let s=await Ie({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 L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ha,"deleteConsumer");async function Za({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 Ie({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}'.`,R,C="";try{R=await y.json(),C=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,R),new L(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Za,"createSubscription");async function At({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 Ie({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 L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(At,"updateSubscription");async function _t({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 Ie({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 L(`${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 L(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 L(c)}return u.data[0]}i(_t,"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 ur(n){return n.replaceAll("_","-")}i(ur,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ii(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 Da({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ar.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 Ua({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=ur(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 Za({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 Ha({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:se,detail:p.message})}return x.ok(n,e,{title:Qe})}i(ii,"onCustomerSubscriptionCreated");async function si(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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await At({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(si,"onCustomerSubscriptionDeleted");async function ai(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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=ur(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 At({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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ar.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 At({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 _t({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 At({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(ai,"onCustomerSubscriptionUpdated");var ui=class extends gn{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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.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(!op(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Na(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 ii(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ai(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await si(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=Fs({inboundPolicies:[new Ct({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[Re,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function op(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(op,"isMetricsRegion");var Fa=new WeakMap,qa={},cr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Fa.set(e,t)}};async function $a(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=Fa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`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=qa[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async R=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(R),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}}),qa[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i($a,"AmberfloMeteringInboundPolicy");async function lr(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(lr,"sha256");var ja=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=ja.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await lr(JSON.stringify({policyName:n,options:t}))}`,ja.set(n,r)),r}i(ge,"getPolicyCacheName");var Ba="key-metadata-cache-type";function ip(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(ip,"getKeyValue");async function dr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.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=ip(a,o);if(!u||u==="")return s("No key present");let c=await sp(u),l=await ge(r,void 0,o),d=new de(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!==Ba&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await Ie({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 L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),R={isValid:!0,typeId:Ba,user:{sub:A.name,data:A.metadata}};return n.user=R.user,d.put(c,R,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function sp(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(sp,"hashValue");var za=dr;var rn=require("jose");var Va=require("jose");var ci=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 li&&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,Va.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 di("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Lt("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 Lt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ga(n,e,t){let r=new ci(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ga,"createRemoteJWKSet");var Lt=class extends L{static{i(this,"JWKSError")}},li=class extends Lt{static{i(this,"JWKSNoMatchingKey")}},di=class extends Lt{static{i(this,"JWKSTimeout")}};var pr={},ap=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);pr[r.jwkUrl]=Ga(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,rn.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,rn.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),up=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,rn.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=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?ap(r,e):up,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 Wa=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=class{constructor(e){this.options=e;this.authHeader=`Bearer ${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 cp=[],gr=class n extends fe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:x.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of cp)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return 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)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Ds(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new L(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Ja=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(R=>R.username===h&&R.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 fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function Ka(n,e){return new Date(n,e+1,0).getDate()}i(Ka,"getDaysInMonth");function pi(n,e){return n<=e?e-n:6-n+e+1}i(pi,"getDaysBetweenWeekdays");var hr=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=Ka(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"?pi(d,p):pi(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=fr(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=fr(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}=fr(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 lp={min:0,max:59},dp={min:0,max:59},pp={min:0,max:23},mp={min:1,max:31},gp={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"}},fp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},hp={"@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 mi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=hp[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 hr({seconds:lt(t,lp),minutes:lt(r,dp),hours:lt(o,pp),days:lt(s,mp),months:new Set(Array.from(lt(a,gp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,fp)).map(c=>c%7))})}i(mi,"parseCronExpression");var yr=class extends fe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),oe(e,t).optional("problem","object"),e.problem&&oe(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=[mi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>mi(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 yp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function bp(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(bp,"digestMessage");var wp=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 bp(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 Ya(n,e,t,r){f("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await wp(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);yp.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(Ya,"CachingInboundPolicy");var Xa=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 re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Qa=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 re(n,{headers:o})},"ClearHeadersInboundPolicy");var eu=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 tu=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",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var nu=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 ye(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ru=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=be.instance,s=Wt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var ou=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=Rp(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(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 Rp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Rp,"getToken");var iu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var su=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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",au=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,R=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||R.length>0&&R.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 uu=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 lu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return gi(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 gi(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 cu(a[u])}else return a.length>0?cu(a[0]):gi(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 cu(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(cu,"generateResponse");var gi=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 Pp="Incoming",Ep={logRequestBody:!0,logResponseBody:!0};function du(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(du,"headersToObject");function pu(){return new Date().toISOString()}i(pu,"timestamp");var fi=new WeakMap,Ip={};function fu(n,e){let t=fi.get(n);t||(t=Ip);let r=Object.assign({...t},e);fi.set(n,r)}i(fu,"setMoesifContext");async function mu(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(mu,"readBody");var xp={},hi;function gu(){if(!hi)throw new L("Invalid State - no _lastLogger");return hi}i(gu,"getLastLogger");function Tp(n){let e=xp[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);gu().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||gu().error({status:o.status,body:await o.text()})})),e}i(Tp,"getDispatcher");async function hu(n,e,t,r){f("policy.inbound.moesif-analytics"),hi=e.log;let o=pu(),s=Object.assign(Ep,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await mu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tp(s.applicationId),d=n.headers.get("true-client-ip"),p=fi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:du(n.headers)},y=s.logResponseBody?await mu(u,e):void 0,A={time:pu(),status:u.status,headers:du(u.headers),body:y},R={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Pp};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(hu,"MoesifInboundPolicy");async function yu(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(yu,"loadSubscription");async function bu(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(bu,"consumeSubcriptionQuotas");var vp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function br(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(br,"validateMeters");function wu(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)vp.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(wu,"parseAllowedSubscriptionStatuses");function Ru(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(Ru,"compareMeters");var wr=class extends fe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Ft)}static setMeters(e,t){br(t,"setMeters"),he.set(e,mn,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){oe(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=he.get(t,mn),a={...this.options.meters,...s};br(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=wu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,C,H)=>{let N=he.get(H,Ft);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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=he.get(H,mn),j={...this.options.meters,...q};if(br(j,this.policyName),o.includes(R.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${R.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=Ru(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 bu(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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await yu(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`),he.set(t,Ft,p));let h=he.get(t,Ft);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(R=>!Object.keys(h.meters).includes(R));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 R of Object.keys(a))if(h.meters[R].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var Pu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Eu=require("jose");var yi,Iu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!yi)try{yi=await(0,Eu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:yi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ou=Be(Ze());var Tu=Be(Ze());var xu=(0,Tu.debug)("zuplo:policies:RateLimitInboundPolicy"),vu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Ot]=I.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=St(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,R=await ge(r,void 0,t),C=new de(R,e),H=Kn(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),xu(`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()){xu(`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 Su=(0,Ou.debug)("zuplo:policies:RateLimitInboundPolicy"),Sp="strict",bi=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Sp)==="async")return vu(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[Ot]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",R=St(r,a),H=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Kn(H,y,R,e.requestId);return N.count>h?(Su(`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;Su(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wi;function Cu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Cu,"headersToNameValuePairs");function Op(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Op,"queryToNameValueParis");function Cp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Cp,"parseIntOrUndefined");var Au={};async function _u(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return wi||(wi={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:wi,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:Cu(n.headers),queryString:Op(n.query)},response:{status:a.status,statusText:a.statusText,headers:Cu(a.headers),content:{size:Cp(n.headers.get("content-length"))}}}]}}},d=Au[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}}),Au[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(_u,"ReadmeMetricsInboundPolicy");var Lu=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 re(n,{headers:s})},"RemoveHeadersInboundPolicy");var ku=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 Nu=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 re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Mu=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 Du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Uu=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?Du():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Du():n},"RequestSizeLimitInboundPolicy");function Hu(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Hu,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function Zu(n,e){return`_${et(n)}__${et(e)}`}i(Zu,"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 Dt=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"),Ut=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=Rr(t,r,o,c.name),p=be.instance.schemaValidator[d],h=p(e[c.name]),y=Ri(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"),Ri=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 qu(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")}`,R=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 R}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=Pr(n.route.path,e.method,o),u=be.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=Ri(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(qu,"handleBodyValidation");function Fu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Dt(n),s=Ut(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(Fu,"handleHeadersValidation");function $u(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Dt(n),o=Ut(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($u,"handlePathParameterValidation");function ju(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Dt(n),o=Ut(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(ju,"handleQueryParameterValidation");var Pi=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ju(e,n,t);if(r!==void 0||(r=$u(e,n,t),r!==void 0)||(r=Fu(e,n,t),r!==void 0))return r;let o=await qu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Bu=Pi;var zu=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 Vu=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Gu=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 re(n,{headers:s})},"SetHeadersInboundPolicy");var Wu=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 Ju=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 re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ku=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 Ap=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Yu=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 Ap(t.sleepInMs),n},"SleepInboundPolicy");var Xu=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ye(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))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 L(`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 Qu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await _p(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 _p(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ie({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 L("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 L("Response returned from Azure AD is not in the expected format.")}i(_p,"getAccessToken");var ec="https://accounts.google.com/o/oauth2/token",Ei,tc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),oe(t,r).required("serviceAccountJson","string"),Ei||(Ei=await ve.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 ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ei,audience:ec,payload:o}),l=await _n(ec,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 Lp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",kp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ii,nc=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),oe(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(kp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ii||(Ii=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("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 L(`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 L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await lr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ii,audience:Lp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Ys(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("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 xi,rc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),oe(t,r).required("audience","string").required("serviceAccountJson","string"),xi||(xi=await ve.init(t.serviceAccountJson));let o=await De({serviceAccount:xi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var oc="https://www.googleapis.com/oauth2/v4/token",Ti,ic=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ti||(Ti=await ve.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 ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Ti,audience:oc,payload:o}),l=await _n(oc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("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 sc=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 ac=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((R,C)=>e(R,"name",{value:C,configurable:!0}),"__name"),o=i((R,C)=>i(function(){return C||(0,R[t(R)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){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");R.buildOptions=H,R.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"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 S=[];S.startIndex=U.lastIndex-W[0].length;let T=W.length;for(let Z=0;Z<T;Z++)S.push(W[Z]);G.push(S),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");R.isExist=function(I){return typeof I<"u"},R.isEmptyObject=function(I){return Object.keys(I).length===0},R.merge=function(I,U,G){if(U){let W=Object.keys(U),S=W.length;for(let T=0;T<S;T++)G==="strict"?I[W[T]]=[U[W[T]]]:I[W[T]]=U[W[T]]}},R.getValue=function(I){return R.isExist(I)?I:""},R.isName=j,R.getAllMatches=q,R.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,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"(R,C){var H=a();function N(S,T){let Z={};if(S[T+3]==="O"&&S[T+4]==="C"&&S[T+5]==="T"&&S[T+6]==="Y"&&S[T+7]==="P"&&S[T+8]==="E"){T=T+9;let ce=1,X=!1,te=!1,Oe="";for(;T<S.length;T++)if(S[T]==="<"&&!te){if(X&&j(S,T))T+=7,[entityName,val,T]=B(S,T+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(S,T))T+=8;else if(X&&U(S,T))T+=8;else if(X&&G(S,T))T+=9;else if(q)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Oe=""}else if(S[T]===">"){if(te?S[T-1]==="-"&&S[T-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else S[T]==="["?X=!0:Oe+=S[T];if(ce!==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(S,T){let Z="";for(;T<S.length&&S[T]!=="'"&&S[T]!=='"';T++)Z+=S[T];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[T++],X="";for(;T<S.length&&S[T]!==ce;T++)X+=S[T];return[Z,X,T]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(S,T){return S[T+1]==="!"&&S[T+2]==="-"&&S[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="N"&&S[T+4]==="T"&&S[T+5]==="I"&&S[T+6]==="T"&&S[T+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="L"&&S[T+4]==="E"&&S[T+5]==="M"&&S[T+6]==="E"&&S[T+7]==="N"&&S[T+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(S,T){return S[T+1]==="!"&&S[T+2]==="A"&&S[T+3]==="T"&&S[T+4]==="T"&&S[T+5]==="L"&&S[T+6]==="I"&&S[T+7]==="S"&&S[T+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(S,T){return S[T+1]==="!"&&S[T+2]==="N"&&S[T+3]==="O"&&S[T+4]==="T"&&S[T+5]==="A"&&S[T+6]==="T"&&S[T+7]==="I"&&S[T+8]==="O"&&S[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(S){if(H.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(R,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 S=W[1],T=W[2],Z=j(W[3]),ce=W[4]||W[6];if(!U.leadingZeros&&T.length>0&&S&&G[2]!==".")return I;if(!U.leadingZeros&&T.length>0&&!S&&G[1]!==".")return I;{let X=Number(G),te=""+X;return te.search(/[eE]/)!==-1||ce?U.eNotation?X:I:G.indexOf(".")!==-1?te==="0"&&Z===""||te===Z||S&&te==="-"+Z?X:I:T?Z===te||S+Z===te?X:I:G===te||G===S+te?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"(R,C){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,16))}},this.addExternalEntities=I,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(P){let E=Object.keys(P);for(let _=0;_<E.length;_++){let z=E[_];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:P[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(P,E,_,z,k,M,ne){if(P!==void 0&&(this.options.trimValues&&!z&&(P=P.trim()),P.length>0)){ne||(P=this.replaceEntitiesValue(P));let $=this.options.tagValueProcessor(E,P,_,k,M);return $==null?P:typeof $!=typeof P||$!==P?$:this.options.trimValues?le(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?le(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(U,"parseTextData"),r(U,"parseTextData");function G(P){if(this.options.removeNSPrefix){let E=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(P=_+E[1])}return P}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(P,E,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let z=H.getAllMatches(P,W),k=z.length,M={};for(let ne=0;ne<k;ne++){let $=this.resolveNameSpace(z[ne][1]),D=z[ne][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,E);ie==null?M[ae]=D:typeof ie!=typeof D||ie!==D?M[ae]=ie:M[ae]=le(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=M,ne}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var T=r(function(P){P=P.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(Qd,"validateComputedSignature");function ep(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(ep,"parseHeader");function tp(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(tp,"secureCompare");async function np(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]=ri[s[u]];return a.join("")}i(np,"computeHMACSignatureAsync");var ri=new Array(256);for(let n=0;n<ri.length;n++)ri[n]=n.toString(16).padStart(2,"0");var Ct=class extends fe{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),f("policy.inbound.stripe-webhook-verification")}async handler(e,t){oe(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 ka(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 Na(n){return n!==null&&typeof n=="object"&&"id"in n&&Te(n.id)&&"type"in n&&Te(n.type)}i(Na,"isStripeWebhookEvent");var rp={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 L(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 L(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 L(s)}return o}},ar=rp;var oi="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ma="My API Key";async function Da({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`,oi);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ma,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await Ie({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 L(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(Da,"createConsumer");async function Ua({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=g.instance,u=new URL(`/v1/buckets/${n}/consumers`,oi);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Ma,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Ie({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 L(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ua,"createConsumerInvite");async function Ha({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=g.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,oi);o.searchParams.set("with-api-key","true");let s=await Ie({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 L(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Ha,"deleteConsumer");async function Za({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 Ie({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}'.`,R,C="";try{R=await y.json(),C=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(A,R),new L(`${A} ${C}`)}n.log.info("Successfully created monetization subscription.",d)}i(Za,"createSubscription");async function At({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 Ie({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 L(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(At,"updateSubscription");async function _t({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 Ie({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 L(`${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 L(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 L(c)}return u.data[0]}i(_t,"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 ur(n){return n.replaceAll("_","-")}i(ur,"stripeStatusToMeteringStatus");function ct(n){return new Date(n*1e3).toISOString()}i(ct,"unixTimestampToISOString");async function ii(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 Da({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ar.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 Ua({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=ur(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 Za({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 Ha({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:se,detail:p.message})}return x.ok(n,e,{title:Qe})}i(ii,"onCustomerSubscriptionCreated");async function si(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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await At({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(si,"onCustomerSubscriptionDeleted");async function ai(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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=ur(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 At({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 _t({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await ar.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 At({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 _t({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 At({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(ai,"onCustomerSubscriptionUpdated");var ui=class extends gn{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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.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(!op(h))throw new m(`StripeMonetizationPlugin - The value '${h}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!Na(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 ii(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await ai(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:h,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await si(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=Fs({inboundPolicies:[new Ct({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});oe(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new pe({processors:[Re,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function op(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(op,"isMetricsRegion");var Fa=new WeakMap,qa={},cr=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Fa.set(e,t)}};async function $a(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=Fa.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new L(`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=qa[t.apiKey];if(!h){let y=t.apiKey,A=n.headers.get("zm-test-id")??"";h=new Q("amberflo-ingest-meter",10,async R=>{try{let C=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(C,{method:"POST",body:JSON.stringify(R),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}}),qa[y]=h}h.enqueue(p),e.waitUntil(h.waitUntilFlushed())}}),n}i($a,"AmberfloMeteringInboundPolicy");async function lr(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(lr,"sha256");var ja=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,s=ja.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await lr(JSON.stringify({policyName:n,options:t}))}`,ja.set(n,r)),r}i(ge,"getPolicyCacheName");var Ba="key-metadata-cache-type";function ip(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(ip,"getKeyValue");async function dr(n,e,t,r){if(f("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.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=ip(a,o);if(!u||u==="")return s("No key present");let c=await sp(u),l=await ge(r,void 0,o),d=new de(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!==Ba&&ee.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:u},y=await Ie({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 L(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${y.status}`)}let A=await y.json(),R={isValid:!0,typeId:Ba,user:{sub:A.name,data:A.metadata}};return n.user=R.user,d.put(c,R,o.cacheTtlSeconds),n}i(dr,"ApiKeyInboundPolicy");async function sp(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(sp,"hashValue");var za=dr;var rn=require("jose");var Va=require("jose");var ci=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 li&&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,Va.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 di("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Lt("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 Lt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ga(n,e,t){let r=new ci(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Ga,"createRemoteJWKSet");var Lt=class extends L{static{i(this,"JWKSError")}},li=class extends Lt{static{i(this,"JWKSNoMatchingKey")}},di=class extends Lt{static{i(this,"JWKSTimeout")}};var pr={},ap=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!pr[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await ge(n,void 0,r),u=new de(a,e);pr[r.jwkUrl]=Ga(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else pr[r.jwkUrl]=(0,rn.createRemoteJWKSet)(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await(0,rn.jwtVerify)(t,pr[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),up=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,rn.jwtVerify)(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=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?ap(r,e):up,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 Wa=i(async(n,e,t,r)=>(f("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var mr=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 cp=[],gr=class n extends fe{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),f("policy.inbound.axiomatics-authz"),oe(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new mr(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:x.unauthorized(e,t);let o=new URL(e.url),s=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};s.Request.AccessSubject?s.Request.AccessSubject.push(a):s.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),s.Request.Action?s.Request.Action.push(a):s.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,request:e,context:t});for(let a of cp)s=await a(e,t,s);try{let a=await this.pdpService.makePdpRequest(s);return 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)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:s}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Ds(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new L(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):s.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Ja=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(R=>R.username===h&&R.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 fr(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i(fr,"extractDateElements");function Ka(n,e){return new Date(n,e+1,0).getDate()}i(Ka,"getDaysInMonth");function pi(n,e){return n<=e?e-n:6-n+e+1}i(pi,"getDaysBetweenWeekdays");var hr=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=Ka(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"?pi(d,p):pi(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=fr(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=fr(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}=fr(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 lp={min:0,max:59},dp={min:0,max:59},pp={min:0,max:23},mp={min:1,max:31},gp={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"}},fp={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},hp={"@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 mi(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=hp[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 hr({seconds:lt(t,lp),minutes:lt(r,dp),hours:lt(o,pp),days:lt(s,mp),months:new Set(Array.from(lt(a,gp)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,fp)).map(c=>c%7))})}i(mi,"parseCronExpression");var yr=class extends fe{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),f("policy.inbound.brownout"),oe(e,t).optional("problem","object"),e.problem&&oe(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=[mi(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>mi(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 yp=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function bp(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(bp,"digestMessage");var wp=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 bp(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 Ya(n,e,t,r){f("policy.inbound.caching");let o=await ge(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await wp(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);yp.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(Ya,"CachingInboundPolicy");var Xa=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 re(n,{method:t.method})},"ChangeMethodInboundPolicy");var Qa=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 re(n,{headers:o})},"ClearHeadersInboundPolicy");var eu=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 tu=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",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var nu=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 ye(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var ru=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=be.instance,s=Wt(t.policies,o?.routeData.policies);return Po(s)(n,e)},"CompositeInboundPolicy");var ou=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=Rp(o);if(!s)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),u=new de(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 Rp(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(Rp,"getToken");var iu=i(async(n,e,t,r)=>(f("policy.inbound.firebase-jwt-auth"),oe(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var su=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 re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var kt="__unknown__",au=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,R=o.block.regionCodes,C=o.block.asns;return A.length>0&&A.includes(s)&&!c||R.length>0&&R.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 uu=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 lu=i(async(n,e,t,r)=>{f("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return gi(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 gi(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 cu(a[u])}else return a.length>0?cu(a[0]):gi(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 cu(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(cu,"generateResponse");var gi=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 Pp="Incoming",Ep={logRequestBody:!0,logResponseBody:!0};function du(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(du,"headersToObject");function pu(){return new Date().toISOString()}i(pu,"timestamp");var fi=new WeakMap,Ip={};function fu(n,e){let t=fi.get(n);t||(t=Ip);let r=Object.assign({...t},e);fi.set(n,r)}i(fu,"setMoesifContext");async function mu(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(mu,"readBody");var xp={},hi;function gu(){if(!hi)throw new L("Invalid State - no _lastLogger");return hi}i(gu,"getLastLogger");function Tp(n){let e=xp[n];return e||(e=new Q("moesif-inbound",100,async t=>{let r=JSON.stringify(t);gu().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||gu().error({status:o.status,body:await o.text()})})),e}i(Tp,"getDispatcher");async function hu(n,e,t,r){f("policy.inbound.moesif-analytics"),hi=e.log;let o=pu(),s=Object.assign(Ep,t);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await mu(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Tp(s.applicationId),d=n.headers.get("true-client-ip"),p=fi.get(e)??{},h={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:du(n.headers)},y=s.logResponseBody?await mu(u,e):void 0,A={time:pu(),status:u.status,headers:du(u.headers),body:y},R={request:h,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Pp};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(hu,"MoesifInboundPolicy");async function yu(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(yu,"loadSubscription");async function bu(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(bu,"consumeSubcriptionQuotas");var vp=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function br(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(br,"validateMeters");function wu(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)vp.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(wu,"parseAllowedSubscriptionStatuses");function Ru(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(Ru,"compareMeters");var wr=class extends fe{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,Ft)}static setMeters(e,t){br(t,"setMeters"),he.set(e,mn,t)}constructor(e,t){super(e,t),f("policy.inbound.monetization")}async handler(e,t){oe(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=he.get(t,mn),a={...this.options.meters,...s};br(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=wu(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,C,H)=>{let N=he.get(H,Ft);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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let q=he.get(H,mn),j={...this.options.meters,...q};if(br(j,this.policyName),o.includes(R.status)&&N&&j){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${N.id}' with meters '${JSON.stringify(j)} on response status '${R.status}'`);let{metersInSubscription:I,metersNotInSubscription:U}=Ru(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 bu(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(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await yu(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`),he.set(t,Ft,p));let h=he.get(t,Ft);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(R=>!Object.keys(h.meters).includes(R));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 R of Object.keys(a))if(h.meters[R].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};var Pu=i(async(n,e,t,r)=>(f("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var Eu=require("jose");var yi,Iu=i(async(n,e,t,r)=>{if(f("policy.inbound.propel-auth-jwt-auth"),!yi)try{yi=await(0,Eu.importSPKI)(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:yi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Ou=Be(Ze());var Tu=Be(Ze());var xu=(0,Tu.debug)("zuplo:policies:RateLimitInboundPolicy"),vu=i(async(n,e,t,r)=>{let o=ee.getLogger(e),s=i((j,I)=>{let U={};return(!j||j==="retry-after")&&(U[Ot]=I.toString()),x.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await vt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",h=St(r,o),A=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${c}`,R=await ge(r,void 0,t),C=new de(R,e),H=Kn(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),xu(`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()){xu(`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 Su=(0,Ou.debug)("zuplo:policies:RateLimitInboundPolicy"),Sp="strict",bi=i(async(n,e,t,r)=>{if(f("policy.inbound.rate-limit"),(t.mode??Sp)==="async")return vu(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[Ot]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await vt(r,t)(n,e,r),p=d.key,h=d.requestsAllowed??t.requestsAllowed,y=d.timeWindowMinutes??t.timeWindowMinutes,A=t.headerMode??"retry-after",R=St(r,a),H=`rate-limit${g.instance.isTestMode?g.instance.build.BUILD_ID:""}/${r}/${p}`,N=await Kn(H,y,R,e.requestId);return N.count>h?(Su(`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;Su(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wi;function Cu(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Cu,"headersToNameValuePairs");function Op(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Op,"queryToNameValueParis");function Cp(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Cp,"parseIntOrUndefined");var Au={};async function _u(n,e,t,r){f("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return wi||(wi={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:wi,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:Cu(n.headers),queryString:Op(n.query)},response:{status:a.status,statusText:a.statusText,headers:Cu(a.headers),content:{size:Cp(n.headers.get("content-length"))}}}]}}},d=Au[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}}),Au[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(_u,"ReadmeMetricsInboundPolicy");var Lu=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 re(n,{headers:s})},"RemoveHeadersInboundPolicy");var ku=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 Nu=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 re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Mu=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 Du=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Uu=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?Du():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Du():n},"RequestSizeLimitInboundPolicy");function Hu(n,e,t){return`_${et(n+"_"+e+"_"+t)}`}i(Hu,"getRawOperationDataIdentifierName");function Rr(n,e,t,r){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+"_"+t.toLowerCase()+`_${r.toLowerCase()}`}i(Rr,"getIdForParameterSchema");function Pr(n,e,t){return`_${et(n.toLowerCase())}_`+e.toLowerCase()+`_rb_${et(t.toLowerCase())}`}i(Pr,"getIdForRequestBodySchema");function Zu(n,e){return`_${et(n)}__${et(e)}`}i(Zu,"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 Dt=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"),Ut=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=Rr(t,r,o,c.name),p=be.instance.schemaValidator[d],h=p(e[c.name]),y=Ri(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"),Ri=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 qu(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")}`,R=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 R}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=Pr(n.route.path,e.method,o),u=be.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=Ri(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(qu,"handleBodyValidation");function Fu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Dt(n),s=Ut(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(Fu,"handleHeadersValidation");function $u(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Dt(n),o=Ut(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($u,"handlePathParameterValidation");function ju(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Dt(n),o=Ut(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(ju,"handleQueryParameterValidation");var Pi=i(async(n,e,t)=>{f("policy.inbound.request-validation");let r=ju(e,n,t);if(r!==void 0||(r=$u(e,n,t),r!==void 0)||(r=Fu(e,n,t),r!==void 0))return r;let o=await qu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Bu=Pi;var zu=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 Vu=i(async(n,e,t)=>(f("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Gu=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 re(n,{headers:s})},"SetHeadersInboundPolicy");var Wu=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 Ju=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 re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Ku=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 Ap=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Yu=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 Ap(t.sleepInMs),n},"SleepInboundPolicy");var Xu=i(async(n,e,t,r)=>{f("policy.inbound.supabase-jwt-auth"),oe(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await ye(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))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 L(`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 Qu=i(async(n,e,t,r)=>{f("policy.inbound.upstream-azure-ad-service-auth"),oe(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),s=new de(o,e),a=await s.get(r);if(!a){let u=await _p(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 _p(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Ie({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 L("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 L("Response returned from Azure AD is not in the expected format.")}i(_p,"getAccessToken");var ec="https://accounts.google.com/o/oauth2/token",Ei,tc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-firebase-admin-auth"),oe(t,r).required("serviceAccountJson","string"),Ei||(Ei=await ve.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 ge(r,void 0,t),a=new de(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:Ei,audience:ec,payload:o}),l=await _n(ec,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new L("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 Lp="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",kp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ii,nc=i(async(n,e,t,r)=>{if(f("policy.inbound.upstream-firebase-user-auth"),oe(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(kp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ii||(Ii=await ve.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new L("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 L(`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 L(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),u=new de(a,e),c={uid:s,claims:o},l=await lr(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:Ii,audience:Lp,payload:c}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Ys(h,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new L("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 xi,rc=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-jwt"),oe(t,r).required("audience","string").required("serviceAccountJson","string"),xi||(xi=await ve.init(t.serviceAccountJson));let o=await De({serviceAccount:xi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var oc="https://www.googleapis.com/oauth2/v4/token",Ti,ic=i(async(n,e,t,r)=>{f("policy.inbound.upstream-gcp-service-auth"),oe(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ti||(Ti=await ve.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 ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new dt(s):a=new de(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Ti,audience:oc,payload:o}),l=await _n(oc,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new L("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new L("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 sc=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 ac=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((R,C)=>e(R,"name",{value:C,configurable:!0}),"__name"),o=i((R,C)=>i(function(){return C||(0,R[t(R)[0]])((C={exports:{}}).exports,C),C.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){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");R.buildOptions=H,R.defaultOptions=C}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"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 S=[];S.startIndex=U.lastIndex-W[0].length;let T=W.length;for(let Z=0;Z<T;Z++)S.push(W[Z]);G.push(S),W=U.exec(I)}return G},"getAllMatches"),j=r(function(I){let U=B.exec(I);return!(U===null||typeof U>"u")},"isName");R.isExist=function(I){return typeof I<"u"},R.isEmptyObject=function(I){return Object.keys(I).length===0},R.merge=function(I,U,G){if(U){let W=Object.keys(U),S=W.length;for(let T=0;T<S;T++)G==="strict"?I[W[T]]=[U[W[T]]]:I[W[T]]=U[W[T]]}},R.getValue=function(I){return R.isExist(I)?I:""},R.isName=j,R.getAllMatches=q,R.nameRegexp=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,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"(R,C){var H=a();function N(S,T){let Z={};if(S[T+3]==="O"&&S[T+4]==="C"&&S[T+5]==="T"&&S[T+6]==="Y"&&S[T+7]==="P"&&S[T+8]==="E"){T=T+9;let ce=1,X=!1,te=!1,Oe="";for(;T<S.length;T++)if(S[T]==="<"&&!te){if(X&&j(S,T))T+=7,[entityName,val,T]=B(S,T+1),val.indexOf("&")===-1&&(Z[W(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(X&&I(S,T))T+=8;else if(X&&U(S,T))T+=8;else if(X&&G(S,T))T+=9;else if(q)te=!0;else throw new Error("Invalid DOCTYPE");ce++,Oe=""}else if(S[T]===">"){if(te?S[T-1]==="-"&&S[T-2]==="-"&&(te=!1,ce--):ce--,ce===0)break}else S[T]==="["?X=!0:Oe+=S[T];if(ce!==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(S,T){let Z="";for(;T<S.length&&S[T]!=="'"&&S[T]!=='"';T++)Z+=S[T];if(Z=Z.trim(),Z.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ce=S[T++],X="";for(;T<S.length&&S[T]!==ce;T++)X+=S[T];return[Z,X,T]}i(B,"readEntityExp"),r(B,"readEntityExp");function q(S,T){return S[T+1]==="!"&&S[T+2]==="-"&&S[T+3]==="-"}i(q,"isComment"),r(q,"isComment");function j(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="N"&&S[T+4]==="T"&&S[T+5]==="I"&&S[T+6]==="T"&&S[T+7]==="Y"}i(j,"isEntity"),r(j,"isEntity");function I(S,T){return S[T+1]==="!"&&S[T+2]==="E"&&S[T+3]==="L"&&S[T+4]==="E"&&S[T+5]==="M"&&S[T+6]==="E"&&S[T+7]==="N"&&S[T+8]==="T"}i(I,"isElement"),r(I,"isElement");function U(S,T){return S[T+1]==="!"&&S[T+2]==="A"&&S[T+3]==="T"&&S[T+4]==="T"&&S[T+5]==="L"&&S[T+6]==="I"&&S[T+7]==="S"&&S[T+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function G(S,T){return S[T+1]==="!"&&S[T+2]==="N"&&S[T+3]==="O"&&S[T+4]==="T"&&S[T+5]==="A"&&S[T+6]==="T"&&S[T+7]==="I"&&S[T+8]==="O"&&S[T+9]==="N"}i(G,"isNotation"),r(G,"isNotation");function W(S){if(H.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}i(W,"validateEntityName"),r(W,"validateEntityName"),C.exports=N}}),l=o({"../../node_modules/strnum/strnum.js"(R,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 S=W[1],T=W[2],Z=j(W[3]),ce=W[4]||W[6];if(!U.leadingZeros&&T.length>0&&S&&G[2]!==".")return I;if(!U.leadingZeros&&T.length>0&&!S&&G[1]!==".")return I;{let X=Number(G),te=""+X;return te.search(/[eE]/)!==-1||ce?U.eNotation?X:I:G.indexOf(".")!==-1?te==="0"&&Z===""||te===Z||S&&te==="-"+Z?X:I:T?Z===te||S+Z===te?X:I:G===te||G===S+te?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"(R,C){"use strict";var H=a(),N=u(),B=c(),q=l(),j=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,_)=>String.fromCharCode(Number.parseInt(_,16))}},this.addExternalEntities=I,this.parseXml=T,this.parseTextData=U,this.resolveNameSpace=G,this.buildAttributesMap=S,this.isItStopNode=te,this.replaceEntitiesValue=ce,this.readStopNodeData=V,this.saveTextToParentTag=X,this.addChild=Z}};function I(P){let E=Object.keys(P);for(let _=0;_<E.length;_++){let z=E[_];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:P[z]}}}i(I,"addExternalEntities"),r(I,"addExternalEntities");function U(P,E,_,z,k,M,ne){if(P!==void 0&&(this.options.trimValues&&!z&&(P=P.trim()),P.length>0)){ne||(P=this.replaceEntitiesValue(P));let $=this.options.tagValueProcessor(E,P,_,k,M);return $==null?P:typeof $!=typeof P||$!==P?$:this.options.trimValues?le(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?le(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(U,"parseTextData"),r(U,"parseTextData");function G(P){if(this.options.removeNSPrefix){let E=P.split(":"),_=P.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(P=_+E[1])}return P}i(G,"resolveNameSpace"),r(G,"resolveNameSpace");var W=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(P,E,_){if(!this.options.ignoreAttributes&&typeof P=="string"){let z=H.getAllMatches(P,W),k=z.length,M={};for(let ne=0;ne<k;ne++){let $=this.resolveNameSpace(z[ne][1]),D=z[ne][4],ae=this.options.attributeNamePrefix+$;if($.length)if(this.options.transformAttributeName&&(ae=this.options.transformAttributeName(ae)),ae==="__proto__"&&(ae="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ie=this.options.attributeValueProcessor($,D,E);ie==null?M[ae]=D:typeof ie!=typeof D||ie!==D?M[ae]=ie:M[ae]=le(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(M[ae]=!0)}if(!Object.keys(M).length)return;if(this.options.attributesGroupName){let ne={};return ne[this.options.attributesGroupName]=M,ne}return M}}i(S,"buildAttributesMap"),r(S,"buildAttributesMap");var T=r(function(P){P=P.replace(/\r\n?/g,`
|
|
72
72
|
`);let E=new N("!xml"),_=E,z="",k="";for(let M=0;M<P.length;M++)if(P[M]==="<")if(P[M+1]==="/"){let $=b(P,">",M,"Closing Tag is not closed."),D=P.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)),_&&(z=this.saveTextToParentTag(z,_,k));let ae=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;ae&&this.options.unpairedTags.indexOf(ae)!==-1?(ie=k.lastIndexOf(".",k.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=k.lastIndexOf("."),k=k.substring(0,ie),_=this.tagsNodeStack.pop(),z="",M=$}else if(P[M+1]==="?"){let $=O(P,M,!1,"?>");if(!$)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,_,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(_,D,k)}M=$.closeIndex+1}else if(P.substr(M+1,3)==="!--"){let $=b(P,"-->",M+4,"Comment is not closed.");if(this.options.commentPropName){let D=P.substring(M+4,$-2);z=this.saveTextToParentTag(z,_,k),_.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}M=$}else if(P.substr(M+1,2)==="!D"){let $=B(P,M);this.docTypeEntities=$.entities,M=$.i}else if(P.substr(M+1,2)==="!["){let $=b(P,"]]>",M,"CDATA is not closed.")-2,D=P.substring(M+9,$);z=this.saveTextToParentTag(z,_,k);let ae=this.parseTextData(D,_.tagname,k,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?_.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):_.add(this.options.textNodeName,ae),M=$+2}else{let $=O(P,M,this.options.removeNSPrefix),D=$.tagName,ae=$.rawTagName,ie=$.tagExp,Ae=$.attrExpPresent,Si=$.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),_&&z&&_.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,_,k,!1));let Oi=_;if(Oi&&this.options.unpairedTags.indexOf(Oi.tagname)!==-1&&(_=this.tagsNodeStack.pop(),k=k.substring(0,k.lastIndexOf("."))),D!==E.tagname&&(k+=k?"."+D:D),this.isItStopNode(this.options.stopNodes,k,D)){let Ce="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)M=$.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)M=$.closeIndex;else{let _r=this.readStopNodeData(P,ae,Si+1);if(!_r)throw new Error(`Unexpected end of ${ae}`);M=_r.i,Ce=_r.tagContent}let Ar=new N(D);D!==ie&&Ae&&(Ar[":@"]=this.buildAttributesMap(ie,k,D)),Ce&&(Ce=this.parseTextData(Ce,D,k,!0,Ae,!0,!0)),k=k.substr(0,k.lastIndexOf(".")),Ar.add(this.options.textNodeName,Ce),this.addChild(_,Ar,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 Ce=new N(D);D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(_,Ce,k),k=k.substr(0,k.lastIndexOf("."))}else{let Ce=new N(D);this.tagsNodeStack.push(_),D!==ie&&Ae&&(Ce[":@"]=this.buildAttributesMap(ie,k,D)),this.addChild(_,Ce,k),_=Ce}z="",M=Si}}else z+=P[M];return E.child},"parseXml");function Z(P,E,_){let z=this.options.updateTag(E.tagname,_,E[":@"]);z===!1||(typeof z=="string"&&(E.tagname=z),P.addChild(E))}i(Z,"addChild"),r(Z,"addChild");var ce=r(function(P){if(this.options.processEntities){for(let E in this.docTypeEntities){let _=this.docTypeEntities[E];P=P.replace(_.regx,_.val)}for(let E in this.lastEntities){let _=this.lastEntities[E];P=P.replace(_.regex,_.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let _=this.htmlEntities[E];P=P.replace(_.regex,_.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function X(P,E,_,z){return P&&(z===void 0&&(z=Object.keys(E.child).length===0),P=this.parseTextData(P,E.tagname,_,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,z),P!==void 0&&P!==""&&E.add(this.options.textNodeName,P),P=""),P}i(X,"saveTextToParentTag"),r(X,"saveTextToParentTag");function te(P,E,_){let z="*."+_;for(let k in P){let M=P[k];if(z===M||E===M)return!0}return!1}i(te,"isItStopNode"),r(te,"isItStopNode");function Oe(P,E,_=">"){let z,k="";for(let M=E;M<P.length;M++){let ne=P[M];if(z)ne===z&&(z="");else if(ne==='"'||ne==="'")z=ne;else if(ne===_[0])if(_[1]){if(P[M+1]===_[1])return{data:k,index:M}}else return{data:k,index:M};else ne===" "&&(ne=" ");k+=ne}}i(Oe,"tagExpWithClosingIndex"),r(Oe,"tagExpWithClosingIndex");function b(P,E,_,z){let k=P.indexOf(E,_);if(k===-1)throw new Error(z);return k+E.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(P,E,_,z=">"){let k=Oe(P,E+1,z);if(!k)return;let M=k.data,ne=k.index,$=M.search(/\s/),D=M,ae=!0;$!==-1&&(D=M.substring(0,$),M=M.substring($+1).trimStart());let ie=D;if(_){let Ae=D.indexOf(":");Ae!==-1&&(D=D.substr(Ae+1),ae=D!==k.data.substr(Ae+1))}return{tagName:D,tagExp:M,closeIndex:ne,attrExpPresent:ae,rawTagName:ie}}i(O,"readTagExp"),r(O,"readTagExp");function V(P,E,_){let z=_,k=1;for(;_<P.length;_++)if(P[_]==="<")if(P[_+1]==="/"){let M=b(P,">",_,`${E} is not closed`);if(P.substring(_+2,M).trim()===E&&(k--,k===0))return{tagContent:P.substring(z,_),i:M};_=M}else if(P[_+1]==="?")_=b(P,"?>",_+1,"StopNode is not closed.");else if(P.substr(_+1,3)==="!--")_=b(P,"-->",_+3,"StopNode is not closed.");else if(P.substr(_+1,2)==="![")_=b(P,"]]>",_,"StopNode is not closed.")-2;else{let M=O(P,_,">");M&&((M&&M.tagName)===E&&M.tagExp[M.tagExp.length-1]!=="/"&&k++,_=M.closeIndex)}}i(V,"readStopNodeData"),r(V,"readStopNodeData");function le(P,E,_){if(E&&typeof P=="string"){let z=P.trim();return z==="true"?!0:z==="false"?!1:q(P,_)}else return H.isExist(P)?P:""}i(le,"parseValue"),r(le,"parseValue"),C.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"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 S=0;S<j.length;S++){let T=j[S],Z=N(T),ce="";if(U===void 0?ce=Z:ce=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,ce),te=q(X,I);T[":@"]?B(X,T[":@"],ce,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,ce,te)?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),S=W.length;for(let T=0;T<S;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"),R.prettify=C}}),h=o({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var C=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},H,O);let V=[],le=!1,P=!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 _=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",$,te(b,E))}let M=U(b,E);if(M===!1)return Z("InvalidAttr","Attributes for '"+k+"' have open quote.",te(b,E));let ne=M.value;if(E=M.index,ne[ne.length-1]==="/"){let $=E-ne.length;ne=ne.substring(0,ne.length-1);let D=W(ne,O);if(D===!0)le=!0;else return Z(D.err.code,D.err.msg,te(b,$+D.err.line))}else if(z)if(M.tagClosed){if(ne.trim().length>0)return Z("InvalidTag","Closing tag '"+k+"' can't have attributes or invalid starting.",te(b,_));{let $=V.pop();if(k!==$.tagName){let D=te(b,$.tagStartPos);return Z("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+k+"'.",te(b,_))}V.length==0&&(P=!0)}}else return Z("InvalidTag","Closing tag '"+k+"' doesn't have proper closing.",te(b,E));else{let $=W(ne,O);if($!==!0)return Z($.err.code,$.err.msg,te(b,E-ne.length+$.err.line));if(P===!0)return Z("InvalidXml","Multiple possible root nodes found.",te(b,E));O.unpairedTags.indexOf(k)!==-1||V.push({tagName:k,tagStartPos:_}),le=!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.",te(b,E));E=$}else if(P===!0&&!N(b[E]))return Z("InvalidXml","Extra text at the end",te(b,E));b[E]==="<"&&E--}}else{if(N(b[E]))continue;return Z("InvalidChar","char '"+b[E]+"' is not expected.",te(b,E))}if(le){if(V.length==1)return Z("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",te(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,O){let V=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let le=b.substr(V,O-V);if(O>5&&le==="xml")return Z("InvalidXml","XML declaration allowed only at the start of the document.",te(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(B,"readPI"),r(B,"readPI");function q(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let V=1;for(O+=8;O<b.length;O++)if(b[O]==="<")V++;else if(b[O]===">"&&(V--,V===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(q,"readCommentAndCDATA"),r(q,"readCommentAndCDATA");var j='"',I="'";function U(b,O){let V="",le="",P=!1;for(;O<b.length;O++){if(b[O]===j||b[O]===I)le===""?le=b[O]:le!==b[O]||(le="");else if(b[O]===">"&&le===""){P=!0;break}V+=b[O]}return le!==""?!1:{value:V,index:O,tagClosed:P}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var G=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function W(b,O){let V=C.getAllMatches(b,G),le={};for(let P=0;P<V.length;P++){if(V[P][1].length===0)return Z("InvalidAttr","Attribute '"+V[P][2]+"' has no space in starting.",Oe(V[P]));if(V[P][3]!==void 0&&V[P][4]===void 0)return Z("InvalidAttr","Attribute '"+V[P][2]+"' is without value.",Oe(V[P]));if(V[P][3]===void 0&&!O.allowBooleanAttributes)return Z("InvalidAttr","boolean attribute '"+V[P][2]+"' is not allowed.",Oe(V[P]));let E=V[P][2];if(!ce(E))return Z("InvalidAttr","Attribute '"+E+"' is an invalid name.",Oe(V[P]));if(!le.hasOwnProperty(E))le[E]=1;else return Z("InvalidAttr","Attribute '"+E+"' is repeated.",Oe(V[P]))}return!0}i(W,"validateAttributeString"),r(W,"validateAttributeString");function S(b,O){let V=/\d/;for(b[O]==="x"&&(O++,V=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(V))break}return-1}i(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function T(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,S(b,O);let V=0;for(;O<b.length;O++,V++)if(!(b[O].match(/\w/)&&V<20)){if(b[O]===";")break;return-1}return O}i(T,"validateAmpersand"),r(T,"validateAmpersand");function Z(b,O,V){return{err:{code:b,msg:O,line:V.line||V,col:V.col}}}i(Z,"getErrorObject"),r(Z,"getErrorObject");function ce(b){return C.isName(b)}i(ce,"validateAttrName"),r(ce,"validateAttrName");function X(b){return C.isName(b)}i(X,"validateTagName"),r(X,"validateTagName");function te(b,O){let V=b.substring(0,O).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}i(te,"getLineNumberForPosition"),r(te,"getLineNumberForPosition");function Oe(b){return b.startIndex+b[1].length}i(Oe,"getPositionFromMatch"),r(Oe,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,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 S=q.validate(I,U);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.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 '
'");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 Er=class extends $e{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),f("policy.outbound.xml-to-json"),oe(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=ac({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 L(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 Ir=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 xr=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),Fn().waitUntil(this.#e.waitUntilFlushed())}};var uc=10,cc=3e4,Tr=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=cc,this.#r=uc}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:cc,this.#r=uc}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 Np(()=>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);Fn().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 Np(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(Np,"waitUntilTrue");var vi=["sha-1","sha-256","sha-384","sha-512"],vr=class{static{i(this,"BaseCryptoBeta")}};var Sr=class extends vr{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(!vi.includes(e.toLowerCase()))throw new L(`Algorithm ${e} is not supported. Try using ${vi.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 Or=class{constructor(e){this.context=e}static{i(this,"BaseKeyValueStore")}};var Cr=class extends Or{static{i(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=g.instance.runtime.ZUPLO_KV;if(!t)throw new dn("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)}};
|
|
@@ -32,5 +32,5 @@
|
|
|
32
32
|
`))):a=e.stylize("[Circular]","special")),ee(o)){if(g&&s.match(/^\d+$/))return a;o=JSON.stringify(""+s),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}n(z,"formatProperty");function yt(e,t){if(ee(t))return e.stylize("undefined","undefined");if(te(t)){let i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(bt(t))return e.stylize(""+t,"number");if(pt(t))return e.stylize(""+t,"boolean");if(ne(t))return e.stylize("null","null")}n(yt,"formatPrimitive");function Ot(e,t,i){let u=0;return e.reduce(function(g,o){return u++,o.indexOf(`
|
|
33
33
|
`)>=0&&u++,g+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?i[0]+(t===""?"":t+`
|
|
34
34
|
`)+" "+e.join(`,
|
|
35
|
-
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}n(Ot,"reduceToSingleString")});var oe=R(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.format=void 0;var Rt=K(),Lt=ie(),Tt=n((e,...t)=>(0,Rt.format)(Lt.inspect,e,t),"format");C.format=Tt});var ue=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var Pt=X(),wt=oe(),N=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,Pt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let s=Date.now()-(this.last||Date.now());i=(0,wt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${s}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=N;var S=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function se(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(se,"extract");var L;function Ct(e){e||(e=[]),typeof e=="string"&&(e=se(e)),L=new S(e)}n(Ct,"withoutEnv");m.withoutEnv=Ct;function Nt(e){let t=globalThis.DEBUG;L||(L=new S(se(t)));let i=new N(L,e);return L.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}n(Nt,"debug");m.debug=Nt});var Mt={};ye(Mt,{PdpService:()=>$});module.exports=Re(Mt);var ge=Oe(ue());var E=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};var Z="2024-03-14",ce=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function le(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Z,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:ce[Z]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(le,"getMockEnvironment");var b=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=le()),this.#e}constructor({build:t,runtime:i}){let u;try{if(i.__ZUPLO_CONFIG){let s=atob(i.__ZUPLO_CONFIG);u=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=u??{},this.build=t,this.runtime=i,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var y=(0,ge.debug)("zuplo:runtime:external-service");function St(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}n(St,"getServiceAuth");async function fe(e,t){let i=St();if(i)if(y(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let a;if(i.customServiceMapping&&i.customServiceMapping[s])a=`https://${i.customServiceMapping[s]}`;else if(b.instance.useLegacyServiceRouting)a=`https://${s}.zuptunnel.com`;else{y("Using sha256 service routing");let d=b.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)a=`https://${await At(s,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw y("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}let f=new URL(`${a}${u.pathname}${u.search}`);y(`Calling external service: ${f.toString()}`);let h=await A.fetch(f.toString(),g);if(h.status===403&&h.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:a}),new E("Could not connect to secure tunnel.");return h}else throw y("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw y("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}n(fe,"externalServiceHandler");async function At(e,t,i,u){let s=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),a=It(u);y(`Hashing service name: ${g}-${s}.${g}-${o}-${a}`);let f=await ae(`${g}-${s}`),h=await ae(`${g}-${o}-${a}`);return`${f}.${h}`}n(At,"hashServiceName");async function ae(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(ae,"hashSegment");function It(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(It,"sanitizeEnvironmentType");var he=new Map;he.set("service:",fe);var de=globalThis.fetch;function D(e,t){let i=Ut(t);if(typeof e=="string"){let u=new URL(e),s=he.get(u.protocol);return s?s(e,i):de(e,i)}else return de(e,i)}n(D,"internalFetch");globalThis.fetch=D;var Ut=n(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var vt={fetch:D},A=vt;var $=class{constructor(t){this.options=t;this.authHeader=`
|
|
35
|
+
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}n(Ot,"reduceToSingleString")});var oe=R(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.format=void 0;var Rt=K(),Lt=ie(),Tt=n((e,...t)=>(0,Rt.format)(Lt.inspect,e,t),"format");C.format=Tt});var ue=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var Pt=X(),wt=oe(),N=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,Pt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let s=Date.now()-(this.last||Date.now());i=(0,wt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${s}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=N;var S=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function se(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(se,"extract");var L;function Ct(e){e||(e=[]),typeof e=="string"&&(e=se(e)),L=new S(e)}n(Ct,"withoutEnv");m.withoutEnv=Ct;function Nt(e){let t=globalThis.DEBUG;L||(L=new S(se(t)));let i=new N(L,e);return L.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}n(Nt,"debug");m.debug=Nt});var Mt={};ye(Mt,{PdpService:()=>$});module.exports=Re(Mt);var ge=Oe(ue());var E=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};var Z="2024-03-14",ce=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function le(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Z,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,COMPATIBILITY_FLAGS:ce[Z]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(le,"getMockEnvironment");var b=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=le()),this.#e}constructor({build:t,runtime:i}){let u;try{if(i.__ZUPLO_CONFIG){let s=atob(i.__ZUPLO_CONFIG);u=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=u??{},this.build=t,this.runtime=i,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var y=(0,ge.debug)("zuplo:runtime:external-service");function St(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}n(St,"getServiceAuth");async function fe(e,t){let i=St();if(i)if(y(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let a;if(i.customServiceMapping&&i.customServiceMapping[s])a=`https://${i.customServiceMapping[s]}`;else if(b.instance.useLegacyServiceRouting)a=`https://${s}.zuptunnel.com`;else{y("Using sha256 service routing");let d=b.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)a=`https://${await At(s,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw y("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}let f=new URL(`${a}${u.pathname}${u.search}`);y(`Calling external service: ${f.toString()}`);let h=await A.fetch(f.toString(),g);if(h.status===403&&h.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:a}),new E("Could not connect to secure tunnel.");return h}else throw y("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw y("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}n(fe,"externalServiceHandler");async function At(e,t,i,u){let s=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),a=It(u);y(`Hashing service name: ${g}-${s}.${g}-${o}-${a}`);let f=await ae(`${g}-${s}`),h=await ae(`${g}-${o}-${a}`);return`${f}.${h}`}n(At,"hashServiceName");async function ae(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(ae,"hashSegment");function It(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(It,"sanitizeEnvironmentType");var he=new Map;he.set("service:",fe);var de=globalThis.fetch;function D(e,t){let i=Ut(t);if(typeof e=="string"){let u=new URL(e),s=he.get(u.protocol);return s?s(e,i):de(e,i)}else return de(e,i)}n(D,"internalFetch");globalThis.fetch=D;var Ut=n(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var vt={fetch:D},A=vt;var $=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{n(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let i=await A.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!i.ok)throw new Error(`Request to PDP service failed with response status ${i.status}.`);return await i.json()}};
|
|
36
36
|
/*! For license information please see exports.js.LEGAL.txt */
|
|
@@ -32,5 +32,5 @@ import{a as E}from"./chunk-4NFZOV2A.js";import{a as r,b as R,c as he}from"./chun
|
|
|
32
32
|
`))):l=e.stylize("[Circular]","special")),Q(o)){if(g&&a.match(/^\d+$/))return l;o=JSON.stringify(""+a),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+l}r(j,"formatProperty");function gt(e,t){if(Q(t))return e.stylize("undefined","undefined");if(ee(t)){let i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(ut(t))return e.stylize(""+t,"number");if(st(t))return e.stylize(""+t,"boolean");if(te(t))return e.stylize("null","null")}r(gt,"formatPrimitive");function ft(e,t,i){let u=0;return e.reduce(function(g,o){return u++,o.indexOf(`
|
|
33
33
|
`)>=0&&u++,g+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?i[0]+(t===""?"":t+`
|
|
34
34
|
`)+" "+e.join(`,
|
|
35
|
-
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}r(ft,"reduceToSingleString")});var ie=R(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.format=void 0;var ht=X(),pt=re(),dt=r((e,...t)=>(0,ht.format)(pt.inspect,e,t),"format");z.format=dt});var se=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var bt=V(),mt=ie(),A=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,bt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let a=Date.now()-(this.last||Date.now());i=(0,mt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${a}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=A;var N=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function oe(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(oe,"extract");var C;function yt(e){e||(e=[]),typeof e=="string"&&(e=oe(e)),C=new N(e)}r(yt,"withoutEnv");m.withoutEnv=yt;function wt(e){let t=globalThis.DEBUG;C||(C=new N(oe(t)));let i=new A(C,e);return C.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}r(wt,"debug");m.debug=wt});var H=class extends Error{static{r(this,"SystemError")}constructor(t,i){super(t,i),this.name="InternalError"}},d=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends d{static{r(this,"ConfigurationError")}constructor(t,i){super(t,i),this.name="ConfigurationError"}},k=class extends d{static{r(this,"FeatureNotEnabledError")}constructor(t,i){super(t,i),this.name="FeatureNotEnabledError"}};var ue=he(se());var w=(0,ue.debug)("zuplo:runtime:external-service");function Rt(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=E.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}r(Rt,"getServiceAuth");async function ae(e,t){let i=Rt();if(i)if(w(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),a=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let l;if(i.customServiceMapping&&i.customServiceMapping[a])l=`https://${i.customServiceMapping[a]}`;else if(E.instance.useLegacyServiceRouting)l=`https://${a}.zuptunnel.com`;else{w("Using sha256 service routing");let h=E.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)l=`https://${await Ct(a,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw w("Cannot use sha256 service routing, missing build variables"),new d("Failed to generate fully qualified tunnel url.")}let f=new URL(`${l}${u.pathname}${u.search}`);w(`Calling external service: ${f.toString()}`);let p=await M.fetch(f.toString(),g);if(p.status===403&&p.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:l}),new d("Could not connect to secure tunnel.");return p}else throw w("Cannot call external service with Request object"),new d("Currently, we only support fetch(<some_string>, ...).");else throw w("There is no external service auth configured for this zup."),new d("There are no external services configured for this zup.")}r(ae,"externalServiceHandler");async function Ct(e,t,i,u){let a=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),l=Et(u);w(`Hashing service name: ${g}-${a}.${g}-${o}-${l}`);let f=await ce(`${g}-${a}`),p=await ce(`${g}-${o}-${l}`);return`${f}.${p}`}r(Ct,"hashServiceName");async function ce(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(ce,"hashSegment");function Et(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(Et,"sanitizeEnvironmentType");var ge=new Map;ge.set("service:",ae);var le=globalThis.fetch;function U(e,t){let i=St(t);if(typeof e=="string"){let u=new URL(e),a=ge.get(u.protocol);return a?a(e,i):le(e,i)}else return le(e,i)}r(U,"internalFetch");globalThis.fetch=U;var St=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Ot={fetch:U},M=Ot;var fe=class{constructor(t){this.options=t;this.authHeader=`
|
|
36
|
-
/*! For license information please see chunk-
|
|
35
|
+
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}r(ft,"reduceToSingleString")});var ie=R(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.format=void 0;var ht=X(),pt=re(),dt=r((e,...t)=>(0,ht.format)(pt.inspect,e,t),"format");z.format=dt});var se=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var bt=V(),mt=ie(),A=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,bt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let a=Date.now()-(this.last||Date.now());i=(0,mt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${a}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=A;var N=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function oe(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(oe,"extract");var C;function yt(e){e||(e=[]),typeof e=="string"&&(e=oe(e)),C=new N(e)}r(yt,"withoutEnv");m.withoutEnv=yt;function wt(e){let t=globalThis.DEBUG;C||(C=new N(oe(t)));let i=new A(C,e);return C.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}r(wt,"debug");m.debug=wt});var H=class extends Error{static{r(this,"SystemError")}constructor(t,i){super(t,i),this.name="InternalError"}},d=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends d{static{r(this,"ConfigurationError")}constructor(t,i){super(t,i),this.name="ConfigurationError"}},k=class extends d{static{r(this,"FeatureNotEnabledError")}constructor(t,i){super(t,i),this.name="FeatureNotEnabledError"}};var ue=he(se());var w=(0,ue.debug)("zuplo:runtime:external-service");function Rt(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=E.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}r(Rt,"getServiceAuth");async function ae(e,t){let i=Rt();if(i)if(w(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),a=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let l;if(i.customServiceMapping&&i.customServiceMapping[a])l=`https://${i.customServiceMapping[a]}`;else if(E.instance.useLegacyServiceRouting)l=`https://${a}.zuptunnel.com`;else{w("Using sha256 service routing");let h=E.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)l=`https://${await Ct(a,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw w("Cannot use sha256 service routing, missing build variables"),new d("Failed to generate fully qualified tunnel url.")}let f=new URL(`${l}${u.pathname}${u.search}`);w(`Calling external service: ${f.toString()}`);let p=await M.fetch(f.toString(),g);if(p.status===403&&p.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:l}),new d("Could not connect to secure tunnel.");return p}else throw w("Cannot call external service with Request object"),new d("Currently, we only support fetch(<some_string>, ...).");else throw w("There is no external service auth configured for this zup."),new d("There are no external services configured for this zup.")}r(ae,"externalServiceHandler");async function Ct(e,t,i,u){let a=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),l=Et(u);w(`Hashing service name: ${g}-${a}.${g}-${o}-${l}`);let f=await ce(`${g}-${a}`),p=await ce(`${g}-${o}-${l}`);return`${f}.${p}`}r(Ct,"hashServiceName");async function ce(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(ce,"hashSegment");function Et(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(Et,"sanitizeEnvironmentType");var ge=new Map;ge.set("service:",ae);var le=globalThis.fetch;function U(e,t){let i=St(t);if(typeof e=="string"){let u=new URL(e),a=ge.get(u.protocol);return a?a(e,i):le(e,i)}else return le(e,i)}r(U,"internalFetch");globalThis.fetch=U;var St=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Ot={fetch:U},M=Ot;var fe=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{r(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let i=await M.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!i.ok)throw new Error(`Request to PDP service failed with response status ${i.status}.`);return await i.json()}};export{se as a,H as b,d as c,q as d,k as e,M as f,fe as g};
|
|
36
|
+
/*! For license information please see chunk-LPFDZM3G.js.LEGAL.txt */
|
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as Ue,d as be,e as ca,f as _n,g as Nn,h as la,i as da}from"./chunk-CRZT3N5H.js";import{a as Ve,b as K,c as N,d as m,e as Wo,f as $,g as Ko}from"./chunk-M2WV76HS.js";import{a as y}from"./chunk-4NFZOV2A.js";import{a as s,c as Be}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var $t=globalThis,Jo=$t.caches;if(Jo){let n=Jo.open;$t.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete $t.caches.default,Object.freeze($t.caches)}var Yo=new Map,Dn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},nt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Yo.get(e);r||(r=new Dn(t),Yo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Mn="__zuplo-expiry-header",Pt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Mn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Mn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Mn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ue=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new nt(r),this.#n=new Pt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Qo="zuplo-request-id",Ge="zp-rid",Hn="zp-body-removed",We="cf-ray",Xo="x-real-ip",Un="cf-ipcity",Zn="cf-ipcontinent",qn="cf-ipcountry",Fn="cf-iplongitude",$n="cf-iplatitude",ei="cf-region",ti="cf-region-code",ni="cf-metro-code",ri="cf-postal-code",oi="cf-timezone",ii="zp-ipcity",si="zp-ipcontinent",ai="zp-ipcountry",ui="zp-iplongitude",ci="zp-iplatitude",li="true-client-ip",jn="zp-asn",zn="zp-asorg",Bn="zp-colo",Vn="zp-postalcode",Gn="zp-metrocode",Wn="zp-region",Kn="zp-regioncode",Jn="zp-timezone",di=[Un,Zn,qn,Fn,$n,jn,zn,Bn,Vn,Gn,Wn,Kn,Jn],pi=["zp-","cf-"],mi=[Ge,We,Hn];var It=Symbol("zuplo_meters"),jt=Symbol("zuplo_dynamic_meters"),zt="system-logger";var es=Be(Ve());import{trace as Ka}from"@opentelemetry/api";import{SpanStatusCode as pa,trace as ma}from"@opentelemetry/api";import{SpanStatusCode as er,trace as tr}from"@opentelemetry/api";var gi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function fi(n){gi=n}s(fi,"setTelemetryInitFunction");var hi=s(n=>gi(n),"proxyHandler");var Ze=class{static{s(this,"RuntimePlugin")}},De=class extends Ze{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Bt=class extends De{static{s(this,"MeteringPlugin")}},Et=class extends Ze{static{s(this,"TelemetryPlugin")}};var Vt=new Set,yi=new Set;function f(n){yi.has(n)||(yi.add(n),Vt.add(n))}s(f,"trackFeature");function bi(){let n=[...Vt];return Vt.clear(),n}s(bi,"getUnsentFeatures");function wi(n){for(let e of n)Vt.add(e)}s(wi,"restoreFeatures");var xt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new N("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await xt.problemResponseFormat(e,t,r)}};function Gt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Gt(t)}return Object.freeze(n)}s(Gt,"deepFreeze");var ee=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Gt(this.#e)}get params(){return Gt(this.#t)}user};var vt={},Me=[],Yn=[],Qn=[],Xn=[];var Wt={addPlugin(n){Me.push(n)},addRequestHook(n){Yn.push(n)},addResponseSendingHook(n){Qn.push(n)},addResponseSendingFinalHook(n){Xn.push(n)}},Pi=s(async(n,e)=>{if(Yn.length===0)return n;let t=tr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of Yn){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof ee||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:er.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ii=s(async(n,e,t)=>{if(Qn.length===0)return n;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of Qn)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:er.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ei=s(async(n,e,t)=>{if(Xn.length===0)return;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Xn)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:er.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ri=!1;async function xi(n){if(!Ri){n&&(f("runtime.extensions"),await n(Wt)),vt.value=Wt;for(let e of Me)if(e instanceof Et){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});fi(t)}for(let e of Me)e instanceof De&&await e.initialize(Wt);xt.setProblemResponseFormat(Wt.problemResponseFormat),Ri=!0}}s(xi,"initializeRuntime");var nr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function rr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(nr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(nr.Json)||!e?JSON.stringify(n):n}s(rr,"serialize");function rt(n){return me.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(me.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(rt,"isSystemRoute");var ce=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>ma.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:pa.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async R=>{let O=a.pop();return O?O(o,i,t,u):await this.#e(async j=>{let Z=await r(j,i);return ga(Z)},t)(R,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(rt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Tt(o,l);i.dispatchEvent(p);let g=ge.getContextExtensions(i),h=g.latestRequest,C;try{C=await p.mutableResponse}catch(R){return i.log.error(R),t.errorHandler(o,i,R)}try{C=await g.onResponseSending(C,h,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,i,R)}try{C=await Ii(C,h,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,i,R)}i.dispatchEvent(new St(o,C));try{await g.onResponseSendingFinal(l,h,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await Ei(l,h,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return C}};function ga(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(rr(n),{headers:{"content-type":"application/json"}})}s(ga,"resultToResponse");var Kt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Kt||{}),vi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var fa={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},or=fa;function ha(n){return`${new URL(n.url).pathname}`}s(ha,"instance");function ya(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(We);return r&&(t.rayId=r),t}s(ya,"trace");var ba=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ha(e),trace:ya(e,t),...r},additionalHeaders:o,statusText:or[n.status]}),"merge"),ir=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:vi[e],...t}}},v=class extends ir{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=ba(this.getProblemFromStatus(e),t,r,o,i);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var qe=class extends Ze{static{s(this,"MetricsPlugin")}};var Y=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,Y.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=bi(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Y.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),wi(u)}}};var ie=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Ot.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ot={name:"__system-no-version",pathPrefix:""};var fe=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(We)??void 0,c=n.headers.get(li)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ie&&(d=e.route.systemRouteName);let p=ge.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Jt(e)),Me.forEach(C=>{if(C instanceof qe){let R=C.getTransport();h.push(R)}}),h.forEach(C=>{C.pushMetrics(g,e)}),a},"metricsProcessor");var sr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return v.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Y.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ce({processors:[fe],handler:t,gateway:e}),o=new ie({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:wa}=Object.prototype,{propertyIsEnumerable:Ra}=Object.prototype;function ar(n){return wa.call(n)}s(ar,"toString");function Ie(n){return typeof n=="string"}s(Ie,"isString");function ot(n){return Ie(n)&&n!==""}s(ot,"isNonEmptyString");function Ti(n){return ar(n)==="[object RegExp]"}s(Ti,"isRegexp");function Si(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ra.call(n,e))]}s(Si,"getOwnEnumerableKeys");function Je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Je,"isObject");function ur(n){return typeof n=="number"&&!isNaN(n)}s(ur,"isNumber");function cr(n){return n===!0||n===!1}s(cr,"isBoolean");function Oi(n){return typeof n>"u"}s(Oi,"isUndefined");function Ci(n){return Oi(n)||n===null}s(Ci,"isUndefinedOrNull");function Ct(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Ct,"isErrorLike");var Ai=new Map;function it(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Ai.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ai.set(n,r),r}s(it,"statusCodesStringToNumberArray");function Ye(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new N(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ye,"getValueFromRequestUser");function Li(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new N(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new N(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(Li,"selectPropertyUsingJsonPath");function Qe(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Qe,"parseValueToStringArray");function ki(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Je(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!ur(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!cr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=lr(t,"allowedHeaders"),o=lr(t,"allowedMethods"),i=lr(t,"exposeHeaders"),a;try{a=Qe(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(ki,"parseCorsPolicies");function lr(n,e){let t;if(n[e]!==void 0)try{t=Qe(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(lr,"parseOptionalProperty");var Yt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Qt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var dr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return v.notFound(a,u);let h=g.routeConfiguration,C=Pa(l,d,p,h,t);return C.isValid?new Response(void 0,{status:200,statusText:"OK",headers:C.headers}):(C.error&&u.log.warn(C.error),v.notFound(a,u))},"optionsHandler"),o=new ce({processors:[fe],handler:r,gateway:e}),i=new ie({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Pa=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Yt(a.allowedOrigins,t);return u?{isValid:!0,headers:Qt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var _i=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ce({processors:[fe],handler:t,gateway:e}),o=new ie({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var pr=new ie({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ni=s((n,e)=>{let t=s(async(o,i)=>{let a=vt.value?.notFoundHandler;if(a){let u=ge.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,i)},"notFoundHandler"),r=new ce({processors:[fe],handler:t,gateway:e});n.addRoute(pr,r.execute)},"registerNotMatchedHandler");var Ia=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Di=s(n=>{Ia.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Di(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ea(o,t.routeData.corsPolicies),u=xa(n,a),c=new Headers(i.headers);return Di(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ea=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),xa=s((n,e)=>{let t=Yt(e.allowedOrigins,n.headers.get("origin"));return t?Qt(e,t):{}},"getCorsHeaders");var mr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ce({processors:[Xt],handler:t,gateway:e}),o=new ie({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Mi,trace as Hi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var en=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new N(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},pe=class extends en{static{s(this,"InboundPolicy")}},Fe=class extends en{static{s(this,"OutboundPolicy")}};var hr=class extends pe{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},yr=class extends Fe{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},gr=new Map;function At(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!gr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new hr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);gr.set(a.name,c)}),t.map(i=>{let a=gr.get(i);if(a===void 0)throw new N("Internal error. Policy not found in cache.");return a})}s(At,"getInboundPolicyInstances");var fr=new Map;function va(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!fr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new yr(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);fr.set(i.name,u)}),t.map(o=>{let i=fr.get(o);if(i===void 0)throw new N("Internal error. Policy not found in cache.");return i})}s(va,"getOutboundPolicyInstances");var br=s(n=>async(e,t)=>{let r=ge.getContextExtensions(t),o=Hi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof ee||p instanceof Response)return d.end(),p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Mi.ERROR}),d.recordException(g),g}});if(l instanceof ee)u=l;else if(l instanceof Request)u=new ee(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ta=s(n=>async(e,t,r)=>{let o=Hi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Mi.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),tn=s(async(n,e,t,r)=>{let o=At(e.route,t.routeData.policies),i=va(e.route,t.routeData.policies);return Zi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Ui({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Zi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ui,"createInternalPolicyProcessor");async function Zi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=br(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ta(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Zi,"executePolicyProcessor");function qi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Sa,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Oa(l,o)}i=u+1}return t}s(qi,"parse");function Sa(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Sa,"decode");function Oa(n,e){try{return e(n)}catch{return n}}s(Oa,"tryDecode");function Fi(n,e){try{let t=/v\d+(-\d+)?/g,o=qi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Fi,"devPortalBaseURL");var $i="/__zuplo/dev-portal",Ca="dev-portal-id",Aa="dev-portal-host",La="zp-account",ka="zp-project",_a="dev-portal-build",Na=`
|
|
25
|
+
import{a as Ue,d as be,e as ca,f as _n,g as Nn,h as la,i as da}from"./chunk-CRZT3N5H.js";import{a as Ve,b as K,c as N,d as m,e as Wo,f as $,g as Ko}from"./chunk-LPFDZM3G.js";import{a as y}from"./chunk-4NFZOV2A.js";import{a as s,c as Be}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var $t=globalThis,Jo=$t.caches;if(Jo){let n=Jo.open;$t.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete $t.caches.default,Object.freeze($t.caches)}var Yo=new Map,Dn=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},nt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Yo.get(e);r||(r=new Dn(t),Yo.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Mn="__zuplo-expiry-header",Pt=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Mn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(Mn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Mn,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var ue=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new nt(r),this.#n=new Pt(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}};var Qo="zuplo-request-id",Ge="zp-rid",Hn="zp-body-removed",We="cf-ray",Xo="x-real-ip",Un="cf-ipcity",Zn="cf-ipcontinent",qn="cf-ipcountry",Fn="cf-iplongitude",$n="cf-iplatitude",ei="cf-region",ti="cf-region-code",ni="cf-metro-code",ri="cf-postal-code",oi="cf-timezone",ii="zp-ipcity",si="zp-ipcontinent",ai="zp-ipcountry",ui="zp-iplongitude",ci="zp-iplatitude",li="true-client-ip",jn="zp-asn",zn="zp-asorg",Bn="zp-colo",Vn="zp-postalcode",Gn="zp-metrocode",Wn="zp-region",Kn="zp-regioncode",Jn="zp-timezone",di=[Un,Zn,qn,Fn,$n,jn,zn,Bn,Vn,Gn,Wn,Kn,Jn],pi=["zp-","cf-"],mi=[Ge,We,Hn];var It=Symbol("zuplo_meters"),jt=Symbol("zuplo_dynamic_meters"),zt="system-logger";var es=Be(Ve());import{trace as Ka}from"@opentelemetry/api";import{SpanStatusCode as pa,trace as ma}from"@opentelemetry/api";import{SpanStatusCode as er,trace as tr}from"@opentelemetry/api";var gi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function fi(n){gi=n}s(fi,"setTelemetryInitFunction");var hi=s(n=>gi(n),"proxyHandler");var Ze=class{static{s(this,"RuntimePlugin")}},De=class extends Ze{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Bt=class extends De{static{s(this,"MeteringPlugin")}},Et=class extends Ze{static{s(this,"TelemetryPlugin")}};var Vt=new Set,yi=new Set;function f(n){yi.has(n)||(yi.add(n),Vt.add(n))}s(f,"trackFeature");function bi(){let n=[...Vt];return Vt.clear(),n}s(bi,"getUnsentFeatures");function wi(n){for(let e of n)Vt.add(e)}s(wi,"restoreFeatures");var xt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(f("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new N("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await xt.problemResponseFormat(e,t,r)}};function Gt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Gt(t)}return Object.freeze(n)}s(Gt,"deepFreeze");var ee=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Gt(this.#e)}get params(){return Gt(this.#t)}user};var vt={},Me=[],Yn=[],Qn=[],Xn=[];var Wt={addPlugin(n){Me.push(n)},addRequestHook(n){Yn.push(n)},addResponseSendingHook(n){Qn.push(n)},addResponseSendingFinalHook(n){Xn.push(n)}},Pi=s(async(n,e)=>{if(Yn.length===0)return n;let t=tr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of Yn){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof ee||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:er.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ii=s(async(n,e,t)=>{if(Qn.length===0)return n;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of Qn)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:er.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ei=s(async(n,e,t)=>{if(Xn.length===0)return;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Xn)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:er.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ri=!1;async function xi(n){if(!Ri){n&&(f("runtime.extensions"),await n(Wt)),vt.value=Wt;for(let e of Me)if(e instanceof Et){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});fi(t)}for(let e of Me)e instanceof De&&await e.initialize(Wt);xt.setProblemResponseFormat(Wt.problemResponseFormat),Ri=!0}}s(xi,"initializeRuntime");var nr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function rr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(nr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(nr.Json)||!e?JSON.stringify(n):n}s(rr,"serialize");function rt(n){return me.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(me.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(rt,"isSystemRoute");var ce=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>ma.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:pa.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async R=>{let O=a.pop();return O?O(o,i,t,u):await this.#e(async j=>{let Z=await r(j,i);return ga(Z)},t)(R,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(rt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Tt(o,l);i.dispatchEvent(p);let g=ge.getContextExtensions(i),h=g.latestRequest,C;try{C=await p.mutableResponse}catch(R){return i.log.error(R),t.errorHandler(o,i,R)}try{C=await g.onResponseSending(C,h,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,i,R)}try{C=await Ii(C,h,i)}catch(R){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${R.message}'`,R),t.errorHandler(o,i,R)}i.dispatchEvent(new St(o,C));try{await g.onResponseSendingFinal(l,h,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}try{await Ei(l,h,i)}catch(R){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${R.message}'`,R),R}return C}};function ga(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(rr(n),{headers:{"content-type":"application/json"}})}s(ga,"resultToResponse");var Kt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Kt||{}),vi={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var fa={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},or=fa;function ha(n){return`${new URL(n.url).pathname}`}s(ha,"instance");function ya(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(We);return r&&(t.rayId=r),t}s(ya,"trace");var ba=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ha(e),trace:ya(e,t),...r},additionalHeaders:o,statusText:or[n.status]}),"merge"),ir=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:vi[e],...t}}},v=class extends ir{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=ba(this.getProblemFromStatus(e),t,r,o,i);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var qe=class extends Ze{static{s(this,"MetricsPlugin")}};var Y=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,Y.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=bi(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Y.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),wi(u)}}};var ie=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.version=Ot.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ot={name:"__system-no-version",pathPrefix:""};var fe=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(We)??void 0,c=n.headers.get(li)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ie&&(d=e.route.systemRouteName);let p=ge.getContextExtensions(e).latestRequest,g={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Jt(e)),Me.forEach(C=>{if(C instanceof qe){let R=C.getTransport();h.push(R)}}),h.forEach(C=>{C.pushMetrics(g,e)}),a},"metricsProcessor");var sr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return v.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Y.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ce({processors:[fe],handler:t,gateway:e}),o=new ie({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:wa}=Object.prototype,{propertyIsEnumerable:Ra}=Object.prototype;function ar(n){return wa.call(n)}s(ar,"toString");function Ie(n){return typeof n=="string"}s(Ie,"isString");function ot(n){return Ie(n)&&n!==""}s(ot,"isNonEmptyString");function Ti(n){return ar(n)==="[object RegExp]"}s(Ti,"isRegexp");function Si(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ra.call(n,e))]}s(Si,"getOwnEnumerableKeys");function Je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Je,"isObject");function ur(n){return typeof n=="number"&&!isNaN(n)}s(ur,"isNumber");function cr(n){return n===!0||n===!1}s(cr,"isBoolean");function Oi(n){return typeof n>"u"}s(Oi,"isUndefined");function Ci(n){return Oi(n)||n===null}s(Ci,"isUndefinedOrNull");function Ct(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Ct,"isErrorLike");var Ai=new Map;function it(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=Ai.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ai.set(n,r),r}s(it,"statusCodesStringToNumberArray");function Ye(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new N(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ye,"getValueFromRequestUser");function Li(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new N(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new N(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(Li,"selectPropertyUsingJsonPath");function Qe(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Qe,"parseValueToStringArray");function ki(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Je(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!ur(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!cr(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=lr(t,"allowedHeaders"),o=lr(t,"allowedMethods"),i=lr(t,"exposeHeaders"),a;try{a=Qe(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(ki,"parseCorsPolicies");function lr(n,e){let t;if(n[e]!==void 0)try{t=Qe(n[e])}catch(r){throw new m(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(lr,"parseOptionalProperty");var Yt=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Qt=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var dr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return v.notFound(a,u);let h=g.routeConfiguration,C=Pa(l,d,p,h,t);return C.isValid?new Response(void 0,{status:200,statusText:"OK",headers:C.headers}):(C.error&&u.log.warn(C.error),v.notFound(a,u))},"optionsHandler"),o=new ce({processors:[fe],handler:r,gateway:e}),i=new ie({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Pa=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Yt(a.allowedOrigins,t);return u?{isValid:!0,headers:Qt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var _i=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new ce({processors:[fe],handler:t,gateway:e}),o=new ie({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var pr=new ie({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ni=s((n,e)=>{let t=s(async(o,i)=>{let a=vt.value?.notFoundHandler;if(a){let u=ge.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,i)},"notFoundHandler"),r=new ce({processors:[fe],handler:t,gateway:e});n.addRoute(pr,r.execute)},"registerNotMatchedHandler");var Ia=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Di=s(n=>{Ia.forEach(e=>n.delete(e))},"stripCorsHeaders"),Xt=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Di(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ea(o,t.routeData.corsPolicies),u=xa(n,a),c=new Headers(i.headers);return Di(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ea=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),xa=s((n,e)=>{let t=Yt(e.allowedOrigins,n.headers.get("origin"));return t?Qt(e,t):{}},"getCorsHeaders");var mr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ce({processors:[Xt],handler:t,gateway:e}),o=new ie({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Mi,trace as Hi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var en=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new N(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},pe=class extends en{static{s(this,"InboundPolicy")}},Fe=class extends en{static{s(this,"OutboundPolicy")}};var hr=class extends pe{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},yr=class extends Fe{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},gr=new Map;function At(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!gr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new hr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);gr.set(a.name,c)}),t.map(i=>{let a=gr.get(i);if(a===void 0)throw new N("Internal error. Policy not found in cache.");return a})}s(At,"getInboundPolicyInstances");var fr=new Map;function va(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!fr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new yr(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);fr.set(i.name,u)}),t.map(o=>{let i=fr.get(o);if(i===void 0)throw new N("Internal error. Policy not found in cache.");return i})}s(va,"getOutboundPolicyInstances");var br=s(n=>async(e,t)=>{let r=ge.getContextExtensions(t),o=Hi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof ee||p instanceof Response)return d.end(),p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Mi.ERROR}),d.recordException(g),g}});if(l instanceof ee)u=l;else if(l instanceof Request)u=new ee(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ta=s(n=>async(e,t,r)=>{let o=Hi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Mi.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),tn=s(async(n,e,t,r)=>{let o=At(e.route,t.routeData.policies),i=va(e.route,t.routeData.policies);return Zi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Ui({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Zi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ui,"createInternalPolicyProcessor");async function Zi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=br(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ta(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Zi,"executePolicyProcessor");function qi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Sa,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Oa(l,o)}i=u+1}return t}s(qi,"parse");function Sa(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Sa,"decode");function Oa(n,e){try{return e(n)}catch{return n}}s(Oa,"tryDecode");function Fi(n,e){try{let t=/v\d+(-\d+)?/g,o=qi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Fi,"devPortalBaseURL");var $i="/__zuplo/dev-portal",Ca="dev-portal-id",Aa="dev-portal-host",La="zp-account",ka="zp-project",_a="dev-portal-build",Na=`
|
|
26
26
|
<!DOCTYPE html>
|
|
27
27
|
<html lang="en">
|
|
28
28
|
<head>
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{g as o}from"../../chunk-
|
|
25
|
+
import{g as o}from"../../chunk-LPFDZM3G.js";import"../../chunk-4NFZOV2A.js";import"../../chunk-4DUPDUSC.js";export{o as PdpService};
|
|
26
26
|
/*! For license information please see exports.js.LEGAL.txt */
|
package/package.json
CHANGED
|
File without changes
|