@zuplo/graphql 5.1809.0 → 5.1810.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
@@ -74,7 +74,7 @@ Signature verification is impossible without access to the original signed mater
74
74
  `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Wr.StripeSignatureVerificationError(t,e,{message:"Timestamp outside the tolerance zone"});return!0}o(wR,"validateComputedSignature");function vR(e,t){return typeof e!="string"?null:e.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===t&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(vR,"parseHeader");function TR(e,t){if(e.length!==t.length)return!1;let r=e.length,n=0;for(let i=0;i<r;++i)n|=e.charCodeAt(i)^t.charCodeAt(i);return n===0}o(TR,"secureCompare");async function $b(e,t){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(e)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Vp[s[c]];return a.join("")}o($b,"computeHMACSignatureAsync");Wn.computeHMACSignatureAsync=$b;var Vp=new Array(256);for(let e=0;e<Vp.length;e++)Vp[e]=e.toString(16).padStart(2,"0")});var Mt=b(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.optionValidator=void 0;var Qn=k(),SR=st();function IR(e,t){if(!(0,SR.isObject)(e))throw new Qn.ConfigurationError(`Options on policy '${t}' is expected to be an object. Received the type '${typeof e}'.`);let r=o((s,a,c)=>{let u=e[s];if(!(c&&u===void 0)){if(u===void 0)throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Qn.ConfigurationError(`Value of '${String(s)}' on policy '${t}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(IR,"optionValidator");Ua.optionValidator=IR});var Bp=b(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.StripeWebhookVerificationInboundPolicy=void 0;var PR=Pi(),AR=pe(),RR=jb(),OR=Mt(),Gp=class extends PR.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(t,r){(0,OR.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=t.headers.get("stripe-signature");try{let i=await t.clone().text();await(0,RR.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){return r.log.error("Error validating stripe webhook",i),AR.HttpProblems.badRequest(t,r,{title:"Webhook Error",detail:i.message})}return t}};ka.StripeWebhookVerificationInboundPolicy=Gp});var Gb=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.isStripeWebhookEvent=void 0;var Vb=st();function NR(e){return e!==null&&typeof e=="object"&&"id"in e&&(0,Vb.isString)(e.id)&&"type"in e&&(0,Vb.isString)(e.type)}o(NR,"isStripeWebhookEvent");Fa.isStripeWebhookEvent=NR});var Bb=b(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.MeteringPlugin=void 0;var xR=It(),Kp=class extends xR.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};Ha.MeteringPlugin=Kp});var Jb=b(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var Kb=k(),CR={getSubscription:async({subscriptionId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new Kb.RuntimeError(s)}return i},getCustomer:async({customerId:e,stripeSecretKey:t,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${e}`,{headers:{Authorization:`Bearer ${t}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new Kb.RuntimeError(s)}return i}};Jp.default=CR});var zb=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.deleteConsumer=Ir.createConsumerInvite=Ir.createConsumer=void 0;var zp=k(),Wp=Ze(),Qp=oe(),Yp=Cn(),Zp="https://api-key-management-service-eq7z4lly2a-ue.a.run.app";async function DR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=Qp.Environment.instance,u=new URL(`/v1/buckets/${e}/consumers`,Zp);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,Yp.fetchRetry)({retryDelayMs:5,retries:2,logger:Wp.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),h=await p.json();if(p.status!==200){let f="Error creating API Key Consumer";throw a.log.error(f,h),new zp.RuntimeError(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:t,stripeProductId:r}),l}o(DR,"createConsumer");Ir.createConsumer=DR;async function LR({apiKeyBucketName:e,stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=Qp.Environment.instance,c=new URL(`/v1/buckets/${e}/consumers`,Zp);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:"API Subscription",tags:{subscriptionExternalId:t,planExternalIds:[r]},metadata:{stripeSubscriptionId:t,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,Yp.fetchRetry)({retryDelayMs:5,retries:2,logger:Wp.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 h="Error creating API Key Consumer";throw s.log.error(h,p),new zp.RuntimeError(h)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:t,stripeProductId:r}),u}o(LR,"createConsumerInvite");Ir.createConsumerInvite=LR;async function MR({apiKeyBucketName:e,consumerId:t,context:r}){let{authApiJWT:n}=Qp.Environment.instance,i=new URL(`/v1/buckets/${e}/consumers/${t}`,Zp);i.searchParams.set("with-api-key","true");let s=await(0,Yp.fetchRetry)({retryDelayMs:5,retries:2,logger:Wp.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 deleting API Key Consumer";throw r.log.error(c,a),new zp.RuntimeError(c)}return r.log.info(`Successfully deleted API Key Consumer '${t}`),t}o(MR,"deleteConsumer");Ir.deleteConsumer=MR});var qa=b(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getSubscription=Ar.updateSubscription=Ar.createSubscription=void 0;var Pr=k(),Xp=Ze(),eh=oe(),th=Cn(),rh=st();async function UR({context:e,stripeSubscriptionId:t,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c}){let u={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:t,planExternalIds:[r],customerKey:n,customerExternalId:a},{authApiJWT:l,meteringServiceUrl:d}=eh.Environment.instance;if(!(0,rh.isNonEmptyString)(l))throw new Pr.SystemError("No Zuplo JWT token set.");let p=await(0,th.fetchRetry)({retryDelayMs:5,retries:2,logger:Xp.SystemLogMap.getLogger(e)},`${d}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"POST",body:JSON.stringify(u)});if(!p.ok){let h="Error creating metering subscription.",f;try{f=await p.json()}catch{f={status:p.status,statusText:p.statusText}}throw e.log.error(h,f),new Pr.RuntimeError(h)}e.log.info("Successfully created/updated metering subscription.",u)}o(UR,"createSubscription");Ar.createSubscription=UR;async function kR({context:e,meteringSubscriptionId:t,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=eh.Environment.instance;if(!(0,rh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,th.fetchRetry)({retryDelayMs:5,retries:2,logger:Xp.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${r}/subscriptions/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":e.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating metering subscription to '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw e.log.error(c,u),new Pr.RuntimeError(c)}e.log.info(`Successfully update metering subscription to '${JSON.stringify(n)}'.`)}o(kR,"updateSubscription");Ar.updateSubscription=kR;async function FR({context:e,stripeSubscriptionId:t,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=eh.Environment.instance;if(!(0,rh.isNonEmptyString)(i))throw new Pr.SystemError("No Zuplo JWT token set.");let a=await(0,th.fetchRetry)({retryDelayMs:5,retries:2,logger:Xp.SystemLogMap.getLogger(e)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${t}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":e.requestId},method:"GET"});if(!a.ok){let u="Error querying for metering subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw e.log.error(u,l),new Pr.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 Stripe metering plugin webhook.";throw e.log.error(u),new Pr.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 Stripe metering plugin webhook.";throw e.log.error(u),new Pr.RuntimeError(u)}return c.data[0]}o(FR,"getSubscription");Ar.getSubscription=FR});var nh=b($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.stripeStatusToMeteringStatus=void 0;function HR(e){return e.replaceAll("_","-")}o(HR,"stripeStatusToMeteringStatus");$a.stripeStatusToMeteringStatus=HR});var Wb=b(Qi=>{"use strict";var qR=Qi&&Qi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qi,"__esModule",{value:!0});var Qr=pe(),$R=qR(Jb()),ih=zb(),jR=qa(),VR=nh();async function GR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Qr.HttpProblems.badRequest(e,t,{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 t.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Qr.HttpProblems.badRequest(e,t,{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,ih.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:t});else{let l=await $R.default.getCustomer({logger:t.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!l.email)return t.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),Qr.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,ih.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l.email,context:t})}if(!u)return Qr.HttpProblems.internalServerError(e,t,{detail:"No consumer was created, skipping creation of subscription"});try{let l=(0,VR.stripeStatusToMeteringStatus)(r.data.object.status);await(0,jR.createSubscription)({context:t,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:l})}catch(l){return await(0,ih.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:t}),Qr.HttpProblems.internalServerError(e,t,{detail:l.message})}return Qr.HttpProblems.ok(e,t)}o(GR,"onCustomerSubscriptionCreated");Qi.default=GR});var Yb=b(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var oh=pe(),Qb=qa();async function BR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),oh.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),oh.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,Qb.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,Qb.updateSubscription)({context:t,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),oh.HttpProblems.ok(e,t)}o(BR,"onCustomerSubscriptionDeleted");sh.default=BR});var Zb=b(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var Yi=pe(),ja=qa(),KR=nh();async function JR(e,t,r,n){let i=r.data.object.id;if(!i)return t.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),Yi.HttpProblems.badRequest(e,t,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return t.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Yi.HttpProblems.badRequest(e,t,{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){let c=await(0,ja.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,KR.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,ja.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),Yi.HttpProblems.ok(e,t)}if(a.plan&&a.plan.product!==r.data.object.plan.product){let c=await(0,ja.getSubscription)({context:t,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,ja.updateSubscription)({context:t,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[r.data.object.plan.product]}}),Yi.HttpProblems.ok(e,t)}}return t.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),Yi.HttpProblems.badRequest(e,t,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(JR,"onCustomerSubscriptionUpdated");ah.default=JR});var e_=b(Yn=>{"use strict";var uh=Yn&&Yn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.StripeMeteringPlugin=void 0;var Va=Ki(),Ga=k(),zR=jt(),WR=Bp(),Xb=pe(),QR=ir(),YR=mn(),ZR=pl(),XR=ft(),eO=oe(),tO=Gb(),rO=Bb(),nO=uh(Wb()),iO=uh(Yb()),oO=uh(Zb()),ch=class extends rO.MeteringPlugin{static{o(this,"StripeMeteringPlugin")}options;constructor(t){super(),this.options=t}registerRoutes(t,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(Va.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Va.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Ga.ConfigurationError("StripeMeteringPlugin - No 'meteringBucketId' property provided");if(!d)if(Va.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Va.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Ga.ConfigurationError("StripeMeteringPlugin - No 'apiKeyBucketName' property provided");if(!eO.Environment.instance.build.ACCOUNT_NAME)throw new Ga.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!sO(p))throw new Ga.ConfigurationError(`StripeMeteringPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let h=await c.json();if(!(0,tO.isStripeWebhookEvent)(h))return Xb.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await(0,nO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,oO.default)(c,u,h,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,iO.default)(c,u,h,{meteringBucketId:l});default:return Xb.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe metering plugin webhook."})}},"stripeWebhookHandler"),i=(0,YR.createInternalPolicyProcessor)({inboundPolicies:[new WR.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]}),s=new zR.Pipeline({processors:[QR.metricsProcessor,i],handler:n,gateway:r}),a=new XR.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:ZR.SystemRouteName.StripePlugin});t.addRoute(a,s.execute)}};Yn.StripeMeteringPlugin=ch;function sO(e){return e!==null&&typeof e=="string"&&["us-central1","europe-west4"].includes(e)}o(sO,"isMetricsRegion")});var o_=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.AmberfloMeteringInboundPolicy=Zn.AmberfloMeteringPolicy=void 0;var t_=k(),aO=Oe(),r_=sr(),i_=new WeakMap,n_={},lh=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(t,r){i_.set(t,r)}};Zn.AmberfloMeteringPolicy=lh;async function cO(e,t,r,n){if(!r.statusCodes)throw new t_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,r_.statusCodesStringToNumberArray)(r.statusCodes);return t.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=i_.get(t),c=r.customerId;if(r.customerIdPropertyPath){if(!e.user)throw new t_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,r_.getValueFromRequestUser)(e.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){t.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){t.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)},h=n_[r.apiKey];if(!h){let f=r.apiKey,y=e.headers.get("zm-test-id")??"";h=new aO.BatchDispatch("amberflo-ingest-meter",10,async _=>{try{let I=r.url??"https://app.amberflo.io/ingest",O=await fetch(I,{method:"POST",body:JSON.stringify(_),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});O.ok||t.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${O.status}: ${await O.text()}`)}catch(I){throw t.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),n_[f]=h}h.enqueue(p),t.waitUntil(h.waitUntilFlushed())}}),e}o(cO,"AmberfloMeteringInboundPolicy");Zn.AmberfloMeteringInboundPolicy=cO});var dh=b(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.sha256=void 0;async function uO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest({name:"SHA-256"},t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(uO,"sha256");Ba.sha256=uO});var Wt=b(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.getPolicyCacheName=void 0;var lO=dh(),s_=new Map;async function dO(e,t){let r,n=s_.get(e);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,lO.sha256)(JSON.stringify({policyName:e,options:t}))}`,s_.set(e,r)),r}o(dO,"getPolicyCacheName");Ka.getPolicyCacheName=dO});var fh=b(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.ApiKeyInboundPolicy=void 0;var pO=Wt(),hO=er(),a_=Ki(),ph=k(),fO=Vt(),c_=Ze(),hh=oe(),mO=Cn(),u_="key-metadata-cache-type";function yO(e,t){return t.authScheme===""?e:e.replace(`${t.authScheme} `,"")}o(yO,"getKeyValue");async function gO(e,t,r,n){if(!r.bucketName)if(a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=a_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new ph.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 ph.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?e:fO.HttpProblems.unauthorized(e,t,{detail:I}),"unauthorizedResponse"),a=e.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=yO(a,i);if(!c||c==="")return s("No key present");let u=await bO(c),l=await(0,pO.getPolicyCacheName)(n,i),d=new hO.MemoryZoneReadThroughCache(l,t),p=await d.get(u);if(p&&p.isValid===!0)return e.user=p.user,e;if(p&&!p.isValid)return p.typeId!==u_&&c_.SystemLogMap.getLogger(t).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let h={key:c},f=await(0,mO.fetchRetry)({retryDelayMs:5,retries:2,logger:c_.SystemLogMap.getLogger(t)},`${hh.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":t.requestId,"zp-dn":hh.Environment.instance.deploymentName??"unknown","User-Agent":hh.Environment.instance.systemUserAgent},body:JSON.stringify(h)});if(f.status===401)return t.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(f.status!==200){try{let I=await f.text(),O=JSON.parse(I);t.log.error("Unexpected response from key service",O)}catch{t.log.error("Invalid response from key service")}throw new ph.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${f.status}`)}let y=await f.json(),_={isValid:!0,typeId:u_,user:{sub:y.name,data:y.metadata}};return e.user=_.user,d.put(u,_,i.cacheTtlSeconds),e}o(gO,"ApiKeyInboundPolicy");Ja.ApiKeyInboundPolicy=gO;async function bO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(bO,"hashValue")});var l_=b(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.ApiAuthKeyInboundPolicy=void 0;var _O=fh();za.ApiAuthKeyInboundPolicy=_O.ApiKeyInboundPolicy});var Qt=b(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.OpenIdJwtInboundPolicy=void 0;var yh=(Qs(),Io(Ws)),gh=k(),EO=pe(),mh={},wO=o(async(e,t)=>{if(!t.jwkUrl||typeof t.jwkUrl!="string")throw new gh.ConfigurationError("Invalid State - jwkUrl not set");mh[t.jwkUrl]||(mh[t.jwkUrl]=(0,yh.createRemoteJWKSet)(new URL(t.jwkUrl),t.headers?{headers:t.headers}:void 0));let{payload:r}=await(0,yh.jwtVerify)(e,mh[t.jwkUrl],{issuer:t.issuer,audience:t.audience});return r},"jwkVerifier"),vO=o(async(e,t)=>{let r;if(t.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof t.secret=="string"){let s=new TextEncoder().encode(t.secret);r=new Uint8Array(s)}else r=t.secret;let{payload:n}=await(0,yh.jwtVerify)(e,r,{issuer:t.issuer,audience:t.audience});return n},"secretVerifier"),TO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization"),s="bearer ",a=o(h=>EO.HttpProblems.unauthorized(e,t,{detail:h}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new gh.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new gh.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?wO:vO,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 h=i.substring(s.length);if(!h||h.length===0)return a("No bearer token on authorization header");try{return await c(h,r)}catch(f){let y=new URL(e.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?t.log.warn(`Expired token used on url: ${y.pathname} `,f):t.log.warn(`Invalid token on: ${e.method} ${y.pathname}`,f),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?e:l;let d=r.subPropertyName??"sub",p=l[d];return p?(e.user={sub:p,data:l},e):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");Wa.OpenIdJwtInboundPolicy=TO});var d_=b(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.Auth0JwtInboundPolicy=void 0;var SO=Qt(),IO=o(async(e,t,r,n)=>(0,SO.OpenIdJwtInboundPolicy)(e,t,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");Qa.Auth0JwtInboundPolicy=IO});var p_=b(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.BasicAuthInboundPolicy=void 0;var PO=pe(),AO=o(async(e,t,r)=>{let n=e.headers.get("Authorization"),i="basic ",s=o(l=>PO.HttpProblems.unauthorized(e,t,{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 h=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(_=>_.username===h&&_.password===f);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?e:c;let u=c.username;return e.user={sub:u,data:c.data},e},"BasicAuthInboundPolicy");Ya.BasicAuthInboundPolicy=AO});var h_=b(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.CachingInboundPolicy=void 0;var RO=Wt(),OO=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function NO(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(NO,"digestMessage");var xO=o(async(e,t)=>{let r=[...t.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...t.headers??[]],n=[];for(let[d,p]of e.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await NO(JSON.stringify(n)),s=new URL(e.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=t.cacheHttpMethods?.includes(e.method.toUpperCase())&&e.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",e.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":e.method})},"createCacheKeyRequest");async function CO(e,t,r,n){let i=await(0,RO.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await xO(e,r),u=await s.match(c);return u||(t.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(e.method.toUpperCase()))return;let h=r?.expirationSecondsTtl??60,f=new Response(p.body,p);OO.forEach(y=>f.headers.delete(y)),f.headers.set("cache-control",`s-maxage=${h}`),t.waitUntil(s.put(c,f))}catch(d){t.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),e)}o(CO,"CachingInboundPolicy");Za.CachingInboundPolicy=CO});var f_=b(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.ChangeMethodInboundPolicy=void 0;var DO=k(),LO=Be(),MO=o(async(e,t,r,n)=>{if(!r.method)throw new DO.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new LO.ZuploRequest(e,{method:r.method})},"ChangeMethodInboundPolicy");Xa.ChangeMethodInboundPolicy=MO});var m_=b(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.ClearHeadersInboundPolicy=void 0;var UO=Be(),kO=o(async(e,t,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=e.headers.get(a);c&&i.set(a,c)}),new UO.ZuploRequest(e,{headers:i})},"ClearHeadersInboundPolicy");ec.ClearHeadersInboundPolicy=kO});var y_=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.ClearHeadersOutboundPolicy=void 0;var FO=o(async(e,t,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=e.headers.get(c);u&&s.set(c,u)}),new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})},"ClearHeadersOutboundPolicy");tc.ClearHeadersOutboundPolicy=FO});var g_=b(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ClerkJwtInboundPolicy=void 0;var HO=Qt(),qO=o(async(e,t,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,HO.OpenIdJwtInboundPolicy)(e,t,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");rc.ClerkJwtInboundPolicy=qO});var __=b(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.CognitoJwtInboundPolicy=void 0;var b_=k(),$O=Qt(),jO=o(async(e,t,r,n)=>{if(!r.userPoolId)throw new b_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new b_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,$O.OpenIdJwtInboundPolicy)(e,t,{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");nc.CognitoJwtInboundPolicy=jO});var w_=b(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.CompositeInboundPolicy=void 0;var VO=k(),GO=kr(),E_=mn(),BO=o(async(e,t,r,n)=>{if(!r.policies||r.policies.length===0)throw new VO.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=GO.Gateway.instance,s=(0,E_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,E_.toStackedInboundHandler)(s)(e,t)},"CompositeInboundPolicy");ic.CompositeInboundPolicy=BO});var v_=b(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.CurityPhantomTokenInboundPolicy=void 0;var KO=Wt(),JO=er(),oc=pe(),zO=o(async(e,t,r,n)=>{let i=e.headers.get("Authorization");if(!i)return oc.HttpProblems.unauthorized(e,t,{detail:"No authorization header"});let s=WO(i);if(!s)return oc.HttpProblems.unauthorized(e,t,{detail:"Failed to parse token from Authorization header"});let a=await(0,KO.getPolicyCacheName)(n,r),c=new JO.MemoryZoneReadThroughCache(a,t),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?(t.log.error(`Error introspecting token - ${l.status}: '${d}'`),oc.HttpProblems.internalServerError(e,t,{detail:"Problem encountered authorizing the HTTP request"})):oc.HttpProblems.unauthorized(e,t)}return e.headers.set("Authorization",`Bearer ${u}`),e},"CurityPhantomTokenInboundPolicy");sc.CurityPhantomTokenInboundPolicy=zO;function WO(e){return e.split(" ")[0]==="Bearer"?e.split(" ")[1]:null}o(WO,"getToken")});var T_=b(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.FirebaseJwtInboundPolicy=void 0;var QO=Mt(),YO=Qt(),ZO=o(async(e,t,r,n)=>((0,QO.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,YO.OpenIdJwtInboundPolicy)(e,t,{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");ac.FirebaseJwtInboundPolicy=ZO});var S_=b(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.FormDataToJsonInboundPolicy=void 0;var XO=Be(),eN=o(async(e,t,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=e.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"}):e;let a=await e.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(e.headers);return u.set("content-type","application/json"),u.delete("content-length"),new XO.ZuploRequest(e,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");cc.FormDataToJsonInboundPolicy=eN});var I_=b(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.GeoFilterInboundPolicy=void 0;var tN=k(),rN=pe(),Xn="__unknown__",nN=o(async(e,t,r,n)=>{let i={allow:{countries:ti(r.allow?.countries,"allow.countries",n),regionCodes:ti(r.allow?.regionCodes,"allow.regionCode",n),asns:ti(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ti(r.block?.countries,"block.countries",n),regionCodes:ti(r.block?.regionCodes,"block.regionCode",n),asns:ti(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=t.incomingRequestProperties.country?.toLowerCase()??Xn,a=t.incomingRequestProperties.regionCode?.toLowerCase()??Xn,c=t.incomingRequestProperties.asn?.toString()??Xn,u=i.ignoreUnknown&&s===Xn,l=i.ignoreUnknown&&a===Xn,d=i.ignoreUnknown&&c===Xn,p=i.allow.countries,h=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||h.length>0&&!h.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return ei(e,t,n,s,a,c);let y=i.block.countries,_=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||_.length>0&&_.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?ei(e,t,n,s,a,c):e},"GeoFilterInboundPolicy");uc.GeoFilterInboundPolicy=nN;function ei(e,t,r,n,i,s){return t.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),rN.HttpProblems.forbidden(e,t,{geographicContext:{country:n,regionCode:i,asn:s}})}o(ei,"blockedResponse");function ti(e,t,r){if(typeof e=="string")return e.split(",").map(n=>n.trim().toLowerCase());if(typeof e>"u")return[];if(Array.isArray(e))return e.map(n=>n.trim().toLowerCase());throw new tN.ConfigurationError(`Invalid '${t}' for GeoFilterInboundPolicy '${r}': '${e}', must be a string or string[]`)}o(ti,"toLowerStringArray")});var P_=b(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.JWTScopeValidationInboundPolicy=void 0;var iN=o(async(e,t,r)=>{let n=e.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 e},"JWTScopeValidationInboundPolicy");lc.JWTScopeValidationInboundPolicy=iN});var R_=b(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.MockApiInboundPolicy=void 0;var oN=pe(),sN=o(async(e,t,r,n)=>{let i=t.route.raw().responses;if(!i)return bh(n,e,t,"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 bh(n,e,t,"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(h=>{a.push({responseName:c,contentName:l,exampleName:h,exampleValue:d[h]})})})}),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_(a[c])}else return a.length>0?A_(a[0]):bh(n,e,t,"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");dc.MockApiInboundPolicy=sN;function A_(e){let t=JSON.stringify(e.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",e.contentName),e.responseName){case"1XX":return new Response(t,{status:100,headers:r});case"2XX":return new Response(t,{status:200,headers:r});case"3XX":return new Response(t,{status:300,headers:r});case"4XX":return new Response(t,{status:400,headers:r});case"5XX":case"default":return new Response(t,{status:500,headers:r});default:return new Response(t,{status:Number(e.responseName),headers:r})}}o(A_,"generateResponse");var bh=o((e,t,r,n)=>{let i=`Error in policy: ${e} - On route ${t.method} ${r.route.path}. ${n}`;return oN.HttpProblems.internalServerError(t,r,{detail:i})},"getProblemDetailResponse")});var D_=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.MoesifInboundPolicy=ri.setMoesifContext=void 0;var aN=k(),cN=Oe(),uN="Incoming",lN={logRequestBody:!0,logResponseBody:!0};function O_(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}o(O_,"headersToObject");function N_(){return new Date().toISOString()}o(N_,"timestamp");var _h=new WeakMap,dN={};function pN(e,t){let r=_h.get(e);r||(r=dN);let n=Object.assign({...r},t);_h.set(e,n)}o(pN,"setMoesifContext");ri.setMoesifContext=pN;async function x_(e,t){let r=e.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await e.clone().json()}catch(i){t.log.error(i)}let n=await e.clone().text();return t.log.debug({textBody:n}),n}o(x_,"readBody");var hN={},Eh;function C_(){if(!Eh)throw new aN.RuntimeError("Invalid State - no _lastLogger");return Eh}o(C_,"getLastLogger");function fN(e){let t=hN[e];return t||(t=new cN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);C_().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":e},body:n});i.ok||C_().error({status:i.status,body:await i.text()})})),t}o(fN,"getDispatcher");async function mN(e,t,r,n){Eh=t.log;let i=N_(),s=Object.assign(lN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await x_(e,t):void 0;return t.addResponseSendingFinalHook(async(c,u)=>{let l=fN(s.applicationId),d=e.headers.get("true-client-ip"),p=_h.get(t)??{},h={time:i,uri:e.url,verb:e.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:O_(e.headers)},f=s.logResponseBody?await x_(c,t):void 0,y={time:N_(),status:c.status,headers:O_(c.headers),body:f},_={request:h,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:uN};l.enqueue(_),t.waitUntil(l.waitUntilFlushed())}),e}o(mN,"MoesifInboundPolicy");ri.MoesifInboundPolicy=mN});var U_=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.consumeSubcriptionQuotas=ni.loadSubscription=void 0;var L_=Ze(),M_=oe();async function yN(e,t,r,n){let i=L_.SystemLogMap.getLogger(e),{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${t}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.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.";e.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(yN,"loadSubscription");ni.loadSubscription=yN;async function gN(e,t,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=M_.Environment.instance,c=L_.SystemLogMap.getLogger(e);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${t}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":e.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.";e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){e.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(gN,"consumeSubcriptionQuotas");ni.consumeSubcriptionQuotas=gN});var k_=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.parseAllowedSubscriptionStatuses=ii.validateMeters=void 0;var Yr=k(),bN=sr(),_N=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function EN(e,t){try{let r=[];for(let n in e)typeof e[n]!="number"&&!(Number.isInteger(e[n])&&/^-?\d+$/.test(e[n].toString()))&&r.push(n);if(r.length>0)throw new Yr.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 Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'meters' is invalid. ${r.message}`):r}}o(EN,"validateMeters");ii.validateMeters=EN;function wN(e,t){if(e)try{if(e.length===0)throw new Yr.ConfigurationError("Must set valid subscription statuses");let r=(0,bN.parseValueToStringArray)(e),n=[];for(let i of r)_N.has(i)||n.push(i);if(n.length>0)throw new Yr.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return e}catch(r){throw r instanceof Yr.ConfigurationError?new Yr.ConfigurationError(`MonetizationInboundPolicy '${t}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(wN,"parseAllowedSubscriptionStatuses");ii.parseAllowedSubscriptionStatuses=wN});var H_=b(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.MonetizationInboundPolicy=void 0;var Zr=un(),Xr=ap(),pc=Ki(),wh=k(),vN=Pi(),en=pe(),TN=sr(),SN=Mt(),F_=U_(),hc=k_(),vh=class extends vN.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(t){return Xr.ContextData.get(t,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(t,r){(0,hc.validateMeters)(r,"setMeters"),Xr.ContextData.set(t,Zr.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(t,r){if((0,SN.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),!this.options.meterOnStatusCodes)throw new wh.ConfigurationError(`Invalid MonetizationInboundPolicy '${this.policyName}' - The property 'meterOnStatusCodes' must be an array of HTTP status code numbers`);let n=this.options.allowRequestsOverQuota??!1,i=Array.isArray(this.options.meterOnStatusCodes)?this.options.meterOnStatusCodes:(0,TN.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=Xr.ContextData.get(r,Zr.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,hc.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,hc.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(_,I,O)=>{let g=Xr.ContextData.get(O,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(pc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=pc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new wh.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let R=Xr.ContextData.get(O,Zr.DYNAMIC_METERS_CONTEXT_DATA),K={...this.options.meters,...R};(0,hc.validateMeters)(K,this.policyName),i.includes(_.status)&&g&&K&&(O.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(K)} on response status '${_.status}'`),await(0,F_.consumeSubcriptionQuotas)(O,g.id,this.policyName,this.options.bucketId,K))});let l=t.user;if(!l)return c?t:en.HttpProblems.unauthorized(t,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(pc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=pc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new wh.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,F_.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?t:en.HttpProblems.unauthorized(t,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.`),en.HttpProblems.unauthorized(t,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),Xr.ContextData.set(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let h=Xr.ContextData.get(r,Zr.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!h)return c?t:(r.log.warn("Subscription is not available for user"),en.HttpProblems.paymentRequired(t,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(h&&Object.keys(h.meters).length===0)return r.log.error(`Quota is not set up for subscription '${h.id}'`),en.HttpProblems.tooManyRequests(t,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(_=>!Object.keys(h.meters).includes(_));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),en.HttpProblems.tooManyRequests(t,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let _ of Object.keys(a))if(h.meters[_].consumed<=0&&!n)return en.HttpProblems.tooManyRequests(t,r,{detail:`Quota exceeded for meter '${_}'`,title:"Quota Exceeded"});return t}};fc.MonetizationInboundPolicy=vh});var q_=b(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.OktaJwtInboundPolicy=void 0;var IN=Qt(),PN=o(async(e,t,r,n)=>(0,IN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");mc.OktaJwtInboundPolicy=PN});var $_=b(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.PropelAuthJwtInboundPolicy=void 0;var AN=(Qs(),Io(Ws)),RN=Qt(),Th,ON=o(async(e,t,r,n)=>{if(!Th)try{Th=await(0,AN.importSPKI)(r.verifierKey,"RS256")}catch(i){throw t.log.error("Could not import verifier key"),i}return(0,RN.OpenIdJwtInboundPolicy)(e,t,{issuer:r.authUrl,secret:Th,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");yc.PropelAuthJwtInboundPolicy=ON});var j_=b(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 We=st(),ut=class extends Error{static{o(this,"ValidationError")}constructor(t){super(t)}};Z.ValidationError=ut;var Zi=class extends ut{static{o(this,"ArgumentUndefinedError")}constructor(t){super(`The argument '${t}' is undefined.`)}};Z.ArgumentUndefinedError=Zi;var Xi=class extends ut{static{o(this,"ArgumentTypeError")}constructor(t,r){super(`The argument '${t}' must be of type '${r}'.`)}};Z.ArgumentTypeError=Xi;function NN(e,t){if((0,We.isUndefined)(e))throw new Zi(t)}o(NN,"throwIfUndefined");Z.throwIfUndefined=NN;function Sh(e,t){if((0,We.isUndefinedOrNull)(e))throw new Zi(t)}o(Sh,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=Sh;function xN(e,t){if(Sh(e,t),!(0,We.isString)(e))throw new Xi(t,"string")}o(xN,"throwIfNotString");Z.throwIfNotString=xN;function CN(e,t){if(Sh(e,t),!(0,We.isNumber)(e))throw new Xi(t,"number")}o(CN,"throwIfNotNumber");Z.throwIfNotNumber=CN;var eo=class extends ut{static{o(this,"OptionUndefinedError")}constructor(t,r,n){super(`The option '${n}' on the ${t} named '${r}' is undefined.`)}};Z.OptionUndefinedError=eo;var oi=class extends ut{static{o(this,"OptionTypeError")}constructor(t,r,n,i){super(`The option '${n}' on the ${t} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=oi;function DN(e,t,r,n){if((0,We.isUndefined)(n))throw new eo(e,t,r)}o(DN,"throwIfOptionUndefined");Z.throwIfOptionUndefined=DN;function gc(e,t,r,n){if((0,We.isUndefinedOrNull)(n))throw new eo(e,t,r)}o(gc,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=gc;function LN(e,t,r,n){if(gc(e,t,r,n),!(0,We.isString)(n))throw new oi(e,t,r,"string")}o(LN,"throwIfOptionNotString");Z.throwIfOptionNotString=LN;function MN(e,t,r,n){if(gc(e,t,r,n),!(0,We.isNumber)(n))throw new oi(e,t,r,"number")}o(MN,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=MN;function UN(e,t,r,n){if(gc(e,t,r,n),!(0,We.isObject)(n))throw new oi(e,t,r,"object")}o(UN,"throwIfOptionNotObject");Z.throwIfOptionNotObject=UN;function kN(e,t){if((0,We.isUndefined)(e))throw new ut(t)}o(kN,"throwIfStateUndefined");Z.throwIfStateUndefined=kN;function bc(e,t){if((0,We.isUndefinedOrNull)(e))throw new ut(t)}o(bc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=bc;function FN(e,t){if(bc(e,t),!(0,We.isString)(e))throw new ut(t);return!0}o(FN,"throwIfStateNotString");Z.throwIfStateNotString=FN;function HN(e,t){if(bc(e,t),!(0,We.isNumber)(e))throw new ut(t);return!0}o(HN,"throwIfStateNotNumber");Z.throwIfStateNotNumber=HN;function qN(e,t){if(bc(e,t),!(0,We.isObject)(e))throw new ut(t);return!0}o(qN,"throwIfStateNotObject");Z.throwIfStateNotObject=qN});var V_=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.InMemoryRedisClient=si.StandardRedisClient=void 0;var Ih=k(),_c=j_(),Ph=class e{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(t,r,n,i){this.redisClientUrl=t,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(t,r,n,i){return(0,_c.throwIfNotString)(t,"redisClientUrl"),(0,_c.throwIfNotString)(r,"clientAuthToken"),e.instance||(e.instance=new e(t,r,n,i)),e.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:t,body:r,method:n,requestId:i}){(0,_c.throwIfNotString)(t,"url");let s=await fetch(`${this.redisClientUrl}${t}`,{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 Ih.SystemError("Redis client failed with 401: Unauthorized"):new Ih.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};si.StandardRedisClient=Ph;var Ah=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:t,body:r,method:n}){if((0,_c.throwIfNotString)(t,"url"),n==="POST"&&t==="/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 Ih.SystemError("The in-memory redis client only supports /rate-limit calls")}};si.InMemoryRedisClient=Ah});var z_=b(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.RateLimitInboundPolicy=void 0;var $N=Ur(),jN=Wt(),VN=No(),Ut=k(),GN=pe(),G_=Ze(),to=oe(),B_=V_(),K_=st(),Ec=(0,$N.debug)("zuplo:policies:RateLimitInboundPolicy"),BN="strict",KN=o(e=>{let t=e.headers.get("cf-connecting-ip")??e.headers.get("true-client-ip");if(t)return t;let r=e.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),JN=o(async e=>({key:`ip-${KN(e)}`}),"getIP"),zN=o(async e=>({key:`user-${e.user?.sub??"anonymous"}`}),"getUser"),WN=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),wc;function QN(e,t){let r;if(wc)return wc;if(to.Environment.instance.isLocalDevelopment)return t.info("Using in-memory redis client for local development."),r=new B_.InMemoryRedisClient,wc=r,r;let{authApiJWT:n,redisURL:i}=to.Environment.instance;if(!(0,K_.isString)(i))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - rate limit service URL not configured`);if(!(0,K_.isString)(n))throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - service authentication not configured`);if(i&&(r=B_.StandardRedisClient.initialize(i,n,to.Environment.instance.deploymentName??"unknown",to.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Ut.SystemError(`RateLimitInboundPolicy '${e}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return wc=r,r}o(QN,"getRedisClient");async function J_(e,t,r,n,i){let s=Math.floor(t*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:e}),requestId:i})}o(J_,"getCountAndUpdateExpiry");function YN(e,t){let r;if(e.rateLimitBy==="function"){if(!e.identifier)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!e.identifier.module)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!e.identifier.export)throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=e.identifier.module[e.identifier.export],!r||typeof r!="function")throw new Ut.ConfigurationError(`RateLimitInboundPolicy '${t}' - 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 Ut.RuntimeError(u)}return c},"outerFunction")}o(YN,"wrapUserFunction");var ZN="Retry-After",XN=o(async(e,t,r,n)=>{let i=Date.now(),s=G_.SystemLogMap.getLogger(t),a=o((u,l)=>{if(r.throwOnFailure)throw new Ut.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[ZN]=l.toString()),GN.HttpProblems.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l={function:YN(r,n),user:zN,ip:JN,all:WN}[r.rateLimitBy],d=await l(e,t,n),p=d.key,h=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",_=QN(n,s),O=`bucket/${to.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??BN)==="async"){let R=await(0,jN.getPolicyCacheName)(n,r),K=new VN.ZoneCache(R,{logger:G_.SystemLogMap.getLogger(t)}),w=J_(O,f,_,s,t.requestId),S=await K.get(O);if(S!==void 0&&S<=Date.now()){Ec(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${O}' (async mode)`);let x=Math.round((S-Date.now())/1e3);return c(y,x)}return t.addEventListener("responseSending",x=>{try{let E=x,P=E.mutableResponse;E.mutableResponse=(async()=>{let C=await w;if(C.count>h){let H=Date.now()+C.ttlSeconds*1e3,D=K.put(O,H,C.ttlSeconds).catch(X=>{throw s.error(new Ut.SystemError("Error caching rate limit result.",{cause:X})),X});return t.waitUntil(D),Ec(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (async mode)`),c(y,C.ttlSeconds)}return P})()}catch(E){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,E)}}),e}let v=await J_(O,f,_,s,t.requestId);return v.count>h?(Ec(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${O}' (strict mode)`),c(y,v.ttlSeconds)):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-i;Ec(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");vc.RateLimitInboundPolicy=XN});var Z_=b(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.ReadmeMetricsInboundPolicy=void 0;var ex=Oe(),Rh=oe(),W_=sr(),Oh;function Q_(e){let t=[];for(let[r,n]of e)t.push({name:r,value:n});return t}o(Q_,"headersToNameValuePairs");function tx(e){let t=[];return Object.entries(e).forEach(([r,n])=>{t.push({name:r,value:n})}),t}o(tx,"queryToNameValueParis");function rx(e){if(e===null)return;let t=parseFloat(e);if(!isNaN(t))return t}o(rx,"parseIntOrUndefined");var Y_={};async function nx(e,t,r,n){let i=new Date,s=Date.now();return Oh||(Oh={name:"zuplo",version:Rh.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Rh.Environment.instance.build.ZUPLO_VERSION}`}),t.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userLabelPropertyPath,"userLabelPropertyPath"):e.user?.sub,u=r.userEmailPropertyPath&&e.user?(0,W_.getValueFromRequestUser)(e.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:e.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Rh.Environment.instance.isDeno,group:{label:c,email:u,id:e.user?.sub??"anonymous"},request:{log:{creator:Oh,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:e.method,url:r.useFullRequestPath?new URL(e.url).pathname:t.route.path,httpVersion:"2",headers:Q_(e.headers),queryString:tx(e.query)},response:{status:a.status,statusText:a.statusText,headers:Q_(a.headers),content:{size:rx(e.headers.get("content-length"))}}}]}}},d=Y_[r.apiKey];if(!d){let p=r.apiKey;d=new ex.BatchDispatch("readme-metering-inbound-policy",10,async h=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(h),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&t.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(f){throw t.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),Y_[p]=d}d.enqueue(l),t.waitUntil(d.waitUntilFlushed())}catch(c){t.log.error(c)}}),e}o(nx,"ReadmeMetricsInboundPolicy");Tc.ReadmeMetricsInboundPolicy=nx});var X_=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.RemoveHeadersInboundPolicy=void 0;var ix=k(),ox=Be(),sx=o(async(e,t,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new ix.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(e.headers);return i.forEach(c=>{s.delete(c)}),new ox.ZuploRequest(e,{headers:s})},"RemoveHeadersInboundPolicy");Sc.RemoveHeadersInboundPolicy=sx});var eE=b(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.RemoveHeadersOutboundPolicy=void 0;var ax=k(),cx=o(async(e,t,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new ax.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(e.headers);return s.forEach(u=>{a.delete(u)}),new Response(e.body,{headers:a,status:e.status,statusText:e.statusText})},"RemoveHeadersOutboundPolicy");Ic.RemoveHeadersOutboundPolicy=cx});var tE=b(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.RemoveQueryParamsInboundPolicy=void 0;var ux=k(),lx=Be(),dx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new ux.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(e.url);return i.forEach(c=>{s.searchParams.delete(c)}),new lx.ZuploRequest(s.toString(),e)},"RemoveQueryParamsInboundPolicy");Pc.RemoveQueryParamsInboundPolicy=dx});var rE=b(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.ReplaceStringOutboundPolicy=void 0;var px=o(async(e,t,r,n)=>{let i=await e.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})},"ReplaceStringOutboundPolicy");Ac.ReplaceStringOutboundPolicy=px});var iE=b(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.RequestSizeLimitInboundPolicy=void 0;var nE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),hx=o(async(e,t,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(e.method))return e;let i=e.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?nE():s&&n?e:(await e.clone().text()).length>r.maxSizeInBytes?nE():e},"RequestSizeLimitInboundPolicy");Rc.RequestSizeLimitInboundPolicy=hx});var Oc=b(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.sanitizedIdentifierName=lt.getIdForRefSchema=lt.getIdForRequestBodySchema=lt.getIdForParameterSchema=lt.getRawOperationDataIdentifierName=void 0;function fx(e,t,r){return`_${tn(e+"_"+t+"_"+r)}`}o(fx,"getRawOperationDataIdentifierName");lt.getRawOperationDataIdentifierName=fx;function mx(e,t,r,n){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(mx,"getIdForParameterSchema");lt.getIdForParameterSchema=mx;function yx(e,t,r){return`_${tn(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${tn(r.toLowerCase())}`}o(yx,"getIdForRequestBodySchema");lt.getIdForRequestBodySchema=yx;function gx(e,t){return`_${tn(e)}__${tn(t)}`}o(gx,"getIdForRefSchema");lt.getIdForRefSchema=gx;function tn(e){let t=[];for(let r=0;r<e.length;r++){let n=e.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)?t.push(e.charAt(r)):t.push("_")}return t.join("")}o(tn,"sanitizedIdentifierName");lt.sanitizedIdentifierName=tn});var ro=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.getErrorsFromValidator=qe.shouldReject=qe.shouldLog=qe.logErrors=qe.validateParameters=qe.getParametersForOperation=void 0;var bx=kr(),_x=Oc(),Ex=o(e=>{let t=e.route.raw();return t.parameters?t.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");qe.getParametersForOperation=Ex;var wx=o((e,t,r,n,i)=>{let s=[],a=!0,c=[];return e.forEach(u=>{let l=u.required||i==="path";if(l&&!t[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!t[u.name])){let d=(0,_x.getIdForParameterSchema)(r,n,i,u.name),p=bx.Gateway.instance.schemaValidator[d],h=p(t[u.name]),f=(0,qe.getErrorsFromValidator)(p.errors);h||(a=!1,c.push(`${i} parameter: ${u.name} : ${t[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${f.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");qe.validateParameters=wx;var vx=o((e,t,r,n,i)=>{n?e.log[t](r,n,i):e.log[t](r,i)},"logErrors");qe.logErrors=vx;var Tx=o(e=>e==="log-only"||e==="reject-and-log","shouldLog");qe.shouldLog=Tx;var Sx=o(e=>e==="reject-only"||e==="reject-and-log","shouldReject");qe.shouldReject=Sx;var Ix=o(e=>e?.map(t=>t.instancePath===void 0||t.instancePath===""?t.message??"Unknown validation error":t.instancePath.replace("/","")+" "+t.message)??["Unknown validation error"],"getErrorsFromValidator");qe.getErrorsFromValidator=Ix});var oE=b(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.handleBodyValidation=void 0;var Px=kr(),Nc=pe(),Ax=Oc(),et=ro();async function Rx(e,t,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await t.clone().json()}catch(f){let y=`Error in request body for method : ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,_=Nc.HttpProblems.badRequest(t,e,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",y,[n],f),(0,et.shouldReject)(r.validateBody))return _}if(!t.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${t.method} in route: ${e.route.path}`,y=Nc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}let i=t.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,Ax.getIdForRequestBodySchema)(e.route.path,t.method,i),c=Px.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${t.method} in route: ${e.route.path} with content-type: ${t.headers.get("Content-Type")}`,y=Nc.HttpProblems.badRequest(t,e,{detail:f});return(0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",f,[n],[f]),(0,et.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,et.getErrorsFromValidator)(l),h=Nc.HttpProblems.badRequest(t,e,{detail:`${d}, see errors property for more details`,errors:p});if((0,et.shouldLog)(r.validateBody)&&(0,et.logErrors)(e,r.logLevel??"info",d,[n],p),(0,et.shouldReject)(r.validateBody))return h}o(Rx,"handleBodyValidation");xc.handleBodyValidation=Rx});var sE=b(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.handleHeadersValidation=void 0;var Ox=pe(),no=ro();function Nx(e,t,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};t.headers.forEach((a,c)=>{n[c]=a});let i=(0,no.getParametersForOperation)(e),s=(0,no.validateParameters)(i.filter(a=>a.location==="header"),n,e.route.path,t.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=Ox.HttpProblems.badRequest(t,e,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,no.shouldLog)(r.validateHeaders)&&(0,no.logErrors)(e,r.logLevel??"info",a,s.invalidValues,s.errors),(0,no.shouldReject)(r.validateHeaders))return c}}o(Nx,"handleHeadersValidation");Cc.handleHeadersValidation=Nx});var aE=b(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.handlePathParameterValidation=void 0;var xx=pe(),io=ro();function Cx(e,t,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,io.getParametersForOperation)(e),i=(0,io.validateParameters)(n.filter(s=>s.location==="path"),t.params,e.route.path,t.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=xx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,io.shouldLog)(r.validatePathParameters)&&(0,io.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,io.shouldReject)(r.validatePathParameters))return a}}o(Cx,"handlePathParameterValidation");Dc.handlePathParameterValidation=Cx});var cE=b(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.handleQueryParameterValidation=void 0;var Dx=pe(),oo=ro();function Lx(e,t,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,oo.getParametersForOperation)(e),i=(0,oo.validateParameters)(n.filter(s=>s.location==="query"),t.query,e.route.path,t.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=Dx.HttpProblems.badRequest(t,e,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,oo.shouldLog)(r.validateQueryParameters)&&(0,oo.logErrors)(e,r.logLevel??"info",s,i.invalidValues,i.errors),(0,oo.shouldReject)(r.validateQueryParameters))return a}}o(Lx,"handleQueryParameterValidation");Lc.handleQueryParameterValidation=Lx});var uE=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy=void 0;var Mx=oE(),Ux=sE(),kx=aE(),Fx=cE(),Hx=o(async(e,t,r)=>{let n=(0,Fx.handleQueryParameterValidation)(t,e,r);if(n!==void 0||(n=(0,kx.handlePathParameterValidation)(t,e,r),n!==void 0)||(n=(0,Ux.handleHeadersValidation)(t,e,r),n!==void 0))return n;let i=await(0,Mx.handleBodyValidation)(t,e,r);return i!==void 0?i:e},"RequestValidationInboundPolicy");rn.RequestValidationInboundPolicy=Hx;rn.SchemaBasedRequestValidation=rn.RequestValidationInboundPolicy});var lE=b(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.RequireOriginInboundPolicy=void 0;var qx=k(),$x=pe(),jx=o(async(e,t,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new qx.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=e.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return $x.HttpProblems.forbidden(e,t,{detail:a})}return e},"RequireOriginInboundPolicy");Mc.RequireOriginInboundPolicy=jx});var dE=b(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.SetBodyInboundPolicy=void 0;var Vx=Be(),Gx=o(async(e,t,r)=>new Vx.ZuploRequest(e,{body:r.body}),"SetBodyInboundPolicy");Uc.SetBodyInboundPolicy=Gx});var hE=b(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.SetHeadersInboundPolicy=void 0;var pE=k(),Bx=Be(),Kx=o(async(e,t,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new pE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(e.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new pE.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 Bx.ZuploRequest(e,{headers:s})},"SetHeadersInboundPolicy");kc.SetHeadersInboundPolicy=Kx});var mE=b(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.SetHeadersOutboundPolicy=void 0;var fE=k(),Jx=o(async(e,t,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new fE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(e.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new fE.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(e.body,{headers:a,status:e.status,statusText:e.statusText})},"SetHeadersOutboundPolicy");Fc.SetHeadersOutboundPolicy=Jx});var gE=b(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.SetQueryParamsInboundPolicy=void 0;var yE=k(),zx=Be(),Wx=o(async(e,t,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new yE.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(e.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new yE.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 zx.ZuploRequest(s.toString(),e)},"SetQueryParamsInboundPolicy");Hc.SetQueryParamsInboundPolicy=Wx});var bE=b(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.SetStatusOutboundPolicy=void 0;var Qx=o(async(e,t,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(e.body,{headers:e.headers,status:n.status,statusText:n.statusText??e.statusText})},"SetStatusOutboundPolicy");qc.SetStatusOutboundPolicy=Qx});var _E=b($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.SleepInboundPolicy=void 0;var Yx=k(),Zx=o(async e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),Xx=o(async(e,t,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Yx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await Zx(r.sleepInMs),e},"SleepInboundPolicy");$c.SleepInboundPolicy=Xx});var wE=b(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.SupabaseJwtInboundPolicy=void 0;var EE=k(),eC=pe(),tC=Be(),rC=Mt(),nC=Qt(),iC=o(async(e,t,r,n)=>{(0,rC.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,nC.OpenIdJwtInboundPolicy)(e,t,i,n);if(s instanceof Response)return s;if(!(s instanceof tC.ZuploRequest))throw new EE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=e.user?.data.app_metadata;if(!c)throw new EE.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?eC.HttpProblems.unauthorized(e,t,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");jc.SupabaseJwtInboundPolicy=iC});var TE=b(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var oC=Wt(),sC=er(),vE=k(),aC=Cn(),cC=Mt(),uC=o(async(e,t,r,n)=>{(0,cC.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,oC.getPolicyCacheName)(n,r),s=new sC.MemoryZoneReadThroughCache(i,t),a=await s.get(n);if(!a){let c=await lC(r,t);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return e.headers.set("Authorization",`Bearer ${a}`),e},"UpstreamAzureAdServiceAuthInboundPolicy");Vc.UpstreamAzureAdServiceAuthInboundPolicy=uC;async function lC(e,t){let r=new URLSearchParams({client_id:e.activeDirectoryClientId,scope:`${e.activeDirectoryClientId}/.default`,client_secret:e.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,aC.fetchRetry)({retries:e.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${e.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();t.log.error("Could not get token from Azure AD",s)}catch{}throw new vE.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 vE.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(lC,"getAccessToken")});var IE=b(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var dC=Wt(),pC=er(),hC=k(),Nh=Dn(),fC=Mt(),SE="https://accounts.google.com/o/oauth2/token",xh,mC=o(async(e,t,r,n)=>{(0,fC.optionValidator)(r,n).required("serviceAccountJson","string"),xh||(xh=await Nh.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,dC.getPolicyCacheName)(n,r),a=new pC.MemoryZoneReadThroughCache(s,t),c=await a.get(n);if(!c){let u=await(0,Nh.getTokenFromGcpServiceAccount)({serviceAccount:xh,audience:SE,payload:i}),l=await(0,Nh.exchangeGgpJwtForIdToken)(SE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new hC.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamFirebaseAdminAuthInboundPolicy");Gc.UpstreamFirebaseAdminAuthInboundPolicy=mC});var PE=b(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.UpstreamFirebaseUserAuthInboundPolicy=void 0;var yC=Wt(),gC=er(),ai=k(),bC=dh(),Ch=Dn(),_C=sr(),EC=Mt(),wC="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",vC=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Dh,TC=o(async(e,t,r,n)=>{if((0,EC.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new ai.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(vC.indexOf(p)!==-1)throw new ai.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Dh||(Dh=await Ch.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=e.user?.sub}else if(r.userIdPropertyPath){if(!e.user)throw new ai.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,_C.getValueFromRequestUser)(e.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new ai.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,yC.getPolicyCacheName)(n,r),c=new gC.MemoryZoneReadThroughCache(a,t),u={uid:s,claims:i},l=await(0,bC.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Ch.getTokenFromGcpServiceAccount)({serviceAccount:Dh,audience:wC,payload:u}),h=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,f=await(0,Ch.exchangeFirebaseJwtForIdToken)(h,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new ai.RuntimeError("Invalid token response from Firebase");d=f.idToken,c.put(l,d,(f.expiresIn?parseInt(f.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${d}`),e},"UpstreamFirebaseUserAuthInboundPolicy");Bc.UpstreamFirebaseUserAuthInboundPolicy=TC});var RE=b(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.UpstreamGcpJwtInboundPolicy=void 0;var AE=Dn(),SC=Mt(),Lh,IC=o(async(e,t,r,n)=>{(0,SC.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),Lh||(Lh=await AE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,AE.getTokenFromGcpServiceAccount)({serviceAccount:Lh,audience:r.audience});return e.headers.set("Authorization",`Bearer ${i}`),e},"UpstreamGcpJwtInboundPolicy");Kc.UpstreamGcpJwtInboundPolicy=IC});var NE=b(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.UpstreamGcpServiceAuthInboundPolicy=void 0;var PC=Wt(),AC=ju(),RC=er(),so=k(),Mh=Dn(),OC=sr(),NC=Mt(),OE="https://www.googleapis.com/oauth2/v4/token",Uh,xC=o(async(e,t,r,n)=>{(0,NC.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Uh||(Uh=await Mh.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new so.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,OC.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof so.ConfigurationError?new so.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,PC.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new AC.MemoryCache(s):a=new RC.MemoryZoneReadThroughCache(s,t);let c=await a.get(n);if(!c){let u=await(0,Mh.getTokenFromGcpServiceAccount)({serviceAccount:Uh,audience:OE,payload:i}),l=await(0,Mh.exchangeGgpJwtForIdToken)(OE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new so.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new so.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${c}`),e},"UpstreamGcpServiceAuthInboundPolicy");Jc.UpstreamGcpServiceAuthInboundPolicy=xC});var CE=b(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.ValidateJsonSchemaInbound=void 0;var CC=k(),xE=pe(),DC=o(async(e,t,r)=>{let n=e.clone(),i;try{i=await n.json()}catch{return xE.HttpProblems.badRequest(e,t,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return e;let{errors:a}=r.validator;if(!a)throw new CC.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 xE.HttpProblems.badRequest(e,t,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");zc.ValidateJsonSchemaInbound=DC});var LE=b((KK,DE)=>{"use strict";var LC=Object.defineProperty,J=o((e,t)=>LC(e,"name",{value:t,configurable:!0}),"u"),Rr=o((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"E"),MC=Rr(e=>{var t={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=J(function(n){return Object.assign({},t,n)},"buildOptions");e.buildOptions=r,e.defaultOptions=t}),kh=Rr(e=>{"use strict";var t=":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=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+t+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=J(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let h=d.length;for(let f=0;f<h;f++)p.push(d[f]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=J(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let h=0;h<p;h++)l==="strict"?c[d[h]]=[u[d[h]]]:c[d[h]]=u[d[h]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=n}),UC=Rr((e,t)=>{"use strict";var r=class{static{o(this,"P")}static{J(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})}};t.exports=r}),kC=Rr((e,t)=>{var r=kh();function n(p,h){let f={};if(p[h+3]==="O"&&p[h+4]==="C"&&p[h+5]==="T"&&p[h+6]==="Y"&&p[h+7]==="P"&&p[h+8]==="E"){h=h+9;let y=1,_=!1,I=!1,O="";for(;h<p.length;h++)if(p[h]==="<"&&!I){if(_&&a(p,h))h+=7,[entityName,val,h]=i(p,h+1),val.indexOf("&")===-1&&(f[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(_&&c(p,h))h+=8;else if(_&&u(p,h))h+=8;else if(_&&l(p,h))h+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,O=""}else if(p[h]===">"){if(I?p[h-1]==="-"&&p[h-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[h]==="["?_=!0:O+=p[h];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:f,i:h}}o(n,"ue"),J(n,"readDocType");function i(p,h){let f="";for(;h<p.length&&p[h]!=="'"&&p[h]!=='"';h++)f+=p[h];if(f=f.trim(),f.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[h++],_="";for(;h<p.length&&p[h]!==y;h++)_+=p[h];return[f,_,h]}o(i,"le"),J(i,"readEntityExp");function s(p,h){return p[h+1]==="!"&&p[h+2]==="-"&&p[h+3]==="-"}o(s,"ce"),J(s,"isComment");function a(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="N"&&p[h+4]==="T"&&p[h+5]==="I"&&p[h+6]==="T"&&p[h+7]==="Y"}o(a,"de"),J(a,"isEntity");function c(p,h){return p[h+1]==="!"&&p[h+2]==="E"&&p[h+3]==="L"&&p[h+4]==="E"&&p[h+5]==="M"&&p[h+6]==="E"&&p[h+7]==="N"&&p[h+8]==="T"}o(c,"ge"),J(c,"isElement");function u(p,h){return p[h+1]==="!"&&p[h+2]==="A"&&p[h+3]==="T"&&p[h+4]==="T"&&p[h+5]==="L"&&p[h+6]==="I"&&p[h+7]==="S"&&p[h+8]==="T"}o(u,"ae"),J(u,"isAttlist");function l(p,h){return p[h+1]==="!"&&p[h+2]==="N"&&p[h+3]==="O"&&p[h+4]==="T"&&p[h+5]==="A"&&p[h+6]==="T"&&p[h+7]==="I"&&p[h+8]==="O"&&p[h+9]==="N"}o(l,"he"),J(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"pe"),J(d,"validateEntityName"),t.exports=n}),FC=Rr((e,t)=>{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],h=d[2],f=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&h.length>0&&p&&l[2]!=="."||!u.leadingZeros&&h.length>0&&!p&&l[1]!==".")return c;{let _=Number(l),I=""+_;return I.search(/[eE]/)!==-1||y?u.eNotation?_:c:l.indexOf(".")!==-1?I==="0"&&f===""||I===f||p&&I==="-"+f?_:c:h?f===I||p+f===I?_:c:l===I||l===p+I?_:c}}else return c}}o(s,"Te"),J(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,"ye"),J(a,"trimZeros"),t.exports=s}),HC=Rr((e,t)=>{"use strict";var r=kh(),n=UC(),i=kC(),s=FC(),a=class{static{o(this,"C")}static{J(this,"OrderedObjParser")}constructor(w){this.options=w,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=h,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=R,this.saveTextToParentTag=_,this.addChild=f}};function c(w){let S=Object.keys(w);for(let x=0;x<S.length;x++){let E=S[x];this.lastEntities[E]={regex:new RegExp("&"+E+";","g"),val:w[E]}}}o(c,"Oe"),J(c,"addExternalEntities");function u(w,S,x,E,P,C,H){if(w!==void 0&&(this.options.trimValues&&!E&&(w=w.trim()),w.length>0)){H||(w=this.replaceEntitiesValue(w));let D=this.options.tagValueProcessor(S,w,x,P,C);return D==null?w:typeof D!=typeof w||D!==w?D:this.options.trimValues?K(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?K(w,this.options.parseTagValue,this.options.numberParseOptions):w}}o(u,"Ae"),J(u,"parseTextData");function l(w){if(this.options.removeNSPrefix){let S=w.split(":"),x=w.charAt(0)==="/"?"/":"";if(S[0]==="xmlns")return"";S.length===2&&(w=x+S[1])}return w}o(l,"ve"),J(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(w,S,x){if(!this.options.ignoreAttributes&&typeof w=="string"){let E=r.getAllMatches(w,d),P=E.length,C={};for(let H=0;H<P;H++){let D=this.resolveNameSpace(E[H][1]),X=E[H][4],ie=this.options.attributeNamePrefix+D;if(D.length)if(this.options.transformAttributeName&&(ie=this.options.transformAttributeName(ie)),ie==="__proto__"&&(ie="#__proto__"),X!==void 0){this.options.trimValues&&(X=X.trim()),X=this.replaceEntitiesValue(X);let Ge=this.options.attributeValueProcessor(D,X,S);Ge==null?C[ie]=X:typeof Ge!=typeof X||Ge!==X?C[ie]=Ge:C[ie]=K(X,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(C[ie]=!0)}if(!Object.keys(C).length)return;if(this.options.attributesGroupName){let H={};return H[this.options.attributesGroupName]=C,H}return C}}o(p,"Ce"),J(p,"buildAttributesMap");var h=J(function(w){w=w.replace(/\r\n?/g,`
75
75
  `);let S=new n("!xml"),x=S,E="",P="";for(let C=0;C<w.length;C++)if(w[C]==="<")if(w[C+1]==="/"){let H=g(w,">",C,"Closing Tag is not closed."),D=w.substring(C+2,H).trim();if(this.options.removeNSPrefix){let Ge=D.indexOf(":");Ge!==-1&&(D=D.substr(Ge+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),x&&(E=this.saveTextToParentTag(E,x,P));let X=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 ie=0;X&&this.options.unpairedTags.indexOf(X)!==-1?(ie=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ie=P.lastIndexOf("."),P=P.substring(0,ie),x=this.tagsNodeStack.pop(),E="",C=H}else if(w[C+1]==="?"){let H=v(w,C,!1,"?>");if(!H)throw new Error("Pi Tag is not closed.");if(E=this.saveTextToParentTag(E,x,P),!(this.options.ignoreDeclaration&&H.tagName==="?xml"||this.options.ignorePiTags)){let D=new n(H.tagName);D.add(this.options.textNodeName,""),H.tagName!==H.tagExp&&H.attrExpPresent&&(D[":@"]=this.buildAttributesMap(H.tagExp,P,H.tagName)),this.addChild(x,D,P)}C=H.closeIndex+1}else if(w.substr(C+1,3)==="!--"){let H=g(w,"-->",C+4,"Comment is not closed.");if(this.options.commentPropName){let D=w.substring(C+4,H-2);E=this.saveTextToParentTag(E,x,P),x.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}C=H}else if(w.substr(C+1,2)==="!D"){let H=i(w,C);this.docTypeEntities=H.entities,C=H.i}else if(w.substr(C+1,2)==="!["){let H=g(w,"]]>",C,"CDATA is not closed.")-2,D=w.substring(C+9,H);E=this.saveTextToParentTag(E,x,P);let X=this.parseTextData(D,x.tagname,P,!0,!1,!0,!0);X==null&&(X=""),this.options.cdataPropName?x.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):x.add(this.options.textNodeName,X),C=H+2}else{let H=v(w,C,this.options.removeNSPrefix),D=H.tagName,X=H.rawTagName,ie=H.tagExp,Ge=H.attrExpPresent,cn=H.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),x&&E&&x.tagname!=="!xml"&&(E=this.saveTextToParentTag(E,x,P,!1));let yf=x;if(yf&&this.options.unpairedTags.indexOf(yf.tagname)!==-1&&(x=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),D!==S.tagname&&(P+=P?"."+D:D),this.isItStopNode(this.options.stopNodes,P,D)){let ot="";if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1)C=H.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)C=H.closeIndex;else{let Mu=this.readStopNodeData(w,X,cn+1);if(!Mu)throw new Error(`Unexpected end of ${X}`);C=Mu.i,ot=Mu.tagContent}let Lu=new n(D);D!==ie&&Ge&&(Lu[":@"]=this.buildAttributesMap(ie,P,D)),ot&&(ot=this.parseTextData(ot,D,P,!0,Ge,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),Lu.add(this.options.textNodeName,ot),this.addChild(x,Lu,P)}else{if(ie.length>0&&ie.lastIndexOf("/")===ie.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),P=P.substr(0,P.length-1),ie=D):ie=ie.substr(0,ie.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let ot=new n(D);D!==ie&&Ge&&(ot[":@"]=this.buildAttributesMap(ie,P,D)),this.addChild(x,ot,P),P=P.substr(0,P.lastIndexOf("."))}else{let ot=new n(D);this.tagsNodeStack.push(x),D!==ie&&Ge&&(ot[":@"]=this.buildAttributesMap(ie,P,D)),this.addChild(x,ot,P),x=ot}E="",C=cn}}else E+=w[C];return S.child},"parseXml");function f(w,S,x){let E=this.options.updateTag(S.tagname,x,S[":@"]);E===!1||(typeof E=="string"&&(S.tagname=E),w.addChild(S))}o(f,"Fe"),J(f,"addChild");var y=J(function(w){if(this.options.processEntities){for(let S in this.docTypeEntities){let x=this.docTypeEntities[S];w=w.replace(x.regx,x.val)}for(let S in this.lastEntities){let x=this.lastEntities[S];w=w.replace(x.regex,x.val)}if(this.options.htmlEntities)for(let S in this.htmlEntities){let x=this.htmlEntities[S];w=w.replace(x.regex,x.val)}w=w.replace(this.ampEntity.regex,this.ampEntity.val)}return w},"replaceEntitiesValue");function _(w,S,x,E){return w&&(E===void 0&&(E=Object.keys(S.child).length===0),w=this.parseTextData(w,S.tagname,x,!1,S[":@"]?Object.keys(S[":@"]).length!==0:!1,E),w!==void 0&&w!==""&&S.add(this.options.textNodeName,w),w=""),w}o(_,"_e"),J(_,"saveTextToParentTag");function I(w,S,x){let E="*."+x;for(let P in w){let C=w[P];if(E===C||S===C)return!0}return!1}o(I,"Ve"),J(I,"isItStopNode");function O(w,S,x=">"){let E,P="";for(let C=S;C<w.length;C++){let H=w[C];if(E)H===E&&(E="");else if(H==='"'||H==="'")E=H;else if(H===x[0])if(x[1]){if(w[C+1]===x[1])return{data:P,index:C}}else return{data:P,index:C};else H===" "&&(H=" ");P+=H}}o(O,"me"),J(O,"tagExpWithClosingIndex");function g(w,S,x,E){let P=w.indexOf(S,x);if(P===-1)throw new Error(E);return P+S.length-1}o(g,"T"),J(g,"findClosingIndex");function v(w,S,x,E=">"){let P=O(w,S+1,E);if(!P)return;let C=P.data,H=P.index,D=C.search(/\s/),X=C,ie=!0;D!==-1&&(X=C.substring(0,D),C=C.substring(D+1).trimStart());let Ge=X;if(x){let cn=X.indexOf(":");cn!==-1&&(X=X.substr(cn+1),ie=X!==P.data.substr(cn+1))}return{tagName:X,tagExp:C,closeIndex:H,attrExpPresent:ie,rawTagName:Ge}}o(v,"k"),J(v,"readTagExp");function R(w,S,x){let E=x,P=1;for(;x<w.length;x++)if(w[x]==="<")if(w[x+1]==="/"){let C=g(w,">",x,`${S} is not closed`);if(w.substring(x+2,C).trim()===S&&(P--,P===0))return{tagContent:w.substring(E,x),i:C};x=C}else if(w[x+1]==="?")x=g(w,"?>",x+1,"StopNode is not closed.");else if(w.substr(x+1,3)==="!--")x=g(w,"-->",x+3,"StopNode is not closed.");else if(w.substr(x+1,2)==="![")x=g(w,"]]>",x,"StopNode is not closed.")-2;else{let C=v(w,x,">");C&&((C&&C.tagName)===S&&C.tagExp[C.tagExp.length-1]!=="/"&&P++,x=C.closeIndex)}}o(R,"je"),J(R,"readStopNodeData");function K(w,S,x){if(S&&typeof w=="string"){let E=w.trim();return E==="true"?!0:E==="false"?!1:s(w,x)}else return r.isExist(w)?w:""}o(K,"F"),J(K,"parseValue"),t.exports=a}),qC=Rr(e=>{"use strict";function t(a,c){return r(a,c)}o(t,"qe"),J(t,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let h=a[p],f=n(h),y="";if(u===void 0?y=f:y=u+"."+f,f===c.textNodeName)l===void 0?l=h[f]:l+=""+h[f];else{if(f===void 0)continue;if(h[f]){let _=r(h[f],c,y),I=s(_,c);h[":@"]?i(_,h[":@"],y,c):Object.keys(_).length===1&&_[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?_=_[c.textNodeName]:Object.keys(_).length===0&&(c.alwaysCreateTextNode?_[c.textNodeName]="":_=""),d[f]!==void 0&&d.hasOwnProperty(f)?(Array.isArray(d[f])||(d[f]=[d[f]]),d[f].push(_)):c.isArray(f,y,I)?d[f]=[_]:d[f]=_}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"G"),J(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,"Re"),J(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let h=0;h<p;h++){let f=d[h];l.isArray(f,u+"."+f,!0,!0)?a[f]=[c[f]]:a[f]=c[f]}}}o(i,"$e"),J(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,"Be"),J(s,"isLeafTag"),e.prettify=t}),$C=Rr(e=>{"use strict";var t=kh(),r={allowBooleanAttributes:!1,unpairedTags:[]};e.validate=function(g,v){v=Object.assign({},r,v);let R=[],K=!1,w=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let S=0;S<g.length;S++)if(g[S]==="<"&&g[S+1]==="?"){if(S+=2,S=i(g,S),S.err)return S}else if(g[S]==="<"){let x=S;if(S++,g[S]==="!"){S=s(g,S);continue}else{let E=!1;g[S]==="/"&&(E=!0,S++);let P="";for(;S<g.length&&g[S]!==">"&&g[S]!==" "&&g[S]!==" "&&g[S]!==`
76
76
  `&&g[S]!=="\r";S++)P+=g[S];if(P=P.trim(),P[P.length-1]==="/"&&(P=P.substring(0,P.length-1),S--),!_(P)){let D;return P.trim().length===0?D="Invalid space after '<'.":D="Tag '"+P+"' is an invalid name.",f("InvalidTag",D,I(g,S))}let C=u(g,S);if(C===!1)return f("InvalidAttr","Attributes for '"+P+"' have open quote.",I(g,S));let H=C.value;if(S=C.index,H[H.length-1]==="/"){let D=S-H.length;H=H.substring(0,H.length-1);let X=d(H,v);if(X===!0)K=!0;else return f(X.err.code,X.err.msg,I(g,D+X.err.line))}else if(E)if(C.tagClosed){if(H.trim().length>0)return f("InvalidTag","Closing tag '"+P+"' can't have attributes or invalid starting.",I(g,x));{let D=R.pop();if(P!==D.tagName){let X=I(g,D.tagStartPos);return f("InvalidTag","Expected closing tag '"+D.tagName+"' (opened in line "+X.line+", col "+X.col+") instead of closing tag '"+P+"'.",I(g,x))}R.length==0&&(w=!0)}}else return f("InvalidTag","Closing tag '"+P+"' doesn't have proper closing.",I(g,S));else{let D=d(H,v);if(D!==!0)return f(D.err.code,D.err.msg,I(g,S-H.length+D.err.line));if(w===!0)return f("InvalidXml","Multiple possible root nodes found.",I(g,S));v.unpairedTags.indexOf(P)!==-1||R.push({tagName:P,tagStartPos:x}),K=!0}for(S++;S<g.length;S++)if(g[S]==="<")if(g[S+1]==="!"){S++,S=s(g,S);continue}else if(g[S+1]==="?"){if(S=i(g,++S),S.err)return S}else break;else if(g[S]==="&"){let D=h(g,S);if(D==-1)return f("InvalidChar","char '&' is not expected.",I(g,S));S=D}else if(w===!0&&!n(g[S]))return f("InvalidXml","Extra text at the end",I(g,S));g[S]==="<"&&S--}}else{if(n(g[S]))continue;return f("InvalidChar","char '"+g[S]+"' is not expected.",I(g,S))}if(K){if(R.length==1)return f("InvalidTag","Unclosed tag '"+R[0].tagName+"'.",I(g,R[0].tagStartPos));if(R.length>0)return f("InvalidXml","Invalid '"+JSON.stringify(R.map(S=>S.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return f("InvalidXml","Start tag expected.",1);return!0};function n(g){return g===" "||g===" "||g===`
77
- `||g==="\r"}o(n,"W"),J(n,"isWhiteSpace");function i(g,v){let R=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let K=g.substr(R,v-R);if(v>5&&K==="xml")return f("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"z"),J(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let R=1;for(v+=8;v<g.length;v++)if(g[v]==="<")R++;else if(g[v]===">"&&(R--,R===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"K"),J(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let R="",K="",w=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)K===""?K=g[v]:K!==g[v]||(K="");else if(g[v]===">"&&K===""){w=!0;break}R+=g[v]}return K!==""?!1:{value:R,index:v,tagClosed:w}}o(u,"Le"),J(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let R=t.getAllMatches(g,l),K={};for(let w=0;w<R.length;w++){if(R[w][1].length===0)return f("InvalidAttr","Attribute '"+R[w][2]+"' has no space in starting.",O(R[w]));if(R[w][3]!==void 0&&R[w][4]===void 0)return f("InvalidAttr","Attribute '"+R[w][2]+"' is without value.",O(R[w]));if(R[w][3]===void 0&&!v.allowBooleanAttributes)return f("InvalidAttr","boolean attribute '"+R[w][2]+"' is not allowed.",O(R[w]));let S=R[w][2];if(!y(S))return f("InvalidAttr","Attribute '"+S+"' is an invalid name.",O(R[w]));if(!K.hasOwnProperty(S))K[S]=1;else return f("InvalidAttr","Attribute '"+S+"' is repeated.",O(R[w]))}return!0}o(d,"H"),J(d,"validateAttributeString");function p(g,v){let R=/\d/;for(g[v]==="x"&&(v++,R=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(R))break}return-1}o(p,"Ue"),J(p,"validateNumberAmpersand");function h(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let R=0;for(;v<g.length;v++,R++)if(!(g[v].match(/\w/)&&R<20)){if(g[v]===";")break;return-1}return v}o(h,"xe"),J(h,"validateAmpersand");function f(g,v,R){return{err:{code:g,msg:v,line:R.line||R,col:R.col}}}o(f,"a"),J(f,"getErrorObject");function y(g){return t.isName(g)}o(y,"Ge"),J(y,"validateAttrName");function _(g){return t.isName(g)}o(_,"Je"),J(_,"validateTagName");function I(g,v){let R=g.substring(0,v).split(/\r?\n/);return{line:R.length,col:R[R.length-1].length+1}}o(I,"h"),J(I,"getLineNumberForPosition");function O(g){return g.startIndex+g[1].length}o(O,"I"),J(O,"getPositionFromMatch")}),{buildOptions:jC}=MC(),VC=HC(),{prettify:GC}=qC(),BC=$C(),KC=class{static{o(this,"_")}static{J(this,"XMLParser")}constructor(e){this.externalEntities={},this.options=jC(e)}parse(e,t){if(typeof e!="string")if(e.toString)e=e.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(t){t===!0&&(t={});let i=BC.validate(e,t);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}let r=new VC(this.options);r.addExternalEntities(this.externalEntities);let n=r.parseXml(e);return this.options.preserveOrder||n===void 0?n:GC(n,this.options)}addEntity(e,t){if(t.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(e.indexOf("&")!==-1||e.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(t==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}};DE.exports=KC;});var ME=b(ci=>{"use strict";var JC=ci&&ci.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ci,"__esModule",{value:!0});ci.XmlToJsonOutbound=void 0;var zC=k(),WC=JC(LE()),QC=o(async(e,t,r,n,i)=>{let s;try{let u=await e.text();s=new WC.default().parse(u)}catch(u){let l=`XmlToJsonOutbound - Error parsing XML contents in policy '${i}'.`;throw r.log.error(l,u),new zC.RuntimeError(l)}let a=new Headers(e.headers);return a.set("content-type","application/json"),new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:a})},"XmlToJsonOutbound");ci.XmlToJsonOutbound=QC});var UE=b(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.ServiceProviderImpl=void 0;var YC=k(),Fh=class{static{o(this,"ServiceProviderImpl")}services=new Map;addService(t,r){if(this.services.get(t))throw new YC.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Wc.ServiceProviderImpl=Fh});var WE=b(m=>{"use strict";var ZC=m&&m.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Hh=m&&m.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ZC(t,e,r)},XC=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.MonetizationInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.OutboundPolicy=m.InboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.RuntimeError=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.XmlToJsonOutbound=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=void 0;vf();var eD=er();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return eD.MemoryZoneReadThroughCache}});var tD=No();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return tD.ZoneCache}});var kE=Fr();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return kE.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return kE.ResponseSentEvent}});var rD=ap();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return rD.ContextData}});var qh=Ki();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return qh.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return qh.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return qh.isZuploReadableEnvVariableName}});var FE=k();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return FE.ConfigurationError}});Object.defineProperty(m,"RuntimeError",{enumerable:!0,get:function(){return FE.RuntimeError}});var nD=up();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return nD.originalFetch}});var HE=Qg();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return HE.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return HE.purgeGatewayCache}});var qE=hb();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return qE.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return qE.awsLambdaHandler}});var iD=mb();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return iD.openApiSpecHandler}});var oD=yb();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return oD.redirectHandler}});var sD=bb();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return sD.urlForwardHandler}});var aD=Eb();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return aD.urlRewriteHandler}});var cD=vb();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return cD.webSocketHandler}});var uD=Ib();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return uD.webSocketPipelineHandler}});var lD=hl();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return lD.HttpStatusCode}});Hh(Db(),m);Hh(Ub(),m);var dD=kb();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return dD.AuditLogDataStaxProvider}});var pD=Hb();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return pD.AuditLogPlugin}});Hh(e_(),m);var $E=Pi();Object.defineProperty(m,"InboundPolicy",{enumerable:!0,get:function(){return $E.InboundPolicy}});Object.defineProperty(m,"OutboundPolicy",{enumerable:!0,get:function(){return $E.OutboundPolicy}});var jE=o_();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringPolicy}});var hD=l_();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return hD.ApiAuthKeyInboundPolicy}});var fD=fh();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return fD.ApiKeyInboundPolicy}});var mD=d_();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return mD.Auth0JwtInboundPolicy}});var yD=p_();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return yD.BasicAuthInboundPolicy}});var gD=h_();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return gD.CachingInboundPolicy}});var bD=f_();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return bD.ChangeMethodInboundPolicy}});var _D=m_();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return _D.ClearHeadersInboundPolicy}});var ED=y_();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return ED.ClearHeadersOutboundPolicy}});var wD=g_();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return wD.ClerkJwtInboundPolicy}});var vD=__();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return vD.CognitoJwtInboundPolicy}});var TD=w_();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return TD.CompositeInboundPolicy}});var SD=v_();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return SD.CurityPhantomTokenInboundPolicy}});var ID=T_();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return ID.FirebaseJwtInboundPolicy}});var PD=S_();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return PD.FormDataToJsonInboundPolicy}});var AD=I_();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return AD.GeoFilterInboundPolicy}});var RD=P_();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return RD.JWTScopeValidationInboundPolicy}});var OD=R_();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return OD.MockApiInboundPolicy}});var VE=D_();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return VE.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return VE.setMoesifContext}});var ND=H_();Object.defineProperty(m,"MonetizationInboundPolicy",{enumerable:!0,get:function(){return ND.MonetizationInboundPolicy}});var xD=q_();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return xD.OktaJwtInboundPolicy}});var CD=Qt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return CD.OpenIdJwtInboundPolicy}});var DD=$_();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return DD.PropelAuthJwtInboundPolicy}});var GE=z_();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});var LD=Z_();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return LD.ReadmeMetricsInboundPolicy}});var MD=X_();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return MD.RemoveHeadersInboundPolicy}});var UD=eE();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return UD.RemoveHeadersOutboundPolicy}});var kD=tE();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return kD.RemoveQueryParamsInboundPolicy}});var FD=rE();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return FD.ReplaceStringOutboundPolicy}});var HD=iE();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return HD.RequestSizeLimitInboundPolicy}});var BE=uE();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return BE.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return BE.SchemaBasedRequestValidation}});var qD=lE();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return qD.RequireOriginInboundPolicy}});var $D=dE();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return $D.SetBodyInboundPolicy}});var jD=hE();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return jD.SetHeadersInboundPolicy}});var VD=mE();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return VD.SetHeadersOutboundPolicy}});var GD=gE();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return GD.SetQueryParamsInboundPolicy}});var BD=bE();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return BD.SetStatusOutboundPolicy}});var KD=_E();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return KD.SleepInboundPolicy}});var JD=Bp();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return JD.StripeWebhookVerificationInboundPolicy}});var zD=wE();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return zD.SupabaseJwtInboundPolicy}});var WD=TE();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return WD.UpstreamAzureAdServiceAuthInboundPolicy}});var QD=IE();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return QD.UpstreamFirebaseAdminAuthInboundPolicy}});var YD=PE();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return YD.UpstreamFirebaseUserAuthInboundPolicy}});var ZD=RE();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return ZD.UpstreamGcpJwtInboundPolicy}});var XD=NE();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return XD.UpstreamGcpServiceAuthInboundPolicy}});var eL=CE();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return eL.ValidateJsonSchemaInbound}});var tL=ME();Object.defineProperty(m,"XmlToJsonOutbound",{enumerable:!0,get:function(){return tL.XmlToJsonOutbound}});var rL=pe();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return rL.HttpProblems}});var nL=Ho();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return nL.ProblemResponseFormatter}});var iL=Be();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return iL.ZuploRequest}});var oL=qr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return oL.SystemRouteName}});var KE=Zd();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return KE.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return KE.Router}});var JE=nl();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return JE.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return JE.serialize}});var sL=UE();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return sL.ServiceProviderImpl}});var zE=Cl();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return zE.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return zE.SYSTEM_LOGGER}});var aL=ml();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return XC(aL).default}});var cL=Ze();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return cL.SystemLogMap}});var ao=Oc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return ao.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return ao.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return ao.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return ao.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return ao.sanitizedIdentifierName}})});var QE=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.BaseCryptoBeta=ui.supportedDigests=void 0;ui.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var $h=class{static{o(this,"BaseCryptoBeta")}};ui.BaseCryptoBeta=$h});var YE=b(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.WorkerCryptoBeta=void 0;var jh=QE(),uL=k(),Vh=class extends jh.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(t,r){if(!jh.supportedDigests.includes(t.toLowerCase()))throw new uL.RuntimeError(`Algorithm ${t} is not supported. Try using ${jh.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};Qc.WorkerCryptoBeta=Vh});var ZE=b(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.BaseKeyValueStore=void 0;var Gh=class{static{o(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};Yc.BaseKeyValueStore=Gh});var ew=b(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.WorkerKeyValueStore=void 0;var XE=k(),lL=ZE(),Bh=class extends lL.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new XE.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new XE.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Zc.WorkerKeyValueStore=Bh});var Vt=b(_t=>{"use strict";var dL=_t&&_t.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),pL=_t&&_t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&dL(t,e,r)};Object.defineProperty(_t,"__esModule",{value:!0});_t.KeyValueStore=_t.CryptoBeta=void 0;pL(WE(),_t);var hL=YE();Object.defineProperty(_t,"CryptoBeta",{enumerable:!0,get:function(){return hL.WorkerCryptoBeta}});var fL=ew();Object.defineProperty(_t,"KeyValueStore",{enumerable:!0,get:function(){return fL.WorkerKeyValueStore}})});var w1={};So(w1,{GraphQLComplexityLimitInboundPolicy:()=>Cw,GraphQLDisableIntrospectionInboundPolicy:()=>Lw});module.exports=Io(w1);var wi=bf(Vt());function ee(e,t){if(!!!e)throw new Error(t)}o(ee,"devAssert");function Ae(e){return typeof e=="object"&&e!==null}o(Ae,"isObjectLike");function kt(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}o(kt,"invariant");var mL=/\r\n|[\n\r]/g;function li(e,t){let r=0,n=1;for(let i of e.body.matchAll(mL)){if(typeof i.index=="number"||kt(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}o(li,"getLocation");function Kh(e){return Xc(e.source,li(e.source,e.start))}o(Kh,"printLocation");function Xc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,s=e.locationOffset.line-1,a=t.line+s,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
77
+ `||g==="\r"}o(n,"W"),J(n,"isWhiteSpace");function i(g,v){let R=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let K=g.substr(R,v-R);if(v>5&&K==="xml")return f("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"z"),J(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let R=1;for(v+=8;v<g.length;v++)if(g[v]==="<")R++;else if(g[v]===">"&&(R--,R===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"K"),J(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let R="",K="",w=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)K===""?K=g[v]:K!==g[v]||(K="");else if(g[v]===">"&&K===""){w=!0;break}R+=g[v]}return K!==""?!1:{value:R,index:v,tagClosed:w}}o(u,"Le"),J(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let R=t.getAllMatches(g,l),K={};for(let w=0;w<R.length;w++){if(R[w][1].length===0)return f("InvalidAttr","Attribute '"+R[w][2]+"' has no space in starting.",O(R[w]));if(R[w][3]!==void 0&&R[w][4]===void 0)return f("InvalidAttr","Attribute '"+R[w][2]+"' is without value.",O(R[w]));if(R[w][3]===void 0&&!v.allowBooleanAttributes)return f("InvalidAttr","boolean attribute '"+R[w][2]+"' is not allowed.",O(R[w]));let S=R[w][2];if(!y(S))return f("InvalidAttr","Attribute '"+S+"' is an invalid name.",O(R[w]));if(!K.hasOwnProperty(S))K[S]=1;else return f("InvalidAttr","Attribute '"+S+"' is repeated.",O(R[w]))}return!0}o(d,"H"),J(d,"validateAttributeString");function p(g,v){let R=/\d/;for(g[v]==="x"&&(v++,R=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(R))break}return-1}o(p,"Ue"),J(p,"validateNumberAmpersand");function h(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let R=0;for(;v<g.length;v++,R++)if(!(g[v].match(/\w/)&&R<20)){if(g[v]===";")break;return-1}return v}o(h,"xe"),J(h,"validateAmpersand");function f(g,v,R){return{err:{code:g,msg:v,line:R.line||R,col:R.col}}}o(f,"a"),J(f,"getErrorObject");function y(g){return t.isName(g)}o(y,"Ge"),J(y,"validateAttrName");function _(g){return t.isName(g)}o(_,"Je"),J(_,"validateTagName");function I(g,v){let R=g.substring(0,v).split(/\r?\n/);return{line:R.length,col:R[R.length-1].length+1}}o(I,"h"),J(I,"getLineNumberForPosition");function O(g){return g.startIndex+g[1].length}o(O,"I"),J(O,"getPositionFromMatch")}),{buildOptions:jC}=MC(),VC=HC(),{prettify:GC}=qC(),BC=$C(),KC=class{static{o(this,"_")}static{J(this,"XMLParser")}constructor(e){this.externalEntities={},this.options=jC(e)}parse(e,t){if(typeof e!="string")if(e.toString)e=e.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(t){t===!0&&(t={});let i=BC.validate(e,t);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}let r=new VC(this.options);r.addExternalEntities(this.externalEntities);let n=r.parseXml(e);return this.options.preserveOrder||n===void 0?n:GC(n,this.options)}addEntity(e,t){if(t.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(e.indexOf("&")!==-1||e.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(t==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}};DE.exports=KC;});var ME=b(ci=>{"use strict";var JC=ci&&ci.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ci,"__esModule",{value:!0});ci.XmlToJsonOutboundPolicy=void 0;var zC=k(),WC=JC(LE()),QC=o(async(e,t,r,n,i)=>{let s;try{let u=await e.text();s=new WC.default().parse(u)}catch(u){let l=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${i}'.`;throw r.log.error(l,u),new zC.RuntimeError(l)}let a=new Headers(e.headers);return a.set("content-type","application/json"),new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:a})},"XmlToJsonOutboundPolicy");ci.XmlToJsonOutboundPolicy=QC});var UE=b(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.ServiceProviderImpl=void 0;var YC=k(),Fh=class{static{o(this,"ServiceProviderImpl")}services=new Map;addService(t,r){if(this.services.get(t))throw new YC.SystemError(`A service with the name ${t} already exists -- you cannot have duplicate services`);this.services.set(t,r)}getService(t){return this.services.get(t)}};Wc.ServiceProviderImpl=Fh});var WE=b(m=>{"use strict";var ZC=m&&m.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Hh=m&&m.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ZC(t,e,r)},XC=m&&m.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(m,"__esModule",{value:!0});m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.MonetizationInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.OutboundPolicy=m.InboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.RuntimeError=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.XmlToJsonOutboundPolicy=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=void 0;vf();var eD=er();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return eD.MemoryZoneReadThroughCache}});var tD=No();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return tD.ZoneCache}});var kE=Fr();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return kE.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return kE.ResponseSentEvent}});var rD=ap();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return rD.ContextData}});var qh=Ki();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return qh.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return qh.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return qh.isZuploReadableEnvVariableName}});var FE=k();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return FE.ConfigurationError}});Object.defineProperty(m,"RuntimeError",{enumerable:!0,get:function(){return FE.RuntimeError}});var nD=up();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return nD.originalFetch}});var HE=Qg();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return HE.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return HE.purgeGatewayCache}});var qE=hb();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return qE.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return qE.awsLambdaHandler}});var iD=mb();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return iD.openApiSpecHandler}});var oD=yb();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return oD.redirectHandler}});var sD=bb();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return sD.urlForwardHandler}});var aD=Eb();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return aD.urlRewriteHandler}});var cD=vb();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return cD.webSocketHandler}});var uD=Ib();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return uD.webSocketPipelineHandler}});var lD=hl();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return lD.HttpStatusCode}});Hh(Db(),m);Hh(Ub(),m);var dD=kb();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return dD.AuditLogDataStaxProvider}});var pD=Hb();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return pD.AuditLogPlugin}});Hh(e_(),m);var $E=Pi();Object.defineProperty(m,"InboundPolicy",{enumerable:!0,get:function(){return $E.InboundPolicy}});Object.defineProperty(m,"OutboundPolicy",{enumerable:!0,get:function(){return $E.OutboundPolicy}});var jE=o_();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return jE.AmberfloMeteringPolicy}});var hD=l_();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return hD.ApiAuthKeyInboundPolicy}});var fD=fh();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return fD.ApiKeyInboundPolicy}});var mD=d_();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return mD.Auth0JwtInboundPolicy}});var yD=p_();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return yD.BasicAuthInboundPolicy}});var gD=h_();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return gD.CachingInboundPolicy}});var bD=f_();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return bD.ChangeMethodInboundPolicy}});var _D=m_();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return _D.ClearHeadersInboundPolicy}});var ED=y_();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return ED.ClearHeadersOutboundPolicy}});var wD=g_();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return wD.ClerkJwtInboundPolicy}});var vD=__();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return vD.CognitoJwtInboundPolicy}});var TD=w_();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return TD.CompositeInboundPolicy}});var SD=v_();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return SD.CurityPhantomTokenInboundPolicy}});var ID=T_();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return ID.FirebaseJwtInboundPolicy}});var PD=S_();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return PD.FormDataToJsonInboundPolicy}});var AD=I_();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return AD.GeoFilterInboundPolicy}});var RD=P_();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return RD.JWTScopeValidationInboundPolicy}});var OD=R_();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return OD.MockApiInboundPolicy}});var VE=D_();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return VE.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return VE.setMoesifContext}});var ND=H_();Object.defineProperty(m,"MonetizationInboundPolicy",{enumerable:!0,get:function(){return ND.MonetizationInboundPolicy}});var xD=q_();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return xD.OktaJwtInboundPolicy}});var CD=Qt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return CD.OpenIdJwtInboundPolicy}});var DD=$_();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return DD.PropelAuthJwtInboundPolicy}});var GE=z_();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return GE.RateLimitInboundPolicy}});var LD=Z_();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return LD.ReadmeMetricsInboundPolicy}});var MD=X_();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return MD.RemoveHeadersInboundPolicy}});var UD=eE();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return UD.RemoveHeadersOutboundPolicy}});var kD=tE();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return kD.RemoveQueryParamsInboundPolicy}});var FD=rE();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return FD.ReplaceStringOutboundPolicy}});var HD=iE();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return HD.RequestSizeLimitInboundPolicy}});var BE=uE();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return BE.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return BE.SchemaBasedRequestValidation}});var qD=lE();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return qD.RequireOriginInboundPolicy}});var $D=dE();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return $D.SetBodyInboundPolicy}});var jD=hE();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return jD.SetHeadersInboundPolicy}});var VD=mE();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return VD.SetHeadersOutboundPolicy}});var GD=gE();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return GD.SetQueryParamsInboundPolicy}});var BD=bE();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return BD.SetStatusOutboundPolicy}});var KD=_E();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return KD.SleepInboundPolicy}});var JD=Bp();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return JD.StripeWebhookVerificationInboundPolicy}});var zD=wE();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return zD.SupabaseJwtInboundPolicy}});var WD=TE();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return WD.UpstreamAzureAdServiceAuthInboundPolicy}});var QD=IE();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return QD.UpstreamFirebaseAdminAuthInboundPolicy}});var YD=PE();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return YD.UpstreamFirebaseUserAuthInboundPolicy}});var ZD=RE();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return ZD.UpstreamGcpJwtInboundPolicy}});var XD=NE();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return XD.UpstreamGcpServiceAuthInboundPolicy}});var eL=CE();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return eL.ValidateJsonSchemaInbound}});var tL=ME();Object.defineProperty(m,"XmlToJsonOutboundPolicy",{enumerable:!0,get:function(){return tL.XmlToJsonOutboundPolicy}});var rL=pe();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return rL.HttpProblems}});var nL=Ho();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return nL.ProblemResponseFormatter}});var iL=Be();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return iL.ZuploRequest}});var oL=qr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return oL.SystemRouteName}});var KE=Zd();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return KE.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return KE.Router}});var JE=nl();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return JE.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return JE.serialize}});var sL=UE();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return sL.ServiceProviderImpl}});var zE=Cl();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return zE.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return zE.SYSTEM_LOGGER}});var aL=ml();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return XC(aL).default}});var cL=Ze();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return cL.SystemLogMap}});var ao=Oc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return ao.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return ao.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return ao.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return ao.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return ao.sanitizedIdentifierName}})});var QE=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.BaseCryptoBeta=ui.supportedDigests=void 0;ui.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var $h=class{static{o(this,"BaseCryptoBeta")}};ui.BaseCryptoBeta=$h});var YE=b(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.WorkerCryptoBeta=void 0;var jh=QE(),uL=k(),Vh=class extends jh.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(t,r){if(!jh.supportedDigests.includes(t.toLowerCase()))throw new uL.RuntimeError(`Algorithm ${t} is not supported. Try using ${jh.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(t,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};Qc.WorkerCryptoBeta=Vh});var ZE=b(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.BaseKeyValueStore=void 0;var Gh=class{static{o(this,"BaseKeyValueStore")}context;constructor(t){this.context=t}};Yc.BaseKeyValueStore=Gh});var ew=b(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.WorkerKeyValueStore=void 0;var XE=k(),lL=ZE(),Bh=class extends lL.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(t){super(t);let n=globalThis.ZUPLO_KV;if(!n)throw new XE.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(t,r,n){if(typeof t!="string")throw new XE.ConfigurationError("value must be of type string");return this.#e.put(t,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(t,r){return this.#e.get(t,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(t){return this.#e.delete(t)}};Zc.WorkerKeyValueStore=Bh});var Vt=b(_t=>{"use strict";var dL=_t&&_t.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),pL=_t&&_t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&dL(t,e,r)};Object.defineProperty(_t,"__esModule",{value:!0});_t.KeyValueStore=_t.CryptoBeta=void 0;pL(WE(),_t);var hL=YE();Object.defineProperty(_t,"CryptoBeta",{enumerable:!0,get:function(){return hL.WorkerCryptoBeta}});var fL=ew();Object.defineProperty(_t,"KeyValueStore",{enumerable:!0,get:function(){return fL.WorkerKeyValueStore}})});var w1={};So(w1,{GraphQLComplexityLimitInboundPolicy:()=>Cw,GraphQLDisableIntrospectionInboundPolicy:()=>Lw});module.exports=Io(w1);var wi=bf(Vt());function ee(e,t){if(!!!e)throw new Error(t)}o(ee,"devAssert");function Ae(e){return typeof e=="object"&&e!==null}o(Ae,"isObjectLike");function kt(e,t){if(!!!e)throw new Error(t??"Unexpected invariant triggered.")}o(kt,"invariant");var mL=/\r\n|[\n\r]/g;function li(e,t){let r=0,n=1;for(let i of e.body.matchAll(mL)){if(typeof i.index=="number"||kt(!1),i.index>=t)break;r=i.index+i[0].length,n+=1}return{line:n,column:t+1-r}}o(li,"getLocation");function Kh(e){return Xc(e.source,li(e.source,e.start))}o(Kh,"printLocation");function Xc(e,t){let r=e.locationOffset.column-1,n="".padStart(r)+e.body,i=t.line-1,s=e.locationOffset.line-1,a=t.line+s,c=t.line===1?r:0,u=t.column+c,l=`${e.name}:${a}:${u}
78
78
  `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let h=Math.floor(u/80),f=u%80,y=[];for(let _=0;_<p.length;_+=80)y.push(p.slice(_,_+80));return l+tw([[`${a} |`,y[0]],...y.slice(1,h+1).map(_=>["|",_]),["|","^".padStart(f)],["|",y[h+1]]])}return l+tw([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(Xc,"printSourceLocation");function tw(e){let t=e.filter(([n,i])=>i!==void 0),r=Math.max(...t.map(([n])=>n.length));return t.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
79
79
  `)}o(tw,"printPrefixedLines");function yL(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}o(yL,"toNormalizedOptions");var j=class e extends Error{static{o(this,"GraphQLError")}constructor(t,...r){var n,i,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=yL(r);super(t),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=rw(Array.isArray(a)?a:a?[a]:void 0);let h=rw((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(h==null||(i=h[0])===null||i===void 0?void 0:i.source),this.positions=u??h?.map(y=>y.start),this.locations=u&&c?u.map(y=>li(c,y)):h?.map(y=>li(y.source,y.start));let f=Ae(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??f)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(t+=`
80
80
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1809.0",
3
+ "version": "5.1810.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {