@zuplo/runtime 6.40.3 → 6.40.4

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.
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as i}from"./chunk-PPV7V43C.js";var N=(e=>(e.Build="build-data",e.CorsPreflight="cors-preflight",e.DeveloperPortal="developer-portal",e.ZudokuPortal="zudoku-portal",e.DeveloperPortalLegacy="developer-portal-legacy",e.StripePlugin="stripe-plugin",e.EmptyGatewayCatchall="empty-gateway-catchall",e.Ping="ping",e.UnmatchedPath="unmatched-path",e))(N||{});function b(t){if(t.length>=255)throw new TypeError("Alphabet too long");let r=new Uint8Array(256);for(let e=0;e<r.length;e++)r[e]=255;for(let e=0;e<t.length;e++){let o=t.charAt(e),_=o.charCodeAt(0);if(r[_]!==255)throw new TypeError(o+" is ambiguous");r[_]=e}let n=t.length,f=t.charAt(0),m=Math.log(n)/Math.log(256),h=Math.log(256)/Math.log(n);function E(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let o=0,_=0,a=0,g=e.length;for(;a!==g&&e[a]===0;)a++,o++;let d=(g-a)*h+1>>>0,u=new Uint8Array(d);for(;a!==g;){let s=e[a],O=0;for(let p=d-1;(s!==0||O<_)&&p!==-1;p--,O++)s+=256*u[p]>>>0,u[p]=s%n>>>0,s=s/n>>>0;if(s!==0)throw new Error("Non-zero carry");_=O,a++}let c=d-_;for(;c!==d&&u[c]===0;)c++;let P=f.repeat(o);for(;c<d;++c)P+=t.charAt(u[c]);return P}i(E,"encode");function A(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let o=0,_=0,a=0;for(;e[o]===f;)_++,o++;let g=(e.length-o)*m+1>>>0,d=new Uint8Array(g);for(;e[o];){let s=r[e.charCodeAt(o)];if(s===255)return;let O=0;for(let p=g-1;(s!==0||O<a)&&p!==-1;p--,O++)s+=n*d[p]>>>0,d[p]=s%256>>>0,s=s/256>>>0;if(s!==0)throw new Error("Non-zero carry");a=O,o++}let u=g-a;for(;u!==g&&d[u]===0;)u++;let c=new Uint8Array(_+(g-u)),P=_;for(;u!==g;)c[P++]=d[u++];return c}i(A,"decodeUnsafe");function C(e){let o=A(e);if(o)return o;throw new Error("Non-base"+n+" character")}return i(C,"decode"),{encode:E,decodeUnsafe:A,decode:C}}i(b,"base");var T=b;var v="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=T(v);var U="2024-09-02",R=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function y(){return new l({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:U,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:R[U]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(y,"getMockEnvironment");var l=class t{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(r){this.#e||(this.#e=new t(r),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=y()),this.#e}constructor({build:r,runtime:n}){let f;try{if(n.__ZUPLO_CONFIG){let m=atob(n.__ZUPLO_CONFIG);f=JSON.parse(m)}if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let m=new TextDecoder().decode(I.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),h=JSON.parse(m);for(let E of Object.keys(h))n[E]||(n[E]=h[E])}}catch(m){console.error("Failed to parse runtime configuration",m)}this.config=f??{},this.build=r,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get zudokuHostUrl(){return this.runtime.__ZUPLO_ZUDOKU_HOST_URL??this.config.zudoku_host_url??"https://zudoku.zuploedge.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var w=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function M(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!w.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(M,"isRestrictedEnvVariableName");function S(t){return!!t.startsWith("ZUPLO_")}i(S,"isZuploReadableEnvVariableName");var X=new Proxy({},{get(t,r){let n=String(r);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return l.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return l.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return l.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return l.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return l.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return l.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return l.instance.build.COMPATIBILITY_DATE}if(!(M(n)&&!S(n)))return l.instance.runtime[n]}});function ne(t,r,n){return`_${L(`${t}_${r}_${n}`)}`}i(ne,"getRawOperationDataIdentifierName");function re(t,r,n,f){return`_${L(t.toLowerCase())}_${r.toLowerCase()}_${n.toLowerCase()}_${f.toLowerCase()}`}i(re,"getIdForParameterSchema");function ie(t,r,n){return`_${L(t.toLowerCase())}_${r.toLowerCase()}_rb_${L(n.toLowerCase())}`}i(ie,"getIdForRequestBodySchema");function oe(t,r){return`_${L(t)}_${L(r)}`}i(oe,"getIdForRefSchema");function L(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}i(L,"sanitizedIdentifierName");export{l as a,N as b,M as c,S as d,X as e,ne as f,re as g,ie as h,oe as i,L as j};
26
- /*! For license information please see chunk-IF4DUSCR.js.LEGAL.txt */
25
+ import{a as i}from"./chunk-PPV7V43C.js";var N=(e=>(e.Build="build-data",e.CorsPreflight="cors-preflight",e.DeveloperPortal="developer-portal",e.ZudokuPortal="zudoku-portal",e.DeveloperPortalLegacy="developer-portal-legacy",e.StripePlugin="stripe-plugin",e.EmptyGatewayCatchall="empty-gateway-catchall",e.Ping="ping",e.UnmatchedPath="unmatched-path",e))(N||{});function b(t){if(t.length>=255)throw new TypeError("Alphabet too long");let r=new Uint8Array(256);for(let e=0;e<r.length;e++)r[e]=255;for(let e=0;e<t.length;e++){let o=t.charAt(e),_=o.charCodeAt(0);if(r[_]!==255)throw new TypeError(o+" is ambiguous");r[_]=e}let n=t.length,f=t.charAt(0),m=Math.log(n)/Math.log(256),h=Math.log(256)/Math.log(n);function E(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let o=0,_=0,a=0,g=e.length;for(;a!==g&&e[a]===0;)a++,o++;let d=(g-a)*h+1>>>0,u=new Uint8Array(d);for(;a!==g;){let s=e[a],O=0;for(let p=d-1;(s!==0||O<_)&&p!==-1;p--,O++)s+=256*u[p]>>>0,u[p]=s%n>>>0,s=s/n>>>0;if(s!==0)throw new Error("Non-zero carry");_=O,a++}let c=d-_;for(;c!==d&&u[c]===0;)c++;let P=f.repeat(o);for(;c<d;++c)P+=t.charAt(u[c]);return P}i(E,"encode");function A(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let o=0,_=0,a=0;for(;e[o]===f;)_++,o++;let g=(e.length-o)*m+1>>>0,d=new Uint8Array(g);for(;e[o];){let s=r[e.charCodeAt(o)];if(s===255)return;let O=0;for(let p=g-1;(s!==0||O<a)&&p!==-1;p--,O++)s+=n*d[p]>>>0,d[p]=s%256>>>0,s=s/256>>>0;if(s!==0)throw new Error("Non-zero carry");a=O,o++}let u=g-a;for(;u!==g&&d[u]===0;)u++;let c=new Uint8Array(_+(g-u)),P=_;for(;u!==g;)c[P++]=d[u++];return c}i(A,"decodeUnsafe");function C(e){let o=A(e);if(o)return o;throw new Error("Non-base"+n+" character")}return i(C,"decode"),{encode:E,decodeUnsafe:A,decode:C}}i(b,"base");var T=b;var v="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=T(v);var U="2024-09-02",R=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function y(){return new l({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:U,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:R[U]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(y,"getMockEnvironment");var l=class t{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(r){this.#e||(this.#e=new t(r),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=y()),this.#e}constructor({build:r,runtime:n}){let f;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let m=new TextDecoder().decode(I.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),h=JSON.parse(m);for(let E of Object.keys(h))n[E]||(n[E]=h[E])}if(n.__ZUPLO_CONFIG){let m=atob(n.__ZUPLO_CONFIG);f=JSON.parse(m)}}catch(m){console.error("Failed to parse runtime configuration",m)}this.config=f??{},this.build=r,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get zudokuHostUrl(){return this.runtime.__ZUPLO_ZUDOKU_HOST_URL??this.config.zudoku_host_url??"https://zudoku.zuploedge.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var w=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function M(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!w.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}i(M,"isRestrictedEnvVariableName");function S(t){return!!t.startsWith("ZUPLO_")}i(S,"isZuploReadableEnvVariableName");var X=new Proxy({},{get(t,r){let n=String(r);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return l.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return l.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return l.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return l.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return l.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return l.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return l.instance.build.COMPATIBILITY_DATE}if(!(M(n)&&!S(n)))return l.instance.runtime[n]}});function ne(t,r,n){return`_${L(`${t}_${r}_${n}`)}`}i(ne,"getRawOperationDataIdentifierName");function re(t,r,n,f){return`_${L(t.toLowerCase())}_${r.toLowerCase()}_${n.toLowerCase()}_${f.toLowerCase()}`}i(re,"getIdForParameterSchema");function ie(t,r,n){return`_${L(t.toLowerCase())}_${r.toLowerCase()}_rb_${L(n.toLowerCase())}`}i(ie,"getIdForRequestBodySchema");function oe(t,r){return`_${L(t)}_${L(r)}`}i(oe,"getIdForRefSchema");function L(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}i(L,"sanitizedIdentifierName");export{l as a,N as b,M as c,S as d,X as e,ne as f,re as g,ie as h,oe as i,L as j};
26
+ /*! For license information please see chunk-G45SN3PW.js.LEGAL.txt */
package/out/esm/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as h,b as Ue,e as Pe,f as Iu,g as Kn,h as Qn,i as Eu,j as xu}from"./chunk-IF4DUSCR.js";import{a as i,b as Ru,c as Pu}from"./chunk-PPV7V43C.js";var Us=Ru(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.parse=pc;In.serialize=mc;var sc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ac=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,uc=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,cc=/^[\u0020-\u003A\u003D-\u007E]*$/,lc=Object.prototype.toString,dc=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function pc(n,e){let t=new dc,r=n.length;if(r<2)return t;let o=e?.decode||gc,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?r:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=Ms(n,s,a),d=qs(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let f=Ms(n,a+1,c),y=qs(n,c,f),v=o(n.slice(f,y));t[p]=v}s=c+1}while(s<r);return t}i(pc,"parse");function Ms(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}i(Ms,"startIndex");function qs(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}i(qs,"endIndex");function mc(n,e,t){let r=t?.encode||encodeURIComponent;if(!sc.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!ac.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+o;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge}if(t.domain){if(!uc.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!cc.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!fc(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():t.sameSite){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}i(mc,"serialize");function gc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(gc,"decode");function fc(n){return lc.call(n)==="[object Date]"}i(fc,"isDate")});var Tu=!1;function dt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(dt,"code");function pt(n,e){return Tu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(pt,"run");function vu(n){return pt(n,dt([31],39))}i(vu,"red");function Cu(n){return pt(n,dt([32],39))}i(Cu,"green");function Ou(n){return pt(n,dt([33],39))}i(Ou,"yellow");function Su(n){return pt(n,dt([34],39))}i(Su,"blue");function Au(n){return pt(n,dt([35],39))}i(Au,"magenta");function ku(n){return pt(n,dt([36],39))}i(ku,"cyan");var Tp=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var Di=[vu,Cu,Ou,Su,Au,ku];function Lu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(Lu,"hashCode");function Mi(n){let e=Math.abs(Lu(n));return Di[e%Di.length]}i(Mi,"generateColor");function qi(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
25
+ import{a as h,b as Ue,e as Pe,f as Iu,g as Kn,h as Qn,i as Eu,j as xu}from"./chunk-G45SN3PW.js";import{a as i,b as Ru,c as Pu}from"./chunk-PPV7V43C.js";var Us=Ru(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.parse=pc;In.serialize=mc;var sc=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ac=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,uc=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,cc=/^[\u0020-\u003A\u003D-\u007E]*$/,lc=Object.prototype.toString,dc=(()=>{let n=i(function(){},"C");return n.prototype=Object.create(null),n})();function pc(n,e){let t=new dc,r=n.length;if(r<2)return t;let o=e?.decode||gc,s=0;do{let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s),c=u===-1?r:u;if(a>c){s=n.lastIndexOf(";",a-1)+1;continue}let l=Ms(n,s,a),d=qs(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let f=Ms(n,a+1,c),y=qs(n,c,f),v=o(n.slice(f,y));t[p]=v}s=c+1}while(s<r);return t}i(pc,"parse");function Ms(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}i(Ms,"startIndex");function qs(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}i(qs,"endIndex");function mc(n,e,t){let r=t?.encode||encodeURIComponent;if(!sc.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!ac.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=n+"="+o;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge}if(t.domain){if(!uc.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain}if(t.path){if(!cc.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path}if(t.expires){if(!fc(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():t.sameSite){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}i(mc,"serialize");function gc(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}i(gc,"decode");function fc(n){return lc.call(n)==="[object Date]"}i(fc,"isDate")});var Tu=!1;function dt(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(dt,"code");function pt(n,e){return Tu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(pt,"run");function vu(n){return pt(n,dt([31],39))}i(vu,"red");function Cu(n){return pt(n,dt([32],39))}i(Cu,"green");function Ou(n){return pt(n,dt([33],39))}i(Ou,"yellow");function Su(n){return pt(n,dt([34],39))}i(Su,"blue");function Au(n){return pt(n,dt([35],39))}i(Au,"magenta");function ku(n){return pt(n,dt([36],39))}i(ku,"cyan");var Tp=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var Di=[vu,Cu,Ou,Su,Au,ku];function Lu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(Lu,"hashCode");function Mi(n){let e=Math.abs(Lu(n));return Di[e%Di.length]}i(Mi,"generateColor");function qi(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
26
26
  `).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(qi,"format");function je(n,e,t,r){let o={seen:[],stylize:_u,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=Du),an(o,n,o.depth)}i(je,"inspect");je.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};je.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function _u(n,e){return n}i(_u,"stylizeNoColor");function Nu(n){return typeof n=="boolean"}i(Nu,"isBoolean");function Hi(n){return n===void 0}i(Hi,"isUndefined");function Du(n,e){let t=je.styles[e];return t?"\x1B["+je.colors[t][0]+"m"+n+"\x1B["+je.colors[t][1]+"m":n}i(Du,"stylizeWithColor");function Yn(n){return typeof n=="function"}i(Yn,"isFunction");function $i(n){return typeof n=="string"}i($i,"isString");function Mu(n){return typeof n=="number"}i(Mu,"isNumber");function Zi(n){return n===null}i(Zi,"isNull");function Fi(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Fi,"hasOwn");function Xn(n){return rr(n)&&or(n)==="[object RegExp]"}i(Xn,"isRegExp");function rr(n){return typeof n=="object"&&n!==null}i(rr,"isObject");function er(n){return rr(n)&&(or(n)==="[object Error]"||n instanceof Error)}i(er,"isError");function Ui(n){return rr(n)&&or(n)==="[object Date]"}i(Ui,"isDate");function or(n){return Object.prototype.toString.call(n)}i(or,"objectToString");function qu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(qu,"arrayToHash");function Uu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Fi(e,String(a))?s.push(nr(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(nr(n,e,t,r,a,!0))}),s}i(Uu,"formatArray");function tr(n){return"["+Error.prototype.toString.call(n)+"]"}i(tr,"formatError");function an(n,e,t){if(n.customInspect&&e&&Yn(e.inspect)&&e.inspect!==je&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return $i(d)||(d=an(n,d,t)),d}let r=Hu(n,e);if(r)return r;let o=Object.keys(e),s=qu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(er(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tr(e);if(o.length===0){if(Yn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Xn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Ui(e))return n.stylize(Date.prototype.toString.call(e),"date");if(er(e))return tr(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Yn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Xn(e)&&(a=" "+RegExp.prototype.toString.call(e)),Ui(e)&&(a=" "+Date.prototype.toUTCString.call(e)),er(e)&&(a=" "+tr(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Xn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=Uu(n,e,t,s,o):l=o.map(function(d){return nr(n,e,t,s,d,u)}),n.seen.pop(),$u(l,a,c)}i(an,"formatValue");function nr(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Fi(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Zi(t)?u=an(n,c.value,null):u=an(n,c.value,t-1),u.indexOf(`
27
27
  `)>-1&&(s?u=u.split(`
28
28
  `).map(function(l){return" "+l}).join(`
@@ -77,7 +77,7 @@ Signature verification is impossible without access to the original signed mater
77
77
  `+d}):new Me(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
78
78
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
79
79
  `+l+`
80
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(vl,"validateComputedSignature");function Cl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Cl,"parseHeader");function Ol(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Ol,"secureCompare");async function Sl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Ho[s[u]];return a.join("")}i(Sl,"computeHMACSignatureAsync");var Ho=new Array(256);for(let n=0;n<Ho.length;n++)Ho[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ha(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ya(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(ya,"isStripeWebhookEvent");var Al={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o},"getUpcomingInvoice")},Mn=Al;var $o="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ba="My API Key";async function wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,$o);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(wa,"createConsumer");async function Ra({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,$o);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new k(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ra,"createConsumerInvite");async function Pa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,$o);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Pa,"deleteConsumer");async function Ia({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ft(p))throw new K("No Zuplo JWT token set.");let y=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ia,"createSubscription");async function Pt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Pt,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(It,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function qn(n){return n.replaceAll("_","-")}i(qn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function Zo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await wa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Mn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ra({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=qn(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Ia({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await Pa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Xe})}i(Zo,"onCustomerSubscriptionCreated");async function Fo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return E.ok(n,e,{title:Xe})}i(Fo,"onCustomerSubscriptionDeleted");async function jo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=qn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Mn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}i(jo,"onCustomerSubscriptionUpdated");var Ea=class extends pn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!kl(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ya(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Zo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await jo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Fo(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),s=Ns({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function kl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(kl,"isMetricsRegion");var Ta=new WeakMap,xa={},zo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ta.set(e,t)}};async function Ll(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ve(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ta.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=$e(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=xa[t.apiKey];if(!f){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";f=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await H.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${A.message}`),A}}),xa[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Ll,"AmberfloMeteringInboundPolicy");async function ct(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(ct,"sha256");var va=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=va.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,va.set(n,r)),r}i(se,"getPolicyCacheName");var Ca="key-metadata-cache-type";function _l(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(_l,"getKeyValue");async function Bo(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(N=>o.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=_l(a,o);if(!u||u==="")return s("No key present");let c=await Nl(u),l=await se(r,void 0,o),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Ca&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(f)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:Ca,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,o.cacheTtlSeconds),n}i(Bo,"ApiKeyInboundPolicy");async function Nl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Nl,"hashValue");var Dl=Bo;var Oa=Symbol("aserto-authz-resource-context"),Go=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){te.set(e,Oa,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let o=te.get(t,Oa),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?$e(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await H.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as ql,jwtVerify as Aa}from"jose";import{createLocalJWKSet as Ml}from"jose";var Vo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Wo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Ml(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await H.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Et("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Et("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Sa(n,e,t){let r=new Vo(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Sa,"createRemoteJWKSet");var Et=class extends k{static{i(this,"JWKSError")}},Wo=class extends Et{static{i(this,"JWKSNoMatchingKey")}},Jo=class extends Et{static{i(this,"JWKSTimeout")}};var Un={},Ul=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Un[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new ie(a,e);Un[r.jwkUrl]=Sa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Un[r.jwkUrl]=ql(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Aa(t,Un[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Hl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await Aa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Re=i(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Ul(r,e):Hl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",f=d[p];return f?(n.user={sub:f,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var $l=i(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Re(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Hn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await H.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Ko=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Hn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Zl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===f&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function $n(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i($n,"extractDateElements");function ka(n,e){return new Date(n,e+1,0).getDate()}i(ka,"getDaysInMonth");function Qo(n,e){return n<=e?e-n:6-n+e+1}i(Qo,"getDaysBetweenWeekdays");var Zn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=ka(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?Qo(d,p):Qo(p,d);l=e==="next"?o+f:o-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=$n(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=$n(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=$n(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Fl={min:0,max:59},jl={min:0,max:59},zl={min:0,max:23},Bl={min:1,max:31},Gl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Vl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Wl={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function Yo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Wl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Zn({seconds:lt(t,Fl),minutes:lt(r,jl),hours:lt(o,zl),days:lt(s,Bl),months:new Set(Array.from(lt(a,Gl)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Vl)).map(c=>c%7))})}i(Yo,"parseCronExpression");var Xo=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Yo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Yo(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Jl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Kl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Kl,"digestMessage");var Ql=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Kl(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Yl(n,e,t,r){g("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ql(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Jl.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Yl,"CachingInboundPolicy");var Xl=i(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var ed=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var td=i(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var nd=i(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Re(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var rd=i(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return Re(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Fn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},ei=class extends Fn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ti=class extends Fn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function od(n,e){if(vs(n))throw new ei(e)}i(od,"throwIfUndefinedOrNull");function La(n,e){if(od(n,e),!xe(n))throw new ti(e,"string")}i(La,"throwIfNotString");var ni=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},id=500,ri=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){La(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},id);let a,u=new Headers({"content-type":"application/json"});_e(u,o);try{a=await H.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},xt;function et(n,e){if(xt)return xt;if(!h.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),xt=new ni,xt;let{redisURL:t,authApiJWT:r}=h.instance;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(r))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return xt=new ri(t),xt}i(et,"getRateLimitClient");var sd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function Tt(n,e){return{function:ld(e,"RateLimitInboundPolicy",n),user:ud,ip:ad,all:cd}[e.rateLimitBy??"ip"]}i(Tt,"getRateLimitByFunctions");var ad=i(async n=>({key:`ip-${sd(n)}`}),"getIP"),ud=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),cd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function ld(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(ld,"wrapUserFunction");var vt="Retry-After";var _a=be("zuplo:policies:ComplexRateLimitInboundPolicy"),oi=Symbol("complex-rate-limit-counters"),ii=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=te.get(e,oi)??{};Object.assign(r,t),te.set(e,oi,t)}static getIncrements(e){return te.get(e,oi)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=et(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[vt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Tt(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);_a(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:f,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){o.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:f,limit:N})),v=await s.multiCount(y,t.requestId);return dd(v,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;_a(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function dd(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(dd,"findOverLimits");var pd=i(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Ft(t.policies,o?.routeData.policies);return Gr(s)(n,e)},"CompositeInboundPolicy");var md=i(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new m(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=jt(r.policies,s?.routeData.policies);return Vr(a)(n,e,t)},"CompositeOutboundPolicy");var gd=i(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return E.unauthorized(n,e,{detail:"No authorization header"});let s=fd(o);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await H.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function fd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(fd,"getToken");var hd=i(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Re(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var yd=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ct="__unknown__",bd=i(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:St(t.allow?.countries,"allow.countries",r),regionCodes:St(t.allow?.regionCodes,"allow.regionCode",r),asns:St(t.allow?.asns,"allow.asOrganization",r)},block:{countries:St(t.block?.countries,"block.countries",r),regionCodes:St(t.block?.regionCodes,"block.regionCode",r),asns:St(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Ct,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ct,u=e.incomingRequestProperties.asn?.toString()??Ct,c=o.ignoreUnknown&&s===Ct,l=o.ignoreUnknown&&a===Ct,d=o.ignoreUnknown&&u===Ct,p=o.allow.countries,f=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ot(n,e,r,s,a,u);let v=o.block.countries,R=o.block.regionCodes,A=o.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ot(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ot(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ot,"blockedResponse");function St(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(St,"toLowerStringArray");var wd=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Rd=i(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return si(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return si(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Na(a[u])}else return a.length>0?Na(a[0]):si(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Na(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Na,"generateResponse");var si=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return E.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Pd="Incoming",Id={logRequestBody:!0,logResponseBody:!0};function Da(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Da,"headersToObject");function Ma(){return new Date().toISOString()}i(Ma,"timestamp");var ai=new WeakMap,Ed={};function xd(n,e){let t=ai.get(n);t||(t=Ed);let r=Object.assign({...t},e);ai.set(n,r)}i(xd,"setMoesifContext");async function qa(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(qa,"readBody");var Td={},ui;function Ua(){if(!ui)throw new k("Invalid State - no _lastLogger");return ui}i(Ua,"getLastLogger");function vd(n){let e=Td[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ua().debug("posting",r);let o=await H.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ua().error({status:o.status,body:await o.text()})})),e}i(vd,"getDispatcher");async function Cd(n,e,t,r){g("policy.inbound.moesif-analytics"),ui=e.log;let o=Ma(),s=Object.assign(Id,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await qa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=vd(s.applicationId),d=n.headers.get("true-client-ip"),p=ai.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Da(n.headers)},y=s.logResponseBody?await qa(u,e):void 0,v={time:Ma(),status:u.status,headers:Da(u.headers),body:y},R={request:f,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Pd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(Cd,"MoesifInboundPolicy");async function Ha(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ha,"loadSubscription");async function $a(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i($a,"consumeSubcriptionQuotas");var Od=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function jn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(jn,"validateMeters");function Za(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=it(n),r=[];for(let o of t)Od.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Za,"parseAllowedSubscriptionStatuses");function Fa(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Fa,"compareMeters");var ci=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return te.get(e,Dt)}static setMeters(e,t){jn(t,"setMeters");let r=te.get(e,Mt)??{};Object.assign(r,t),te.set(e,Mt,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Ve(this.options.meterOnStatusCodes),s=te.get(t,Mt),a={...this.options.meters,...s};jn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Za(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=te.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=te.get(N,Mt),$={...this.options.meters,...z};if(jn($,this.policyName),o.includes(R.status)&&S&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify($)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:U}=Fa(S.meters,$);if(U&&Object.keys(U).length>0){let V=Object.keys(U);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await $a(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ha(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),te.set(t,Dt,p));let f=te.get(t,Dt);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(f.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(f.meters[R].available<=0&&!r)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};async function zn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(zn,"getClientCredentialsAccessToken");var At=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Bn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new m("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await H.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new At("unknown",`Unknown error. Status: ${c.status}`):new At(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var ja="X-OpenFGA-Client-Method",za="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Bn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Xt(r,ja,"BatchCheck"),Xt(r,za,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof At)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,ja,"ListRelations"),Xt(c,za,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Ba=Symbol("openfga-authz-context-data"),kt=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];te.set(e,Ba,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=te.get(t,Ba);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new K(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await zn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ga=["us1","eu1","au1"],li=class extends kt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ga.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ga.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Sd=i(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Re(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var di=class extends kt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as Ad}from"jose";var pi,kd=i(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!pi)try{pi=await Ad(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Re(n,e,{issuer:t.authUrl,secret:pi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var mi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Va="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var gi=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=Ld(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=_d(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=et(this.policyName,o),f=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,f),r&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{r&&(R+=`${A} - allowed: ${N} value: ${f.meters[A]??0}
80
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Me(e,n,{message:"Timestamp outside the tolerance zone"});return!0}i(vl,"validateComputedSignature");function Cl(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}i(Cl,"parseHeader");function Ol(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}i(Ol,"secureCompare");async function Sl(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),s=new Uint8Array(o),a=new Array(s.length);for(let u=0;u<s.length;u++)a[u]=Ho[s[u]];return a.join("")}i(Sl,"computeHMACSignatureAsync");var Ho=new Array(256);for(let n=0;n<Ho.length;n++)Ho[n]=n.toString(16).padStart(2,"0");function W(n,e,t="policy",r){let o=`${t} '${e}'`;if(!ot(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let s=i((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=i((c,l)=>(s(c,l,!0),{optional:a,required:u}),"optional"),u=i((c,l)=>(s(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}i(W,"optionValidator");var Yt=class extends ce{static{i(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){W(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await ha(o,r,this.options.signingSecret)}catch(o){let s=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);s=c?c[1].trim():a,s.startsWith("No signatures found matching the expected signature for payload")&&(s="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",s),E.badRequest(e,t,{title:"Webhook Error",detail:s})}return e}};function ya(n){return n!==null&&typeof n=="object"&&"id"in n&&xe(n.id)&&"type"in n&&xe(n.type)}i(ya,"isStripeWebhookEvent");var Al={getSubscription:i(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving subscription from Stripe API.";throw t.error(s,o),new k(s)}return o},"getSubscription"),getCustomer:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer from Stripe API.";throw t.error(s,o),new k(s)}return o},"getCustomer"),getUpcomingInvoice:i(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await H.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(s,o),new k(s)}return o},"getUpcomingInvoice")},Mn=Al;var $o="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ba="My API Key";async function wa({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:s,context:a}){let{authApiJWT:u}=h.instance,c=new URL(`/v1/buckets/${n}/consumers`,$o);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:s,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let y="Error creating API Key Consumer";throw a.log.error(y,f),new k(y)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}i(wa,"createConsumer");async function Ra({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:s}){let{authApiJWT:a}=h.instance,u=new URL(`/v1/buckets/${n}/consumers`,$o);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ba,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(s)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new k(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}i(Ra,"createConsumerInvite");async function Pa({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=h.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,$o);o.searchParams.set("with-api-key","true");let s=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}i(Pa,"deleteConsumer");async function Ia({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=h.instance;if(!ft(p))throw new K("No Zuplo JWT token set.");let y=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${f}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!y.ok){let v=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,R,A="";try{R=await y.json(),A=R.detail??R.title}catch{R={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:y.status,detail:y.statusText}}throw n.log.error(v,R),new k(`${v} ${A}`)}n.log.info("Successfully created monetization subscription.",d)}i(Ia,"createSubscription");async function Pt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}i(Pt,"updateSubscription");async function It({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:s}=h.instance;if(!ft(o))throw new K("No Zuplo JWT token set.");let a=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(n)},`${s}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,l),new k(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new k(c)}return u.data[0]}i(It,"getSubscription");var ae="Skipping since we're unable to process the webhook event.",Xe="Successfully processed the webhook event",Ie="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function qn(n){return n.replaceAll("_","-")}i(qn,"stripeStatusToMeteringStatus");function ut(n){return new Date(n*1e3).toISOString()}i(ut,"unixTimestampToISOString");async function Zo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});let u=s.product,c,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,c=await wa({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Mn.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ra({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),E.ok(n,e,{title:ae,detail:p.message})}if(!c)return E.ok(n,e,{title:ae,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=qn(t.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}});let y;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(y={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:ut(t.data.object.trial_end),trialStartDate:ut(t.data.object.trial_start)}),await Ia({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:y})}catch(p){return await Pa({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),E.ok(n,e,{title:ae,detail:p.message})}return E.ok(n,e,{title:Xe})}i(Zo,"onCustomerSubscriptionCreated");async function Fo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});try{let a=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId});await Pt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ie})}return E.ok(n,e,{title:Xe})}i(Fo,"onCustomerSubscriptionDeleted");async function jo(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=t.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),E.ok(n,e,{title:ae,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==h.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),E.ok(n,e,{title:ae,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=qn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=ut(t.data.object.trial_end)),await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Mn.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let u=await It({context:e,stripeSubscriptionId:o,stripeCustomerId:s,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?ut(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?ut(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await Pt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return E.ok(n,e,{title:ae,detail:`The event 'customer.subscription.updated' could not be processed. ${u.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ie})}return E.ok(n,e,{title:Xe})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),E.ok(n,e,{title:ae,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ie})}i(jo,"onCustomerSubscriptionUpdated");var Ea=class extends pn{constructor(t){super();this.options=t;g("monetization.stripe")}static{i(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=i(async(c,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!h.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!kl(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let y=await c.json();if(!ya(y))return E.ok(c,l,{title:ae,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ie});switch(l.log.info(`Received Stripe webhook event of type '${y.type}' with ID '${y.id}'.`),y.type){case"customer.subscription.created":return await Zo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await jo(c,l,y,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await Fo(c,l,y,{meteringBucketId:d});default:return E.ok(c,l,{title:ae,detail:`Event '${y.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ie})}},"stripeWebhookHandler"),s=Ns({inboundPolicies:[new Yt({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});W(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new de({processors:[fe,s],handler:o,gateway:r}),u=new ue({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function kl(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}i(kl,"isMetricsRegion");var Ta=new WeakMap,xa={},zo=class{static{i(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ta.set(e,t)}};async function Ll(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=Ve(t.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(o.includes(s.status)){let a=Ta.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=$e(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=xa[t.apiKey];if(!f){let y=t.apiKey,v=n.headers.get("zm-test-id")??"";f=new Y("amberflo-ingest-meter",10,async R=>{try{let A=t.url??"https://app.amberflo.io/ingest",N=await H.fetch(A,{method:"POST",body:JSON.stringify(R),headers:{"content-type":"application/json","x-api-key":y,"zm-test-id":v}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(A){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${A.message}`),A}}),xa[y]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}i(Ll,"AmberfloMeteringInboundPolicy");async function ct(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}i(ct,"sha256");var va=new Map;async function se(n,e,t){let r,o=`${n}-${e}`,s=va.get(o);return s!==void 0?r=s:(r=`zuplo-policy-${await ct(JSON.stringify({policyName:n,options:t}))}`,va.set(n,r)),r}i(se,"getPolicyCacheName");var Ca="key-metadata-cache-type";function _l(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}i(_l,"getKeyValue");async function Bo(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Pe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let s=i(N=>o.allowUnauthenticatedRequests?n:E.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let u=_l(a,o);if(!u||u==="")return s("No key present");let c=await Nl(u),l=await se(r,void 0,o),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Ca&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:u},y=new Headers({"content-type":"application/json"});_e(y,e.requestId);let v=await we({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${h.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:y,body:JSON.stringify(f)});if(v.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),s("Authorization Failed");if(v.status!==200){try{let N=await v.text(),S=JSON.parse(N);e.log.error("Unexpected response from key service",S)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${v.status}`)}let R=await v.json(),A={isValid:!0,typeId:Ca,user:{apiKeyId:R.id,sub:R.name,data:R.metadata}};return n.user=A.user,d.put(c,A,o.cacheTtlSeconds),n}i(Bo,"ApiKeyInboundPolicy");async function Nl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Nl,"hashValue");var Dl=Bo;var Oa=Symbol("aserto-authz-resource-context"),Go=class extends ce{static{i(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){te.set(e,Oa,t)}constructor(e,t){if(super(e,t),W(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new m(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let c=await se(this.policyName,void 0,this.options);this.cache=new ie(c,t)}let r=i(c=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:c}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),E.unauthorized(e,t);let o=te.get(t,Oa),s;o?.policyInstance?s=o.policyInstance:this.options.policyName?s={name:this.options.policyName}:s={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?$e(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,u={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:s};try{t.log.debug("Aserto Request",u);let c=await H.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(u)});if(c.status!==200){let d=`Error calling Aserto service. Status: ${c.status}`;try{d=(await c.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),c.status>=400&&c.status<500?r(d):E.internalServerError(e,t)}let l=await c.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(c){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,c),E.internalServerError(e,t)}}};import{createRemoteJWKSet as ql,jwtVerify as Aa}from"jose";import{createLocalJWKSet as Ml}from"jose";var Vo=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{i(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Wo&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",h.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Ml(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let s,a,u=!1;typeof AbortController=="function"&&(s=new AbortController,a=setTimeout(()=>{u=!0,s.abort()},t));let c=await H.fetch(e.href,{signal:s?s.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Jo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new Et("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Et("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Sa(n,e,t){let r=new Vo(n,e,t);return async(o,s)=>r.getKey(o,s)}i(Sa,"createRemoteJWKSet");var Et=class extends k{static{i(this,"JWKSError")}},Wo=class extends Et{static{i(this,"JWKSNoMatchingKey")}},Jo=class extends Et{static{i(this,"JWKSTimeout")}};var Un={},Ul=i((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Un[r.jwkUrl]){let s=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(s=r.useExperimentalInMemoryCache),s){let a=await se(n,void 0,r),u=new ie(a,e);Un[r.jwkUrl]=Sa(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Un[r.jwkUrl]=ql(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Aa(t,Un[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Hl=i(async(n,e)=>{let t;if(e.secret===void 0)throw new m("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);t=new Uint8Array(s)}else t=e.secret;let{payload:r}=await Aa(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Re=i(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",s=n.headers.get(o),a="bearer ",u=i(y=>E.unauthorized(n,e,{detail:y}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=t.jwkUrl?Ul(r,e):Hl,d=await i(async()=>{if(!s)return u("No authorization header");if(s.toLowerCase().indexOf(a)!==0)return u("Invalid bearer token format for authorization header");let y=s.substring(a.length);if(!y||y.length===0)return u("No bearer token on authorization header");try{return await c(y,t)}catch(v){let R=new URL(n.url);return"code"in v&&v.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${R.pathname} `,v):e.log.warn(`Invalid token on: ${n.method} ${R.pathname}`,v),u("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",f=d[p];return f?(n.user={sub:f,data:d},n):u(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var $l=i(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Re(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Hn=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{i(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await H.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Ko=class n extends ce{static{i(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),W(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Hn(e)}async handler(e,t){let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),s=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(s,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(s,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),this.addAttributesToCategory(s,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:s,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:s,context:t});try{t.log.debug("PDP Request",s);let a=await this.pdpService.makePdpRequest(s);return t.log.debug("PDP Response",a),a.Response.every(u=>u.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),E.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let s=this.options[e];if(s){let a=[];s.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var Zl=i(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",s=i(l=>E.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=await i(async()=>{if(!r)return await s("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await s("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),y=d.substring(p+1),v=t.accounts.find(R=>R.username===f&&R.password===y);return v||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function $n(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}i($n,"extractDateElements");function ka(n,e){return new Date(n,e+1,0).getDate()}i(ka,"getDaysInMonth");function Qo(n,e){return n<=e?e-n:6-n+e+1}i(Qo,"getDaysBetweenWeekdays");var Zn=class{static{i(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:s,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!s||s.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(s).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=i((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let s=this.findAllowedSecond(e,t.second);if(s!==void 0)return{hour:r,minute:o,second:s};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let s=ka(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>s?e==="next"?void 0:s:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>s&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?Qo(d,p):Qo(p,d);l=e==="next"?o+f:o-f,(l>s||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=$n(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let s=this.months.length*5;for(let a=0;a<s;a++){let u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=$n(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let s=this.reversed.months.length*5;for(let a=0;a<s;a++){let u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let s=0;s<e;s++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:s,month:a,weekday:u}=$n(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(s)!==-1||this.weekdays.indexOf(u)!==-1:this.days.indexOf(s)!==-1&&this.weekdays.indexOf(u)!==-1}};var Fl={min:0,max:59},jl={min:0,max:59},zl={min:0,max:23},Bl={min:1,max:31},Gl={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},Vl={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},Wl={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function lt(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{lt(d,e).forEach(f=>t.add(f))}),t;let o=i(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),s=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(s===null)return t.add(o(n)),t;let a=s[1]==="*"?e.min:o(s[3]),u=s[1]==="*"?e.max:o(s[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=s[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}i(lt,"parseElement");function Yo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=Wl[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],s=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],u=e.length===6?e[5]:e[4];return new Zn({seconds:lt(t,Fl),minutes:lt(r,jl),hours:lt(o,zl),days:lt(s,Bl),months:new Set(Array.from(lt(a,Gl)).map(c=>c-1)),weekdays:new Set(Array.from(lt(u,Vl)).map(c=>c%7))})}i(Yo,"parseCronExpression");var Xo=class extends ce{static{i(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),W(e,t).optional("problem","object"),e.problem&&W(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new m(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[Yo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Yo(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(s=>s.matchDate(r))){let s=E.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return E.format(s,e,t)}return e}};var Jl=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function Kl(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}i(Kl,"digestMessage");var Ql=i(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await Kl(JSON.stringify(r)),s=new URL(n.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${s.origin}${s.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Yl(n,e,t,r){g("policy.inbound.caching");let o=await se(r,t.cacheId,t),s=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Ql(n,t),c=await s.match(u);return c||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let f=t?.expirationSecondsTtl??60,y=new Response(p.body,p);Jl.forEach(v=>y.headers.delete(v)),y.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(u,y))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}i(Yl,"CachingInboundPolicy");var Xl=i(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new re(n,{method:t.method})},"ChangeMethodInboundPolicy");var ed=i(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new re(n,{headers:o})},"ClearHeadersInboundPolicy");var td=i(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],s=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&s.set(u,c)}),new Response(n.body,{headers:s,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var nd=i(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),s=new URL(o);return s.pathname="/.well-known/jwks.json",Re(n,e,{issuer:o.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var rd=i(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return Re(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Fn=class extends Error{static{i(this,"ValidationError")}constructor(e){super(e)}},ei=class extends Fn{static{i(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},ti=class extends Fn{static{i(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function od(n,e){if(vs(n))throw new ei(e)}i(od,"throwIfUndefinedOrNull");function La(n,e){if(od(n,e),!xe(n))throw new ti(e,"string")}i(La,"throwIfNotString");var ni=class{static{i(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),s=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:s}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:s});let u=this.keyValueStore.get(e);return Promise.resolve({count:u.value,ttlSeconds:Math.round((u.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},id=500,ri=class{constructor(e){this.clientUrl=e}static{i(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){La(e,"url");let s=new AbortController;setTimeout(()=>{s.abort()},id);let a,u=new Headers({"content-type":"application/json"});_e(u,o);try{a=await H.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:s.signal,headers:u})}catch(l){throw console.error("Rate limit service timed out",l),new K("Rate limiting service failed.",{cause:l})}let c=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return c;throw a.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await ct(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await ct(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},xt;function et(n,e){let{redisURL:t,authApiJWT:r}=h.instance;if(xt)return xt;if(!r)return e.info("Using in-memory rate limit client for local development."),xt=new ni,xt;if(!xe(t))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!xe(r))throw new K(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return xt=new ri(t),xt}i(et,"getRateLimitClient");var sd=i(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function Tt(n,e){return{function:ld(e,"RateLimitInboundPolicy",n),user:ud,ip:ad,all:cd}[e.rateLimitBy??"ip"]}i(Tt,"getRateLimitByFunctions");var ad=i(async n=>({key:`ip-${sd(n)}`}),"getIP"),ud=i(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),cd=i(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function ld(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return i(async(s,a,u)=>{let c=await r(s,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new k(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new k(l)}return c},"outerFunction")}i(ld,"wrapUserFunction");var vt="Retry-After";var _a=be("zuplo:policies:ComplexRateLimitInboundPolicy"),oi=Symbol("complex-rate-limit-counters"),ii=class n extends ce{static{i(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=te.get(e,oi)??{};Object.assign(r,t),te.set(e,oi,t)}static getIncrements(e){return te.get(e,oi)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),W(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&W(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new m(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=Q.getLogger(t),s=et(this.policyName,o),a=i((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=i((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[vt]=l.toString()),E.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await Tt(this.policyName,this.options)(e,t,this.policyName),d=h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let A=n.getIncrements(t);_a(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(A)}`);let N=Object.entries(p).map(([F])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${F}`,ttlSeconds:f,increment:A[F]??0})),S=s.multiIncrement(N,t.requestId);t.waitUntil(S),await S}catch(A){o.error(A),t.log.error(A)}});let y=Object.entries(p).map(([A,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${A}`,ttlSeconds:f,limit:N})),v=await s.multiCount(y,t.requestId);return dd(v,y).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;_a(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function dd(n,e){let t=[];for(let r of n){let o=e.find(s=>s.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}i(dd,"findOverLimits");var pd=i(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=ge.instance,s=Ft(t.policies,o?.routeData.policies);return Gr(s)(n,e)},"CompositeInboundPolicy");var md=i(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new m(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let s=ge.instance,a=jt(r.policies,s?.routeData.policies);return Vr(a)(n,e,t)},"CompositeOutboundPolicy");var gd=i(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return E.unauthorized(n,e,{detail:"No authorization header"});let s=fd(o);if(!s)return E.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await se(r,void 0,t),u=new ie(a,e),c=await u.get(s);if(!c){let l=await H.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)c=d,u.put(s,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),E.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):E.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function fd(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}i(fd,"getToken");var hd=i(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),W(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Re(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var yd=i(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",s=n.headers.get("content-type")?.toLowerCase();if(!s||![o,r].includes(s))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new re(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var Ct="__unknown__",bd=i(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:St(t.allow?.countries,"allow.countries",r),regionCodes:St(t.allow?.regionCodes,"allow.regionCode",r),asns:St(t.allow?.asns,"allow.asOrganization",r)},block:{countries:St(t.block?.countries,"block.countries",r),regionCodes:St(t.block?.regionCodes,"block.regionCode",r),asns:St(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Ct,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Ct,u=e.incomingRequestProperties.asn?.toString()??Ct,c=o.ignoreUnknown&&s===Ct,l=o.ignoreUnknown&&a===Ct,d=o.ignoreUnknown&&u===Ct,p=o.allow.countries,f=o.allow.regionCodes,y=o.allow.asns;if(p.length>0&&!p.includes(s)&&!c||f.length>0&&!f.includes(a)&&!l||y.length>0&&!y.includes(u)&&!d)return Ot(n,e,r,s,a,u);let v=o.block.countries,R=o.block.regionCodes,A=o.block.asns;return v.length>0&&v.includes(s)&&!c||R.length>0&&R.includes(a)&&!l||A.length>0&&A.includes(u)&&!d?Ot(n,e,r,s,a,u):n},"GeoFilterInboundPolicy");function Ot(n,e,t,r,o,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${s}')`),E.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:s}})}i(Ot,"blockedResponse");function St(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}i(St,"toLowerStringArray");var wd=i(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!i((s,a)=>a.every(u=>s.includes(u)),"scopeChecker")(r,t.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Rd=i(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return si(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(o),a=[];if(s.length===0)return si(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Na(a[u])}else return a.length>0?Na(a[0]):si(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function Na(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}i(Na,"generateResponse");var si=i((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return E.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Pd="Incoming",Id={logRequestBody:!0,logResponseBody:!0};function Da(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}i(Da,"headersToObject");function Ma(){return new Date().toISOString()}i(Ma,"timestamp");var ai=new WeakMap,Ed={};function xd(n,e){let t=ai.get(n);t||(t=Ed);let r=Object.assign({...t},e);ai.set(n,r)}i(xd,"setMoesifContext");async function qa(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}i(qa,"readBody");var Td={},ui;function Ua(){if(!ui)throw new k("Invalid State - no _lastLogger");return ui}i(Ua,"getLastLogger");function vd(n){let e=Td[n];return e||(e=new Y("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ua().debug("posting",r);let o=await H.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ua().error({status:o.status,body:await o.text()})})),e}i(vd,"getDispatcher");async function Cd(n,e,t,r){g("policy.inbound.moesif-analytics"),ui=e.log;let o=Ma(),s=Object.assign(Id,t);if(!s.applicationId)throw new m(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=s.logRequestBody?await qa(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=vd(s.applicationId),d=n.headers.get("true-client-ip"),p=ai.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Da(n.headers)},y=s.logResponseBody?await qa(u,e):void 0,v={time:Ma(),status:u.status,headers:Da(u.headers),body:y},R={request:f,response:v,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Pd};l.enqueue(R),e.waitUntil(l.waitUntilFlushed())}),n}i(Cd,"MoesifInboundPolicy");async function Ha(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:s,meteringServiceUrl:a}=h.instance,u;try{let l=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}i(Ha,"loadSubscription");async function $a(n,e,t,r,o){let{authApiJWT:s,meteringServiceUrl:a}=h.instance,u=Q.getLogger(n);try{let c=await H.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}i($a,"consumeSubcriptionQuotas");var Od=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function jn(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new m(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}i(jn,"validateMeters");function Za(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=it(n),r=[];for(let o of t)Od.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}i(Za,"parseAllowedSubscriptionStatuses");function Fa(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}i(Fa,"compareMeters");var ci=class extends ce{static{i(this,"MonetizationInboundPolicy")}static getSubscription(e){return te.get(e,Dt)}static setMeters(e,t){jn(t,"setMeters");let r=te.get(e,Mt)??{};Object.assign(r,t),te.set(e,Mt,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){W(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=Ve(this.options.meterOnStatusCodes),s=te.get(t,Mt),a={...this.options.meters,...s};jn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Za(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(R,A,N)=>{let S=te.get(N,Dt);if((this.options.allowRequestsWithoutSubscription??!1)&&!S){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let z=te.get(N,Mt),$={...this.options.meters,...z};if(jn($,this.policyName),o.includes(R.status)&&S&&$){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${S.id}' with meters '${JSON.stringify($)} on response status '${R.status}'`);let{metersInSubscription:C,metersNotInSubscription:U}=Fa(S.meters,$);if(U&&Object.keys(U).length>0){let V=Object.keys(U);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await $a(N,S.id,this.policyName,this.options.bucketId,C)}});let l=e.user;if(!l)return u?e:E.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Pe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Pe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Ha(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:E.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),E.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),te.set(t,Dt,p));let f=te.get(t,Dt);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),E.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),E.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let v=Object.keys(a).filter(R=>!Object.keys(f.meters).includes(R));if(v.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${v.join(", ")}`),E.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${v.join(", ")}`,title:"Quota Exceeded"});for(let R of Object.keys(a))if(f.meters[R].available<=0&&!r)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${R}'`,title:"Quota Exceeded"});return e}};async function zn(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await we({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,s)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}i(zn,"getClientCredentialsAccessToken");var At=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{i(this,"OpenFGAError")}},Bn=class{static{i(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new m("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let s=new Headers(r.headers||{});s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.set("User-Agent",h.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,u=new Request(a,{method:t,headers:s,body:o?JSON.stringify(o):void 0}),c=await H.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new At("unknown",`Unknown error. Status: ${c.status}`):new At(l.code,l.message)}return c.json()}};function Xt(n,e,t){!n[e]&&t&&(n[e]=t)}i(Xt,"setHeaderIfNotSet");var ja="X-OpenFGA-Client-Method",za="X-OpenFGA-Client-Bulk-Request-Id",en=class extends Bn{static{i(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Xt(r,ja,"BatchCheck"),Xt(r,za,crypto.randomUUID()),{responses:await Promise.all(e.map(async s=>this.check(s,Object.assign({},t,r)).then(a=>(a._request=s,a)).catch(a=>{if(a instanceof At)throw a;return{allowed:void 0,error:a,_request:s}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:s,contextualTuples:a,context:u}=e,{headers:c={}}=t;if(Xt(c,ja,"ListRelations"),Xt(c,za,crypto.randomUUID()),!s?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(s.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:u})),Object.assign({},t,c)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Ba=Symbol("openfga-authz-context-data"),kt=class extends ce{static{i(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];te.set(e,Ba,r)}constructor(e,t){if(super(e,t),W(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")W(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")W(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")W(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`${this.policyType} '${this.policyName}' - The 'credentials.type' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new en({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await se(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=i(a=>this.options.allowUnauthorizedRequests?e:E.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=te.get(t,Ba);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let s=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:s});return t.log.debug("OpenFGA Response",a),a.responses.every(u=>u.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),E.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new K(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let s=await zn({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",s.access_token,s.expires_in),{Authorization:`Bearer ${s.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var Ga=["us1","eu1","au1"],li=class extends kt{static{i(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!Ga.includes(e.region))throw new m(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${Ga.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Sd=i(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Re(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var di=class extends kt{static{i(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as Ad}from"jose";var pi,kd=i(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!pi)try{pi=await Ad(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Re(n,e,{issuer:t.authUrl,secret:pi,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var mi="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Va="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var gi=class n extends ce{static{i(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),W(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=Q.getLogger(t);try{let s=Ld(this.options,this.policyName),a=s.functions.getAnchorDate(e,t,this.policyName),u=s.functions.getQuotaDetail(e,t,this.policyName),[c,l]=await Promise.all([a,u]),d=_d(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=et(this.policyName,o),f=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,f),r&&t.log.debug("QuotaInboundPolicy: quotaResult",f),c&&new Date(f.anchorDate).getTime()!==c.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${c}') did not match the stored, immutable anchorDate ('${f.anchorDate}')`);let y=Object.assign({},s.defaultAllowances);Object.assign(y,l.allowances);let v=[],R="";if(Object.entries(y).forEach(([A,N])=>{r&&(R+=`${A} - allowed: ${N} value: ${f.meters[A]??0}
81
81
  `),(f.meters[A]??0)>=N&&v.push(A)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",R),v.length>0)return E.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${v.join(", ")}'`});t.addResponseSendingFinalHook(async(A,N,S)=>{if(r&&S.log.debug(`QuotaInboundPolicy: backend response - ${A.status}: ${A.statusText}`),!s.quotaOnStatusCodes.includes(A.status))return;let F=te.get(S,mi),z={config:{period:s.period,anchorDate:c?.toISOString()??""},increments:F};r&&S.log.debug("QuotaInboundPolicy: setQuotaDetails",z);let $=p.setQuota(d,z,S.requestId);S.waitUntil($)})}catch(s){o.error(s),t.log.error(s)}return e}static setMeters(e,t){let r=te.get(e,mi)??{};Object.assign(r,t),te.set(e,mi,r)}static getUsage(e,t){let r=te.get(e,`${Va}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){te.set(e,`${Va}-${t}`,r)}};function Ld(n,e){let t=i(async s=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${s.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=i(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new m(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:Ve(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}i(Ld,"validateAndParseOptions");function _d(n,e){return encodeURIComponent(`${e}-${n}`)}i(_d,"processKey");var Wa=be("zuplo:policies:RateLimitInboundPolicy"),Ja=i(async(n,e,t,r)=>{let o=Q.getLogger(e),s=i(($,C)=>{let U={};return(!$||$==="retry-after")&&(U[vt]=C.toString()),E.tooManyRequests(n,e,void 0,U)},"rateLimited"),u=await Tt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=et(r,o),v=`rate-limit${h.instance.isTestMode?h.instance.build.BUILD_ID:""}/${r}/${c}`,R=await se(r,void 0,t),A=new ie(R,e),N=f.getCountAndUpdateExpiry(v,d,e.requestId),S;i(async()=>{let $=await N;if($.count>l){let C=Date.now()+$.ttlSeconds*1e3;A.put(v,C,$.ttlSeconds),Wa(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${v}' (async mode)`),S=s(p,$.ttlSeconds)}},"asyncCheck")();let z=await A.get(v);if(z!==void 0&&z>Date.now()){Wa(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${v}' (async mode)`);let $=Math.round((z-Date.now())/1e3);return s(p,$)}return e.addResponseSendingHook(async $=>S??$),n},"AsyncRateLimitInboundPolicyImpl");function fi(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}i(fi,"convertToNumber");var Ka=be("zuplo:policies:RateLimitInboundPolicy"),Nd="strict",Qa=i(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Nd)==="async")return Ja(n,e,t,r);let s=Date.now(),a=Q.getLogger(e),u=i((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=i((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[vt]=d.toString()),E.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await Tt(r,t)(n,e,r),p=d.key,f=fi(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),y=fi(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),v=t.headerMode??"retry-after",R=et(r,a),N=`rate-limit${h.instance.isTestMode||h.instance.isWorkingCopy?h.instance.build.BUILD_ID:""}/${r}/${p}`,S=await R.getCountAndUpdateExpiry(N,y,e.requestId);return S.count>f?(Ka(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),c(v,S.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-s;Ka(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var hi;function Ya(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}i(Ya,"headersToNameValuePairs");function Dd(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}i(Dd,"queryToNameValueParis");function Md(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}i(Md,"parseIntOrUndefined");var Xa={};async function qd(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,s=Date.now();return hi||(hi={name:"zuplo",version:h.instance.build.ZUPLO_VERSION,comment:`zuplo/${h.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?$e(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?$e(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:h.instance.isWorkingCopy||h.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:hi,entries:[{startedDateTime:o.toISOString(),time:Date.now()-s,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:Ya(n.headers),queryString:Dd(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ya(a.headers),content:{size:Md(n.headers.get("content-length"))}}}]}}},d=Xa[t.apiKey];if(!d){let p=t.apiKey;d=new Y("readme-metering-inbound-policy",10,async f=>{try{let y=t.url??"https://metrics.readme.io/request",v=await H.fetch(y,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});v.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${v.status}: '${await v.text()}'`)}catch(y){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${y.message}'`),y}}),Xa[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}i(qd,"ReadmeMetricsInboundPolicy");var Ud=i(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let s=new Headers(n.headers);return o.forEach(u=>{s.delete(u)}),new re(n,{headers:s})},"RemoveHeadersInboundPolicy");var Hd=i(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let s=r?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return s.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var $d=i(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let s=new URL(n.url);return o.forEach(u=>{s.searchParams.delete(u)}),new re(s.toString(),n)},"RemoveQueryParamsInboundPolicy");var Zd=i(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),s=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(s,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var eu=i(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Fd=i(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),s=o!==null?parseInt(o):void 0;return s&&!isNaN(s)&&s>t.maxSizeInBytes?eu():s&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?eu():n},"RequestSizeLimitInboundPolicy");var Lt=i(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),_t=i((n,e,t,r,o)=>{let s=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,s.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Kn(t,r,o,c.name),p=ge.instance.schemaValidator[d],f=p(e[c.name]),y=yi(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),s.push(`Invalid value for ${o} parameter: '${c.name}' ${y.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:s}},"validateParameters"),Ae=i((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),ke=i(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Le=i(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),yi=i(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function tu(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(y){let v=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,R=E.badRequest(e,n,{detail:`${v}, see errors property for more details`,errors:`${y}`});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",v,[r],y),Le(t.validateBody))return R}if(!e.headers.get("Content-Type")){let y=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?v:void 0}let o=e.headers.get("Content-Type"),s=o.indexOf(";");s>-1&&(o=o.substring(0,s));let a=Qn(n.route.path,e.method,o),u=ge.instance.schemaValidator[a];if(!u){let y=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=E.badRequest(e,n,{detail:y});return ke(t.validateBody)&&Ae(n,t.logLevel??"info",y,[r],[y]),Le(t.validateBody)?v:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=yi(l),f=E.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(ke(t.validateBody)&&Ae(n,t.logLevel??"info",d,[r],p),Le(t.validateBody))return f}i(tu,"handleBodyValidation");function nu(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Lt(n),s=_t(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",u=E.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:s.errors});if(ke(t.validateHeaders)&&Ae(n,t.logLevel??"info",a,s.invalidValues,s.errors),Le(t.validateHeaders))return u}}i(nu,"handleHeadersValidation");function ru(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let s="Path parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validatePathParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validatePathParameters))return a}}i(ru,"handlePathParameterValidation");function ou(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Lt(n),o=_t(r.filter(s=>s.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let s="Query parameters validation failed",a=E.badRequest(e,n,{detail:`${s}, see errors property for more details`,errors:o.errors});if(ke(t.validateQueryParameters)&&Ae(n,t.logLevel??"info",s,o.invalidValues,o.errors),Le(t.validateQueryParameters))return a}}i(ou,"handleQueryParameterValidation");var iu=i(async(n,e,t)=>{g("policy.inbound.request-validation");let r=ou(e,n,t);if(r!==void 0||(r=ru(e,n,t),r!==void 0)||(r=nu(e,n,t),r!==void 0))return r;let o=await tu(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),jd=iu;var zd=i(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let s=n.headers.get("origin");if(!s||!o.includes(s)){let a=t.failureDetail??"Forbidden";return E.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Bd=i(async(n,e,t)=>(g("policy.inbound.set-body"),new re(n,{body:t.body})),"SetBodyInboundPolicy");var Gd=i(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let s=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.has(u.name)||c)&&s.set(u.name,u.value)}),new re(n,{headers:s})},"SetHeadersInboundPolicy");var Vd=i(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let s=r.headers;if(!s||!Array.isArray(s)||s.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return s.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var Wd=i(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let s=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!s.searchParams.has(u.name)||c)&&s.searchParams.set(u.name,u.value)}),new re(s.toString(),n)},"SetQueryParamsInboundPolicy");var Jd=i(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new m(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var Kd=i(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Qd=i(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Kd(t.sleepInMs),n},"SleepInboundPolicy");var Yd=i(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),W(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},s=await Re(n,e,o,r);if(s instanceof Response)return s;if(!(s instanceof re))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return s;let u=n.user?.data.app_metadata;if(!u)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?E.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");var Xd=i(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),W(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await se(r,void 0,t),s=new ie(o,e),a=await s.get(r);if(!a){let u=await ep(t,e);s.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ep(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let s=await r.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}i(ep,"getAccessToken");var su="https://accounts.google.com/o/oauth2/token",bi,tp=i(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),W(t,r).required("serviceAccountJson","string"),bi||(bi=await Te.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await se(r,void 0,t),a=new ie(s,e),u=await a.get(r);if(!u){let c=await De({serviceAccount:bi,audience:su,payload:o}),l=await Tn(su,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var np="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",rp=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],wi,op=i(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),W(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(rp.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}wi||(wi=await Te.init(t.serviceAccountJson));let s=t.userId;if(!s&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=$e(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new k(`Unable to determine user from for the policy ${r}`);let a=await se(r,void 0,t),u=new ie(a,e),c={uid:s,claims:o},l=await ct(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await De({serviceAccount:wi,audience:np,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,y=await Qs(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!y.idToken)throw new k("Invalid token response from Firebase");d=y.idToken,u.put(l,d,(y.expiresIn?parseInt(y.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var tn=class{static{i(this,"ZuploServices")}static async getIDToken(e,t){let r=new ie("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await se("zuplo-token",void 0,t),s=await r.get(o);if(s)return s;let{authClientId:a,authClientSecret:u,developerApiUrl:c,zuploClientAuthBucketId:l}=h.instance;if(!a||!u)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await zn({tokenEndpointUrl:`${c}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:u,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var au="service-account-id-token",Ri=class extends ce{static{i(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),W(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await se(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new ze(this.cacheName):r=new ie(this.cacheName,t);let o=await r.get(au);if(!o){let s=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await tn.getIDToken(t,{audience:s}),u=await Js(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!u.access_token||!u.expires_in)throw new k("Invalid token response from GCP");let c=u.access_token,l=await Ks({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:c},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(au,c,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Pi,ip=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),W(t,r).required("audience","string").required("serviceAccountJson","string"),Pi||(Pi=await Te.init(t.serviceAccountJson));let o=await De({serviceAccount:Pi,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var uu="https://www.googleapis.com/oauth2/v4/token",Ii,sp=i(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),W(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ii||(Ii=await Te.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=it(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let s=await se(r,void 0,t),a;t.useMemoryCacheOnly?a=new ze(s):a=new ie(s,e);let u=await a.get(r);if(!u){let c=await De({serviceAccount:Ii,audience:uu,payload:o}),l=await Tn(uu,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var ap=i(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return E.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new K("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return E.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var cu=i(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=i((R,A)=>e(R,"name",{value:A,configurable:!0}),"__name"),o=i((R,A)=>i(function(){return A||(0,R[t(R)[0]])((A={exports:{}}).exports,A),A.exports},"__require"),"__commonJS"),s=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(R){var A={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:i(function(S,F){return F},"tagValueProcessor"),attributeValueProcessor:i(function(S,F){return F},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:i(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:i(function(S,F,z){return S},"updateTag")},N=r(function(S){return Object.assign({},A,S)},"buildOptions");R.buildOptions=N,R.defaultOptions=A}}),a=o({"node_modules/fast-xml-parser/src/util.js"(R){"use strict";var A=":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",N=A+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S="["+A+"]["+N+"]*",F=new RegExp("^"+S+"$"),z=r(function(C,U){let V=[],j=U.exec(C);for(;j;){let x=[];x.startIndex=U.lastIndex-j[0].length;let I=j.length;for(let M=0;M<I;M++)x.push(j[M]);V.push(x),j=U.exec(C)}return V},"getAllMatches"),$=r(function(C){let U=F.exec(C);return!(U===null||typeof U>"u")},"isName");R.isExist=function(C){return typeof C<"u"},R.isEmptyObject=function(C){return Object.keys(C).length===0},R.merge=function(C,U,V){if(U){let j=Object.keys(U),x=j.length;for(let I=0;I<x;I++)V==="strict"?C[j[I]]=[U[j[I]]]:C[j[I]]=U[j[I]]}},R.getValue=function(C){return R.isExist(C)?C:""},R.isName=$,R.getAllMatches=z,R.nameRegexp=S}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(R,A){"use strict";var N=class{static{i(this,"XmlNode")}static{r(this,"XmlNode")}constructor(S){this.tagname=S,this.child=[],this[":@"]={}}add(S,F){S==="__proto__"&&(S="#__proto__"),this.child.push({[S]:F})}addChild(S){S.tagname==="__proto__"&&(S.tagname="#__proto__"),S[":@"]&&Object.keys(S[":@"]).length>0?this.child.push({[S.tagname]:S.child,":@":S[":@"]}):this.child.push({[S.tagname]:S.child})}};A.exports=N}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(R,A){var N=a();function S(x,I){let M={};if(x[I+3]==="O"&&x[I+4]==="C"&&x[I+5]==="T"&&x[I+6]==="Y"&&x[I+7]==="P"&&x[I+8]==="E"){I=I+9;let le=1,J=!1,X=!1,Ce="";for(;I<x.length;I++)if(x[I]==="<"&&!X){if(J&&$(x,I))I+=7,[entityName,val,I]=F(x,I+1),val.indexOf("&")===-1&&(M[j(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(J&&C(x,I))I+=8;else if(J&&U(x,I))I+=8;else if(J&&V(x,I))I+=9;else if(z)X=!0;else throw new Error("Invalid DOCTYPE");le++,Ce=""}else if(x[I]===">"){if(X?x[I-1]==="-"&&x[I-2]==="-"&&(X=!1,le--):le--,le===0)break}else x[I]==="["?J=!0:Ce+=x[I];if(le!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:I}}i(S,"readDocType"),r(S,"readDocType");function F(x,I){let M="";for(;I<x.length&&x[I]!=="'"&&x[I]!=='"';I++)M+=x[I];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let le=x[I++],J="";for(;I<x.length&&x[I]!==le;I++)J+=x[I];return[M,J,I]}i(F,"readEntityExp"),r(F,"readEntityExp");function z(x,I){return x[I+1]==="!"&&x[I+2]==="-"&&x[I+3]==="-"}i(z,"isComment"),r(z,"isComment");function $(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="N"&&x[I+4]==="T"&&x[I+5]==="I"&&x[I+6]==="T"&&x[I+7]==="Y"}i($,"isEntity"),r($,"isEntity");function C(x,I){return x[I+1]==="!"&&x[I+2]==="E"&&x[I+3]==="L"&&x[I+4]==="E"&&x[I+5]==="M"&&x[I+6]==="E"&&x[I+7]==="N"&&x[I+8]==="T"}i(C,"isElement"),r(C,"isElement");function U(x,I){return x[I+1]==="!"&&x[I+2]==="A"&&x[I+3]==="T"&&x[I+4]==="T"&&x[I+5]==="L"&&x[I+6]==="I"&&x[I+7]==="S"&&x[I+8]==="T"}i(U,"isAttlist"),r(U,"isAttlist");function V(x,I){return x[I+1]==="!"&&x[I+2]==="N"&&x[I+3]==="O"&&x[I+4]==="T"&&x[I+5]==="A"&&x[I+6]==="T"&&x[I+7]==="I"&&x[I+8]==="O"&&x[I+9]==="N"}i(V,"isNotation"),r(V,"isNotation");function j(x){if(N.isName(x))return x;throw new Error(`Invalid entity name ${x}`)}i(j,"validateEntityName"),r(j,"validateEntityName"),A.exports=S}}),l=o({"../../node_modules/strnum/strnum.js"(R,A){var N=/^[-+]?0x[a-fA-F0-9]+$/,S=/^([\-\+])?(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 F={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function z(C,U={}){if(U=Object.assign({},F,U),!C||typeof C!="string")return C;let V=C.trim();if(U.skipLike!==void 0&&U.skipLike.test(V))return C;if(U.hex&&N.test(V))return Number.parseInt(V,16);{let j=S.exec(V);if(j){let x=j[1],I=j[2],M=$(j[3]),le=j[4]||j[6];if(!U.leadingZeros&&I.length>0&&x&&V[2]!==".")return C;if(!U.leadingZeros&&I.length>0&&!x&&V[1]!==".")return C;{let J=Number(V),X=""+J;return X.search(/[eE]/)!==-1||le?U.eNotation?J:C:V.indexOf(".")!==-1?X==="0"&&M===""||X===M||x&&X==="-"+M?J:C:I?M===X||x+M===X?J:C:V===X||V===x+X?J:C}}else return C}}i(z,"toNumber"),r(z,"toNumber");function $(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}i($,"trimZeros"),r($,"trimZeros"),A.exports=z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(R,A){"use strict";var N=a(),S=u(),F=c(),z=l(),$=class{static{i(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(P){this.options=P,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:i((T,L)=>String.fromCharCode(Number.parseInt(L,16)),"val")}},this.addExternalEntities=C,this.parseXml=I,this.parseTextData=U,this.resolveNameSpace=V,this.buildAttributesMap=x,this.isItStopNode=X,this.replaceEntitiesValue=le,this.readStopNodeData=G,this.saveTextToParentTag=J,this.addChild=M}};function C(P){let T=Object.keys(P);for(let L=0;L<T.length;L++){let B=T[L];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:P[B]}}}i(C,"addExternalEntities"),r(C,"addExternalEntities");function U(P,T,L,B,_,D,ee){if(P!==void 0&&(this.options.trimValues&&!B&&(P=P.trim()),P.length>0)){ee||(P=this.replaceEntitiesValue(P));let Z=this.options.tagValueProcessor(T,P,L,_,D);return Z==null?P:typeof Z!=typeof P||Z!==P?Z:this.options.trimValues?me(P,this.options.parseTagValue,this.options.numberParseOptions):P.trim()===P?me(P,this.options.parseTagValue,this.options.numberParseOptions):P}}i(U,"parseTextData"),r(U,"parseTextData");function V(P){if(this.options.removeNSPrefix){let T=P.split(":"),L=P.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(P=L+T[1])}return P}i(V,"resolveNameSpace"),r(V,"resolveNameSpace");var j=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function x(P,T,L){if(!this.options.ignoreAttributes&&typeof P=="string"){let B=N.getAllMatches(P,j),_=B.length,D={};for(let ee=0;ee<_;ee++){let Z=this.resolveNameSpace(B[ee][1]),q=B[ee][4],pe=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(pe=this.options.transformAttributeName(pe)),pe==="__proto__"&&(pe="#__proto__"),q!==void 0){this.options.trimValues&&(q=q.trim()),q=this.replaceEntitiesValue(q);let oe=this.options.attributeValueProcessor(Z,q,T);oe==null?D[pe]=q:typeof oe!=typeof q||oe!==q?D[pe]=oe:D[pe]=me(q,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(D[pe]=!0)}if(!Object.keys(D).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=D,ee}return D}}i(x,"buildAttributesMap"),r(x,"buildAttributesMap");var I=r(function(P){P=P.replace(/\r\n?/g,`
82
82
  `);let T=new S("!xml"),L=T,B="",_="";for(let D=0;D<P.length;D++)if(P[D]==="<")if(P[D+1]==="/"){let Z=b(P,">",D,"Closing Tag is not closed."),q=P.substring(D+2,Z).trim();if(this.options.removeNSPrefix){let Se=q.indexOf(":");Se!==-1&&(q=q.substr(Se+1))}this.options.transformTagName&&(q=this.options.transformTagName(q)),L&&(B=this.saveTextToParentTag(B,L,_));let pe=_.substring(_.lastIndexOf(".")+1);if(q&&this.options.unpairedTags.indexOf(q)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${q}>`);let oe=0;pe&&this.options.unpairedTags.indexOf(pe)!==-1?(oe=_.lastIndexOf(".",_.lastIndexOf(".")-1),this.tagsNodeStack.pop()):oe=_.lastIndexOf("."),_=_.substring(0,oe),L=this.tagsNodeStack.pop(),B="",D=Z}else if(P[D+1]==="?"){let Z=O(P,D,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,L,_),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let q=new S(Z.tagName);q.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(q[":@"]=this.buildAttributesMap(Z.tagExp,_,Z.tagName)),this.addChild(L,q,_)}D=Z.closeIndex+1}else if(P.substr(D+1,3)==="!--"){let Z=b(P,"-->",D+4,"Comment is not closed.");if(this.options.commentPropName){let q=P.substring(D+4,Z-2);B=this.saveTextToParentTag(B,L,_),L.add(this.options.commentPropName,[{[this.options.textNodeName]:q}])}D=Z}else if(P.substr(D+1,2)==="!D"){let Z=F(P,D);this.docTypeEntities=Z.entities,D=Z.i}else if(P.substr(D+1,2)==="!["){let Z=b(P,"]]>",D,"CDATA is not closed.")-2,q=P.substring(D+9,Z);B=this.saveTextToParentTag(B,L,_);let pe=this.parseTextData(q,L.tagname,_,!0,!1,!0,!0);pe==null&&(pe=""),this.options.cdataPropName?L.add(this.options.cdataPropName,[{[this.options.textNodeName]:q}]):L.add(this.options.textNodeName,pe),D=Z+2}else{let Z=O(P,D,this.options.removeNSPrefix),q=Z.tagName,pe=Z.rawTagName,oe=Z.tagExp,Se=Z.attrExpPresent,_i=Z.closeIndex;this.options.transformTagName&&(q=this.options.transformTagName(q)),L&&B&&L.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,L,_,!1));let Ni=L;if(Ni&&this.options.unpairedTags.indexOf(Ni.tagname)!==-1&&(L=this.tagsNodeStack.pop(),_=_.substring(0,_.lastIndexOf("."))),q!==T.tagname&&(_+=_?"."+q:q),this.isItStopNode(this.options.stopNodes,_,q)){let Oe="";if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1)D=Z.closeIndex;else if(this.options.unpairedTags.indexOf(q)!==-1)D=Z.closeIndex;else{let Jn=this.readStopNodeData(P,pe,_i+1);if(!Jn)throw new Error(`Unexpected end of ${pe}`);D=Jn.i,Oe=Jn.tagContent}let Wn=new S(q);q!==oe&&Se&&(Wn[":@"]=this.buildAttributesMap(oe,_,q)),Oe&&(Oe=this.parseTextData(Oe,q,_,!0,Se,!0,!0)),_=_.substr(0,_.lastIndexOf(".")),Wn.add(this.options.textNodeName,Oe),this.addChild(L,Wn,_)}else{if(oe.length>0&&oe.lastIndexOf("/")===oe.length-1){q[q.length-1]==="/"?(q=q.substr(0,q.length-1),_=_.substr(0,_.length-1),oe=q):oe=oe.substr(0,oe.length-1),this.options.transformTagName&&(q=this.options.transformTagName(q));let Oe=new S(q);q!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,q)),this.addChild(L,Oe,_),_=_.substr(0,_.lastIndexOf("."))}else{let Oe=new S(q);this.tagsNodeStack.push(L),q!==oe&&Se&&(Oe[":@"]=this.buildAttributesMap(oe,_,q)),this.addChild(L,Oe,_),L=Oe}B="",D=_i}}else B+=P[D];return T.child},"parseXml");function M(P,T,L){let B=this.options.updateTag(T.tagname,L,T[":@"]);B===!1||(typeof B=="string"&&(T.tagname=B),P.addChild(T))}i(M,"addChild"),r(M,"addChild");var le=r(function(P){if(this.options.processEntities){for(let T in this.docTypeEntities){let L=this.docTypeEntities[T];P=P.replace(L.regx,L.val)}for(let T in this.lastEntities){let L=this.lastEntities[T];P=P.replace(L.regex,L.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let L=this.htmlEntities[T];P=P.replace(L.regex,L.val)}P=P.replace(this.ampEntity.regex,this.ampEntity.val)}return P},"replaceEntitiesValue");function J(P,T,L,B){return P&&(B===void 0&&(B=Object.keys(T.child).length===0),P=this.parseTextData(P,T.tagname,L,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,B),P!==void 0&&P!==""&&T.add(this.options.textNodeName,P),P=""),P}i(J,"saveTextToParentTag"),r(J,"saveTextToParentTag");function X(P,T,L){let B="*."+L;for(let _ in P){let D=P[_];if(B===D||T===D)return!0}return!1}i(X,"isItStopNode"),r(X,"isItStopNode");function Ce(P,T,L=">"){let B,_="";for(let D=T;D<P.length;D++){let ee=P[D];if(B)ee===B&&(B="");else if(ee==='"'||ee==="'")B=ee;else if(ee===L[0])if(L[1]){if(P[D+1]===L[1])return{data:_,index:D}}else return{data:_,index:D};else ee===" "&&(ee=" ");_+=ee}}i(Ce,"tagExpWithClosingIndex"),r(Ce,"tagExpWithClosingIndex");function b(P,T,L,B){let _=P.indexOf(T,L);if(_===-1)throw new Error(B);return _+T.length-1}i(b,"findClosingIndex"),r(b,"findClosingIndex");function O(P,T,L,B=">"){let _=Ce(P,T+1,B);if(!_)return;let D=_.data,ee=_.index,Z=D.search(/\s/),q=D,pe=!0;Z!==-1&&(q=D.substring(0,Z),D=D.substring(Z+1).trimStart());let oe=q;if(L){let Se=q.indexOf(":");Se!==-1&&(q=q.substr(Se+1),pe=q!==_.data.substr(Se+1))}return{tagName:q,tagExp:D,closeIndex:ee,attrExpPresent:pe,rawTagName:oe}}i(O,"readTagExp"),r(O,"readTagExp");function G(P,T,L){let B=L,_=1;for(;L<P.length;L++)if(P[L]==="<")if(P[L+1]==="/"){let D=b(P,">",L,`${T} is not closed`);if(P.substring(L+2,D).trim()===T&&(_--,_===0))return{tagContent:P.substring(B,L),i:D};L=D}else if(P[L+1]==="?")L=b(P,"?>",L+1,"StopNode is not closed.");else if(P.substr(L+1,3)==="!--")L=b(P,"-->",L+3,"StopNode is not closed.");else if(P.substr(L+1,2)==="![")L=b(P,"]]>",L,"StopNode is not closed.")-2;else{let D=O(P,L,">");D&&((D&&D.tagName)===T&&D.tagExp[D.tagExp.length-1]!=="/"&&_++,L=D.closeIndex)}}i(G,"readStopNodeData"),r(G,"readStopNodeData");function me(P,T,L){if(T&&typeof P=="string"){let B=P.trim();return B==="true"?!0:B==="false"?!1:z(P,L)}else return N.isExist(P)?P:""}i(me,"parseValue"),r(me,"parseValue"),A.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(R){"use strict";function A($,C){return N($,C)}i(A,"prettify"),r(A,"prettify");function N($,C,U){let V,j={};for(let x=0;x<$.length;x++){let I=$[x],M=S(I),le="";if(U===void 0?le=M:le=U+"."+M,M===C.textNodeName)V===void 0?V=I[M]:V+=""+I[M];else{if(M===void 0)continue;if(I[M]){let J=N(I[M],C,le),X=z(J,C);I[":@"]?F(J,I[":@"],le,C):Object.keys(J).length===1&&J[C.textNodeName]!==void 0&&!C.alwaysCreateTextNode?J=J[C.textNodeName]:Object.keys(J).length===0&&(C.alwaysCreateTextNode?J[C.textNodeName]="":J=""),j[M]!==void 0&&j.hasOwnProperty(M)?(Array.isArray(j[M])||(j[M]=[j[M]]),j[M].push(J)):C.isArray(M,le,X)?j[M]=[J]:j[M]=J}}}return typeof V=="string"?V.length>0&&(j[C.textNodeName]=V):V!==void 0&&(j[C.textNodeName]=V),j}i(N,"compress"),r(N,"compress");function S($){let C=Object.keys($);for(let U=0;U<C.length;U++){let V=C[U];if(V!==":@")return V}}i(S,"propName"),r(S,"propName");function F($,C,U,V){if(C){let j=Object.keys(C),x=j.length;for(let I=0;I<x;I++){let M=j[I];V.isArray(M,U+"."+M,!0,!0)?$[M]=[C[M]]:$[M]=C[M]}}}i(F,"assignAttributes"),r(F,"assignAttributes");function z($,C){let{textNodeName:U}=C,V=Object.keys($).length;return!!(V===0||V===1&&($[U]||typeof $[U]=="boolean"||$[U]===0))}i(z,"isLeafTag"),r(z,"isLeafTag"),R.prettify=A}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(R){"use strict";var A=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};R.validate=function(b,O){O=Object.assign({},N,O);let G=[],me=!1,P=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let T=0;T<b.length;T++)if(b[T]==="<"&&b[T+1]==="?"){if(T+=2,T=F(b,T),T.err)return T}else if(b[T]==="<"){let L=T;if(T++,b[T]==="!"){T=z(b,T);continue}else{let B=!1;b[T]==="/"&&(B=!0,T++);let _="";for(;T<b.length&&b[T]!==">"&&b[T]!==" "&&b[T]!==" "&&b[T]!==`
83
83
  `&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let Z;return _.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+_+"' is an invalid name.",M("InvalidTag",Z,X(b,T))}let D=U(b,T);if(D===!1)return M("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,T));let ee=D.value;if(T=D.index,ee[ee.length-1]==="/"){let Z=T-ee.length;ee=ee.substring(0,ee.length-1);let q=j(ee,O);if(q===!0)me=!0;else return M(q.err.code,q.err.msg,X(b,Z+q.err.line))}else if(B)if(D.tagClosed){if(ee.trim().length>0)return M("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let Z=G.pop();if(_!==Z.tagName){let q=X(b,Z.tagStartPos);return M("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(P=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let Z=j(ee,O);if(Z!==!0)return M(Z.err.code,Z.err.msg,X(b,T-ee.length+Z.err.line));if(P===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let Z=I(b,T);if(Z==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=Z}else if(P===!0&&!S(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(S(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(b){return b===" "||b===" "||b===`
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{c as e,d as t,f as a,g as o,h as r,i,j as n}from"../chunk-IF4DUSCR.js";import"../chunk-PPV7V43C.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
25
+ import{c as e,d as t,f as a,g as o,h as r,i,j as n}from"../chunk-G45SN3PW.js";import"../chunk-PPV7V43C.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
26
26
  /*! For license information please see index.js.LEGAL.txt */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.40.3",
4
+ "version": "6.40.4",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {