@zuplo/graphql 5.1848.0 → 5.1851.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.minified.js CHANGED
@@ -71,7 +71,7 @@ Signature verification is impossible without access to the original signed mater
71
71
  `+d}):new Zr.StripeSignatureVerificationError(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
72
72
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
73
73
  `+l+`
74
- `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Zr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(GR,"validateComputedSignature");function KR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(KR,"parseHeader");function JR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(JR,"secureCompare");async function r_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Xp[s[c]];return a.join("")}o(r_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=r_;var Xp=new Array(256);for(let t=0;t<Xp.length;t++)Xp[t]=t.toString(16).padStart(2,"0")});var lt=_(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.optionValidator=void 0;var ri=k(),zR=at();function WR(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,zR.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(WR,"optionValidator");ja.optionValidator=WR});var tf=_(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.StripeWebhookVerificationInboundPolicy=void 0;var QR=_n(),YR=de(),ZR=n_(),XR=lt(),ef=class extends QR.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,XR.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,ZR.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),YR.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Va.StripeWebhookVerificationInboundPolicy=ef});var o_=_(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.isStripeWebhookEvent=void 0;var i_=at();function eO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,i_.isString)(t.id)&&"type"in t&&(0,i_.isString)(t.type)}o(eO,"isStripeWebhookEvent");Ba.isStripeWebhookEvent=eO});var s_=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.MeteringPlugin=void 0;var tO=Ot(),rf=class extends tO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};Ga.MeteringPlugin=rf});var sf=_(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var nf=k(),rO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i}};of.default=rO});var c_=_(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.deleteConsumer=Rr.createConsumerInvite=Rr.createConsumer=void 0;var af=k(),cf=Je(),uf=ie(),lf=kn(),df="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",a_="My API Key";async function nO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=uf.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,df);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:a_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new af.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(nO,"createConsumer");Rr.createConsumer=nO;async function iO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=uf.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,df);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:a_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new af.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(iO,"createConsumerInvite");Rr.createConsumerInvite=iO;async function oO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=uf.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,df);i.searchParams.set("with-api-key","true");let s=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new af.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(oO,"deleteConsumer");Rr.deleteConsumer=oO});var Ka=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getSubscription=Nr.updateSubscription=Nr.createSubscription=void 0;var Or=k(),pf=Je(),ff=ie(),hf=kn(),mf=at();async function sO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c}){let u={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(l))throw new Or.SystemError("No Zuplo JWT token set.");let p=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let f="Error creating monetization subscription.",h;try{h=await p.json()}catch{h={status:p.status,statusText:p.statusText}}throw t.log.error(f,h),new Or.RuntimeError(f)}t.log.info("Successfully created monetization subscription.",u)}o(sO,"createSubscription");Nr.createSubscription=sO;async function aO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(i))throw new Or.SystemError("No Zuplo JWT token set.");let a=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Or.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(aO,"updateSubscription");Nr.updateSubscription=aO;async function cO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(i))throw new Or.SystemError("No Zuplo JWT token set.");let a=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Or.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Or.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Or.RuntimeError(u)}return c.data[0]}o(cO,"getSubscription");Nr.getSubscription=cO});var yf=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.stripeStatusToMeteringStatus=void 0;function uO(t){return t.replaceAll("_","-")}o(uO,"stripeStatusToMeteringStatus");Ja.stripeStatusToMeteringStatus=uO});var u_=_(eo=>{"use strict";var lO=eo&&eo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(eo,"__esModule",{value:!0});var Xr=de(),dO=lO(sf()),gf=c_(),pO=Ka(),fO=yf();async function hO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)u=await(0,gf.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:r.data.object.metadata.zuplo_created_by_email,managerSub:r.data.object.metadata.zuplo_created_by_sub,context:e});else{let l=await dO.default.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!l.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,gf.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l.email,context:e})}if(!u)return Xr.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let l=(0,fO.stripeStatusToMeteringStatus)(r.data.object.status);await(0,pO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await(0,gf.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),Xr.HttpProblems.internalServerError(t,e,{detail:l.message})}return Xr.HttpProblems.ok(t,e)}o(hO,"onCustomerSubscriptionCreated");eo.default=hO});var d_=_(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var bf=de(),l_=Ka();async function mO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),bf.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),bf.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,l_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,l_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),bf.HttpProblems.ok(t,e)}o(mO,"onCustomerSubscriptionDeleted");_f.default=mO});var p_=_(ro=>{"use strict";var yO=ro&&ro.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ro,"__esModule",{value:!0});var to=de(),gO=yO(sf()),za=Ka(),bO=yf();async function _O(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),to.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),to.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,za.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,bO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,za.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),to.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,za.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await gO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,za.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),to.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),to.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(_O,"onCustomerSubscriptionUpdated");ro.default=_O});var h_=_(ni=>{"use strict";var wf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Wa=Qi(),Qa=k(),EO=Gt(),wO=tf(),f_=de(),vO=cr(),TO=En(),SO=wl(),IO=gt(),PO=ie(),AO=o_(),RO=lt(),OO=s_(),NO=wf(u_()),CO=wf(d_()),xO=wf(p_()),Ef=class extends OO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Wa.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Wa.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Qa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Wa.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Wa.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Qa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!PO.Environment.instance.build.ACCOUNT_NAME)throw new Qa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!LO(p))throw new Qa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,AO.isStripeWebhookEvent)(f))return f_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,NO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,xO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,CO.default)(c,u,f,{meteringBucketId:l});default:return f_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,TO.createInternalPolicyProcessor)({inboundPolicies:[new wO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,RO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new EO.Pipeline({processors:[vO.metricsProcessor,i],handler:n,gateway:r}),a=new IO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:SO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=Ef;function LO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(LO,"isMetricsRegion")});var __=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var m_=k(),DO=Ae(),y_=Jt(),b_=new WeakMap,g_={},vf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){b_.set(e,r)}};ii.AmberfloMeteringPolicy=vf;async function MO(t,e,r,n){if(!r.statusCodes)throw new m_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,y_.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=b_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new m_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,y_.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=g_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new DO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let v=r.url??"https://app.amberflo.io/ingest",A=await fetch(v,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${v.message}`),v}}),g_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o(MO,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=MO});var Tf=_(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.sha256=void 0;async function UO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(UO,"sha256");Ya.sha256=UO});var Xt=_(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.getPolicyCacheName=void 0;var kO=Tf(),E_=new Map;async function FO(t,e){let r,n=E_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,kO.sha256)(JSON.stringify({policyName:t,options:e}))}`,E_.set(t,r)),r}o(FO,"getPolicyCacheName");Za.getPolicyCacheName=FO});var Pf=_(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.ApiKeyInboundPolicy=void 0;var HO=Xt(),qO=Bt(),w_=Qi(),Sf=k(),$O=Kt(),v_=Je(),If=ie(),jO=kn(),T_="key-metadata-cache-type";function VO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(VO,"getKeyValue");async function BO(t,e,r,n){if(!r.bucketName)if(w_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=w_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Sf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Sf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:$O.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=VO(a,i);if(!c||c==="")return s("No key present");let u=await GO(c),l=await(0,HO.getPolicyCacheName)(n,i),d=new qO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==T_&&v_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,jO.fetchRetry)({retryDelayMs:5,retries:2,logger:v_.SystemLogMap.getLogger(e)},`${If.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":If.Environment.instance.deploymentName??"unknown","User-Agent":If.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let v=await h.text(),A=JSON.parse(v);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Sf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:T_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(BO,"ApiKeyInboundPolicy");Xa.ApiKeyInboundPolicy=BO;async function GO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(GO,"hashValue")});var S_=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ApiAuthKeyInboundPolicy=void 0;var KO=Pf();ec.ApiAuthKeyInboundPolicy=KO.ApiKeyInboundPolicy});var er=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.OpenIdJwtInboundPolicy=void 0;var Rf=(ta(),Co(ea)),Of=k(),JO=de(),Af={},zO=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Of.ConfigurationError("Invalid State - jwkUrl not set");Af[e.jwkUrl]||(Af[e.jwkUrl]=(0,Rf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Rf.jwtVerify)(t,Af[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),WO=o(async(t,e)=>{let r;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);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Rf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),QO=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>JO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Of.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Of.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?zO:WO,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");tc.OpenIdJwtInboundPolicy=QO});var I_=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.Auth0JwtInboundPolicy=void 0;var YO=er(),ZO=o(async(t,e,r,n)=>(0,YO.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");rc.Auth0JwtInboundPolicy=ZO});var P_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.BasicAuthInboundPolicy=void 0;var XO=de(),eN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>XO.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");nc.BasicAuthInboundPolicy=eN});var A_=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.CachingInboundPolicy=void 0;var tN=Xt(),rN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function nN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(nN,"digestMessage");var iN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await nN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function oN(t,e,r,n){let i=await(0,tN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await iN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);rN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(oN,"CachingInboundPolicy");ic.CachingInboundPolicy=oN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.ChangeMethodInboundPolicy=void 0;var sN=k(),aN=Ke(),cN=o(async(t,e,r,n)=>{if(!r.method)throw new sN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new aN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");oc.ChangeMethodInboundPolicy=cN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.ClearHeadersInboundPolicy=void 0;var uN=Ke(),lN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new uN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");sc.ClearHeadersInboundPolicy=lN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.ClearHeadersOutboundPolicy=void 0;var dN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");ac.ClearHeadersOutboundPolicy=dN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ClerkJwtInboundPolicy=void 0;var pN=er(),fN=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,pN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");cc.ClerkJwtInboundPolicy=fN});var L_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.CognitoJwtInboundPolicy=void 0;var x_=k(),hN=er(),mN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new x_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new x_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,hN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");uc.CognitoJwtInboundPolicy=mN});var M_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.CompositeInboundPolicy=void 0;var yN=k(),gN=qr(),D_=En(),bN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new yN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=gN.Gateway.instance,s=(0,D_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,D_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");lc.CompositeInboundPolicy=bN});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CurityPhantomTokenInboundPolicy=void 0;var _N=Xt(),EN=Bt(),dc=de(),wN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return dc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=vN(i);if(!s)return dc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,_N.getPolicyCacheName)(n,r),c=new EN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),dc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):dc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");pc.CurityPhantomTokenInboundPolicy=wN;function vN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(vN,"getToken")});var k_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.FirebaseJwtInboundPolicy=void 0;var TN=lt(),SN=er(),IN=o(async(t,e,r,n)=>((0,TN.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,SN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");fc.FirebaseJwtInboundPolicy=IN});var F_=_(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.FormDataToJsonInboundPolicy=void 0;var PN=Ke(),AN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new PN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");hc.FormDataToJsonInboundPolicy=AN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.GeoFilterInboundPolicy=void 0;var RN=k(),ON=de(),oi="__unknown__",NN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,v=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||v.length>0&&v.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");mc.GeoFilterInboundPolicy=NN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),ON.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new RN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.JWTScopeValidationInboundPolicy=void 0;var CN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");yc.JWTScopeValidationInboundPolicy=CN});var j_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.MockApiInboundPolicy=void 0;var xN=de(),LN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return Nf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Nf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return $_(a[c])}else return a.length>0?$_(a[0]):Nf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");gc.MockApiInboundPolicy=LN;function $_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o($_,"generateResponse");var Nf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return xN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var J_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var DN=k(),MN=Ae(),UN="Incoming",kN={logRequestBody:!0,logResponseBody:!0};function V_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(V_,"headersToObject");function B_(){return new Date().toISOString()}o(B_,"timestamp");var Cf=new WeakMap,FN={};function HN(t,e){let r=Cf.get(t);r||(r=FN);let n=Object.assign({...r},e);Cf.set(t,n)}o(HN,"setMoesifContext");ci.setMoesifContext=HN;async function G_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(G_,"readBody");var qN={},xf;function K_(){if(!xf)throw new DN.RuntimeError("Invalid State - no _lastLogger");return xf}o(K_,"getLastLogger");function $N(t){let e=qN[t];return e||(e=new MN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);K_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||K_().error({status:i.status,body:await i.text()})})),e}o($N,"getDispatcher");async function jN(t,e,r,n){xf=e.log;let i=B_(),s=Object.assign(kN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await G_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=$N(s.applicationId),d=t.headers.get("true-client-ip"),p=Cf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:V_(t.headers)},h=s.logResponseBody?await G_(c,e):void 0,y={time:B_(),status:c.status,headers:V_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:UN};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(jN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=jN});var Q_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var z_=Je(),W_=ie();async function VN(t,e,r,n){let i=z_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=W_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(VN,"loadSubscription");ui.loadSubscription=VN;async function BN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=W_.Environment.instance,c=z_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(BN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=BN});var Y_=_(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.compareMeters=Cr.parseAllowedSubscriptionStatuses=Cr.validateMeters=void 0;var en=k(),GN=Jt(),KN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function JN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new en.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof en.ConfigurationError?new en.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(JN,"validateMeters");Cr.validateMeters=JN;function zN(t,e){if(t)try{if(t.length===0)throw new en.ConfigurationError("Must set valid subscription statuses");let r=(0,GN.parseValueToStringArray)(t),n=[];for(let i of r)KN.has(i)||n.push(i);if(n.length>0)throw new en.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof en.ConfigurationError?new en.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(zN,"parseAllowedSubscriptionStatuses");Cr.parseAllowedSubscriptionStatuses=zN;function WN(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(WN,"compareMeters");Cr.compareMeters=WN});var eE=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.MonetizationInboundPolicy=void 0;var tn=fn(),rn=gp(),bc=Qi(),Z_=k(),QN=_n(),nn=de(),YN=Jt(),ZN=lt(),X_=Q_(),no=Y_(),Lf=class extends QN.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return rn.ContextData.get(e,tn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,no.validateMeters)(r,"setMeters"),rn.ContextData.set(e,tn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,ZN.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,i=(0,YN.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=rn.ContextData.get(r,tn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,no.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,no.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,v,A)=>{let g=rn.ContextData.get(A,tn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Z_.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=rn.ContextData.get(A,tn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,no.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,no.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,X_.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:nn.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Z_.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,X_.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:nn.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),nn.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),rn.ContextData.set(r,tn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=rn.ContextData.get(r,tn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),nn.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),nn.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),nn.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].consumed<=0&&!n)return nn.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};_c.MonetizationInboundPolicy=Lf});var tE=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.OktaJwtInboundPolicy=void 0;var XN=er(),eC=o(async(t,e,r,n)=>(0,XN.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Ec.OktaJwtInboundPolicy=eC});var rE=_(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.PropelAuthJwtInboundPolicy=void 0;var tC=(ta(),Co(ea)),rC=er(),Df,nC=o(async(t,e,r,n)=>{if(!Df)try{Df=await(0,tC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,rC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Df,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");wc.PropelAuthJwtInboundPolicy=nC});var nE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var io=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=io;var oo=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=oo;function iC(t,e){if((0,Ye.isUndefined)(t))throw new io(e)}o(iC,"throwIfUndefined");Z.throwIfUndefined=iC;function Mf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new io(e)}o(Mf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=Mf;function oC(t,e){if(Mf(t,e),!(0,Ye.isString)(t))throw new oo(e,"string")}o(oC,"throwIfNotString");Z.throwIfNotString=oC;function sC(t,e){if(Mf(t,e),!(0,Ye.isNumber)(t))throw new oo(e,"number")}o(sC,"throwIfNotNumber");Z.throwIfNotNumber=sC;var so=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=so;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function aC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new so(t,e,r)}o(aC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=aC;function vc(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new so(t,e,r)}o(vc,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=vc;function cC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(cC,"throwIfOptionNotString");Z.throwIfOptionNotString=cC;function uC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(uC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=uC;function lC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(lC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=lC;function dC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(dC,"throwIfStateUndefined");Z.throwIfStateUndefined=dC;function Tc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Tc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Tc;function pC(t,e){if(Tc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(pC,"throwIfStateNotString");Z.throwIfStateNotString=pC;function fC(t,e){if(Tc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(fC,"throwIfStateNotNumber");Z.throwIfStateNotNumber=fC;function hC(t,e){if(Tc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(hC,"throwIfStateNotObject");Z.throwIfStateNotObject=hC});var iE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Uf=k(),Sc=nE(),kf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Sc.throwIfNotString)(e,"redisClientUrl"),(0,Sc.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Sc.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Uf.SystemError("Redis client failed with 401: Unauthorized"):new Uf.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=kf;var Ff=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Sc.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Uf.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=Ff});var Hf=_(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.RETRY_AFTER_HEADER=Pe.wrapUserFunction=Pe.getCountAndUpdateExpiry=Pe.getRedisClient=Pe.getAll=Pe.getUser=Pe.getIP=Pe.getRealIP=void 0;var xr=k(),Ic=ie(),oE=iE(),sE=at(),mC=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Pe.getRealIP=mC;var yC=o(async t=>({key:`ip-${(0,Pe.getRealIP)(t)}`}),"getIP");Pe.getIP=yC;var gC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Pe.getUser=gC;var bC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Pe.getAll=bC;var Pc;function _C(t,e){let r;if(Pc)return Pc;if(Ic.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new oE.InMemoryRedisClient,Pc=r,r;let{authApiJWT:n,redisURL:i}=Ic.Environment.instance;if(!(0,sE.isString)(i))throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,sE.isString)(n))throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=oE.StandardRedisClient.initialize(i,n,Ic.Environment.instance.deploymentName??"unknown",Ic.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Pc=r,r}o(_C,"getRedisClient");Pe.getRedisClient=_C;async function EC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(EC,"getCountAndUpdateExpiry");Pe.getCountAndUpdateExpiry=EC;function wC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new xr.RuntimeError(u)}return c},"outerFunction")}o(wC,"wrapUserFunction");Pe.wrapUserFunction=wC;Pe.RETRY_AFTER_HEADER="Retry-After"});var cE=_(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.AsyncRateLimitInboundPolicy=void 0;var vC=sr(),TC=Xt(),SC=de(),IC=Je(),PC=ie(),AC=Bt(),on=Hf(),aE=(0,vC.debug)("zuplo:policies:RateLimitInboundPolicy"),RC=o(async(t,e,r,n)=>{let i=IC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[on.RETRY_AFTER_HEADER]=T.toString()),SC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,on.wrapUserFunction)(r,n),user:on.getUser,ip:on.getIP,all:on.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,on.getRedisClient)(n,i),b=`bucket/${PC.Environment.instance.build.BUILD_ID}/${n}/${l}`,v=await(0,TC.getPolicyCacheName)(n,r),A=new AC.MemoryZoneReadThroughCache(v,e),g=(0,on.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),S;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),aE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),S=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){aE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>S??E),t},"AsyncRateLimitInboundPolicy");Ac.AsyncRateLimitInboundPolicy=RC});var lE=_(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.RateLimitInboundPolicy=void 0;var OC=sr(),NC=k(),CC=de(),xC=Je(),LC=ie(),DC=cE(),sn=Hf(),uE=(0,OC.debug)("zuplo:policies:RateLimitInboundPolicy"),MC="strict",UC=o(async(t,e,r,n)=>{if((r.mode??MC)==="async")return(0,DC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=xC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new NC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[sn.RETRY_AFTER_HEADER]=d.toString()),CC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",v=(0,sn.getRedisClient)(n,a),g=`bucket/${LC.Environment.instance.build.BUILD_ID}/${n}/${f}`,S=await(0,sn.getCountAndUpdateExpiry)(g,y,v,a,e.requestId);return S.count>h?(uE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,S.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;uE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Rc.RateLimitInboundPolicy=UC});var hE=_(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ReadmeMetricsInboundPolicy=void 0;var kC=Ae(),qf=ie(),dE=Jt(),$f;function pE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(pE,"headersToNameValuePairs");function FC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(FC,"queryToNameValueParis");function HC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(HC,"parseIntOrUndefined");var fE={};async function qC(t,e,r,n){let i=new Date,s=Date.now();return $f||($f={name:"zuplo",version:qf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${qf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,dE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,dE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:qf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:$f,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:pE(t.headers),queryString:FC(t.query)},response:{status:a.status,statusText:a.statusText,headers:pE(a.headers),content:{size:HC(t.headers.get("content-length"))}}}]}}},d=fE[r.apiKey];if(!d){let p=r.apiKey;d=new kC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),fE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(qC,"ReadmeMetricsInboundPolicy");Oc.ReadmeMetricsInboundPolicy=qC});var mE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.RemoveHeadersInboundPolicy=void 0;var $C=k(),jC=Ke(),VC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new $C.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new jC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Nc.RemoveHeadersInboundPolicy=VC});var yE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RemoveHeadersOutboundPolicy=void 0;var BC=k(),GC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new BC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Cc.RemoveHeadersOutboundPolicy=GC});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.RemoveQueryParamsInboundPolicy=void 0;var KC=k(),JC=Ke(),zC=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new KC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new JC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");xc.RemoveQueryParamsInboundPolicy=zC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.ReplaceStringOutboundPolicy=void 0;var WC=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Lc.ReplaceStringOutboundPolicy=WC});var EE=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RequestSizeLimitInboundPolicy=void 0;var _E=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),QC=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?_E():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?_E():t},"RequestSizeLimitInboundPolicy");Dc.RequestSizeLimitInboundPolicy=QC});var Mc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function YC(t,e,r){return`_${an(t+"_"+e+"_"+r)}`}o(YC,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=YC;function ZC(t,e,r,n){return`_${an(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(ZC,"getIdForParameterSchema");pt.getIdForParameterSchema=ZC;function XC(t,e,r){return`_${an(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${an(r.toLowerCase())}`}o(XC,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=XC;function ex(t,e){return`_${an(t)}__${an(e)}`}o(ex,"getIdForRefSchema");pt.getIdForRefSchema=ex;function an(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(an,"sanitizedIdentifierName");pt.sanitizedIdentifierName=an});var ao=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var tx=qr(),rx=Mc(),nx=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");je.getParametersForOperation=nx;var ix=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,rx.getIdForParameterSchema)(r,n,i,u.name),p=tx.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=ix;var ox=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=ox;var sx=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=sx;var ax=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=ax;var cx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=cx});var wE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.handleBodyValidation=void 0;var ux=qr(),Uc=de(),lx=Mc(),tt=ao();async function dx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Uc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Uc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,lx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=ux.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Uc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Uc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(dx,"handleBodyValidation");kc.handleBodyValidation=dx});var vE=_(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.handleHeadersValidation=void 0;var px=de(),co=ao();function fx(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,co.getParametersForOperation)(t),s=(0,co.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=px.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,co.shouldLog)(r.validateHeaders)&&(0,co.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,co.shouldReject)(r.validateHeaders))return c}}o(fx,"handleHeadersValidation");Fc.handleHeadersValidation=fx});var TE=_(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.handlePathParameterValidation=void 0;var hx=de(),uo=ao();function mx(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,uo.getParametersForOperation)(t),i=(0,uo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=hx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,uo.shouldLog)(r.validatePathParameters)&&(0,uo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,uo.shouldReject)(r.validatePathParameters))return a}}o(mx,"handlePathParameterValidation");Hc.handlePathParameterValidation=mx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleQueryParameterValidation=void 0;var yx=de(),lo=ao();function gx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=yx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validateQueryParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validateQueryParameters))return a}}o(gx,"handleQueryParameterValidation");qc.handleQueryParameterValidation=gx});var IE=_(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.SchemaBasedRequestValidation=cn.RequestValidationInboundPolicy=void 0;var bx=wE(),_x=vE(),Ex=TE(),wx=SE(),vx=o(async(t,e,r)=>{let n=(0,wx.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Ex.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,_x.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,bx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");cn.RequestValidationInboundPolicy=vx;cn.SchemaBasedRequestValidation=cn.RequestValidationInboundPolicy});var PE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.RequireOriginInboundPolicy=void 0;var Tx=k(),Sx=de(),Ix=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Tx.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Sx.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");$c.RequireOriginInboundPolicy=Ix});var AE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.SetBodyInboundPolicy=void 0;var Px=Ke(),Ax=o(async(t,e,r)=>new Px.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");jc.SetBodyInboundPolicy=Ax});var OE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.SetHeadersInboundPolicy=void 0;var RE=k(),Rx=Ke(),Ox=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new RE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new RE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Rx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Vc.SetHeadersInboundPolicy=Ox});var CE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.SetHeadersOutboundPolicy=void 0;var NE=k(),Nx=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new NE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new NE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Bc.SetHeadersOutboundPolicy=Nx});var LE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetQueryParamsInboundPolicy=void 0;var xE=k(),Cx=Ke(),xx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new xE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new xE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Cx.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Gc.SetQueryParamsInboundPolicy=xx});var DE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetStatusOutboundPolicy=void 0;var Lx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Kc.SetStatusOutboundPolicy=Lx});var ME=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SleepInboundPolicy=void 0;var Dx=k(),Mx=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),Ux=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Dx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await Mx(r.sleepInMs),t},"SleepInboundPolicy");Jc.SleepInboundPolicy=Ux});var kE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SupabaseJwtInboundPolicy=void 0;var UE=k(),kx=de(),Fx=Ke(),Hx=lt(),qx=er(),$x=o(async(t,e,r,n)=>{(0,Hx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,qx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Fx.ZuploRequest))throw new UE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new UE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?kx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");zc.SupabaseJwtInboundPolicy=$x});var HE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var jx=Xt(),Vx=Bt(),FE=k(),Bx=kn(),Gx=lt(),Kx=o(async(t,e,r,n)=>{(0,Gx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,jx.getPolicyCacheName)(n,r),s=new Vx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Jx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Wc.UpstreamAzureAdServiceAuthInboundPolicy=Kx;async function Jx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Bx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new FE.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new FE.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Jx,"getAccessToken")});var $E=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var zx=Xt(),Wx=Bt(),Qx=k(),jf=Fn(),Yx=lt(),qE="https://accounts.google.com/o/oauth2/token",Vf,Zx=o(async(t,e,r,n)=>{(0,Yx.optionValidator)(r,n).required("serviceAccountJson","string"),Vf||(Vf=await jf.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,zx.getPolicyCacheName)(n,r),a=new Wx.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,jf.getTokenFromGcpServiceAccount)({serviceAccount:Vf,audience:qE,payload:i}),l=await(0,jf.exchangeGgpJwtForIdToken)(qE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new Qx.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Qc.UpstreamFirebaseAdminAuthInboundPolicy=Zx});var jE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var Xx=Xt(),eL=Bt(),pi=k(),tL=Tf(),Bf=Fn(),rL=Jt(),nL=lt(),iL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",oL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Gf,sL=o(async(t,e,r,n)=>{if((0,nL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(oL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,rL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,Xx.getPolicyCacheName)(n,r),c=new eL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,tL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:iL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Bf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");Yc.UpstreamFirebaseUserAuthInboundPolicy=sL});var BE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamGcpJwtInboundPolicy=void 0;var VE=Fn(),aL=lt(),Kf,cL=o(async(t,e,r,n)=>{(0,aL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Kf||(Kf=await VE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,VE.getTokenFromGcpServiceAccount)({serviceAccount:Kf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");Zc.UpstreamGcpJwtInboundPolicy=cL});var KE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamGcpServiceAuthInboundPolicy=void 0;var uL=Xt(),lL=Qu(),dL=Bt(),po=k(),Jf=Fn(),pL=Jt(),fL=lt(),GE="https://www.googleapis.com/oauth2/v4/token",zf,hL=o(async(t,e,r,n)=>{(0,fL.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),zf||(zf=await Jf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new po.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,pL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof po.ConfigurationError?new po.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,uL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new lL.MemoryCache(s):a=new dL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Jf.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:GE,payload:i}),l=await(0,Jf.exchangeGgpJwtForIdToken)(GE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new po.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new po.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");Xc.UpstreamGcpServiceAuthInboundPolicy=hL});var zE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.ValidateJsonSchemaInbound=void 0;var mL=k(),JE=de(),yL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return JE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new mL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return JE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");eu.ValidateJsonSchemaInbound=yL});var YE=_((qJ,QE)=>{"use strict";var gL=Object.defineProperty,bL=Object.getOwnPropertyNames,B=o((t,e)=>gL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[bL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Wf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),WE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Wf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,S){S=Object.assign({},r,S);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
74
+ `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Zr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(GR,"validateComputedSignature");function KR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(KR,"parseHeader");function JR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(JR,"secureCompare");async function r_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Xp[s[c]];return a.join("")}o(r_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=r_;var Xp=new Array(256);for(let t=0;t<Xp.length;t++)Xp[t]=t.toString(16).padStart(2,"0")});var lt=_(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.optionValidator=void 0;var ri=k(),zR=at();function WR(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,zR.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(WR,"optionValidator");ja.optionValidator=WR});var tf=_(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.StripeWebhookVerificationInboundPolicy=void 0;var QR=_n(),YR=de(),ZR=n_(),XR=lt(),ef=class extends QR.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,XR.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,ZR.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),YR.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Va.StripeWebhookVerificationInboundPolicy=ef});var o_=_(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.isStripeWebhookEvent=void 0;var i_=at();function eO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,i_.isString)(t.id)&&"type"in t&&(0,i_.isString)(t.type)}o(eO,"isStripeWebhookEvent");Ba.isStripeWebhookEvent=eO});var s_=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.MeteringPlugin=void 0;var tO=Ot(),rf=class extends tO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};Ga.MeteringPlugin=rf});var sf=_(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var nf=k(),rO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new nf.RuntimeError(s)}return i}};of.default=rO});var c_=_(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.deleteConsumer=Rr.createConsumerInvite=Rr.createConsumer=void 0;var af=k(),cf=Je(),uf=ie(),lf=kn(),df="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",a_="My API Key";async function nO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=uf.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,df);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:a_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new af.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(nO,"createConsumer");Rr.createConsumer=nO;async function iO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=uf.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,df);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:a_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new af.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(iO,"createConsumerInvite");Rr.createConsumerInvite=iO;async function oO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=uf.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,df);i.searchParams.set("with-api-key","true");let s=await(0,lf.fetchRetry)({retryDelayMs:5,retries:2,logger:cf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new af.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(oO,"deleteConsumer");Rr.deleteConsumer=oO});var Ka=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getSubscription=Nr.updateSubscription=Nr.createSubscription=void 0;var Or=k(),pf=Je(),ff=ie(),hf=kn(),mf=at();async function sO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c,metadata:u}){let l={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:u},{authApiJWT:d,meteringServiceUrl:p}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(d))throw new Or.SystemError("No Zuplo JWT token set.");let f=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${p}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!f.ok){let h="Error creating monetization subscription.",y;try{y=await f.json()}catch{y={status:f.status,statusText:f.statusText}}throw t.log.error(h,y),new Or.RuntimeError(h)}t.log.info("Successfully created monetization subscription.",l)}o(sO,"createSubscription");Nr.createSubscription=sO;async function aO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(i))throw new Or.SystemError("No Zuplo JWT token set.");let a=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Or.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(aO,"updateSubscription");Nr.updateSubscription=aO;async function cO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=ff.Environment.instance;if(!(0,mf.isNonEmptyString)(i))throw new Or.SystemError("No Zuplo JWT token set.");let a=await(0,hf.fetchRetry)({retryDelayMs:5,retries:2,logger:pf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Or.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Or.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Or.RuntimeError(u)}return c.data[0]}o(cO,"getSubscription");Nr.getSubscription=cO});var yf=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.stripeStatusToMeteringStatus=void 0;function uO(t){return t.replaceAll("_","-")}o(uO,"stripeStatusToMeteringStatus");Ja.stripeStatusToMeteringStatus=uO});var u_=_(eo=>{"use strict";var lO=eo&&eo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(eo,"__esModule",{value:!0});var Xr=de(),dO=lO(sf()),gf=c_(),pO=Ka(),fO=yf();async function hO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u,l,d;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,u=await(0,gf.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await dO.default.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),Xr.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,gf.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!u)return Xr.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=(0,fO.stripeStatusToMeteringStatus)(r.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}}),await(0,pO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f})}catch(p){return await(0,gf.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),Xr.HttpProblems.internalServerError(t,e,{detail:p.message})}return Xr.HttpProblems.ok(t,e)}o(hO,"onCustomerSubscriptionCreated");eo.default=hO});var d_=_(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var bf=de(),l_=Ka();async function mO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),bf.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),bf.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,l_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,l_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),bf.HttpProblems.ok(t,e)}o(mO,"onCustomerSubscriptionDeleted");_f.default=mO});var p_=_(ro=>{"use strict";var yO=ro&&ro.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ro,"__esModule",{value:!0});var to=de(),gO=yO(sf()),za=Ka(),bO=yf();async function _O(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),to.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),to.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,za.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,bO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,za.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),to.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,za.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await gO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,za.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),to.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),to.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(_O,"onCustomerSubscriptionUpdated");ro.default=_O});var h_=_(ni=>{"use strict";var wf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Wa=Qi(),Qa=k(),EO=Gt(),wO=tf(),f_=de(),vO=cr(),TO=En(),SO=wl(),IO=gt(),PO=ie(),AO=o_(),RO=lt(),OO=s_(),NO=wf(u_()),CO=wf(d_()),xO=wf(p_()),Ef=class extends OO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Wa.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Wa.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Qa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Wa.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Wa.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Qa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!PO.Environment.instance.build.ACCOUNT_NAME)throw new Qa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!LO(p))throw new Qa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,AO.isStripeWebhookEvent)(f))return f_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,NO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,xO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,CO.default)(c,u,f,{meteringBucketId:l});default:return f_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,TO.createInternalPolicyProcessor)({inboundPolicies:[new wO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,RO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new EO.Pipeline({processors:[vO.metricsProcessor,i],handler:n,gateway:r}),a=new IO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:SO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=Ef;function LO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(LO,"isMetricsRegion")});var __=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var m_=k(),DO=Ae(),y_=Jt(),b_=new WeakMap,g_={},vf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){b_.set(e,r)}};ii.AmberfloMeteringPolicy=vf;async function MO(t,e,r,n){if(!r.statusCodes)throw new m_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,y_.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=b_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new m_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,y_.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=g_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new DO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let v=r.url??"https://app.amberflo.io/ingest",A=await fetch(v,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(v){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${v.message}`),v}}),g_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o(MO,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=MO});var Tf=_(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.sha256=void 0;async function UO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(UO,"sha256");Ya.sha256=UO});var Xt=_(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.getPolicyCacheName=void 0;var kO=Tf(),E_=new Map;async function FO(t,e){let r,n=E_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,kO.sha256)(JSON.stringify({policyName:t,options:e}))}`,E_.set(t,r)),r}o(FO,"getPolicyCacheName");Za.getPolicyCacheName=FO});var Pf=_(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.ApiKeyInboundPolicy=void 0;var HO=Xt(),qO=Bt(),w_=Qi(),Sf=k(),$O=Kt(),v_=Je(),If=ie(),jO=kn(),T_="key-metadata-cache-type";function VO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(VO,"getKeyValue");async function BO(t,e,r,n){if(!r.bucketName)if(w_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=w_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Sf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Sf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:$O.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=VO(a,i);if(!c||c==="")return s("No key present");let u=await GO(c),l=await(0,HO.getPolicyCacheName)(n,i),d=new qO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==T_&&v_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,jO.fetchRetry)({retryDelayMs:5,retries:2,logger:v_.SystemLogMap.getLogger(e)},`${If.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":If.Environment.instance.deploymentName??"unknown","User-Agent":If.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let v=await h.text(),A=JSON.parse(v);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Sf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:T_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(BO,"ApiKeyInboundPolicy");Xa.ApiKeyInboundPolicy=BO;async function GO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(GO,"hashValue")});var S_=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ApiAuthKeyInboundPolicy=void 0;var KO=Pf();ec.ApiAuthKeyInboundPolicy=KO.ApiKeyInboundPolicy});var er=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.OpenIdJwtInboundPolicy=void 0;var Rf=(ta(),Co(ea)),Of=k(),JO=de(),Af={},zO=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Of.ConfigurationError("Invalid State - jwkUrl not set");Af[e.jwkUrl]||(Af[e.jwkUrl]=(0,Rf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Rf.jwtVerify)(t,Af[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),WO=o(async(t,e)=>{let r;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);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Rf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),QO=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>JO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Of.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Of.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?zO:WO,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");tc.OpenIdJwtInboundPolicy=QO});var I_=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.Auth0JwtInboundPolicy=void 0;var YO=er(),ZO=o(async(t,e,r,n)=>(0,YO.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");rc.Auth0JwtInboundPolicy=ZO});var P_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.BasicAuthInboundPolicy=void 0;var XO=de(),eN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>XO.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");nc.BasicAuthInboundPolicy=eN});var A_=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.CachingInboundPolicy=void 0;var tN=Xt(),rN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function nN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(nN,"digestMessage");var iN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await nN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function oN(t,e,r,n){let i=await(0,tN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await iN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);rN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(oN,"CachingInboundPolicy");ic.CachingInboundPolicy=oN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.ChangeMethodInboundPolicy=void 0;var sN=k(),aN=Ke(),cN=o(async(t,e,r,n)=>{if(!r.method)throw new sN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new aN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");oc.ChangeMethodInboundPolicy=cN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.ClearHeadersInboundPolicy=void 0;var uN=Ke(),lN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new uN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");sc.ClearHeadersInboundPolicy=lN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.ClearHeadersOutboundPolicy=void 0;var dN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");ac.ClearHeadersOutboundPolicy=dN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ClerkJwtInboundPolicy=void 0;var pN=er(),fN=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,pN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");cc.ClerkJwtInboundPolicy=fN});var L_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.CognitoJwtInboundPolicy=void 0;var x_=k(),hN=er(),mN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new x_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new x_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,hN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");uc.CognitoJwtInboundPolicy=mN});var M_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.CompositeInboundPolicy=void 0;var yN=k(),gN=qr(),D_=En(),bN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new yN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=gN.Gateway.instance,s=(0,D_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,D_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");lc.CompositeInboundPolicy=bN});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CurityPhantomTokenInboundPolicy=void 0;var _N=Xt(),EN=Bt(),dc=de(),wN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return dc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=vN(i);if(!s)return dc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,_N.getPolicyCacheName)(n,r),c=new EN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),dc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):dc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");pc.CurityPhantomTokenInboundPolicy=wN;function vN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(vN,"getToken")});var k_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.FirebaseJwtInboundPolicy=void 0;var TN=lt(),SN=er(),IN=o(async(t,e,r,n)=>((0,TN.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,SN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");fc.FirebaseJwtInboundPolicy=IN});var F_=_(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.FormDataToJsonInboundPolicy=void 0;var PN=Ke(),AN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new PN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");hc.FormDataToJsonInboundPolicy=AN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.GeoFilterInboundPolicy=void 0;var RN=k(),ON=de(),oi="__unknown__",NN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,v=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||v.length>0&&v.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");mc.GeoFilterInboundPolicy=NN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),ON.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new RN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.JWTScopeValidationInboundPolicy=void 0;var CN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");yc.JWTScopeValidationInboundPolicy=CN});var j_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.MockApiInboundPolicy=void 0;var xN=de(),LN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return Nf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return Nf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return $_(a[c])}else return a.length>0?$_(a[0]):Nf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");gc.MockApiInboundPolicy=LN;function $_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o($_,"generateResponse");var Nf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return xN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var J_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var DN=k(),MN=Ae(),UN="Incoming",kN={logRequestBody:!0,logResponseBody:!0};function V_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(V_,"headersToObject");function B_(){return new Date().toISOString()}o(B_,"timestamp");var Cf=new WeakMap,FN={};function HN(t,e){let r=Cf.get(t);r||(r=FN);let n=Object.assign({...r},e);Cf.set(t,n)}o(HN,"setMoesifContext");ci.setMoesifContext=HN;async function G_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(G_,"readBody");var qN={},xf;function K_(){if(!xf)throw new DN.RuntimeError("Invalid State - no _lastLogger");return xf}o(K_,"getLastLogger");function $N(t){let e=qN[t];return e||(e=new MN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);K_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||K_().error({status:i.status,body:await i.text()})})),e}o($N,"getDispatcher");async function jN(t,e,r,n){xf=e.log;let i=B_(),s=Object.assign(kN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await G_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=$N(s.applicationId),d=t.headers.get("true-client-ip"),p=Cf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:V_(t.headers)},h=s.logResponseBody?await G_(c,e):void 0,y={time:B_(),status:c.status,headers:V_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:UN};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(jN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=jN});var Q_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var z_=Je(),W_=ie();async function VN(t,e,r,n){let i=z_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=W_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(VN,"loadSubscription");ui.loadSubscription=VN;async function BN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=W_.Environment.instance,c=z_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(BN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=BN});var Y_=_(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.compareMeters=Cr.parseAllowedSubscriptionStatuses=Cr.validateMeters=void 0;var en=k(),GN=Jt(),KN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function JN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new en.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof en.ConfigurationError?new en.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(JN,"validateMeters");Cr.validateMeters=JN;function zN(t,e){if(t)try{if(t.length===0)throw new en.ConfigurationError("Must set valid subscription statuses");let r=(0,GN.parseValueToStringArray)(t),n=[];for(let i of r)KN.has(i)||n.push(i);if(n.length>0)throw new en.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof en.ConfigurationError?new en.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(zN,"parseAllowedSubscriptionStatuses");Cr.parseAllowedSubscriptionStatuses=zN;function WN(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(WN,"compareMeters");Cr.compareMeters=WN});var eE=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.MonetizationInboundPolicy=void 0;var tn=fn(),rn=gp(),bc=Qi(),Z_=k(),QN=_n(),nn=de(),YN=Jt(),ZN=lt(),X_=Q_(),no=Y_(),Lf=class extends QN.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return rn.ContextData.get(e,tn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,no.validateMeters)(r,"setMeters"),rn.ContextData.set(e,tn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,ZN.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,i=(0,YN.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=rn.ContextData.get(r,tn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,no.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,no.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,v,A)=>{let g=rn.ContextData.get(A,tn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Z_.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=rn.ContextData.get(A,tn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,no.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,no.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,X_.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:nn.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=bc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Z_.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,X_.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:nn.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),nn.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),rn.ContextData.set(r,tn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=rn.ContextData.get(r,tn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),nn.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),nn.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),nn.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].consumed<=0&&!n)return nn.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};_c.MonetizationInboundPolicy=Lf});var tE=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.OktaJwtInboundPolicy=void 0;var XN=er(),eC=o(async(t,e,r,n)=>(0,XN.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Ec.OktaJwtInboundPolicy=eC});var rE=_(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.PropelAuthJwtInboundPolicy=void 0;var tC=(ta(),Co(ea)),rC=er(),Df,nC=o(async(t,e,r,n)=>{if(!Df)try{Df=await(0,tC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,rC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Df,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");wc.PropelAuthJwtInboundPolicy=nC});var nE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var io=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=io;var oo=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=oo;function iC(t,e){if((0,Ye.isUndefined)(t))throw new io(e)}o(iC,"throwIfUndefined");Z.throwIfUndefined=iC;function Mf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new io(e)}o(Mf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=Mf;function oC(t,e){if(Mf(t,e),!(0,Ye.isString)(t))throw new oo(e,"string")}o(oC,"throwIfNotString");Z.throwIfNotString=oC;function sC(t,e){if(Mf(t,e),!(0,Ye.isNumber)(t))throw new oo(e,"number")}o(sC,"throwIfNotNumber");Z.throwIfNotNumber=sC;var so=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=so;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function aC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new so(t,e,r)}o(aC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=aC;function vc(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new so(t,e,r)}o(vc,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=vc;function cC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(cC,"throwIfOptionNotString");Z.throwIfOptionNotString=cC;function uC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(uC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=uC;function lC(t,e,r,n){if(vc(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(lC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=lC;function dC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(dC,"throwIfStateUndefined");Z.throwIfStateUndefined=dC;function Tc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Tc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Tc;function pC(t,e){if(Tc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(pC,"throwIfStateNotString");Z.throwIfStateNotString=pC;function fC(t,e){if(Tc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(fC,"throwIfStateNotNumber");Z.throwIfStateNotNumber=fC;function hC(t,e){if(Tc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(hC,"throwIfStateNotObject");Z.throwIfStateNotObject=hC});var iE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Uf=k(),Sc=nE(),kf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Sc.throwIfNotString)(e,"redisClientUrl"),(0,Sc.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Sc.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Uf.SystemError("Redis client failed with 401: Unauthorized"):new Uf.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=kf;var Ff=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Sc.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Uf.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=Ff});var Hf=_(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.RETRY_AFTER_HEADER=Pe.wrapUserFunction=Pe.getCountAndUpdateExpiry=Pe.getRedisClient=Pe.getAll=Pe.getUser=Pe.getIP=Pe.getRealIP=void 0;var xr=k(),Ic=ie(),oE=iE(),sE=at(),mC=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Pe.getRealIP=mC;var yC=o(async t=>({key:`ip-${(0,Pe.getRealIP)(t)}`}),"getIP");Pe.getIP=yC;var gC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Pe.getUser=gC;var bC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Pe.getAll=bC;var Pc;function _C(t,e){let r;if(Pc)return Pc;if(Ic.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new oE.InMemoryRedisClient,Pc=r,r;let{authApiJWT:n,redisURL:i}=Ic.Environment.instance;if(!(0,sE.isString)(i))throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,sE.isString)(n))throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=oE.StandardRedisClient.initialize(i,n,Ic.Environment.instance.deploymentName??"unknown",Ic.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new xr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Pc=r,r}o(_C,"getRedisClient");Pe.getRedisClient=_C;async function EC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(EC,"getCountAndUpdateExpiry");Pe.getCountAndUpdateExpiry=EC;function wC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new xr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new xr.RuntimeError(u)}return c},"outerFunction")}o(wC,"wrapUserFunction");Pe.wrapUserFunction=wC;Pe.RETRY_AFTER_HEADER="Retry-After"});var cE=_(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.AsyncRateLimitInboundPolicy=void 0;var vC=sr(),TC=Xt(),SC=de(),IC=Je(),PC=ie(),AC=Bt(),on=Hf(),aE=(0,vC.debug)("zuplo:policies:RateLimitInboundPolicy"),RC=o(async(t,e,r,n)=>{let i=IC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[on.RETRY_AFTER_HEADER]=T.toString()),SC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,on.wrapUserFunction)(r,n),user:on.getUser,ip:on.getIP,all:on.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,on.getRedisClient)(n,i),b=`bucket/${PC.Environment.instance.build.BUILD_ID}/${n}/${l}`,v=await(0,TC.getPolicyCacheName)(n,r),A=new AC.MemoryZoneReadThroughCache(v,e),g=(0,on.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),S;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),aE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),S=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){aE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>S??E),t},"AsyncRateLimitInboundPolicy");Ac.AsyncRateLimitInboundPolicy=RC});var lE=_(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.RateLimitInboundPolicy=void 0;var OC=sr(),NC=k(),CC=de(),xC=Je(),LC=ie(),DC=cE(),sn=Hf(),uE=(0,OC.debug)("zuplo:policies:RateLimitInboundPolicy"),MC="strict",UC=o(async(t,e,r,n)=>{if((r.mode??MC)==="async")return(0,DC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=xC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new NC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[sn.RETRY_AFTER_HEADER]=d.toString()),CC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",v=(0,sn.getRedisClient)(n,a),g=`bucket/${LC.Environment.instance.build.BUILD_ID}/${n}/${f}`,S=await(0,sn.getCountAndUpdateExpiry)(g,y,v,a,e.requestId);return S.count>h?(uE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,S.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;uE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Rc.RateLimitInboundPolicy=UC});var hE=_(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ReadmeMetricsInboundPolicy=void 0;var kC=Ae(),qf=ie(),dE=Jt(),$f;function pE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(pE,"headersToNameValuePairs");function FC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(FC,"queryToNameValueParis");function HC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(HC,"parseIntOrUndefined");var fE={};async function qC(t,e,r,n){let i=new Date,s=Date.now();return $f||($f={name:"zuplo",version:qf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${qf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,dE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,dE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:qf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:$f,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:pE(t.headers),queryString:FC(t.query)},response:{status:a.status,statusText:a.statusText,headers:pE(a.headers),content:{size:HC(t.headers.get("content-length"))}}}]}}},d=fE[r.apiKey];if(!d){let p=r.apiKey;d=new kC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),fE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(qC,"ReadmeMetricsInboundPolicy");Oc.ReadmeMetricsInboundPolicy=qC});var mE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.RemoveHeadersInboundPolicy=void 0;var $C=k(),jC=Ke(),VC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new $C.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new jC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Nc.RemoveHeadersInboundPolicy=VC});var yE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RemoveHeadersOutboundPolicy=void 0;var BC=k(),GC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new BC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Cc.RemoveHeadersOutboundPolicy=GC});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.RemoveQueryParamsInboundPolicy=void 0;var KC=k(),JC=Ke(),zC=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new KC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new JC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");xc.RemoveQueryParamsInboundPolicy=zC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.ReplaceStringOutboundPolicy=void 0;var WC=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Lc.ReplaceStringOutboundPolicy=WC});var EE=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RequestSizeLimitInboundPolicy=void 0;var _E=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),QC=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?_E():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?_E():t},"RequestSizeLimitInboundPolicy");Dc.RequestSizeLimitInboundPolicy=QC});var Mc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function YC(t,e,r){return`_${an(t+"_"+e+"_"+r)}`}o(YC,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=YC;function ZC(t,e,r,n){return`_${an(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(ZC,"getIdForParameterSchema");pt.getIdForParameterSchema=ZC;function XC(t,e,r){return`_${an(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${an(r.toLowerCase())}`}o(XC,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=XC;function ex(t,e){return`_${an(t)}__${an(e)}`}o(ex,"getIdForRefSchema");pt.getIdForRefSchema=ex;function an(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(an,"sanitizedIdentifierName");pt.sanitizedIdentifierName=an});var ao=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var tx=qr(),rx=Mc(),nx=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");je.getParametersForOperation=nx;var ix=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,rx.getIdForParameterSchema)(r,n,i,u.name),p=tx.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=ix;var ox=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=ox;var sx=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=sx;var ax=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=ax;var cx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=cx});var wE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.handleBodyValidation=void 0;var ux=qr(),Uc=de(),lx=Mc(),tt=ao();async function dx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Uc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Uc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,lx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=ux.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Uc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Uc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(dx,"handleBodyValidation");kc.handleBodyValidation=dx});var vE=_(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.handleHeadersValidation=void 0;var px=de(),co=ao();function fx(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,co.getParametersForOperation)(t),s=(0,co.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=px.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,co.shouldLog)(r.validateHeaders)&&(0,co.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,co.shouldReject)(r.validateHeaders))return c}}o(fx,"handleHeadersValidation");Fc.handleHeadersValidation=fx});var TE=_(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.handlePathParameterValidation=void 0;var hx=de(),uo=ao();function mx(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,uo.getParametersForOperation)(t),i=(0,uo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=hx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,uo.shouldLog)(r.validatePathParameters)&&(0,uo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,uo.shouldReject)(r.validatePathParameters))return a}}o(mx,"handlePathParameterValidation");Hc.handlePathParameterValidation=mx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleQueryParameterValidation=void 0;var yx=de(),lo=ao();function gx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=yx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validateQueryParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validateQueryParameters))return a}}o(gx,"handleQueryParameterValidation");qc.handleQueryParameterValidation=gx});var IE=_(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.SchemaBasedRequestValidation=cn.RequestValidationInboundPolicy=void 0;var bx=wE(),_x=vE(),Ex=TE(),wx=SE(),vx=o(async(t,e,r)=>{let n=(0,wx.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Ex.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,_x.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,bx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");cn.RequestValidationInboundPolicy=vx;cn.SchemaBasedRequestValidation=cn.RequestValidationInboundPolicy});var PE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.RequireOriginInboundPolicy=void 0;var Tx=k(),Sx=de(),Ix=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Tx.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Sx.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");$c.RequireOriginInboundPolicy=Ix});var AE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.SetBodyInboundPolicy=void 0;var Px=Ke(),Ax=o(async(t,e,r)=>new Px.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");jc.SetBodyInboundPolicy=Ax});var OE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.SetHeadersInboundPolicy=void 0;var RE=k(),Rx=Ke(),Ox=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new RE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new RE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Rx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Vc.SetHeadersInboundPolicy=Ox});var CE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.SetHeadersOutboundPolicy=void 0;var NE=k(),Nx=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new NE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new NE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Bc.SetHeadersOutboundPolicy=Nx});var LE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetQueryParamsInboundPolicy=void 0;var xE=k(),Cx=Ke(),xx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new xE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new xE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Cx.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Gc.SetQueryParamsInboundPolicy=xx});var DE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetStatusOutboundPolicy=void 0;var Lx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Kc.SetStatusOutboundPolicy=Lx});var ME=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SleepInboundPolicy=void 0;var Dx=k(),Mx=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),Ux=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Dx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await Mx(r.sleepInMs),t},"SleepInboundPolicy");Jc.SleepInboundPolicy=Ux});var kE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SupabaseJwtInboundPolicy=void 0;var UE=k(),kx=de(),Fx=Ke(),Hx=lt(),qx=er(),$x=o(async(t,e,r,n)=>{(0,Hx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,qx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Fx.ZuploRequest))throw new UE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new UE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?kx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");zc.SupabaseJwtInboundPolicy=$x});var HE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var jx=Xt(),Vx=Bt(),FE=k(),Bx=kn(),Gx=lt(),Kx=o(async(t,e,r,n)=>{(0,Gx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,jx.getPolicyCacheName)(n,r),s=new Vx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Jx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Wc.UpstreamAzureAdServiceAuthInboundPolicy=Kx;async function Jx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Bx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new FE.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new FE.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Jx,"getAccessToken")});var $E=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var zx=Xt(),Wx=Bt(),Qx=k(),jf=Fn(),Yx=lt(),qE="https://accounts.google.com/o/oauth2/token",Vf,Zx=o(async(t,e,r,n)=>{(0,Yx.optionValidator)(r,n).required("serviceAccountJson","string"),Vf||(Vf=await jf.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,zx.getPolicyCacheName)(n,r),a=new Wx.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,jf.getTokenFromGcpServiceAccount)({serviceAccount:Vf,audience:qE,payload:i}),l=await(0,jf.exchangeGgpJwtForIdToken)(qE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new Qx.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Qc.UpstreamFirebaseAdminAuthInboundPolicy=Zx});var jE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var Xx=Xt(),eL=Bt(),pi=k(),tL=Tf(),Bf=Fn(),rL=Jt(),nL=lt(),iL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",oL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Gf,sL=o(async(t,e,r,n)=>{if((0,nL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(oL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,rL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,Xx.getPolicyCacheName)(n,r),c=new eL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,tL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:iL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Bf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");Yc.UpstreamFirebaseUserAuthInboundPolicy=sL});var BE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamGcpJwtInboundPolicy=void 0;var VE=Fn(),aL=lt(),Kf,cL=o(async(t,e,r,n)=>{(0,aL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Kf||(Kf=await VE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,VE.getTokenFromGcpServiceAccount)({serviceAccount:Kf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");Zc.UpstreamGcpJwtInboundPolicy=cL});var KE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamGcpServiceAuthInboundPolicy=void 0;var uL=Xt(),lL=Qu(),dL=Bt(),po=k(),Jf=Fn(),pL=Jt(),fL=lt(),GE="https://www.googleapis.com/oauth2/v4/token",zf,hL=o(async(t,e,r,n)=>{(0,fL.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),zf||(zf=await Jf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new po.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,pL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof po.ConfigurationError?new po.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,uL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new lL.MemoryCache(s):a=new dL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Jf.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:GE,payload:i}),l=await(0,Jf.exchangeGgpJwtForIdToken)(GE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new po.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new po.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");Xc.UpstreamGcpServiceAuthInboundPolicy=hL});var zE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.ValidateJsonSchemaInbound=void 0;var mL=k(),JE=de(),yL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return JE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new mL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return JE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");eu.ValidateJsonSchemaInbound=yL});var YE=_((qJ,QE)=>{"use strict";var gL=Object.defineProperty,bL=Object.getOwnPropertyNames,B=o((t,e)=>gL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[bL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Wf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),WE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Wf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,S){S=Object.assign({},r,S);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
75
75
  `&&g[T]!=="\r";T++)P+=g[T];if(P=P.trim(),P[P.length-1]==="/"&&(P=P.substring(0,P.length-1),T--),!b(P)){let j;return P.trim().length===0?j="Invalid space after '<'.":j="Tag '"+P+"' is an invalid name.",h("InvalidTag",j,v(g,T))}let x=u(g,T);if(x===!1)return h("InvalidAttr","Attributes for '"+P+"' have open quote.",v(g,T));let te=x.value;if(T=x.index,te[te.length-1]==="/"){let j=T-te.length;te=te.substring(0,te.length-1);let D=d(te,S);if(D===!0)V=!0;else return h(D.err.code,D.err.msg,v(g,j+D.err.line))}else if(w)if(x.tagClosed){if(te.trim().length>0)return h("InvalidTag","Closing tag '"+P+"' can't have attributes or invalid starting.",v(g,C));{let j=O.pop();if(P!==j.tagName){let D=v(g,j.tagStartPos);return h("InvalidTag","Expected closing tag '"+j.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+P+"'.",v(g,C))}O.length==0&&(E=!0)}}else return h("InvalidTag","Closing tag '"+P+"' doesn't have proper closing.",v(g,T));else{let j=d(te,S);if(j!==!0)return h(j.err.code,j.err.msg,v(g,T-te.length+j.err.line));if(E===!0)return h("InvalidXml","Multiple possible root nodes found.",v(g,T));S.unpairedTags.indexOf(P)!==-1||O.push({tagName:P,tagStartPos:C}),V=!0}for(T++;T<g.length;T++)if(g[T]==="<")if(g[T+1]==="!"){T++,T=s(g,T);continue}else if(g[T+1]==="?"){if(T=i(g,++T),T.err)return T}else break;else if(g[T]==="&"){let j=f(g,T);if(j==-1)return h("InvalidChar","char '&' is not expected.",v(g,T));T=j}else if(E===!0&&!n(g[T]))return h("InvalidXml","Extra text at the end",v(g,T));g[T]==="<"&&T--}}else{if(n(g[T]))continue;return h("InvalidChar","char '"+g[T]+"' is not expected.",v(g,T))}if(V){if(O.length==1)return h("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",v(g,O[0].tagStartPos));if(O.length>0)return h("InvalidXml","Invalid '"+JSON.stringify(O.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return h("InvalidXml","Start tag expected.",1);return!0};function n(g){return g===" "||g===" "||g===`
76
76
  `||g==="\r"}o(n,"isWhiteSpace"),B(n,"isWhiteSpace");function i(g,S){let O=S;for(;S<g.length;S++)if(g[S]=="?"||g[S]==" "){let V=g.substr(O,S-O);if(S>5&&V==="xml")return h("InvalidXml","XML declaration allowed only at the start of the document.",v(g,S));if(g[S]=="?"&&g[S+1]==">"){S++;break}else continue}return S}o(i,"readPI"),B(i,"readPI");function s(g,S){if(g.length>S+5&&g[S+1]==="-"&&g[S+2]==="-"){for(S+=3;S<g.length;S++)if(g[S]==="-"&&g[S+1]==="-"&&g[S+2]===">"){S+=2;break}}else if(g.length>S+8&&g[S+1]==="D"&&g[S+2]==="O"&&g[S+3]==="C"&&g[S+4]==="T"&&g[S+5]==="Y"&&g[S+6]==="P"&&g[S+7]==="E"){let O=1;for(S+=8;S<g.length;S++)if(g[S]==="<")O++;else if(g[S]===">"&&(O--,O===0))break}else if(g.length>S+9&&g[S+1]==="["&&g[S+2]==="C"&&g[S+3]==="D"&&g[S+4]==="A"&&g[S+5]==="T"&&g[S+6]==="A"&&g[S+7]==="["){for(S+=8;S<g.length;S++)if(g[S]==="]"&&g[S+1]==="]"&&g[S+2]===">"){S+=2;break}}return S}o(s,"readCommentAndCDATA"),B(s,"readCommentAndCDATA");var a='"',c="'";function u(g,S){let O="",V="",E=!1;for(;S<g.length;S++){if(g[S]===a||g[S]===c)V===""?V=g[S]:V!==g[S]||(V="");else if(g[S]===">"&&V===""){E=!0;break}O+=g[S]}return V!==""?!1:{value:O,index:S,tagClosed:E}}o(u,"readAttributeStr"),B(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,S){let O=e.getAllMatches(g,l),V={};for(let E=0;E<O.length;E++){if(O[E][1].length===0)return h("InvalidAttr","Attribute '"+O[E][2]+"' has no space in starting.",A(O[E]));if(O[E][3]!==void 0&&O[E][4]===void 0)return h("InvalidAttr","Attribute '"+O[E][2]+"' is without value.",A(O[E]));if(O[E][3]===void 0&&!S.allowBooleanAttributes)return h("InvalidAttr","boolean attribute '"+O[E][2]+"' is not allowed.",A(O[E]));let T=O[E][2];if(!y(T))return h("InvalidAttr","Attribute '"+T+"' is an invalid name.",A(O[E]));if(!V.hasOwnProperty(T))V[T]=1;else return h("InvalidAttr","Attribute '"+T+"' is repeated.",A(O[E]))}return!0}o(d,"validateAttributeString"),B(d,"validateAttributeString");function p(g,S){let O=/\d/;for(g[S]==="x"&&(S++,O=/[\da-fA-F]/);S<g.length;S++){if(g[S]===";")return S;if(!g[S].match(O))break}return-1}o(p,"validateNumberAmpersand"),B(p,"validateNumberAmpersand");function f(g,S){if(S++,g[S]===";")return-1;if(g[S]==="#")return S++,p(g,S);let O=0;for(;S<g.length;S++,O++)if(!(g[S].match(/\w/)&&O<20)){if(g[S]===";")break;return-1}return S}o(f,"validateAmpersand"),B(f,"validateAmpersand");function h(g,S,O){return{err:{code:g,msg:S,line:O.line||O,col:O.col}}}o(h,"getErrorObject"),B(h,"getErrorObject");function y(g){return e.isName(g)}o(y,"validateAttrName"),B(y,"validateAttrName");function b(g){return e.isName(g)}o(b,"validateTagName"),B(b,"validateTagName");function v(g,S){let O=g.substring(0,S).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}o(v,"getLineNumberForPosition"),B(v,"getLineNumberForPosition");function A(g){return g.startIndex+g[1].length}o(A,"getPositionFromMatch"),B(A,"getPositionFromMatch")}}),_L=vt({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=B(function(n){return Object.assign({},e,n)},"buildOptions");t.buildOptions=r,t.defaultOptions=e}}),EL=vt({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var r=class{static{o(this,"XmlNode")}static{B(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};e.exports=r}}),wL=vt({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var r=Wf();function n(p,f){let h={};if(p[f+3]==="O"&&p[f+4]==="C"&&p[f+5]==="T"&&p[f+6]==="Y"&&p[f+7]==="P"&&p[f+8]==="E"){f=f+9;let y=1,b=!1,v=!1,A="";for(;f<p.length;f++)if(p[f]==="<"&&!v){if(b&&a(p,f))f+=7,[entityName,val,f]=i(p,f+1),val.indexOf("&")===-1&&(h[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&c(p,f))f+=8;else if(b&&u(p,f))f+=8;else if(b&&l(p,f))f+=9;else if(s)v=!0;else throw new Error("Invalid DOCTYPE");y++,A=""}else if(p[f]===">"){if(v?p[f-1]==="-"&&p[f-2]==="-"&&(v=!1,y--):y--,y===0)break}else p[f]==="["?b=!0:A+=p[f];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:h,i:f}}o(n,"readDocType"),B(n,"readDocType");function i(p,f){let h="";for(;f<p.length&&p[f]!=="'"&&p[f]!=='"';f++)h+=p[f];if(h=h.trim(),h.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[f++],b="";for(;f<p.length&&p[f]!==y;f++)b+=p[f];return[h,b,f]}o(i,"readEntityExp"),B(i,"readEntityExp");function s(p,f){return p[f+1]==="!"&&p[f+2]==="-"&&p[f+3]==="-"}o(s,"isComment"),B(s,"isComment");function a(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="N"&&p[f+4]==="T"&&p[f+5]==="I"&&p[f+6]==="T"&&p[f+7]==="Y"}o(a,"isEntity"),B(a,"isEntity");function c(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="L"&&p[f+4]==="E"&&p[f+5]==="M"&&p[f+6]==="E"&&p[f+7]==="N"&&p[f+8]==="T"}o(c,"isElement"),B(c,"isElement");function u(p,f){return p[f+1]==="!"&&p[f+2]==="A"&&p[f+3]==="T"&&p[f+4]==="T"&&p[f+5]==="L"&&p[f+6]==="I"&&p[f+7]==="S"&&p[f+8]==="T"}o(u,"isAttlist"),B(u,"isAttlist");function l(p,f){return p[f+1]==="!"&&p[f+2]==="N"&&p[f+3]==="O"&&p[f+4]==="T"&&p[f+5]==="A"&&p[f+6]==="T"&&p[f+7]==="I"&&p[f+8]==="O"&&p[f+9]==="N"}o(l,"isNotation"),B(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"validateEntityName"),B(d,"validateEntityName"),e.exports=n}}),vL=vt({"../../node_modules/strnum/strnum.js"(t,e){var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],f=d[2],h=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&f.length>0&&p&&l[2]!==".")return c;if(!u.leadingZeros&&f.length>0&&!p&&l[1]!==".")return c;{let b=Number(l),v=""+b;return v.search(/[eE]/)!==-1||y?u.eNotation?b:c:l.indexOf(".")!==-1?v==="0"&&h===""||v===h||p&&v==="-"+h?b:c:f?h===v||p+h===v?b:c:l===v||l===p+v?b:c}}else return c}}o(s,"toNumber"),B(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"trimZeros"),B(a,"trimZeros"),e.exports=s}}),TL=vt({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var r=Wf(),n=EL(),i=wL(),s=vL(),a=class{static{o(this,"OrderedObjParser")}static{B(this,"OrderedObjParser")}constructor(E){this.options=E,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=c,this.parseXml=f,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=v,this.replaceEntitiesValue=y,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=h}};function c(E){let T=Object.keys(E);for(let C=0;C<T.length;C++){let w=T[C];this.lastEntities[w]={regex:new RegExp("&"+w+";","g"),val:E[w]}}}o(c,"addExternalEntities"),B(c,"addExternalEntities");function u(E,T,C,w,P,x,te){if(E!==void 0&&(this.options.trimValues&&!w&&(E=E.trim()),E.length>0)){te||(E=this.replaceEntitiesValue(E));let j=this.options.tagValueProcessor(T,E,C,P,x);return j==null?E:typeof j!=typeof E||j!==E?j:this.options.trimValues?V(E,this.options.parseTagValue,this.options.numberParseOptions):E.trim()===E?V(E,this.options.parseTagValue,this.options.numberParseOptions):E}}o(u,"parseTextData"),B(u,"parseTextData");function l(E){if(this.options.removeNSPrefix){let T=E.split(":"),C=E.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(E=C+T[1])}return E}o(l,"resolveNameSpace"),B(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(E,T,C){if(!this.options.ignoreAttributes&&typeof E=="string"){let w=r.getAllMatches(E,d),P=w.length,x={};for(let te=0;te<P;te++){let j=this.resolveNameSpace(w[te][1]),D=w[te][4],be=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(be=this.options.transformAttributeName(be)),be==="__proto__"&&(be="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let le=this.options.attributeValueProcessor(j,D,T);le==null?x[be]=D:typeof le!=typeof D||le!==D?x[be]=le:x[be]=V(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(x[be]=!0)}if(!Object.keys(x).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=x,te}return x}}o(p,"buildAttributesMap"),B(p,"buildAttributesMap");var f=B(function(E){E=E.replace(/\r\n?/g,`
77
77
  `);let T=new n("!xml"),C=T,w="",P="";for(let x=0;x<E.length;x++)if(E[x]==="<")if(E[x+1]==="/"){let j=g(E,">",x,"Closing Tag is not closed."),D=E.substring(x+2,j).trim();if(this.options.removeNSPrefix){let yt=D.indexOf(":");yt!==-1&&(D=D.substr(yt+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),C&&(w=this.saveTextToParentTag(w,C,P));let be=P.substring(P.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let le=0;be&&this.options.unpairedTags.indexOf(be)!==-1?(le=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):le=P.lastIndexOf("."),P=P.substring(0,le),C=this.tagsNodeStack.pop(),w="",x=j}else if(E[x+1]==="?"){let j=S(E,x,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(w=this.saveTextToParentTag(w,C,P),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let D=new n(j.tagName);D.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(D[":@"]=this.buildAttributesMap(j.tagExp,P,j.tagName)),this.addChild(C,D,P)}x=j.closeIndex+1}else if(E.substr(x+1,3)==="!--"){let j=g(E,"-->",x+4,"Comment is not closed.");if(this.options.commentPropName){let D=E.substring(x+4,j-2);w=this.saveTextToParentTag(w,C,P),C.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}x=j}else if(E.substr(x+1,2)==="!D"){let j=i(E,x);this.docTypeEntities=j.entities,x=j.i}else if(E.substr(x+1,2)==="!["){let j=g(E,"]]>",x,"CDATA is not closed.")-2,D=E.substring(x+9,j);w=this.saveTextToParentTag(w,C,P);let be=this.parseTextData(D,C.tagname,P,!0,!1,!0,!0);be==null&&(be=""),this.options.cdataPropName?C.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):C.add(this.options.textNodeName,be),x=j+2}else{let j=S(E,x,this.options.removeNSPrefix),D=j.tagName,be=j.rawTagName,le=j.tagExp,yt=j.attrExpPresent,Nh=j.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),C&&w&&C.tagname!=="!xml"&&(w=this.saveTextToParentTag(w,C,P,!1));let Ch=C;if(Ch&&this.options.unpairedTags.indexOf(Ch.tagname)!==-1&&(C=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),D!==T.tagname&&(P+=P?"."+D:D),this.isItStopNode(this.options.stopNodes,P,D)){let st="";if(le.length>0&&le.lastIndexOf("/")===le.length-1)x=j.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)x=j.closeIndex;else{let Vu=this.readStopNodeData(E,be,Nh+1);if(!Vu)throw new Error(`Unexpected end of ${be}`);x=Vu.i,st=Vu.tagContent}let ju=new n(D);D!==le&&yt&&(ju[":@"]=this.buildAttributesMap(le,P,D)),st&&(st=this.parseTextData(st,D,P,!0,yt,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),ju.add(this.options.textNodeName,st),this.addChild(C,ju,P)}else{if(le.length>0&&le.lastIndexOf("/")===le.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),P=P.substr(0,P.length-1),le=D):le=le.substr(0,le.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let st=new n(D);D!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,D)),this.addChild(C,st,P),P=P.substr(0,P.lastIndexOf("."))}else{let st=new n(D);this.tagsNodeStack.push(C),D!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,D)),this.addChild(C,st,P),C=st}w="",x=Nh}}else w+=E[x];return T.child},"parseXml");function h(E,T,C){let w=this.options.updateTag(T.tagname,C,T[":@"]);w===!1||(typeof w=="string"&&(T.tagname=w),E.addChild(T))}o(h,"addChild"),B(h,"addChild");var y=B(function(E){if(this.options.processEntities){for(let T in this.docTypeEntities){let C=this.docTypeEntities[T];E=E.replace(C.regx,C.val)}for(let T in this.lastEntities){let C=this.lastEntities[T];E=E.replace(C.regex,C.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let C=this.htmlEntities[T];E=E.replace(C.regex,C.val)}E=E.replace(this.ampEntity.regex,this.ampEntity.val)}return E},"replaceEntitiesValue");function b(E,T,C,w){return E&&(w===void 0&&(w=Object.keys(T.child).length===0),E=this.parseTextData(E,T.tagname,C,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,w),E!==void 0&&E!==""&&T.add(this.options.textNodeName,E),E=""),E}o(b,"saveTextToParentTag"),B(b,"saveTextToParentTag");function v(E,T,C){let w="*."+C;for(let P in E){let x=E[P];if(w===x||T===x)return!0}return!1}o(v,"isItStopNode"),B(v,"isItStopNode");function A(E,T,C=">"){let w,P="";for(let x=T;x<E.length;x++){let te=E[x];if(w)te===w&&(w="");else if(te==='"'||te==="'")w=te;else if(te===C[0])if(C[1]){if(E[x+1]===C[1])return{data:P,index:x}}else return{data:P,index:x};else te===" "&&(te=" ");P+=te}}o(A,"tagExpWithClosingIndex"),B(A,"tagExpWithClosingIndex");function g(E,T,C,w){let P=E.indexOf(T,C);if(P===-1)throw new Error(w);return P+T.length-1}o(g,"findClosingIndex"),B(g,"findClosingIndex");function S(E,T,C,w=">"){let P=A(E,T+1,w);if(!P)return;let x=P.data,te=P.index,j=x.search(/\s/),D=x,be=!0;j!==-1&&(D=x.substring(0,j),x=x.substring(j+1).trimStart());let le=D;if(C){let yt=D.indexOf(":");yt!==-1&&(D=D.substr(yt+1),be=D!==P.data.substr(yt+1))}return{tagName:D,tagExp:x,closeIndex:te,attrExpPresent:be,rawTagName:le}}o(S,"readTagExp"),B(S,"readTagExp");function O(E,T,C){let w=C,P=1;for(;C<E.length;C++)if(E[C]==="<")if(E[C+1]==="/"){let x=g(E,">",C,`${T} is not closed`);if(E.substring(C+2,x).trim()===T&&(P--,P===0))return{tagContent:E.substring(w,C),i:x};C=x}else if(E[C+1]==="?")C=g(E,"?>",C+1,"StopNode is not closed.");else if(E.substr(C+1,3)==="!--")C=g(E,"-->",C+3,"StopNode is not closed.");else if(E.substr(C+1,2)==="![")C=g(E,"]]>",C,"StopNode is not closed.")-2;else{let x=S(E,C,">");x&&((x&&x.tagName)===T&&x.tagExp[x.tagExp.length-1]!=="/"&&P++,C=x.closeIndex)}}o(O,"readStopNodeData"),B(O,"readStopNodeData");function V(E,T,C){if(T&&typeof E=="string"){let w=E.trim();return w==="true"?!0:w==="false"?!1:s(E,C)}else return r.isExist(E)?E:""}o(V,"parseValue"),B(V,"parseValue"),e.exports=a}}),SL=vt({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,c){return r(a,c)}o(e,"prettify"),B(e,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let f=a[p],h=n(f),y="";if(u===void 0?y=h:y=u+"."+h,h===c.textNodeName)l===void 0?l=f[h]:l+=""+f[h];else{if(h===void 0)continue;if(f[h]){let b=r(f[h],c,y),v=s(b,c);f[":@"]?i(b,f[":@"],y,c):Object.keys(b).length===1&&b[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?b=b[c.textNodeName]:Object.keys(b).length===0&&(c.alwaysCreateTextNode?b[c.textNodeName]="":b=""),d[h]!==void 0&&d.hasOwnProperty(h)?(Array.isArray(d[h])||(d[h]=[d[h]]),d[h].push(b)):c.isArray(h,y,v)?d[h]=[b]:d[h]=b}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"compress"),B(r,"compress");function n(a){let c=Object.keys(a);for(let u=0;u<c.length;u++){let l=c[u];if(l!==":@")return l}}o(n,"propName"),B(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let f=0;f<p;f++){let h=d[f];l.isArray(h,u+"."+h,!0,!0)?a[h]=[c[h]]:a[h]=c[h]}}}o(i,"assignAttributes"),B(i,"assignAttributes");function s(a,c){let{textNodeName:u}=c,l=Object.keys(a).length;return!!(l===0||l===1&&(a[u]||typeof a[u]=="boolean"||a[u]===0))}o(s,"isLeafTag"),B(s,"isLeafTag"),t.prettify=e}}),IL=vt({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:r}=_L(),n=TL(),{prettify:i}=SL(),s=WE(),a=class{static{o(this,"XMLParser2")}static{B(this,"XMLParser")}constructor(c){this.externalEntities={},this.options=r(c)}parse(c,u){if(typeof c!="string")if(c.toString)c=c.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(u){u===!0&&(u={});let p=s.validate(c,u);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new n(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(c);return this.options.preserveOrder||d===void 0?d:i(d,this.options)}addEntity(c,u){if(u.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(c.indexOf("&")!==-1||c.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(u==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[c]=u}};e.exports=a}}),PL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var r=`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1848.0",
3
+ "version": "5.1851.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {