@zuplo/graphql 5.1856.0 → 5.1858.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.minified.js +37 -37
  2. package/package.json +1 -1
package/index.minified.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var ov=Object.create;var Ai=Object.defineProperty;var sv=Object.getOwnPropertyDescriptor;var av=Object.getOwnPropertyNames;var cv=Object.getPrototypeOf,uv=Object.prototype.hasOwnProperty;var o=(t,e)=>Ai(t,"name",{value:e,configurable:!0});var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Co=(t,e)=>{for(var r in e)Ai(t,r,{get:e[r],enumerable:!0})},Dh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of av(e))!uv.call(t,i)&&i!==r&&Ai(t,i,{get:()=>e[i],enumerable:!(n=sv(e,i))||n.enumerable});return t};var Mh=(t,e,r)=>(r=t!=null?ov(cv(t)):{},Dh(e||!t||!t.__esModule?Ai(r,"default",{value:t,enumerable:!0}):r,t)),xo=t=>Dh(Ai({},"__esModule",{value:!0}),t);var k=_(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.FeatureNotEnabledError=Rt.ConfigurationError=Rt.RuntimeError=Rt.SystemError=void 0;var Ju=class extends Error{static{o(this,"SystemError")}constructor(e,r){super(e,r),this.name="InternalError"}};Rt.SystemError=Ju;var Ri=class extends Error{static{o(this,"RuntimeError")}extensionMembers;constructor(e,r){typeof e=="string"?super(e,r):(super(e.message,r),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}};Rt.RuntimeError=Ri;var zu=class extends Ri{static{o(this,"ConfigurationError")}constructor(e,r){super(e,r),this.name="ConfigurationError"}};Rt.ConfigurationError=zu;var Wu=class extends Ri{static{o(this,"FeatureNotEnabledError")}constructor(e,r){super(e,r),this.name="FeatureNotEnabledError"}};Rt.FeatureNotEnabledError=Wu});var ie=_(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.Environment=void 0;var lv=k(),Qu=class t{static{o(this,"Environment")}config;static#e;static initialize(e,r){this.#e||(this.#e=new t(e,r))}static get instance(){if(!this.#e)throw new lv.SystemError("Environment has not been initialized");return this.#e}constructor(e,r){let n;try{if(r.__ZUPLO_CONFIG){let i=atob(r.__ZUPLO_CONFIG);n=JSON.parse(i)}}catch{console.warn("Failed to parse runtime configuration")}this.config=n??{},this.build=e,this.runtime=r}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get 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.isDeno?"working-copy":"unknown"}};Lo.Environment=Qu});var Hh=_(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var Uh=ie();Function.prototype.toString=function(){return"[native code]"};var Do=globalThis,kh=Do.caches;if(kh){let t=kh.open;Do.caches.open=function(e){let r=Uh.Environment.instance.deploymentName??Uh.Environment.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete Do.caches.default,Object.freeze(Do.caches)}});var Xu=_(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.MemoryCache=void 0;var dv=1e4,pv=1e3,qh=new Map,Yu=class{static{o(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#r=new Map;#n=[];get(e){let r=this.#r.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.#r.delete(e);return}return r.lastUsed=n,this.#i(),r?.data}put(e,r,n){if(n<=0)return;if(this.#r.size>=this.#e){let a=this.#n.shift();a&&this.#r.delete(a)}let i=Date.now(),s={created:i,lastUsed:i,expiresAt:i+n*1e3,data:r};this.#n.push(e),this.#r.set(e,s)}delete(e){let r=this.#n.indexOf(e);r>=0&&this.#n.slice(r,1),this.#r.delete(e)}get size(){return this.#r.size}#i(){let e=Date.now();this.#t+dv*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#r.forEach((r,n)=>{r.expiresAt>=e&&this.#r.delete(n)})}},Zu=class{static{o(this,"MemoryCache")}constructor(e,r={maxSize:pv}){this.name=e;let n=qh.get(e);n||(n=new Yu(r),qh.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};Mo.MemoryCache=Zu});var rl=_(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.ZoneCache=void 0;var el="__zuplo-expiry-header",tl=class{static{o(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#r;async#n(){return this.#r||(this.#r=await caches.open(this.#t)),this.#r}#i(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#n(),n=this.#i(e),i=await r.match(n);if(!i)return;let s=i.headers.get(el);if(!s){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await i.json()}catch(r){this.logDebug(r)}}async put(e,r,n){let i=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});i.set(el,`${Date.now()+n*1e3}`);let s=await this.#n(),a=this.#i(e),c=new Response(JSON.stringify(r),{headers:i});await s.put(a,c)}async delete(e){let r=await this.#n(),n=this.#i(e);try{await r.delete(n)}catch(i){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",i),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(el,`${Date.now()}`);let n=await this.#n(),i=this.#i(e),s=new Response("",{headers:r});await n.put(i,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};Uo.ZoneCache=tl});var Bt=_(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.MemoryZoneReadThroughCache=void 0;var fv=Xu(),hv=rl(),nl=class{static{o(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new fv.MemoryCache(n),this.#r=new hv.ZoneCache(n,r),this.#n=r}#e;#t;#r;#n;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#r.get(e);if(n){let i=Math.floor((n.expires-Date.now())/1e3);if(i>0)return this.#t.put(e,n.data,i),n.data}}put(e,r,n){this.#t.put(e,r,n);let i={data:r,expires:Date.now()+n*1e3},s=this.#r.put(e,i,n).catch(a=>{this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#n.waitUntil(s)}};ko.MemoryZoneReadThroughCache=nl});var Fr=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.DYNAMIC_METERS_CONTEXT_DATA=x.METERING_SUBSCRIPTION_CONTEXT_DATA=x.INTERNAL_HEADERS_TO_REMOVE=x.VENDOR_HEADERS_TO_ALLOW=x.VENDOR_HEADER_PREFIXES=x.DISPATCH_HEADERS_TO_REMOVE=x.ZP_TIMEZONE_HEADER=x.ZP_REGION_CODE_HEADER=x.ZP_REGION_HEADER=x.ZP_METRO_CODE_HEADER=x.ZP_POSTAL_CODE_HEADER=x.ZP_COLO_HEADER=x.ZP_AS_ORG_HEADER=x.ZP_ASN_HEADER=x.TRUE_CLIENT_IP=x.ZP_IP_LATITUDE_HEADER=x.ZP_IP_LONGITUDE_HEADER=x.ZP_IP_COUNTRY_HEADER=x.ZP_IP_CONTINENT_HEADER=x.ZP_IP_CITY_HEADER=x.CF_TIMEZONE_HEADER=x.CF_POSTAL_CODE_HEADER=x.CF_METRO_CODE_HEADER=x.CF_REGION_CODE_HEADER=x.CF_IP_REGION_HEADER=x.CF_IP_LATITUDE_HEADER=x.CF_IP_LONGITUDE_HEADER=x.CF_IP_COUNTRY_HEADER=x.CF_IP_CONTINENT_HEADER=x.CF_IP_CITY_HEADER=x.X_REAL_IP_HEADER=x.RAY_ID_HEADER=x.BODY_REMOVED_HEADER=x.REQUEST_ID_HEADER=x.LEGACY_REQUEST_ID_HEADER=void 0;x.LEGACY_REQUEST_ID_HEADER="zuplo-request-id";x.REQUEST_ID_HEADER="zp-rid";x.BODY_REMOVED_HEADER="zp-body-removed";x.RAY_ID_HEADER="cf-ray";x.X_REAL_IP_HEADER="x-real-ip";x.CF_IP_CITY_HEADER="cf-ipcity";x.CF_IP_CONTINENT_HEADER="cf-ipcontinent";x.CF_IP_COUNTRY_HEADER="cf-ipcountry";x.CF_IP_LONGITUDE_HEADER="cf-iplongitude";x.CF_IP_LATITUDE_HEADER="cf-iplatitude";x.CF_IP_REGION_HEADER="cf-region";x.CF_REGION_CODE_HEADER="cf-region-code";x.CF_METRO_CODE_HEADER="cf-metro-code";x.CF_POSTAL_CODE_HEADER="cf-postal-code";x.CF_TIMEZONE_HEADER="cf-timezone";x.ZP_IP_CITY_HEADER="zp-ipcity";x.ZP_IP_CONTINENT_HEADER="zp-ipcontinent";x.ZP_IP_COUNTRY_HEADER="zp-ipcountry";x.ZP_IP_LONGITUDE_HEADER="zp-iplongitude";x.ZP_IP_LATITUDE_HEADER="zp-iplatitude";x.TRUE_CLIENT_IP="true-client-ip";x.ZP_ASN_HEADER="zp-asn";x.ZP_AS_ORG_HEADER="zp-asorg";x.ZP_COLO_HEADER="zp-colo";x.ZP_POSTAL_CODE_HEADER="zp-postalcode";x.ZP_METRO_CODE_HEADER="zp-metrocode";x.ZP_REGION_HEADER="zp-region";x.ZP_REGION_CODE_HEADER="zp-regioncode";x.ZP_TIMEZONE_HEADER="zp-timezone";x.DISPATCH_HEADERS_TO_REMOVE=[x.CF_IP_CITY_HEADER,x.CF_IP_CONTINENT_HEADER,x.CF_IP_COUNTRY_HEADER,x.CF_IP_LONGITUDE_HEADER,x.CF_IP_LATITUDE_HEADER,x.ZP_ASN_HEADER,x.ZP_AS_ORG_HEADER,x.ZP_COLO_HEADER,x.ZP_POSTAL_CODE_HEADER,x.ZP_METRO_CODE_HEADER,x.ZP_REGION_HEADER,x.ZP_REGION_CODE_HEADER,x.ZP_TIMEZONE_HEADER];x.VENDOR_HEADER_PREFIXES=["zp-","cf-"];x.VENDOR_HEADERS_TO_ALLOW=[x.REQUEST_ID_HEADER,x.RAY_ID_HEADER,x.BODY_REMOVED_HEADER];x.INTERNAL_HEADERS_TO_REMOVE=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];x.METERING_SUBSCRIPTION_CONTEXT_DATA="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49";x.DYNAMIC_METERS_CONTEXT_DATA="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91"});var Wh=_(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.generateColor=N.colorFunctions=N.stripColor=N.bgRgb24=N.rgb24=N.bgRgb8=N.rgb8=N.bgBrightWhite=N.bgBrightCyan=N.bgBrightMagenta=N.bgBrightBlue=N.bgBrightYellow=N.bgBrightGreen=N.bgBrightRed=N.bgBrightBlack=N.bgWhite=N.bgCyan=N.bgMagenta=N.bgBlue=N.bgYellow=N.bgGreen=N.bgRed=N.bgBlack=N.brightWhite=N.brightCyan=N.brightMagenta=N.brightBlue=N.brightYellow=N.brightGreen=N.brightRed=N.brightBlack=N.gray=N.white=N.cyan=N.magenta=N.blue=N.yellow=N.green=N.red=N.black=N.strikethrough=N.hidden=N.inverse=N.underline=N.italic=N.dim=N.bold=N.reset=N.getColorEnabled=N.setColorEnabled=void 0;var $h=!0,il=!$h;function mv(t){$h||(il=t)}o(mv,"setColorEnabled");N.setColorEnabled=mv;function yv(){return il}o(yv,"getColorEnabled");N.getColorEnabled=yv;function z(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}o(z,"code");function W(t,e){return il?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}o(W,"run");function gv(t){return W(t,z([0],0))}o(gv,"reset");N.reset=gv;function bv(t){return W(t,z([1],22))}o(bv,"bold");N.bold=bv;function _v(t){return W(t,z([2],22))}o(_v,"dim");N.dim=_v;function Ev(t){return W(t,z([3],23))}o(Ev,"italic");N.italic=Ev;function wv(t){return W(t,z([4],24))}o(wv,"underline");N.underline=wv;function vv(t){return W(t,z([7],27))}o(vv,"inverse");N.inverse=vv;function Tv(t){return W(t,z([8],28))}o(Tv,"hidden");N.hidden=Tv;function Sv(t){return W(t,z([9],29))}o(Sv,"strikethrough");N.strikethrough=Sv;function Iv(t){return W(t,z([30],39))}o(Iv,"black");N.black=Iv;function jh(t){return W(t,z([31],39))}o(jh,"red");N.red=jh;function Vh(t){return W(t,z([32],39))}o(Vh,"green");N.green=Vh;function Bh(t){return W(t,z([33],39))}o(Bh,"yellow");N.yellow=Bh;function Gh(t){return W(t,z([34],39))}o(Gh,"blue");N.blue=Gh;function Kh(t){return W(t,z([35],39))}o(Kh,"magenta");N.magenta=Kh;function Jh(t){return W(t,z([36],39))}o(Jh,"cyan");N.cyan=Jh;function Pv(t){return W(t,z([37],39))}o(Pv,"white");N.white=Pv;function Av(t){return zh(t)}o(Av,"gray");N.gray=Av;function zh(t){return W(t,z([90],39))}o(zh,"brightBlack");N.brightBlack=zh;function Rv(t){return W(t,z([91],39))}o(Rv,"brightRed");N.brightRed=Rv;function Ov(t){return W(t,z([92],39))}o(Ov,"brightGreen");N.brightGreen=Ov;function Nv(t){return W(t,z([93],39))}o(Nv,"brightYellow");N.brightYellow=Nv;function Cv(t){return W(t,z([94],39))}o(Cv,"brightBlue");N.brightBlue=Cv;function xv(t){return W(t,z([95],39))}o(xv,"brightMagenta");N.brightMagenta=xv;function Lv(t){return W(t,z([96],39))}o(Lv,"brightCyan");N.brightCyan=Lv;function Dv(t){return W(t,z([97],39))}o(Dv,"brightWhite");N.brightWhite=Dv;function Mv(t){return W(t,z([40],49))}o(Mv,"bgBlack");N.bgBlack=Mv;function Uv(t){return W(t,z([41],49))}o(Uv,"bgRed");N.bgRed=Uv;function kv(t){return W(t,z([42],49))}o(kv,"bgGreen");N.bgGreen=kv;function Fv(t){return W(t,z([43],49))}o(Fv,"bgYellow");N.bgYellow=Fv;function Hv(t){return W(t,z([44],49))}o(Hv,"bgBlue");N.bgBlue=Hv;function qv(t){return W(t,z([45],49))}o(qv,"bgMagenta");N.bgMagenta=qv;function $v(t){return W(t,z([46],49))}o($v,"bgCyan");N.bgCyan=$v;function jv(t){return W(t,z([47],49))}o(jv,"bgWhite");N.bgWhite=jv;function Vv(t){return W(t,z([100],49))}o(Vv,"bgBrightBlack");N.bgBrightBlack=Vv;function Bv(t){return W(t,z([101],49))}o(Bv,"bgBrightRed");N.bgBrightRed=Bv;function Gv(t){return W(t,z([102],49))}o(Gv,"bgBrightGreen");N.bgBrightGreen=Gv;function Kv(t){return W(t,z([103],49))}o(Kv,"bgBrightYellow");N.bgBrightYellow=Kv;function Jv(t){return W(t,z([104],49))}o(Jv,"bgBrightBlue");N.bgBrightBlue=Jv;function zv(t){return W(t,z([105],49))}o(zv,"bgBrightMagenta");N.bgBrightMagenta=zv;function Wv(t){return W(t,z([106],49))}o(Wv,"bgBrightCyan");N.bgBrightCyan=Wv;function Qv(t){return W(t,z([107],49))}o(Qv,"bgBrightWhite");N.bgBrightWhite=Qv;function nr(t,e=255,r=0){return Math.trunc(Math.max(Math.min(t,e),r))}o(nr,"clampAndTruncate");function Yv(t,e){return W(t,z([38,5,nr(e)],39))}o(Yv,"rgb8");N.rgb8=Yv;function Zv(t,e){return W(t,z([48,5,nr(e)],49))}o(Zv,"bgRgb8");N.bgRgb8=Zv;function Xv(t,e){return typeof e=="number"?W(t,z([38,2,e>>16&255,e>>8&255,e&255],39)):W(t,z([38,2,nr(e.r),nr(e.g),nr(e.b)],39))}o(Xv,"rgb24");N.rgb24=Xv;function eT(t,e){return typeof e=="number"?W(t,z([48,2,e>>16&255,e>>8&255,e&255],49)):W(t,z([48,2,nr(e.r),nr(e.g),nr(e.b)],49))}o(eT,"bgRgb24");N.bgRgb24=eT;var tT=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");function rT(t){return t.replace(tT,"")}o(rT,"stripColor");N.stripColor=rT;N.colorFunctions=[jh,Vh,Bh,Gh,Kh,Jh];function nT(t){let e=0,r=t.length,n=0;if(r>0)for(;n<r;)e=(e<<5)-e+t.charCodeAt(n++)|0;return e}o(nT,"hashCode");function iT(t){let e=Math.abs(nT(t));return N.colorFunctions[e%N.colorFunctions.length]}o(iT,"generateColor");N.generateColor=iT});var Qh=_(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.format=void 0;function oT(t,e,...r){let n=0,i=r.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(n>=i)return a;switch(a){case"%s":return String(r[n++]);case"%d":return Number(r[n++]).toString();case"%o":return t(r[n++]).split(`
25
+ "use strict";var ov=Object.create;var Ai=Object.defineProperty;var sv=Object.getOwnPropertyDescriptor;var av=Object.getOwnPropertyNames;var cv=Object.getPrototypeOf,uv=Object.prototype.hasOwnProperty;var o=(t,e)=>Ai(t,"name",{value:e,configurable:!0});var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Co=(t,e)=>{for(var r in e)Ai(t,r,{get:e[r],enumerable:!0})},Dh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of av(e))!uv.call(t,i)&&i!==r&&Ai(t,i,{get:()=>e[i],enumerable:!(n=sv(e,i))||n.enumerable});return t};var Mh=(t,e,r)=>(r=t!=null?ov(cv(t)):{},Dh(e||!t||!t.__esModule?Ai(r,"default",{value:t,enumerable:!0}):r,t)),xo=t=>Dh(Ai({},"__esModule",{value:!0}),t);var k=_(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.FeatureNotEnabledError=Rt.ConfigurationError=Rt.RuntimeError=Rt.SystemError=void 0;var Ju=class extends Error{static{o(this,"SystemError")}constructor(e,r){super(e,r),this.name="InternalError"}};Rt.SystemError=Ju;var Ri=class extends Error{static{o(this,"RuntimeError")}extensionMembers;constructor(e,r){typeof e=="string"?super(e,r):(super(e.message,r),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}};Rt.RuntimeError=Ri;var zu=class extends Ri{static{o(this,"ConfigurationError")}constructor(e,r){super(e,r),this.name="ConfigurationError"}};Rt.ConfigurationError=zu;var Wu=class extends Ri{static{o(this,"FeatureNotEnabledError")}constructor(e,r){super(e,r),this.name="FeatureNotEnabledError"}};Rt.FeatureNotEnabledError=Wu});var re=_(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.Environment=void 0;var lv=k(),Qu=class t{static{o(this,"Environment")}config;static#e;static initialize(e,r){this.#e||(this.#e=new t(e,r))}static get instance(){if(!this.#e)throw new lv.SystemError("Environment has not been initialized");return this.#e}constructor(e,r){let n;try{if(r.__ZUPLO_CONFIG){let i=atob(r.__ZUPLO_CONFIG);n=JSON.parse(i)}}catch{console.warn("Failed to parse runtime configuration")}this.config=n??{},this.build=e,this.runtime=r}build;runtime;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useSha256ServiceRouting(){return this.config.use_sha256_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.dev"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.ENVIRONMENT_TYPE?this.build.ENVIRONMENT_TYPE==="LOCAL_DEVELOPMENT":!1}get 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.isDeno?"working-copy":"unknown"}};Lo.Environment=Qu});var Hh=_(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var Uh=re();Function.prototype.toString=function(){return"[native code]"};var Do=globalThis,kh=Do.caches;if(kh){let t=kh.open;Do.caches.open=function(e){let r=Uh.Environment.instance.deploymentName??Uh.Environment.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete Do.caches.default,Object.freeze(Do.caches)}});var Xu=_(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.MemoryCache=void 0;var dv=1e4,pv=1e3,qh=new Map,Yu=class{static{o(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#r=new Map;#n=[];get(e){let r=this.#r.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.#r.delete(e);return}return r.lastUsed=n,this.#i(),r?.data}put(e,r,n){if(n<=0)return;if(this.#r.size>=this.#e){let a=this.#n.shift();a&&this.#r.delete(a)}let i=Date.now(),s={created:i,lastUsed:i,expiresAt:i+n*1e3,data:r};this.#n.push(e),this.#r.set(e,s)}delete(e){let r=this.#n.indexOf(e);r>=0&&this.#n.slice(r,1),this.#r.delete(e)}get size(){return this.#r.size}#i(){let e=Date.now();this.#t+dv*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#r.forEach((r,n)=>{r.expiresAt>=e&&this.#r.delete(n)})}},Zu=class{static{o(this,"MemoryCache")}constructor(e,r={maxSize:pv}){this.name=e;let n=qh.get(e);n||(n=new Yu(r),qh.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};Mo.MemoryCache=Zu});var rl=_(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.ZoneCache=void 0;var el="__zuplo-expiry-header",tl=class{static{o(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#r;async#n(){return this.#r||(this.#r=await caches.open(this.#t)),this.#r}#i(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#n(),n=this.#i(e),i=await r.match(n);if(!i)return;let s=i.headers.get(el);if(!s){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await i.json()}catch(r){this.logDebug(r)}}async put(e,r,n){let i=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});i.set(el,`${Date.now()+n*1e3}`);let s=await this.#n(),a=this.#i(e),c=new Response(JSON.stringify(r),{headers:i});await s.put(a,c)}async delete(e){let r=await this.#n(),n=this.#i(e);try{await r.delete(n)}catch(i){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",i),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(el,`${Date.now()}`);let n=await this.#n(),i=this.#i(e),s=new Response("",{headers:r});await n.put(i,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};Uo.ZoneCache=tl});var Bt=_(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.MemoryZoneReadThroughCache=void 0;var fv=Xu(),hv=rl(),nl=class{static{o(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new fv.MemoryCache(n),this.#r=new hv.ZoneCache(n,r),this.#n=r}#e;#t;#r;#n;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#r.get(e);if(n){let i=Math.floor((n.expires-Date.now())/1e3);if(i>0)return this.#t.put(e,n.data,i),n.data}}put(e,r,n){this.#t.put(e,r,n);let i={data:r,expires:Date.now()+n*1e3},s=this.#r.put(e,i,n).catch(a=>{this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#n.waitUntil(s)}};ko.MemoryZoneReadThroughCache=nl});var Fr=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.DYNAMIC_METERS_CONTEXT_DATA=x.METERING_SUBSCRIPTION_CONTEXT_DATA=x.INTERNAL_HEADERS_TO_REMOVE=x.VENDOR_HEADERS_TO_ALLOW=x.VENDOR_HEADER_PREFIXES=x.DISPATCH_HEADERS_TO_REMOVE=x.ZP_TIMEZONE_HEADER=x.ZP_REGION_CODE_HEADER=x.ZP_REGION_HEADER=x.ZP_METRO_CODE_HEADER=x.ZP_POSTAL_CODE_HEADER=x.ZP_COLO_HEADER=x.ZP_AS_ORG_HEADER=x.ZP_ASN_HEADER=x.TRUE_CLIENT_IP=x.ZP_IP_LATITUDE_HEADER=x.ZP_IP_LONGITUDE_HEADER=x.ZP_IP_COUNTRY_HEADER=x.ZP_IP_CONTINENT_HEADER=x.ZP_IP_CITY_HEADER=x.CF_TIMEZONE_HEADER=x.CF_POSTAL_CODE_HEADER=x.CF_METRO_CODE_HEADER=x.CF_REGION_CODE_HEADER=x.CF_IP_REGION_HEADER=x.CF_IP_LATITUDE_HEADER=x.CF_IP_LONGITUDE_HEADER=x.CF_IP_COUNTRY_HEADER=x.CF_IP_CONTINENT_HEADER=x.CF_IP_CITY_HEADER=x.X_REAL_IP_HEADER=x.RAY_ID_HEADER=x.BODY_REMOVED_HEADER=x.REQUEST_ID_HEADER=x.LEGACY_REQUEST_ID_HEADER=void 0;x.LEGACY_REQUEST_ID_HEADER="zuplo-request-id";x.REQUEST_ID_HEADER="zp-rid";x.BODY_REMOVED_HEADER="zp-body-removed";x.RAY_ID_HEADER="cf-ray";x.X_REAL_IP_HEADER="x-real-ip";x.CF_IP_CITY_HEADER="cf-ipcity";x.CF_IP_CONTINENT_HEADER="cf-ipcontinent";x.CF_IP_COUNTRY_HEADER="cf-ipcountry";x.CF_IP_LONGITUDE_HEADER="cf-iplongitude";x.CF_IP_LATITUDE_HEADER="cf-iplatitude";x.CF_IP_REGION_HEADER="cf-region";x.CF_REGION_CODE_HEADER="cf-region-code";x.CF_METRO_CODE_HEADER="cf-metro-code";x.CF_POSTAL_CODE_HEADER="cf-postal-code";x.CF_TIMEZONE_HEADER="cf-timezone";x.ZP_IP_CITY_HEADER="zp-ipcity";x.ZP_IP_CONTINENT_HEADER="zp-ipcontinent";x.ZP_IP_COUNTRY_HEADER="zp-ipcountry";x.ZP_IP_LONGITUDE_HEADER="zp-iplongitude";x.ZP_IP_LATITUDE_HEADER="zp-iplatitude";x.TRUE_CLIENT_IP="true-client-ip";x.ZP_ASN_HEADER="zp-asn";x.ZP_AS_ORG_HEADER="zp-asorg";x.ZP_COLO_HEADER="zp-colo";x.ZP_POSTAL_CODE_HEADER="zp-postalcode";x.ZP_METRO_CODE_HEADER="zp-metrocode";x.ZP_REGION_HEADER="zp-region";x.ZP_REGION_CODE_HEADER="zp-regioncode";x.ZP_TIMEZONE_HEADER="zp-timezone";x.DISPATCH_HEADERS_TO_REMOVE=[x.CF_IP_CITY_HEADER,x.CF_IP_CONTINENT_HEADER,x.CF_IP_COUNTRY_HEADER,x.CF_IP_LONGITUDE_HEADER,x.CF_IP_LATITUDE_HEADER,x.ZP_ASN_HEADER,x.ZP_AS_ORG_HEADER,x.ZP_COLO_HEADER,x.ZP_POSTAL_CODE_HEADER,x.ZP_METRO_CODE_HEADER,x.ZP_REGION_HEADER,x.ZP_REGION_CODE_HEADER,x.ZP_TIMEZONE_HEADER];x.VENDOR_HEADER_PREFIXES=["zp-","cf-"];x.VENDOR_HEADERS_TO_ALLOW=[x.REQUEST_ID_HEADER,x.RAY_ID_HEADER,x.BODY_REMOVED_HEADER];x.INTERNAL_HEADERS_TO_REMOVE=["x-b3-sampled","x-b3-spanid","x-b3-traceid","x-envoy-attempt-count","x-envoy-decorator-operation","x-envoy-external-address","x-envoy-peer-metadata","x-envoy-peer-metadata-id","k-proxy-request","fly-client-ip","fly-forwarded-port","fly-forwarded-proto","fly-forwarded-ssl","fly-region","fly-request-id","fly-traceparent","fly-tracestate"];x.METERING_SUBSCRIPTION_CONTEXT_DATA="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49";x.DYNAMIC_METERS_CONTEXT_DATA="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91"});var Wh=_(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.generateColor=N.colorFunctions=N.stripColor=N.bgRgb24=N.rgb24=N.bgRgb8=N.rgb8=N.bgBrightWhite=N.bgBrightCyan=N.bgBrightMagenta=N.bgBrightBlue=N.bgBrightYellow=N.bgBrightGreen=N.bgBrightRed=N.bgBrightBlack=N.bgWhite=N.bgCyan=N.bgMagenta=N.bgBlue=N.bgYellow=N.bgGreen=N.bgRed=N.bgBlack=N.brightWhite=N.brightCyan=N.brightMagenta=N.brightBlue=N.brightYellow=N.brightGreen=N.brightRed=N.brightBlack=N.gray=N.white=N.cyan=N.magenta=N.blue=N.yellow=N.green=N.red=N.black=N.strikethrough=N.hidden=N.inverse=N.underline=N.italic=N.dim=N.bold=N.reset=N.getColorEnabled=N.setColorEnabled=void 0;var $h=!0,il=!$h;function mv(t){$h||(il=t)}o(mv,"setColorEnabled");N.setColorEnabled=mv;function yv(){return il}o(yv,"getColorEnabled");N.getColorEnabled=yv;function z(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}o(z,"code");function W(t,e){return il?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}o(W,"run");function gv(t){return W(t,z([0],0))}o(gv,"reset");N.reset=gv;function bv(t){return W(t,z([1],22))}o(bv,"bold");N.bold=bv;function _v(t){return W(t,z([2],22))}o(_v,"dim");N.dim=_v;function Ev(t){return W(t,z([3],23))}o(Ev,"italic");N.italic=Ev;function wv(t){return W(t,z([4],24))}o(wv,"underline");N.underline=wv;function vv(t){return W(t,z([7],27))}o(vv,"inverse");N.inverse=vv;function Tv(t){return W(t,z([8],28))}o(Tv,"hidden");N.hidden=Tv;function Sv(t){return W(t,z([9],29))}o(Sv,"strikethrough");N.strikethrough=Sv;function Iv(t){return W(t,z([30],39))}o(Iv,"black");N.black=Iv;function jh(t){return W(t,z([31],39))}o(jh,"red");N.red=jh;function Vh(t){return W(t,z([32],39))}o(Vh,"green");N.green=Vh;function Bh(t){return W(t,z([33],39))}o(Bh,"yellow");N.yellow=Bh;function Gh(t){return W(t,z([34],39))}o(Gh,"blue");N.blue=Gh;function Kh(t){return W(t,z([35],39))}o(Kh,"magenta");N.magenta=Kh;function Jh(t){return W(t,z([36],39))}o(Jh,"cyan");N.cyan=Jh;function Pv(t){return W(t,z([37],39))}o(Pv,"white");N.white=Pv;function Av(t){return zh(t)}o(Av,"gray");N.gray=Av;function zh(t){return W(t,z([90],39))}o(zh,"brightBlack");N.brightBlack=zh;function Rv(t){return W(t,z([91],39))}o(Rv,"brightRed");N.brightRed=Rv;function Ov(t){return W(t,z([92],39))}o(Ov,"brightGreen");N.brightGreen=Ov;function Nv(t){return W(t,z([93],39))}o(Nv,"brightYellow");N.brightYellow=Nv;function Cv(t){return W(t,z([94],39))}o(Cv,"brightBlue");N.brightBlue=Cv;function xv(t){return W(t,z([95],39))}o(xv,"brightMagenta");N.brightMagenta=xv;function Lv(t){return W(t,z([96],39))}o(Lv,"brightCyan");N.brightCyan=Lv;function Dv(t){return W(t,z([97],39))}o(Dv,"brightWhite");N.brightWhite=Dv;function Mv(t){return W(t,z([40],49))}o(Mv,"bgBlack");N.bgBlack=Mv;function Uv(t){return W(t,z([41],49))}o(Uv,"bgRed");N.bgRed=Uv;function kv(t){return W(t,z([42],49))}o(kv,"bgGreen");N.bgGreen=kv;function Fv(t){return W(t,z([43],49))}o(Fv,"bgYellow");N.bgYellow=Fv;function Hv(t){return W(t,z([44],49))}o(Hv,"bgBlue");N.bgBlue=Hv;function qv(t){return W(t,z([45],49))}o(qv,"bgMagenta");N.bgMagenta=qv;function $v(t){return W(t,z([46],49))}o($v,"bgCyan");N.bgCyan=$v;function jv(t){return W(t,z([47],49))}o(jv,"bgWhite");N.bgWhite=jv;function Vv(t){return W(t,z([100],49))}o(Vv,"bgBrightBlack");N.bgBrightBlack=Vv;function Bv(t){return W(t,z([101],49))}o(Bv,"bgBrightRed");N.bgBrightRed=Bv;function Gv(t){return W(t,z([102],49))}o(Gv,"bgBrightGreen");N.bgBrightGreen=Gv;function Kv(t){return W(t,z([103],49))}o(Kv,"bgBrightYellow");N.bgBrightYellow=Kv;function Jv(t){return W(t,z([104],49))}o(Jv,"bgBrightBlue");N.bgBrightBlue=Jv;function zv(t){return W(t,z([105],49))}o(zv,"bgBrightMagenta");N.bgBrightMagenta=zv;function Wv(t){return W(t,z([106],49))}o(Wv,"bgBrightCyan");N.bgBrightCyan=Wv;function Qv(t){return W(t,z([107],49))}o(Qv,"bgBrightWhite");N.bgBrightWhite=Qv;function nr(t,e=255,r=0){return Math.trunc(Math.max(Math.min(t,e),r))}o(nr,"clampAndTruncate");function Yv(t,e){return W(t,z([38,5,nr(e)],39))}o(Yv,"rgb8");N.rgb8=Yv;function Zv(t,e){return W(t,z([48,5,nr(e)],49))}o(Zv,"bgRgb8");N.bgRgb8=Zv;function Xv(t,e){return typeof e=="number"?W(t,z([38,2,e>>16&255,e>>8&255,e&255],39)):W(t,z([38,2,nr(e.r),nr(e.g),nr(e.b)],39))}o(Xv,"rgb24");N.rgb24=Xv;function eT(t,e){return typeof e=="number"?W(t,z([48,2,e>>16&255,e>>8&255,e&255],49)):W(t,z([48,2,nr(e.r),nr(e.g),nr(e.b)],49))}o(eT,"bgRgb24");N.bgRgb24=eT;var tT=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");function rT(t){return t.replace(tT,"")}o(rT,"stripColor");N.stripColor=rT;N.colorFunctions=[jh,Vh,Bh,Gh,Kh,Jh];function nT(t){let e=0,r=t.length,n=0;if(r>0)for(;n<r;)e=(e<<5)-e+t.charCodeAt(n++)|0;return e}o(nT,"hashCode");function iT(t){let e=Math.abs(nT(t));return N.colorFunctions[e%N.colorFunctions.length]}o(iT,"generateColor");N.generateColor=iT});var Qh=_(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.format=void 0;function oT(t,e,...r){let n=0,i=r.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(n>=i)return a;switch(a){case"%s":return String(r[n++]);case"%d":return Number(r[n++]).toString();case"%o":return t(r[n++]).split(`
26
26
  `).map(c=>c.trim()).join(" ");case"%O":return t(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch{return"[Circular]"}default:return a}});for(let a of r.splice(n))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+t(a);return s}o(oT,"format");Fo.format=oT});var rm=_(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.inspect=void 0;function Hr(t,e,r,n){let i={seen:[],stylize:sT,showHidden:e??!1,depth:r??2,colors:n??!1,customInspect:!0};return i.colors&&(i.stylize=cT),Ho(i,t,i.depth)}o(Hr,"inspect");qo.inspect=Hr;Hr.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]};Hr.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function sT(t,e){return t}o(sT,"stylizeNoColor");function aT(t){return typeof t=="boolean"}o(aT,"isBoolean");function Zh(t){return t===void 0}o(Zh,"isUndefined");function cT(t,e){let r=Hr.styles[e];return r?"\x1B["+Hr.colors[r][0]+"m"+t+"\x1B["+Hr.colors[r][1]+"m":t}o(cT,"stylizeWithColor");function ol(t){return typeof t=="function"}o(ol,"isFunction");function Xh(t){return typeof t=="string"}o(Xh,"isString");function uT(t){return typeof t=="number"}o(uT,"isNumber");function em(t){return t===null}o(em,"isNull");function tm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(tm,"hasOwn");function sl(t){return ll(t)&&dl(t)==="[object RegExp]"}o(sl,"isRegExp");function ll(t){return typeof t=="object"&&t!==null}o(ll,"isObject");function al(t){return ll(t)&&(dl(t)==="[object Error]"||t instanceof Error)}o(al,"isError");function Yh(t){return ll(t)&&dl(t)==="[object Date]"}o(Yh,"isDate");function dl(t){return Object.prototype.toString.call(t)}o(dl,"objectToString");function lT(t){let e={};return t.forEach(function(r,n){e[r]=!0}),e}o(lT,"arrayToHash");function dT(t,e,r,n,i){let s=[];for(let a=0,c=e.length;a<c;++a)tm(e,String(a))?s.push(ul(t,e,r,n,String(a),!0)):s.push("");return i.forEach(function(a){a.match(/^\d+$/)||s.push(ul(t,e,r,n,a,!0))}),s}o(dT,"formatArray");function cl(t){return"["+Error.prototype.toString.call(t)+"]"}o(cl,"formatError");function Ho(t,e,r){if(t.customInspect&&e&&ol(e.inspect)&&e.inspect!==Hr&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(r,t);return Xh(d)||(d=Ho(t,d,r)),d}let n=pT(t,e);if(n)return n;let i=Object.keys(e),s=lT(i);try{t.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(e))}catch{}if(al(e)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return cl(e);if(i.length===0){if(ol(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(sl(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Yh(e))return t.stylize(Date.prototype.toString.call(e),"date");if(al(e))return cl(e)}let a="",c=!1,u=["{","}"];if(Array.isArray(e)&&(c=!0,u=["[","]"]),ol(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),sl(e)&&(a=" "+RegExp.prototype.toString.call(e)),Yh(e)&&(a=" "+Date.prototype.toUTCString.call(e)),al(e)&&(a=" "+cl(e)),i.length===0&&(!c||e.length==0))return u[0]+a+u[1];if(r<0)return sl(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return c?l=dT(t,e,r,s,i):l=i.map(function(d){return ul(t,e,r,s,d,c)}),t.seen.pop(),fT(l,a,u)}o(Ho,"formatValue");function ul(t,e,r,n,i,s){let a,c,u;u={value:void 0};try{u.value=e[i]}catch{}try{Object.getOwnPropertyDescriptor&&(u=Object.getOwnPropertyDescriptor(e,i)||u)}catch{}if(u.get?u.set?c=t.stylize("[Getter/Setter]","special"):c=t.stylize("[Getter]","special"):u.set&&(c=t.stylize("[Setter]","special")),tm(n,i)||(a="["+i+"]"),c||(t.seen.indexOf(u.value)<0?(em(r)?c=Ho(t,u.value,null):c=Ho(t,u.value,r-1),c.indexOf(`
27
27
  `)>-1&&(s?c=c.split(`
28
28
  `).map(function(l){return" "+l}).join(`
@@ -32,7 +32,7 @@
32
32
  `))):c=t.stylize("[Circular]","special")),Zh(a)){if(s&&i.match(/^\d+$/))return c;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+c}o(ul,"formatProperty");function pT(t,e){if(Zh(e))return t.stylize("undefined","undefined");if(Xh(e)){let r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(uT(e))return t.stylize(""+e,"number");if(aT(e))return t.stylize(""+e,"boolean");if(em(e))return t.stylize("null","null")}o(pT,"formatPrimitive");function fT(t,e,r){let n=0;return t.reduce(function(s,a){return n++,a.indexOf(`
33
33
  `)>=0&&n++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(e===""?"":e+`
34
34
  `)+" "+t.join(`,
35
- `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}o(fT,"reduceToSingleString")});var nm=_($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.format=void 0;var hT=Qh(),mT=rm(),yT=o((t,...e)=>(0,hT.format)(mT.inspect,t,e),"format");$o.format=yT});var or=_(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.debug=ir.withoutEnv=ir.Debugger=void 0;var gT=Wh(),bT=nm(),jo=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,gT.generateColor)(r),this.last=0,this.enabled=e.enabled.some(n=>n.test(r))}log(...e){if(!this.enabled)return;let r,n=e[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,bT.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};ir.Debugger=jo;var Vo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function im(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(im,"extract");var Oi;function _T(t){t||(t=[]),typeof t=="string"&&(t=im(t)),Oi=new Vo(t)}o(_T,"withoutEnv");ir.withoutEnv=_T;function ET(t){let e=globalThis.DEBUG;Oi||(Oi=new Vo(im(e)));let r=new jo(Oi,t);return Oi.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(ET,"debug");ir.debug=ET});var Go=_(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ProblemResponseFormatter=hn.InternalProblemResponseFormatter=void 0;var wT=k(),Bo=class t{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(r,n,i)=>{try{return e(r,n,i)}catch(s){throw new wT.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};hn.InternalProblemResponseFormatter=Bo;var pl=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Bo.problemResponseFormat(e,r,n)}};hn.ProblemResponseFormatter=pl});var sm=_(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.deepFreeze=void 0;function om(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&om(r)}return Object.freeze(t)}o(om,"deepFreeze");Ko.deepFreeze=om});var Ke=_(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ZuploRequest=void 0;var am=sm(),fl=class t extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let i=r?.user;i?this.user=i:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())e[n]=i;this.#e=e}return(0,am.deepFreeze)(this.#e)}get params(){return(0,am.deepFreeze)(this.#t)}user};Jo.ZuploRequest=fl});var Ot=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.initializeRuntime=Ie.invokeOnResponseSendingFinalExtensions=Ie.invokeOnResponseSendingExtensions=Ie.invokeOnRequestExtensions=Ie.plugins=Ie.runtimeExtensions=Ie.SystemRuntimePlugin=Ie.RuntimePlugin=void 0;var cm=k(),vT=Go(),TT=Ke(),Wo=class{static{o(this,"RuntimePlugin")}};Ie.RuntimePlugin=Wo;var Qo=class extends Wo{static{o(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,r){}};Ie.SystemRuntimePlugin=Qo;Ie.runtimeExtensions={};var hl=[];Ie.plugins=hl;var um=[],lm=[],dm=[],zo={addPlugin(t){hl.push(t)},addRequestHook(t){um.push(t)},addResponseSendingHook(t){lm.push(t)},addResponseSendingFinalHook(t){dm.push(t)}},ST=o(async(t,e)=>{let r=t;for(let n of um){let i=await n(r,e);if(i instanceof TT.ZuploRequest)r=i;else{if(i instanceof Response)return i;throw new cm.ConfigurationError(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`)}}return r},"invokeOnRequestExtensions");Ie.invokeOnRequestExtensions=ST;var IT=o(async(t,e,r)=>{let n=t;for(let i of lm){let s=await i(t,e,r);if(s instanceof Response)n=s;else throw new cm.ConfigurationError(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof n}.`)}return n},"invokeOnResponseSendingExtensions");Ie.invokeOnResponseSendingExtensions=IT;var PT=o(async(t,e,r)=>{for(let n of dm)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");Ie.invokeOnResponseSendingFinalExtensions=PT;async function AT(t=()=>Promise.resolve()){await t(zo),Ie.runtimeExtensions.value=zo;for(let e of hl)e instanceof Qo&&await e.initialize(zo);vT.InternalProblemResponseFormatter.setProblemResponseFormat(zo.problemResponseFormat)}o(AT,"initializeRuntime");Ie.initializeRuntime=AT});var ml=_(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.serialize=sr.ContentTypes=void 0;sr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function RT(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(sr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(sr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(RT,"serialize");sr.serialize=RT});var yl=_(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.isSystemRoute=void 0;var pm=qr();function OT(t){return pm.Gateway.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(pm.Gateway.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}o(OT,"isSystemRoute");Yo.isSystemRoute=OT});var Gt=_(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Pipeline=void 0;var gl=$r(),fm=Ot(),NT=ml(),CT=ie(),xT=yl(),bl=class{static{o(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,r)=>async(n,i)=>{try{return await e(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=({processors:e,gateway:r,handler:n})=>async(i,s)=>{let a=[...e],c=o(async b=>{let I=a.pop();return I?I(i,s,r,c):await this.#e(async g=>{let v=await n(g,s);return LT(v)},r)(b,s)},"nextPipe"),l=await c(i),d=new URL(i.url);if((0,xT.isSystemRoute)(d)&&CT.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gl.ResponseSendingEvent(i,l);s.dispatchEvent(p);let f=gl.ZuploContextExtensions.getContextExtensions(s),h=f.latestRequest,y;try{y=await p.mutableResponse}catch(b){return s.log.error(b),r.errorHandler(i,s,b)}try{y=await f.onResponseSending(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}try{y=await(0,fm.invokeOnResponseSendingExtensions)(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}s.dispatchEvent(new gl.ResponseSentEvent(i,y));try{await f.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await(0,fm.invokeOnResponseSendingFinalExtensions)(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return y}};Zo.Pipeline=bl;function LT(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,NT.serialize)(t),{headers:{"content-type":"application/json"}})}o(LT,"resultToResponse")});var es=_(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.MetricsPlugin=void 0;var DT=Ot(),_l=class extends DT.RuntimePlugin{static{o(this,"MetricsPlugin")}};Xo.MetricsPlugin=_l});var Je=_(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.SystemLogMap=void 0;var MT=k(),El=class t{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new MT.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};ts.SystemLogMap=El});var Re=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.BatchDispatch=void 0;var wl=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i??console}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=e=>{this.#i.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};rs.BatchDispatch=wl});var mm=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.EllieMetricsTransport=void 0;var hm=Je(),UT=Re(),ns=ie(),vl=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=ns.Environment.instance.loggingId,this.#e=e,this.#t=new UT.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,hm.SystemLogMap.getLogger(e))}pushMetrics(e,r){this.#r!==void 0&&(this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=ns.Environment.instance,a=e.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":ns.Environment.instance.deploymentName??"unknown","user-agent":ns.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();hm.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};is.EllieMetricsTransport=vl});var gt=_(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.systemNoVersion=jr.SystemRouteConfiguration=void 0;var Tl=class{static{o(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.version=jr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};jr.SystemRouteConfiguration=Tl;jr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var ar=_(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.metricsProcessor=void 0;var ym=Fr(),kT=$r(),FT=Ot(),HT=es(),qT=mm(),$T=gt(),jT=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(ym.RAY_ID_HEADER)??void 0,u=t.headers.get(ym.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof $T.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=kT.ZuploContextExtensions.getContextExtensions(e).latestRequest,f={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new qT.EllieMetricsTransport(e)),FT.plugins.forEach(y=>{if(y instanceof HT.MetricsPlugin){let b=y.getTransport();h.push(b)}}),h.forEach(y=>{y.pushMetrics(f,e)}),a},"metricsProcessor");os.metricsProcessor=jT});var Sl=_(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.SystemRouteName=void 0;var gm;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.StripePlugin="stripe-plugin",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(gm||(ss.SystemRouteName=gm={}))});var _m=_(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0})});var Vr=_(cr=>{"use strict";var VT=cr&&cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Em=cr&&cr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&VT(e,t,r)};Object.defineProperty(cr,"__esModule",{value:!0});Em(Sl(),cr);Em(_m(),cr)});var wm=_(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.registerBuildRoute=void 0;var BT=Kt(),GT=Gt(),KT=ar(),JT=Vr(),zT=gt(),WT=Je(),QT=ie(),YT=o((t,e)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return BT.HttpProblems.notFound(s,a);let l=QT.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&WT.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new GT.Pipeline({processors:[KT.metricsProcessor],handler:r,gateway:e}),i=new zT.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:JT.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");as.registerBuildRoute=YT});var Il=_(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.HTTP_STATUS_TITLES=mn.HttpStatusCode=void 0;var vm;(function(t){t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.ALREADY_REPORTED=208]="ALREADY_REPORTED",t[t.IM_USED=226]="IM_USED",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.SWITCH_PROXY=306]="SWITCH_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",t[t.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",t[t.URI_TOO_LONG=414]="URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.TOO_EARLY=425]="TOO_EARLY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.LOOP_DETECTED=508]="LOOP_DETECTED",t[t.NOT_EXTENDED=510]="NOT_EXTENDED",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(vm||(mn.HttpStatusCode=vm={}));mn.HTTP_STATUS_TITLES={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"}});var Al=_(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var ZT={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};Pl.default=ZT});var de=_(yn=>{"use strict";var XT=yn&&yn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yn,"__esModule",{value:!0});yn.HttpProblems=void 0;var eS=Fr(),H=Il(),tS=XT(Al()),rS=ie(),Rl=Go();function nS(t){return`${new URL(t.url).pathname}`}o(nS,"instance");function iS(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:rS.Environment.instance.build.BUILD_ID},n=t.headers.get(eS.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(iS,"trace");var oS=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:nS(e),trace:iS(e,r),...n},additionalHeaders:i,statusText:tS.default[t.status]}),"merge"),Ol=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?Rl.ProblemResponseFormatter.format(e,r,n):Rl.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:H.HTTP_STATUS_TITLES[e],...r}}},Nl=class extends Ol{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=oS(this.getProblemFromStatus(e),r,n,i,s);return Rl.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(H.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(H.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(H.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(H.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(H.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(H.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(H.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(H.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(H.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(H.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(H.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(H.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(H.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(H.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(H.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(H.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(H.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(H.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(H.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(H.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(H.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};yn.HttpProblems=Nl});var at=_(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.isErrorLike=K.withUndefinedAsNull=K.withNullAsUndefined=K.validateConstraint=K.validateConstraints=K.areFunctions=K.isFunction=K.isEmptyObject=K.assertAllDefined=K.assertIsDefined=K.assertType=K.isUndefinedOrNull=K.isDefined=K.isUndefined=K.isBoolean=K.isIterable=K.isNumber=K.isTypedArray=K.isArray=K.isObject=K.getOwnEnumerableKeys=K.isRegexp=K.isStringArray=K.isNonEmptyString=K.isString=K.toString=void 0;var{toString:sS}=Object.prototype,{propertyIsEnumerable:aS}=Object.prototype;function Tm(t){return sS.call(t)}o(Tm,"toString");K.toString=Tm;function cs(t){return typeof t=="string"}o(cs,"isString");K.isString=cs;function cS(t){return cs(t)&&t!==""}o(cS,"isNonEmptyString");K.isNonEmptyString=cS;function uS(t){return Array.isArray(t)&&t.every(e=>cs(e))}o(uS,"isStringArray");K.isStringArray=uS;function lS(t){return Tm(t)==="[object RegExp]"}o(lS,"isRegexp");K.isRegexp=lS;function dS(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>aS.call(t,e))]}o(dS,"getOwnEnumerableKeys");K.getOwnEnumerableKeys=dS;function Cl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Cl,"isObject");K.isObject=Cl;function pS(t){return Cl(t)&&Array.isArray(t)}o(pS,"isArray");K.isArray=pS;function fS(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(fS,"isTypedArray");K.isTypedArray=fS;function hS(t){return typeof t=="number"&&!isNaN(t)}o(hS,"isNumber");K.isNumber=hS;function mS(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(mS,"isIterable");K.isIterable=mS;function yS(t){return t===!0||t===!1}o(yS,"isBoolean");K.isBoolean=yS;function Sm(t){return typeof t>"u"}o(Sm,"isUndefined");K.isUndefined=Sm;function gS(t){return!Ni(t)}o(gS,"isDefined");K.isDefined=gS;function Ni(t){return Sm(t)||t===null}o(Ni,"isUndefinedOrNull");K.isUndefinedOrNull=Ni;function bS(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o(bS,"assertType");K.assertType=bS;function _S(t){if(Ni(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(_S,"assertIsDefined");K.assertIsDefined=_S;function ES(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Ni(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(ES,"assertAllDefined");K.assertAllDefined=ES;var wS=Object.prototype.hasOwnProperty;function vS(t){if(!Cl(t))return!1;for(let e in t)if(wS.call(t,e))return!1;return!0}o(vS,"isEmptyObject");K.isEmptyObject=vS;function xl(t){return typeof t=="function"}o(xl,"isFunction");K.isFunction=xl;function TS(...t){return t.length>0&&t.every(xl)}o(TS,"areFunctions");K.areFunctions=TS;function SS(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)Im(t[n],e[n])}o(SS,"validateConstraints");K.validateConstraints=SS;function Im(t,e){if(cs(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(xl(e)){try{if(t instanceof e)return}catch{}if(!Ni(t)&&t.constructor===e||e.length===1&&e.call(void 0,t)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Im,"validateConstraint");K.validateConstraint=Im;function IS(t){return t===null?void 0:t}o(IS,"withNullAsUndefined");K.withNullAsUndefined=IS;function PS(t){return typeof t>"u"?null:t}o(PS,"withUndefinedAsNull");K.withUndefinedAsNull=PS;function AS(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(AS,"isErrorLike");K.isErrorLike=AS});var Jt=_(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.parseValueToBoolean=Nt.parseValueToStringArray=Nt.getValueFromRequestUser=Nt.statusCodesStringToNumberArray=void 0;var gn=k(),Ll=at(),Pm=new Map;function RS(t){if(Array.isArray(t)&&!t.some(i=>typeof i!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Pm.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return Pm.set(t,n),n}o(RS,"statusCodesStringToNumberArray");Nt.statusCodesStringToNumberArray=RS;function OS(t,e,r){if(!e.startsWith("."))throw new gn.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new gn.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(OS,"getValueFromRequestUser");Nt.getValueFromRequestUser=OS;function NS(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new gn.ConfigurationError("Received an array that contains non-string values.");return t}if((0,Ll.isString)(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new gn.ConfigurationError(`Expected type of string, received type '${typeof t}'`)}o(NS,"parseValueToStringArray");Nt.parseValueToStringArray=NS;function CS(t){if((0,Ll.isBoolean)(t))return t;if((0,Ll.isString)(t)){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1;throw new gn.ConfigurationError(`Attempted to parse string to boolean, but received ${t} which cannot be parsed.`)}throw new gn.ConfigurationError(`Expected type of boolean, received type '${typeof t}'`)}o(CS,"parseValueToBoolean");Nt.parseValueToBoolean=CS});var ls=_(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.generateCorsHeaders=ur.findMatchingOrigin=ur.parseCorsPolicies=void 0;var Br=k(),Am=Jt(),us=at();function xS(t){if(t==null)return[];if(!Array.isArray(t))throw new Br.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!(0,us.isObject)(r))throw new Br.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,us.isNonEmptyString)(r.name))throw new Br.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,us.isNumber)(r.maxAge))throw new Br.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,us.isBoolean)(r.allowCredentials))throw new Br.ConfigurationError("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Dl(r,"allowedHeaders"),i=Dl(r,"allowedMethods"),s=Dl(r,"exposeHeaders"),a;try{a=(0,Am.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Br.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(xS,"parseCorsPolicies");ur.parseCorsPolicies=xS;function Dl(t,e){let r;if(t[e]!==void 0)try{r=(0,Am.parseValueToStringArray)(t[e])}catch(n){throw new Br.ConfigurationError(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Dl,"parseOptionalProperty");var LS=o((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),i=e.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");ur.findMatchingOrigin=LS;var DS=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");ur.generateCorsHeaders=DS});var Om=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.registerCorsRoute=void 0;var MS=k(),US=Gt(),Ml=de(),kS=ar(),FS=Vr(),HS=gt(),Rm=ls(),qS=o((t,e)=>{let r=e.routeData.corsPolicies,n=o(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return Ml.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let f=t.lookup(l,u);if(!f)return Ml.HttpProblems.notFound(a,c);let h=f.routeConfiguration,y=$S(l,d,p,h,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&c.log.warn(y.error),Ml.HttpProblems.notFound(a,c))},"optionsHandler"),i=new US.Pipeline({processors:[kS.metricsProcessor],handler:n,gateway:e}),s=new HS.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:FS.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");ds.registerCorsRoute=qS;var $S=o((t,e,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new MS.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,Rm.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,Rm.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Nm=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.registerNoRoutes=void 0;var jS=Gt(),VS=ar(),BS=Vr(),GS=gt(),KS=o((t,e)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new jS.Pipeline({processors:[VS.metricsProcessor],handler:r,gateway:e}),i=new GS.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:BS.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");ps.registerNoRoutes=KS});var Cm=_(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.registerNotMatchedHandler=Gr.notFoundRouteConfiguration=void 0;var JS=$r(),zS=Ot(),WS=Gt(),QS=de(),YS=ar(),ZS=Vr(),XS=gt();Gr.notFoundRouteConfiguration=new XS.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:ZS.SystemRouteName.UnmatchedPath});var eI=o((t,e)=>{let r=o(async(i,s)=>{let a=zS.runtimeExtensions.value?.notFoundHandler;if(a){let c=JS.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return QS.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new WS.Pipeline({processors:[YS.metricsProcessor],handler:r,gateway:e});t.addRoute(Gr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Gr.registerNotMatchedHandler=eI});var Ul=_(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.corsProcessor=void 0;var Dm=k(),xm=ls(),tI=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Lm=o(t=>{tI.forEach(e=>t.delete(e))},"stripCorsHeaders"),rI=o(async(t,e,r,n)=>{let i=e.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(t),p=new Headers(d.headers);return Lm(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(t);if(!(s instanceof Response))throw new Dm.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=nI(i,r.routeData.corsPolicies),c=iI(t,a),u=new Headers(s.headers);return Lm(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");fs.corsProcessor=rI;var nI=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Dm.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),iI=o((t,e)=>{let r=(0,xm.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,xm.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var Mm=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.registerPingRoute=void 0;var oI=Gt(),sI=Ul(),aI=Vr(),cI=gt(),uI=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new oI.Pipeline({processors:[sI.corsProcessor],handler:r,gateway:e}),i=new cI.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:aI.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");hs.registerPingRoute=uI});var _n=_(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.OutboundPolicy=bn.InboundPolicy=void 0;var lI=k(),dI=at(),ms=class{static{o(this,"PolicyBase")}options;policyName;constructor(e,r){if(!(0,dI.isString)(r))throw new lI.RuntimeError(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r}},kl=class extends ms{static{o(this,"InboundPolicy")}};bn.InboundPolicy=kl;var Fl=class extends ms{static{o(this,"OutboundPolicy")}};bn.OutboundPolicy=Fl});var En=_(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.createInternalPolicyProcessor=bt.policyProcessor=bt.toStackedInboundHandler=bt.getInboundPolicyInstances=void 0;var pI=$r(),$e=k(),ys=_n(),Um=Ke(),fI=ie(),$l=class extends ys.InboundPolicy{static{o(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},jl=class extends ys.OutboundPolicy{static{o(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Hl=new Map;function km(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Hl.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof ys.InboundPolicy)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new $l(c,a.handler.options,a.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof u.handler}')`);Hl.set(a.name,u)}),r.map(s=>{let a=Hl.get(s);if(a===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return a})}o(km,"getInboundPolicyInstances");bt.getInboundPolicyInstances=km;var ql=new Map;function hI(t,e){let r=t.policies?.outbound??[];return r.filter(i=>!ql.has(i)).forEach(i=>{let s=e?.find(u=>u.name===i);if(!s)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],c;if(typeof a!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ys.OutboundPolicy)c=new a(s.handler.options??{},s.name);else if(typeof a=="function")c=new jl(a,s.handler.options??{},s.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof c.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);ql.set(s.name,c)}),r.map(i=>{let s=ql.get(i);if(s===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return s})}o(hI,"getOutboundPolicyInstances");var mI=o(t=>async(e,r)=>{let n=pI.ZuploContextExtensions.getContextExtensions(r),i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r);if(c instanceof Um.ZuploRequest)s=c;else if(c instanceof Request)s=new Um.ZuploRequest(c);else{if(c instanceof Response)return c;throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");bt.toStackedInboundHandler=mI;var yI=o(t=>async(e,r,n)=>{let i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n);if(!(c instanceof Response))throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),gI=o(async(t,e,r,n)=>{let i=km(e.route,r.routeData.policies),s=hI(e.route,r.routeData.policies);return Fm({request:t,context:e,inboundPolicies:i,outboundPolicies:s,gateway:r,next:n})},"policyProcessor");bt.policyProcessor=gI;function bI({inboundPolicies:t=[],outboundPolicies:e=[]}){return o(async(n,i,s,a)=>Fm({request:n,context:i,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}o(bI,"createInternalPolicyProcessor");bt.createInternalPolicyProcessor=bI;async function Fm({request:t,context:e,inboundPolicies:r,outboundPolicies:n,gateway:i,next:s}){let a=(0,bt.toStackedInboundHandler)(r);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await s(c),l=yI(n),d;return fI.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,t,e):d=u.ok?l(u,t,e):u,d}catch(c){return e.log.error(c),i.errorHandler(t,e,c)}}o(Fm,"executePolicyProcessor")});var Hm=_(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.serialize=wn.parse=void 0;var _I=Object.prototype.toString,gs=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function EI(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||vI,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s);if(c===-1)c=t.length;else if(c<a){s=t.lastIndexOf(";",a-1)+1;continue}let u=t.slice(s,a).trim();if(r[u]===void 0){let l=t.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=II(l,i)}s=c+1}return r}o(EI,"parse");wn.parse=EI;function wI(t,e,r){let n=r||{},i=n.encode||TI;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!gs.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!gs.test(s))throw new TypeError("argument val is invalid");let a=t+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!gs.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!gs.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!SI(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(wI,"serialize");wn.serialize=wI;function vI(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(vI,"decode");function TI(t){return encodeURIComponent(t)}o(TI,"encode");function SI(t){return _I.call(t)==="[object Date]"||t instanceof Date}o(SI,"isDate");function II(t,e){try{return e(t)}catch{return t}}o(II,"tryDecode")});var qm=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.devPortalBaseURL=void 0;var PI=Hm();function AI(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,PI.parse)(e.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:t}catch{}return t}o(AI,"devPortalBaseURL");bs.devPortalBaseURL=AI});var Gm=_(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.registerDevPortalLegacyRedirectRoute=vn.registerDevPortalV3Route=void 0;var Vl=Kt(),jm=Gt(),Vm=ar(),RI=En(),Bm=gt(),OI=qm(),lr=ie(),$m="/__zuplo/dev-portal",NI="dev-portal-id",CI="dev-portal-host",xI="zp-account",LI="zp-project",DI="dev-portal-build",MI=`
35
+ `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}o(fT,"reduceToSingleString")});var nm=_($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.format=void 0;var hT=Qh(),mT=rm(),yT=o((t,...e)=>(0,hT.format)(mT.inspect,t,e),"format");$o.format=yT});var or=_(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.debug=ir.withoutEnv=ir.Debugger=void 0;var gT=Wh(),bT=nm(),jo=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,gT.generateColor)(r),this.last=0,this.enabled=e.enabled.some(n=>n.test(r))}log(...e){if(!this.enabled)return;let r,n=e[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,bT.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};ir.Debugger=jo;var Vo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function im(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(im,"extract");var Oi;function _T(t){t||(t=[]),typeof t=="string"&&(t=im(t)),Oi=new Vo(t)}o(_T,"withoutEnv");ir.withoutEnv=_T;function ET(t){let e=globalThis.DEBUG;Oi||(Oi=new Vo(im(e)));let r=new jo(Oi,t);return Oi.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(ET,"debug");ir.debug=ET});var Go=_(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ProblemResponseFormatter=hn.InternalProblemResponseFormatter=void 0;var wT=k(),Bo=class t{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(e){e&&(t.problemResponseFormat=(r,n,i)=>{try{return e(r,n,i)}catch(s){throw new wT.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};hn.InternalProblemResponseFormatter=Bo;var pl=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await Bo.problemResponseFormat(e,r,n)}};hn.ProblemResponseFormatter=pl});var sm=_(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.deepFreeze=void 0;function om(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&om(r)}return Object.freeze(t)}o(om,"deepFreeze");Ko.deepFreeze=om});var Ke=_(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ZuploRequest=void 0;var am=sm(),fl=class t extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let i=r?.user;i?this.user=i:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())e[n]=i;this.#e=e}return(0,am.deepFreeze)(this.#e)}get params(){return(0,am.deepFreeze)(this.#t)}user};Jo.ZuploRequest=fl});var Ot=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.initializeRuntime=Ie.invokeOnResponseSendingFinalExtensions=Ie.invokeOnResponseSendingExtensions=Ie.invokeOnRequestExtensions=Ie.plugins=Ie.runtimeExtensions=Ie.SystemRuntimePlugin=Ie.RuntimePlugin=void 0;var cm=k(),vT=Go(),TT=Ke(),Wo=class{static{o(this,"RuntimePlugin")}};Ie.RuntimePlugin=Wo;var Qo=class extends Wo{static{o(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,r){}};Ie.SystemRuntimePlugin=Qo;Ie.runtimeExtensions={};var hl=[];Ie.plugins=hl;var um=[],lm=[],dm=[],zo={addPlugin(t){hl.push(t)},addRequestHook(t){um.push(t)},addResponseSendingHook(t){lm.push(t)},addResponseSendingFinalHook(t){dm.push(t)}},ST=o(async(t,e)=>{let r=t;for(let n of um){let i=await n(r,e);if(i instanceof TT.ZuploRequest)r=i;else{if(i instanceof Response)return i;throw new cm.ConfigurationError(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`)}}return r},"invokeOnRequestExtensions");Ie.invokeOnRequestExtensions=ST;var IT=o(async(t,e,r)=>{let n=t;for(let i of lm){let s=await i(t,e,r);if(s instanceof Response)n=s;else throw new cm.ConfigurationError(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof n}.`)}return n},"invokeOnResponseSendingExtensions");Ie.invokeOnResponseSendingExtensions=IT;var PT=o(async(t,e,r)=>{for(let n of dm)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");Ie.invokeOnResponseSendingFinalExtensions=PT;async function AT(t=()=>Promise.resolve()){await t(zo),Ie.runtimeExtensions.value=zo;for(let e of hl)e instanceof Qo&&await e.initialize(zo);vT.InternalProblemResponseFormatter.setProblemResponseFormat(zo.problemResponseFormat)}o(AT,"initializeRuntime");Ie.initializeRuntime=AT});var ml=_(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.serialize=sr.ContentTypes=void 0;sr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function RT(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(sr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(sr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(RT,"serialize");sr.serialize=RT});var yl=_(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.isSystemRoute=void 0;var pm=qr();function OT(t){return pm.Gateway.instance.runtimeSettings.developerPortal.enabled&&t.pathname.startsWith(pm.Gateway.instance.runtimeSettings.developerPortal.sitePathname)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}o(OT,"isSystemRoute");Yo.isSystemRoute=OT});var Gt=_(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Pipeline=void 0;var gl=$r(),fm=Ot(),NT=ml(),CT=re(),xT=yl(),bl=class{static{o(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,r)=>async(n,i)=>{try{return await e(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=({processors:e,gateway:r,handler:n})=>async(i,s)=>{let a=[...e],c=o(async b=>{let I=a.pop();return I?I(i,s,r,c):await this.#e(async g=>{let v=await n(g,s);return LT(v)},r)(b,s)},"nextPipe"),l=await c(i),d=new URL(i.url);if((0,xT.isSystemRoute)(d)&&CT.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new gl.ResponseSendingEvent(i,l);s.dispatchEvent(p);let f=gl.ZuploContextExtensions.getContextExtensions(s),h=f.latestRequest,y;try{y=await p.mutableResponse}catch(b){return s.log.error(b),r.errorHandler(i,s,b)}try{y=await f.onResponseSending(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}try{y=await(0,fm.invokeOnResponseSendingExtensions)(y,h,s)}catch(b){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${b.message}'`,b),r.errorHandler(i,s,b)}s.dispatchEvent(new gl.ResponseSentEvent(i,y));try{await f.onResponseSendingFinal(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}try{await(0,fm.invokeOnResponseSendingFinalExtensions)(l,h,s)}catch(b){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${b.message}'`,b),b}return y}};Zo.Pipeline=bl;function LT(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,NT.serialize)(t),{headers:{"content-type":"application/json"}})}o(LT,"resultToResponse")});var es=_(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.MetricsPlugin=void 0;var DT=Ot(),_l=class extends DT.RuntimePlugin{static{o(this,"MetricsPlugin")}};Xo.MetricsPlugin=_l});var Je=_(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.SystemLogMap=void 0;var MT=k(),El=class t{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(n),new MT.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};ts.SystemLogMap=El});var Re=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.BatchDispatch=void 0;var wl=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i??console}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=e=>{this.#i.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};rs.BatchDispatch=wl});var mm=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.EllieMetricsTransport=void 0;var hm=Je(),UT=Re(),ns=re(),vl=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=ns.Environment.instance.loggingId,this.#e=e,this.#t=new UT.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,hm.SystemLogMap.getLogger(e))}pushMetrics(e,r){this.#r!==void 0&&(this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=ns.Environment.instance,a=e.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":ns.Environment.instance.deploymentName??"unknown","user-agent":ns.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();hm.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};is.EllieMetricsTransport=vl});var gt=_(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.systemNoVersion=jr.SystemRouteConfiguration=void 0;var Tl=class{static{o(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.version=jr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};jr.SystemRouteConfiguration=Tl;jr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var ar=_(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.metricsProcessor=void 0;var ym=Fr(),kT=$r(),FT=Ot(),HT=es(),qT=mm(),$T=gt(),jT=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(ym.RAY_ID_HEADER)??void 0,u=t.headers.get(ym.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof $T.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=kT.ZuploContextExtensions.getContextExtensions(e).latestRequest,f={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:t.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new qT.EllieMetricsTransport(e)),FT.plugins.forEach(y=>{if(y instanceof HT.MetricsPlugin){let b=y.getTransport();h.push(b)}}),h.forEach(y=>{y.pushMetrics(f,e)}),a},"metricsProcessor");os.metricsProcessor=jT});var Sl=_(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.SystemRouteName=void 0;var gm;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.StripePlugin="stripe-plugin",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(gm||(ss.SystemRouteName=gm={}))});var _m=_(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0})});var Vr=_(cr=>{"use strict";var VT=cr&&cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Em=cr&&cr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&VT(e,t,r)};Object.defineProperty(cr,"__esModule",{value:!0});Em(Sl(),cr);Em(_m(),cr)});var wm=_(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.registerBuildRoute=void 0;var BT=Kt(),GT=Gt(),KT=ar(),JT=Vr(),zT=gt(),WT=Je(),QT=re(),YT=o((t,e)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return BT.HttpProblems.notFound(s,a);let l=QT.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&WT.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new GT.Pipeline({processors:[KT.metricsProcessor],handler:r,gateway:e}),i=new zT.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:JT.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");as.registerBuildRoute=YT});var Il=_(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.HTTP_STATUS_TITLES=mn.HttpStatusCode=void 0;var vm;(function(t){t[t.CONTINUE=100]="CONTINUE",t[t.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",t[t.PROCESSING=102]="PROCESSING",t[t.EARLY_HINTS=103]="EARLY_HINTS",t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.ACCEPTED=202]="ACCEPTED",t[t.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.RESET_CONTENT=205]="RESET_CONTENT",t[t.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",t[t.MULTI_STATUS=207]="MULTI_STATUS",t[t.ALREADY_REPORTED=208]="ALREADY_REPORTED",t[t.IM_USED=226]="IM_USED",t[t.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.FOUND=302]="FOUND",t[t.SEE_OTHER=303]="SEE_OTHER",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.USE_PROXY=305]="USE_PROXY",t[t.SWITCH_PROXY=306]="SWITCH_PROXY",t[t.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",t[t.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.UNAUTHORIZED=401]="UNAUTHORIZED",t[t.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",t[t.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",t[t.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",t[t.CONFLICT=409]="CONFLICT",t[t.GONE=410]="GONE",t[t.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",t[t.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",t[t.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",t[t.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",t[t.URI_TOO_LONG=414]="URI_TOO_LONG",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",t[t.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",t[t.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",t[t.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",t[t.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",t[t.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",t[t.LOCKED=423]="LOCKED",t[t.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",t[t.TOO_EARLY=425]="TOO_EARLY",t[t.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",t[t.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",t[t.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t[t.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",t[t.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",t[t.LOOP_DETECTED=508]="LOOP_DETECTED",t[t.NOT_EXTENDED=510]="NOT_EXTENDED",t[t.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(vm||(mn.HttpStatusCode=vm={}));mn.HTTP_STATUS_TITLES={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"}});var Al=_(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var ZT={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};Pl.default=ZT});var de=_(yn=>{"use strict";var XT=yn&&yn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yn,"__esModule",{value:!0});yn.HttpProblems=void 0;var eS=Fr(),H=Il(),tS=XT(Al()),rS=re(),Rl=Go();function nS(t){return`${new URL(t.url).pathname}`}o(nS,"instance");function iS(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:rS.Environment.instance.build.BUILD_ID},n=t.headers.get(eS.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(iS,"trace");var oS=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:nS(e),trace:iS(e,r),...n},additionalHeaders:i,statusText:tS.default[t.status]}),"merge"),Ol=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?Rl.ProblemResponseFormatter.format(e,r,n):Rl.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:H.HTTP_STATUS_TITLES[e],...r}}},Nl=class extends Ol{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=oS(this.getProblemFromStatus(e),r,n,i,s);return Rl.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(H.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(H.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(H.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(H.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(H.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(H.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(H.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(H.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(H.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(H.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(H.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(H.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(H.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(H.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(H.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(H.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(H.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(H.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(H.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(H.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(H.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(H.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(H.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(H.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(H.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(H.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(H.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(H.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(H.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(H.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(H.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(H.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(H.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(H.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(H.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};yn.HttpProblems=Nl});var at=_(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.isErrorLike=K.withUndefinedAsNull=K.withNullAsUndefined=K.validateConstraint=K.validateConstraints=K.areFunctions=K.isFunction=K.isEmptyObject=K.assertAllDefined=K.assertIsDefined=K.assertType=K.isUndefinedOrNull=K.isDefined=K.isUndefined=K.isBoolean=K.isIterable=K.isNumber=K.isTypedArray=K.isArray=K.isObject=K.getOwnEnumerableKeys=K.isRegexp=K.isStringArray=K.isNonEmptyString=K.isString=K.toString=void 0;var{toString:sS}=Object.prototype,{propertyIsEnumerable:aS}=Object.prototype;function Tm(t){return sS.call(t)}o(Tm,"toString");K.toString=Tm;function cs(t){return typeof t=="string"}o(cs,"isString");K.isString=cs;function cS(t){return cs(t)&&t!==""}o(cS,"isNonEmptyString");K.isNonEmptyString=cS;function uS(t){return Array.isArray(t)&&t.every(e=>cs(e))}o(uS,"isStringArray");K.isStringArray=uS;function lS(t){return Tm(t)==="[object RegExp]"}o(lS,"isRegexp");K.isRegexp=lS;function dS(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>aS.call(t,e))]}o(dS,"getOwnEnumerableKeys");K.getOwnEnumerableKeys=dS;function Cl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Cl,"isObject");K.isObject=Cl;function pS(t){return Cl(t)&&Array.isArray(t)}o(pS,"isArray");K.isArray=pS;function fS(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(fS,"isTypedArray");K.isTypedArray=fS;function hS(t){return typeof t=="number"&&!isNaN(t)}o(hS,"isNumber");K.isNumber=hS;function mS(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(mS,"isIterable");K.isIterable=mS;function yS(t){return t===!0||t===!1}o(yS,"isBoolean");K.isBoolean=yS;function Sm(t){return typeof t>"u"}o(Sm,"isUndefined");K.isUndefined=Sm;function gS(t){return!Ni(t)}o(gS,"isDefined");K.isDefined=gS;function Ni(t){return Sm(t)||t===null}o(Ni,"isUndefinedOrNull");K.isUndefinedOrNull=Ni;function bS(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o(bS,"assertType");K.assertType=bS;function _S(t){if(Ni(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(_S,"assertIsDefined");K.assertIsDefined=_S;function ES(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Ni(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(ES,"assertAllDefined");K.assertAllDefined=ES;var wS=Object.prototype.hasOwnProperty;function vS(t){if(!Cl(t))return!1;for(let e in t)if(wS.call(t,e))return!1;return!0}o(vS,"isEmptyObject");K.isEmptyObject=vS;function xl(t){return typeof t=="function"}o(xl,"isFunction");K.isFunction=xl;function TS(...t){return t.length>0&&t.every(xl)}o(TS,"areFunctions");K.areFunctions=TS;function SS(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)Im(t[n],e[n])}o(SS,"validateConstraints");K.validateConstraints=SS;function Im(t,e){if(cs(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(xl(e)){try{if(t instanceof e)return}catch{}if(!Ni(t)&&t.constructor===e||e.length===1&&e.call(void 0,t)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Im,"validateConstraint");K.validateConstraint=Im;function IS(t){return t===null?void 0:t}o(IS,"withNullAsUndefined");K.withNullAsUndefined=IS;function PS(t){return typeof t>"u"?null:t}o(PS,"withUndefinedAsNull");K.withUndefinedAsNull=PS;function AS(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(AS,"isErrorLike");K.isErrorLike=AS});var Jt=_(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.parseValueToBoolean=Nt.parseValueToStringArray=Nt.getValueFromRequestUser=Nt.statusCodesStringToNumberArray=void 0;var gn=k(),Ll=at(),Pm=new Map;function RS(t){if(Array.isArray(t)&&!t.some(i=>typeof i!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=Pm.get(t);if(e)return e;let r=t.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return Pm.set(t,n),n}o(RS,"statusCodesStringToNumberArray");Nt.statusCodesStringToNumberArray=RS;function OS(t,e,r){if(!e.startsWith("."))throw new gn.ConfigurationError(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),i=t;return n.forEach(s=>{if(i===void 0)throw new gn.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(OS,"getValueFromRequestUser");Nt.getValueFromRequestUser=OS;function NS(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new gn.ConfigurationError("Received an array that contains non-string values.");return t}if((0,Ll.isString)(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new gn.ConfigurationError(`Expected type of string, received type '${typeof t}'`)}o(NS,"parseValueToStringArray");Nt.parseValueToStringArray=NS;function CS(t){if((0,Ll.isBoolean)(t))return t;if((0,Ll.isString)(t)){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1;throw new gn.ConfigurationError(`Attempted to parse string to boolean, but received ${t} which cannot be parsed.`)}throw new gn.ConfigurationError(`Expected type of boolean, received type '${typeof t}'`)}o(CS,"parseValueToBoolean");Nt.parseValueToBoolean=CS});var ls=_(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.generateCorsHeaders=ur.findMatchingOrigin=ur.parseCorsPolicies=void 0;var Br=k(),Am=Jt(),us=at();function xS(t){if(t==null)return[];if(!Array.isArray(t))throw new Br.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!(0,us.isObject)(r))throw new Br.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,us.isNonEmptyString)(r.name))throw new Br.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,us.isNumber)(r.maxAge))throw new Br.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,us.isBoolean)(r.allowCredentials))throw new Br.ConfigurationError("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Dl(r,"allowedHeaders"),i=Dl(r,"allowedMethods"),s=Dl(r,"exposeHeaders"),a;try{a=(0,Am.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Br.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(xS,"parseCorsPolicies");ur.parseCorsPolicies=xS;function Dl(t,e){let r;if(t[e]!==void 0)try{r=(0,Am.parseValueToStringArray)(t[e])}catch(n){throw new Br.ConfigurationError(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Dl,"parseOptionalProperty");var LS=o((t,e)=>{if(e===null)return;if(t.find(a=>a==="*"))return e;let n=t.map(a=>a.trim().toLowerCase()),i=e.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");ur.findMatchingOrigin=LS;var DS=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");ur.generateCorsHeaders=DS});var Om=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.registerCorsRoute=void 0;var MS=k(),US=Gt(),Ml=de(),kS=ar(),FS=Vr(),HS=gt(),Rm=ls(),qS=o((t,e)=>{let r=e.routeData.corsPolicies,n=o(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return Ml.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let f=t.lookup(l,u);if(!f)return Ml.HttpProblems.notFound(a,c);let h=f.routeConfiguration,y=$S(l,d,p,h,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):(y.error&&c.log.warn(y.error),Ml.HttpProblems.notFound(a,c))},"optionsHandler"),i=new US.Pipeline({processors:[kS.metricsProcessor],handler:n,gateway:e}),s=new HS.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:FS.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");ds.registerCorsRoute=qS;var $S=o((t,e,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new MS.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,Rm.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,Rm.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Nm=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.registerNoRoutes=void 0;var jS=Gt(),VS=ar(),BS=Vr(),GS=gt(),KS=o((t,e)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new jS.Pipeline({processors:[VS.metricsProcessor],handler:r,gateway:e}),i=new GS.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:BS.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");ps.registerNoRoutes=KS});var Cm=_(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.registerNotMatchedHandler=Gr.notFoundRouteConfiguration=void 0;var JS=$r(),zS=Ot(),WS=Gt(),QS=de(),YS=ar(),ZS=Vr(),XS=gt();Gr.notFoundRouteConfiguration=new XS.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:ZS.SystemRouteName.UnmatchedPath});var eI=o((t,e)=>{let r=o(async(i,s)=>{let a=zS.runtimeExtensions.value?.notFoundHandler;if(a){let c=JS.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return QS.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new WS.Pipeline({processors:[YS.metricsProcessor],handler:r,gateway:e});t.addRoute(Gr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Gr.registerNotMatchedHandler=eI});var Ul=_(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.corsProcessor=void 0;var Dm=k(),xm=ls(),tI=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Lm=o(t=>{tI.forEach(e=>t.delete(e))},"stripCorsHeaders"),rI=o(async(t,e,r,n)=>{let i=e.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(t),p=new Headers(d.headers);return Lm(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(t);if(!(s instanceof Response))throw new Dm.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=nI(i,r.routeData.corsPolicies),c=iI(t,a),u=new Headers(s.headers);return Lm(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");fs.corsProcessor=rI;var nI=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Dm.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),iI=o((t,e)=>{let r=(0,xm.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,xm.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var Mm=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.registerPingRoute=void 0;var oI=Gt(),sI=Ul(),aI=Vr(),cI=gt(),uI=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new oI.Pipeline({processors:[sI.corsProcessor],handler:r,gateway:e}),i=new cI.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:aI.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");hs.registerPingRoute=uI});var _n=_(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.OutboundPolicy=bn.InboundPolicy=void 0;var lI=k(),dI=at(),ms=class{static{o(this,"PolicyBase")}options;policyName;constructor(e,r){if(!(0,dI.isString)(r))throw new lI.RuntimeError(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r}},kl=class extends ms{static{o(this,"InboundPolicy")}};bn.InboundPolicy=kl;var Fl=class extends ms{static{o(this,"OutboundPolicy")}};bn.OutboundPolicy=Fl});var En=_(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.createInternalPolicyProcessor=bt.policyProcessor=bt.toStackedInboundHandler=bt.getInboundPolicyInstances=void 0;var pI=$r(),$e=k(),ys=_n(),Um=Ke(),fI=re(),$l=class extends ys.InboundPolicy{static{o(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},jl=class extends ys.OutboundPolicy{static{o(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Hl=new Map;function km(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Hl.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof ys.InboundPolicy)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new $l(c,a.handler.options,a.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof u.handler}')`);Hl.set(a.name,u)}),r.map(s=>{let a=Hl.get(s);if(a===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return a})}o(km,"getInboundPolicyInstances");bt.getInboundPolicyInstances=km;var ql=new Map;function hI(t,e){let r=t.policies?.outbound??[];return r.filter(i=>!ql.has(i)).forEach(i=>{let s=e?.find(u=>u.name===i);if(!s)throw new $e.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],c;if(typeof a!="function")throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ys.OutboundPolicy)c=new a(s.handler.options??{},s.name);else if(typeof a=="function")c=new jl(a,s.handler.options??{},s.name);else throw new $e.ConfigurationError(`Invalid state - invalid policy '${i}' on route '${t.path}' (typeof policy '${typeof a}')`);if(typeof c.handler!="function")throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);ql.set(s.name,c)}),r.map(i=>{let s=ql.get(i);if(s===void 0)throw new $e.RuntimeError("Internal error. Policy not found in cache.");return s})}o(hI,"getOutboundPolicyInstances");var mI=o(t=>async(e,r)=>{let n=pI.ZuploContextExtensions.getContextExtensions(r),i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r);if(c instanceof Um.ZuploRequest)s=c;else if(c instanceof Request)s=new Um.ZuploRequest(c);else{if(c instanceof Response)return c;throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");bt.toStackedInboundHandler=mI;var yI=o(t=>async(e,r,n)=>{let i=[...t],s=e;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n);if(!(c instanceof Response))throw new $e.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),gI=o(async(t,e,r,n)=>{let i=km(e.route,r.routeData.policies),s=hI(e.route,r.routeData.policies);return Fm({request:t,context:e,inboundPolicies:i,outboundPolicies:s,gateway:r,next:n})},"policyProcessor");bt.policyProcessor=gI;function bI({inboundPolicies:t=[],outboundPolicies:e=[]}){return o(async(n,i,s,a)=>Fm({request:n,context:i,inboundPolicies:t,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}o(bI,"createInternalPolicyProcessor");bt.createInternalPolicyProcessor=bI;async function Fm({request:t,context:e,inboundPolicies:r,outboundPolicies:n,gateway:i,next:s}){let a=(0,bt.toStackedInboundHandler)(r);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await s(c),l=yI(n),d;return fI.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,t,e):d=u.ok?l(u,t,e):u,d}catch(c){return e.log.error(c),i.errorHandler(t,e,c)}}o(Fm,"executePolicyProcessor")});var Hm=_(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.serialize=wn.parse=void 0;var _I=Object.prototype.toString,gs=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function EI(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||vI,s=0;for(;s<t.length;){let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s);if(c===-1)c=t.length;else if(c<a){s=t.lastIndexOf(";",a-1)+1;continue}let u=t.slice(s,a).trim();if(r[u]===void 0){let l=t.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=II(l,i)}s=c+1}return r}o(EI,"parse");wn.parse=EI;function wI(t,e,r){let n=r||{},i=n.encode||TI;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!gs.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!gs.test(s))throw new TypeError("argument val is invalid");let a=t+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!gs.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!gs.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!SI(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(wI,"serialize");wn.serialize=wI;function vI(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(vI,"decode");function TI(t){return encodeURIComponent(t)}o(TI,"encode");function SI(t){return _I.call(t)==="[object Date]"||t instanceof Date}o(SI,"isDate");function II(t,e){try{return e(t)}catch{return t}}o(II,"tryDecode")});var qm=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.devPortalBaseURL=void 0;var PI=Hm();function AI(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,PI.parse)(e.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:t}catch{}return t}o(AI,"devPortalBaseURL");bs.devPortalBaseURL=AI});var Gm=_(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.registerDevPortalLegacyRedirectRoute=vn.registerDevPortalV3Route=void 0;var Vl=Kt(),jm=Gt(),Vm=ar(),RI=En(),Bm=gt(),OI=qm(),lr=re(),$m="/__zuplo/dev-portal",NI="dev-portal-id",CI="dev-portal-host",xI="zp-account",LI="zp-project",DI="dev-portal-build",MI=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -53,16 +53,16 @@
53
53
  `,pad:u,indent:u+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let f=o(h=>{if(c.inlineCharacterLimit===void 0)return h;let y=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return y.length<=c.inlineCharacterLimit?y:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
54
54
  `).replace(new RegExp(p.pad,"g"),u).replace(new RegExp(p.indent,"g"),u+d)},"expandWhiteSpace");if(n.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||(0,Zl.isRegexp)(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>i)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";n.push(a);let h="["+p.newline+a.map((y,b)=>{let I=a.length-1===b?p.newline:","+p.newlineOrSpace,A=s(y,c,u+d,l+1);return c.transform&&(A=c.transform(a,b,A)),p.indent+A+I}).join("")+p.pad+"]";return n.pop(),f(h)}if((0,Zl.isObject)(a)){let h=(0,Zl.getOwnEnumerableKeys)(a);if(c.filter&&(h=h.filter(b=>c.filter?.(a,b))),h.length===0)return"{}";n.push(a);let y="{"+p.newline+h.map((b,I)=>{let A=h.length-1===I?p.newline:","+p.newlineOrSpace,g=typeof b=="symbol",v=!g&&/^[a-z$_][$\w]*$/i.test(b),O=g||v?b:s(b,c,"",l+1),V=s(a[b],c,u+d,l+1);return c.transform&&(V=c.transform(a,b,V)),p.indent+String(O)+": "+V+A}).join("")+p.pad+"}";return n.pop(),f(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
55
55
  `?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,r,0)}o(WI,"stringifyObject");Xl.default=WI});var Ct=_(ze=>{"use strict";var QI=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ze,"__esModule",{value:!0});ze.stringifyNonStringToText=ze.stringifyNonString=ze.messagesToMultilineText=ze.extractBestMessage=ze.makeErrorsSerializable=void 0;var ed=Kr(),Zm=QI(Ym()),Xm=at();function YI(t){return t.map(e=>(0,ed.serializeError)(e))}o(YI,"makeErrorsSerializable");ze.makeErrorsSerializable=YI;function ZI(t){if(t.length===0)return"<no data provided to log>";let e=t[0];return typeof e=="string"?e:e instanceof Error?e.message:ey((0,ed.serializeError)(e))}o(ZI,"extractBestMessage");ze.extractBestMessage=ZI;function XI(t){let e=[];return t.forEach(r=>{if(typeof r=="string")e.push(r);else if((0,Xm.isErrorLike)(r))if(r.stack)e.push(r.stack);else{let n=(0,Zm.default)((0,ed.serializeError)(r));e.push(n)}else if(typeof r=="object"){let n=(0,Zm.default)(r);e.push(n)}else{let n=ty(r);e.push(n)}}),e.join(`
56
- `)}o(XI,"messagesToMultilineText");ze.messagesToMultilineText=XI;function ey(t){return typeof t=="string"?t:JSON.stringify(t)}o(ey,"stringifyNonString");ze.stringifyNonString=ey;function ty(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?(0,Xm.toString)(t):"unknown"}o(ty,"stringifyNonStringToText");ze.stringifyNonStringToText=ty});var G,me,xe=D(()=>{G=crypto,me=o(t=>t instanceof CryptoKey,"isCryptoKey")});var eP,Ts,td=D(()=>{xe();eP=o(async(t,e)=>{let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await G.subtle.digest(r,e))},"digest"),Ts=eP});function Le(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;return t.forEach(i=>{r.set(i,n),n+=i.length}),r}function ry(t,e){return Le(ae.encode(t),new Uint8Array([0]),e)}function rd(t,e,r){if(e<0||e>=Ss)throw new RangeError(`value must be >= 0 and <= ${Ss-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function Is(t){let e=Math.floor(t/Ss),r=t%Ss,n=new Uint8Array(8);return rd(n,e,0),rd(n,r,4),n}function Ps(t){let e=new Uint8Array(4);return rd(e,t),e}function As(t){return Le(Ps(t.length),t)}async function ny(t,e,r){let n=Math.ceil((e>>3)/32),i=new Uint8Array(n*32);for(let s=0;s<n;s++){let a=new Uint8Array(4+t.length+r.length);a.set(Ps(s+1)),a.set(t,4),a.set(r,4+t.length),i.set(await Ts("sha256",a),s*32)}return i.slice(0,e>>3)}var ae,ge,Ss,Pe=D(()=>{td();ae=new TextEncoder,ge=new TextDecoder,Ss=2**32;o(Le,"concat");o(ry,"p2s");o(rd,"writeUInt32BE");o(Is,"uint64be");o(Ps,"uint32be");o(As,"lengthAndInput");o(ny,"concatKdf")});var Rs,ce,nd,pe,De=D(()=>{Pe();Rs=o(t=>{let e=t;typeof e=="string"&&(e=ae.encode(e));let r=32768,n=[];for(let i=0;i<e.length;i+=r)n.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));return btoa(n.join(""))},"encodeBase64"),ce=o(t=>Rs(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),nd=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},"decodeBase64"),pe=o(t=>{let e=t;e instanceof Uint8Array&&(e=ge.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return nd(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var id={};Co(id,{JOSEAlgNotAllowed:()=>pr,JOSEError:()=>Te,JOSENotSupported:()=>J,JWEDecryptionFailed:()=>Wt,JWEInvalid:()=>F,JWKInvalid:()=>Ci,JWKSInvalid:()=>fr,JWKSMultipleMatchingKeys:()=>xi,JWKSNoMatchingKey:()=>Jr,JWKSTimeout:()=>Li,JWSInvalid:()=>ne,JWSSignatureVerificationFailed:()=>zr,JWTClaimValidationFailed:()=>Oe,JWTExpired:()=>Sn,JWTInvalid:()=>Ee});var Te,Oe,Sn,pr,J,Wt,F,ne,Ee,Ci,fr,Jr,xi,Li,zr,Y=D(()=>{Te=class extends Error{static{o(this,"JOSEError")}static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var r;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},Oe=class extends Te{static{o(this,"JWTClaimValidationFailed")}static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},Sn=class extends Te{static{o(this,"JWTExpired")}static get code(){return"ERR_JWT_EXPIRED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},pr=class extends Te{static{o(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},J=class extends Te{static{o(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Wt=class extends Te{static{o(this,"JWEDecryptionFailed")}constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},F=class extends Te{static{o(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},ne=class extends Te{static{o(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},Ee=class extends Te{static{o(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},Ci=class extends Te{static{o(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},fr=class extends Te{static{o(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Jr=class extends Te{static{o(this,"JWKSNoMatchingKey")}constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},xi=class extends Te{static{o(this,"JWKSMultipleMatchingKeys")}constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},Li=class extends Te{static{o(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},zr=class extends Te{static{o(this,"JWSSignatureVerificationFailed")}constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}});var hr,Di=D(()=>{xe();hr=G.getRandomValues.bind(G)});function od(t){switch(t){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new J(`Unsupported JWE Algorithm: ${t}`)}}var Os,Ns=D(()=>{Y();Di();o(od,"bitLength");Os=o(t=>hr(new Uint8Array(od(t)>>3)),"default")});var tP,Cs,sd=D(()=>{Y();Ns();tP=o((t,e)=>{if(e.length<<3!==od(t))throw new F("Invalid Initialization Vector length")},"checkIvLength"),Cs=tP});var rP,In,ad=D(()=>{Y();rP=o((t,e)=>{let r=t.byteLength<<3;if(r!==e)throw new F(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)},"checkCekLength"),In=rP});var nP,oy,sy=D(()=>{nP=o((t,e)=>{if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(t.length!==e.length)throw new TypeError("Input buffers must have the same length");let r=t.length,n=0,i=-1;for(;++i<r;)n|=t[i]^e[i];return n===0},"timingSafeEqual"),oy=nP});function Me(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function mr(t,e){return t.name===e}function xs(t){return parseInt(t.name.slice(4),10)}function iP(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ay(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function cy(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!mr(t.algorithm,"HMAC"))throw Me("HMAC");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!mr(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Me("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!mr(t.algorithm,"RSA-PSS"))throw Me("RSA-PSS");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Me("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!mr(t.algorithm,"ECDSA"))throw Me("ECDSA");let n=iP(e);if(t.algorithm.namedCurve!==n)throw Me(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ay(t,r)}function We(t,e,...r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!mr(t.algorithm,"AES-GCM"))throw Me("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Me(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!mr(t.algorithm,"AES-KW"))throw Me("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Me(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Me("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!mr(t.algorithm,"PBKDF2"))throw Me("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!mr(t.algorithm,"RSA-OAEP"))throw Me("RSA-OAEP");let n=parseInt(e.slice(9),10)||1;if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}ay(t,r)}var yr=D(()=>{o(Me,"unusable");o(mr,"isAlgorithm");o(xs,"getHashLength");o(iP,"getNamedCurve");o(ay,"checkUsage");o(cy,"checkSigCryptoKey");o(We,"checkEncCryptoKey")});function uy(t,e,...r){if(r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor&&e.constructor.name&&(t+=` Received an instance of ${e.constructor.name}`),t}function cd(t,e,...r){return uy(`Key for the ${t} algorithm must be `,e,...r)}var fe,_t=D(()=>{o(uy,"message");fe=o((t,...e)=>uy("Key must be ",t,...e),"default");o(cd,"withAlg")});var ud,oe,Et=D(()=>{xe();ud=o(t=>me(t),"default"),oe=["CryptoKey"]});async function oP(t,e,r,n,i,s){if(!(e instanceof Uint8Array))throw new TypeError(fe(e,"Uint8Array"));let a=parseInt(t.slice(1,4),10),c=await G.subtle.importKey("raw",e.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await G.subtle.importKey("raw",e.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Le(s,n,r,Is(s.length<<3)),d=new Uint8Array((await G.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=oy(i,d)}catch{}if(!p)throw new Wt;let f;try{f=new Uint8Array(await G.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!f)throw new Wt;return f}async function sP(t,e,r,n,i,s){let a;e instanceof Uint8Array?a=await G.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(We(e,t,"decrypt"),a=e);try{return new Uint8Array(await G.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},a,Le(r,i)))}catch{throw new Wt}}var aP,Ls,ld=D(()=>{Pe();sd();ad();sy();Y();xe();yr();_t();Et();o(oP,"cbcDecrypt");o(sP,"gcmDecrypt");aP=o(async(t,e,r,n,i,s)=>{if(!me(e)&&!(e instanceof Uint8Array))throw new TypeError(fe(e,...oe,"Uint8Array"));switch(Cs(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&In(e,parseInt(t.slice(-3),10)),oP(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&In(e,parseInt(t.slice(1,4),10)),sP(t,e,r,n,i,s);default:throw new J("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),Ls=aP});var ly,dy,dd=D(()=>{Y();ly=o(async()=>{throw new J('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},"inflate"),dy=o(async()=>{throw new J('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')},"deflate")});var cP,xt,Pn=D(()=>{cP=o((...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0},"isDisjoint"),xt=cP});function uP(t){return typeof t=="object"&&t!==null}function se(t){if(!uP(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var Qe=D(()=>{o(uP,"isObjectLike");o(se,"isObject")});var lP,An,pd=D(()=>{lP=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],An=lP});function py(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function fy(t,e,r){if(me(t))return We(t,e,r),t;if(t instanceof Uint8Array)return G.subtle.importKey("raw",t,"AES-KW",!0,[r]);throw new TypeError(fe(t,...oe,"Uint8Array"))}var Mi,Ui,Ds=D(()=>{pd();xe();yr();_t();Et();o(py,"checkKeySize");o(fy,"getCryptoKey");Mi=o(async(t,e,r)=>{let n=await fy(e,t,"wrapKey");py(n,t);let i=await G.subtle.importKey("raw",r,...An);return new Uint8Array(await G.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),Ui=o(async(t,e,r)=>{let n=await fy(e,t,"unwrapKey");py(n,t);let i=await G.subtle.unwrapKey("raw",r,n,"AES-KW",...An);return new Uint8Array(await G.subtle.exportKey("raw",i))},"unwrap")});async function Ms(t,e,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!me(t))throw new TypeError(fe(t,...oe));if(We(t,"ECDH"),!me(e))throw new TypeError(fe(e,...oe));We(e,"ECDH","deriveBits");let a=Le(As(ae.encode(r)),As(i),As(s),Ps(n)),c;t.algorithm.name==="X25519"?c=256:t.algorithm.name==="X448"?c=448:c=Math.ceil(parseInt(t.algorithm.namedCurve.substr(-3),10)/8)<<3;let u=new Uint8Array(await G.subtle.deriveBits({name:t.algorithm.name,public:t},e,c));return ny(u,n,a)}async function hy(t){if(!me(t))throw new TypeError(fe(t,...oe));return G.subtle.generateKey(t.algorithm,!0,["deriveBits"])}function Us(t){if(!me(t))throw new TypeError(fe(t,...oe));return["P-256","P-384","P-521"].includes(t.algorithm.namedCurve)||t.algorithm.name==="X25519"||t.algorithm.name==="X448"}var fd=D(()=>{Pe();xe();yr();_t();Et();o(Ms,"deriveKey");o(hy,"generateEpk");o(Us,"ecdhAllowed")});function hd(t){if(!(t instanceof Uint8Array)||t.length<8)throw new F("PBES2 Salt Input must be 8 or more octets")}var yy=D(()=>{Y();o(hd,"checkP2s")});function dP(t,e){if(t instanceof Uint8Array)return G.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]);if(me(t))return We(t,e,"deriveBits","deriveKey"),t;throw new TypeError(fe(t,...oe,"Uint8Array"))}async function gy(t,e,r,n){hd(t);let i=ry(e,t),s=parseInt(e.slice(13,16),10),a={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},c={length:s,name:"AES-KW"},u=await dP(n,e);if(u.usages.includes("deriveBits"))return new Uint8Array(await G.subtle.deriveBits(a,u,s));if(u.usages.includes("deriveKey"))return G.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var by,_y,md=D(()=>{Di();Pe();De();Ds();yy();xe();yr();_t();Et();o(dP,"getCryptoKey");o(gy,"deriveKey");by=o(async(t,e,r,n=2048,i=hr(new Uint8Array(16)))=>{let s=await gy(i,t,n,e);return{encryptedKey:await Mi(t.slice(-6),s,r),p2c:n,p2s:ce(i)}},"encrypt"),_y=o(async(t,e,r,n,i)=>{let s=await gy(i,t,n,e);return Ui(t.slice(-6),s,r)},"decrypt")});function Rn(t){switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new J(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var Ey=D(()=>{Y();o(Rn,"subtleRsaEs")});var Wr,ks=D(()=>{Wr=o((t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}},"default")});var wy,vy,yd=D(()=>{Ey();pd();xe();yr();ks();_t();Et();wy=o(async(t,e,r)=>{if(!me(e))throw new TypeError(fe(e,...oe));if(We(e,t,"encrypt","wrapKey"),Wr(t,e),e.usages.includes("encrypt"))return new Uint8Array(await G.subtle.encrypt(Rn(t),e,r));if(e.usages.includes("wrapKey")){let n=await G.subtle.importKey("raw",r,...An);return new Uint8Array(await G.subtle.wrapKey("raw",n,e,Rn(t)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),vy=o(async(t,e,r)=>{if(!me(e))throw new TypeError(fe(e,...oe));if(We(e,t,"decrypt","unwrapKey"),Wr(t,e),e.usages.includes("decrypt"))return new Uint8Array(await G.subtle.decrypt(Rn(t),e,r));if(e.usages.includes("unwrapKey")){let n=await G.subtle.unwrapKey("raw",r,e,Rn(t),...An);return new Uint8Array(await G.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function ki(t){switch(t){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new J(`Unsupported JWE Algorithm: ${t}`)}}var Lt,Fi=D(()=>{Y();Di();o(ki,"bitLength");Lt=o(t=>hr(new Uint8Array(ki(t)>>3)),"default")});var gd,Ty=D(()=>{gd=o((t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
56
+ `)}o(XI,"messagesToMultilineText");ze.messagesToMultilineText=XI;function ey(t){return typeof t=="string"?t:JSON.stringify(t)}o(ey,"stringifyNonString");ze.stringifyNonString=ey;function ty(t){return typeof t=="string"?t:t===null?"null":typeof t>"u"?"undefined":typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||typeof t=="symbol"?t.toString():typeof t=="function"?`[function ${t.name}]`:typeof t=="object"&&Array.isArray(t)?`[array ${t.length}]`:t instanceof Error?`${t.name??"Error"}: ${t.message??"unknown"}`:typeof t=="object"?(0,Xm.toString)(t):"unknown"}o(ty,"stringifyNonStringToText");ze.stringifyNonStringToText=ty});var G,me,xe=D(()=>{G=crypto,me=o(t=>t instanceof CryptoKey,"isCryptoKey")});var eP,Ts,td=D(()=>{xe();eP=o(async(t,e)=>{let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await G.subtle.digest(r,e))},"digest"),Ts=eP});function Le(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;return t.forEach(i=>{r.set(i,n),n+=i.length}),r}function ry(t,e){return Le(ae.encode(t),new Uint8Array([0]),e)}function rd(t,e,r){if(e<0||e>=Ss)throw new RangeError(`value must be >= 0 and <= ${Ss-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function Is(t){let e=Math.floor(t/Ss),r=t%Ss,n=new Uint8Array(8);return rd(n,e,0),rd(n,r,4),n}function Ps(t){let e=new Uint8Array(4);return rd(e,t),e}function As(t){return Le(Ps(t.length),t)}async function ny(t,e,r){let n=Math.ceil((e>>3)/32),i=new Uint8Array(n*32);for(let s=0;s<n;s++){let a=new Uint8Array(4+t.length+r.length);a.set(Ps(s+1)),a.set(t,4),a.set(r,4+t.length),i.set(await Ts("sha256",a),s*32)}return i.slice(0,e>>3)}var ae,ge,Ss,Pe=D(()=>{td();ae=new TextEncoder,ge=new TextDecoder,Ss=2**32;o(Le,"concat");o(ry,"p2s");o(rd,"writeUInt32BE");o(Is,"uint64be");o(Ps,"uint32be");o(As,"lengthAndInput");o(ny,"concatKdf")});var Rs,ce,nd,pe,De=D(()=>{Pe();Rs=o(t=>{let e=t;typeof e=="string"&&(e=ae.encode(e));let r=32768,n=[];for(let i=0;i<e.length;i+=r)n.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));return btoa(n.join(""))},"encodeBase64"),ce=o(t=>Rs(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),nd=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},"decodeBase64"),pe=o(t=>{let e=t;e instanceof Uint8Array&&(e=ge.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return nd(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var id={};Co(id,{JOSEAlgNotAllowed:()=>pr,JOSEError:()=>Te,JOSENotSupported:()=>J,JWEDecryptionFailed:()=>Wt,JWEInvalid:()=>F,JWKInvalid:()=>Ci,JWKSInvalid:()=>fr,JWKSMultipleMatchingKeys:()=>xi,JWKSNoMatchingKey:()=>Jr,JWKSTimeout:()=>Li,JWSInvalid:()=>ie,JWSSignatureVerificationFailed:()=>zr,JWTClaimValidationFailed:()=>Oe,JWTExpired:()=>Sn,JWTInvalid:()=>Ee});var Te,Oe,Sn,pr,J,Wt,F,ie,Ee,Ci,fr,Jr,xi,Li,zr,Y=D(()=>{Te=class extends Error{static{o(this,"JOSEError")}static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var r;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},Oe=class extends Te{static{o(this,"JWTClaimValidationFailed")}static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},Sn=class extends Te{static{o(this,"JWTExpired")}static get code(){return"ERR_JWT_EXPIRED"}constructor(e,r="unspecified",n="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},pr=class extends Te{static{o(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},J=class extends Te{static{o(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Wt=class extends Te{static{o(this,"JWEDecryptionFailed")}constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},F=class extends Te{static{o(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},ie=class extends Te{static{o(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},Ee=class extends Te{static{o(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},Ci=class extends Te{static{o(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},fr=class extends Te{static{o(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Jr=class extends Te{static{o(this,"JWKSNoMatchingKey")}constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},xi=class extends Te{static{o(this,"JWKSMultipleMatchingKeys")}constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},Li=class extends Te{static{o(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},zr=class extends Te{static{o(this,"JWSSignatureVerificationFailed")}constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}});var hr,Di=D(()=>{xe();hr=G.getRandomValues.bind(G)});function od(t){switch(t){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new J(`Unsupported JWE Algorithm: ${t}`)}}var Os,Ns=D(()=>{Y();Di();o(od,"bitLength");Os=o(t=>hr(new Uint8Array(od(t)>>3)),"default")});var tP,Cs,sd=D(()=>{Y();Ns();tP=o((t,e)=>{if(e.length<<3!==od(t))throw new F("Invalid Initialization Vector length")},"checkIvLength"),Cs=tP});var rP,In,ad=D(()=>{Y();rP=o((t,e)=>{let r=t.byteLength<<3;if(r!==e)throw new F(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)},"checkCekLength"),In=rP});var nP,oy,sy=D(()=>{nP=o((t,e)=>{if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(t.length!==e.length)throw new TypeError("Input buffers must have the same length");let r=t.length,n=0,i=-1;for(;++i<r;)n|=t[i]^e[i];return n===0},"timingSafeEqual"),oy=nP});function Me(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function mr(t,e){return t.name===e}function xs(t){return parseInt(t.name.slice(4),10)}function iP(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ay(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function cy(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!mr(t.algorithm,"HMAC"))throw Me("HMAC");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!mr(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Me("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!mr(t.algorithm,"RSA-PSS"))throw Me("RSA-PSS");let n=parseInt(e.slice(2),10);if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Me("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!mr(t.algorithm,"ECDSA"))throw Me("ECDSA");let n=iP(e);if(t.algorithm.namedCurve!==n)throw Me(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ay(t,r)}function We(t,e,...r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!mr(t.algorithm,"AES-GCM"))throw Me("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Me(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!mr(t.algorithm,"AES-KW"))throw Me("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Me(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Me("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!mr(t.algorithm,"PBKDF2"))throw Me("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!mr(t.algorithm,"RSA-OAEP"))throw Me("RSA-OAEP");let n=parseInt(e.slice(9),10)||1;if(xs(t.algorithm.hash)!==n)throw Me(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}ay(t,r)}var yr=D(()=>{o(Me,"unusable");o(mr,"isAlgorithm");o(xs,"getHashLength");o(iP,"getNamedCurve");o(ay,"checkUsage");o(cy,"checkSigCryptoKey");o(We,"checkEncCryptoKey")});function uy(t,e,...r){if(r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor&&e.constructor.name&&(t+=` Received an instance of ${e.constructor.name}`),t}function cd(t,e,...r){return uy(`Key for the ${t} algorithm must be `,e,...r)}var fe,_t=D(()=>{o(uy,"message");fe=o((t,...e)=>uy("Key must be ",t,...e),"default");o(cd,"withAlg")});var ud,oe,Et=D(()=>{xe();ud=o(t=>me(t),"default"),oe=["CryptoKey"]});async function oP(t,e,r,n,i,s){if(!(e instanceof Uint8Array))throw new TypeError(fe(e,"Uint8Array"));let a=parseInt(t.slice(1,4),10),c=await G.subtle.importKey("raw",e.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await G.subtle.importKey("raw",e.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Le(s,n,r,Is(s.length<<3)),d=new Uint8Array((await G.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=oy(i,d)}catch{}if(!p)throw new Wt;let f;try{f=new Uint8Array(await G.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!f)throw new Wt;return f}async function sP(t,e,r,n,i,s){let a;e instanceof Uint8Array?a=await G.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(We(e,t,"decrypt"),a=e);try{return new Uint8Array(await G.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},a,Le(r,i)))}catch{throw new Wt}}var aP,Ls,ld=D(()=>{Pe();sd();ad();sy();Y();xe();yr();_t();Et();o(oP,"cbcDecrypt");o(sP,"gcmDecrypt");aP=o(async(t,e,r,n,i,s)=>{if(!me(e)&&!(e instanceof Uint8Array))throw new TypeError(fe(e,...oe,"Uint8Array"));switch(Cs(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&In(e,parseInt(t.slice(-3),10)),oP(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&In(e,parseInt(t.slice(1,4),10)),sP(t,e,r,n,i,s);default:throw new J("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),Ls=aP});var ly,dy,dd=D(()=>{Y();ly=o(async()=>{throw new J('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},"inflate"),dy=o(async()=>{throw new J('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')},"deflate")});var cP,xt,Pn=D(()=>{cP=o((...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0},"isDisjoint"),xt=cP});function uP(t){return typeof t=="object"&&t!==null}function se(t){if(!uP(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var Qe=D(()=>{o(uP,"isObjectLike");o(se,"isObject")});var lP,An,pd=D(()=>{lP=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],An=lP});function py(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function fy(t,e,r){if(me(t))return We(t,e,r),t;if(t instanceof Uint8Array)return G.subtle.importKey("raw",t,"AES-KW",!0,[r]);throw new TypeError(fe(t,...oe,"Uint8Array"))}var Mi,Ui,Ds=D(()=>{pd();xe();yr();_t();Et();o(py,"checkKeySize");o(fy,"getCryptoKey");Mi=o(async(t,e,r)=>{let n=await fy(e,t,"wrapKey");py(n,t);let i=await G.subtle.importKey("raw",r,...An);return new Uint8Array(await G.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),Ui=o(async(t,e,r)=>{let n=await fy(e,t,"unwrapKey");py(n,t);let i=await G.subtle.unwrapKey("raw",r,n,"AES-KW",...An);return new Uint8Array(await G.subtle.exportKey("raw",i))},"unwrap")});async function Ms(t,e,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!me(t))throw new TypeError(fe(t,...oe));if(We(t,"ECDH"),!me(e))throw new TypeError(fe(e,...oe));We(e,"ECDH","deriveBits");let a=Le(As(ae.encode(r)),As(i),As(s),Ps(n)),c;t.algorithm.name==="X25519"?c=256:t.algorithm.name==="X448"?c=448:c=Math.ceil(parseInt(t.algorithm.namedCurve.substr(-3),10)/8)<<3;let u=new Uint8Array(await G.subtle.deriveBits({name:t.algorithm.name,public:t},e,c));return ny(u,n,a)}async function hy(t){if(!me(t))throw new TypeError(fe(t,...oe));return G.subtle.generateKey(t.algorithm,!0,["deriveBits"])}function Us(t){if(!me(t))throw new TypeError(fe(t,...oe));return["P-256","P-384","P-521"].includes(t.algorithm.namedCurve)||t.algorithm.name==="X25519"||t.algorithm.name==="X448"}var fd=D(()=>{Pe();xe();yr();_t();Et();o(Ms,"deriveKey");o(hy,"generateEpk");o(Us,"ecdhAllowed")});function hd(t){if(!(t instanceof Uint8Array)||t.length<8)throw new F("PBES2 Salt Input must be 8 or more octets")}var yy=D(()=>{Y();o(hd,"checkP2s")});function dP(t,e){if(t instanceof Uint8Array)return G.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]);if(me(t))return We(t,e,"deriveBits","deriveKey"),t;throw new TypeError(fe(t,...oe,"Uint8Array"))}async function gy(t,e,r,n){hd(t);let i=ry(e,t),s=parseInt(e.slice(13,16),10),a={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},c={length:s,name:"AES-KW"},u=await dP(n,e);if(u.usages.includes("deriveBits"))return new Uint8Array(await G.subtle.deriveBits(a,u,s));if(u.usages.includes("deriveKey"))return G.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var by,_y,md=D(()=>{Di();Pe();De();Ds();yy();xe();yr();_t();Et();o(dP,"getCryptoKey");o(gy,"deriveKey");by=o(async(t,e,r,n=2048,i=hr(new Uint8Array(16)))=>{let s=await gy(i,t,n,e);return{encryptedKey:await Mi(t.slice(-6),s,r),p2c:n,p2s:ce(i)}},"encrypt"),_y=o(async(t,e,r,n,i)=>{let s=await gy(i,t,n,e);return Ui(t.slice(-6),s,r)},"decrypt")});function Rn(t){switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new J(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var Ey=D(()=>{Y();o(Rn,"subtleRsaEs")});var Wr,ks=D(()=>{Wr=o((t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}},"default")});var wy,vy,yd=D(()=>{Ey();pd();xe();yr();ks();_t();Et();wy=o(async(t,e,r)=>{if(!me(e))throw new TypeError(fe(e,...oe));if(We(e,t,"encrypt","wrapKey"),Wr(t,e),e.usages.includes("encrypt"))return new Uint8Array(await G.subtle.encrypt(Rn(t),e,r));if(e.usages.includes("wrapKey")){let n=await G.subtle.importKey("raw",r,...An);return new Uint8Array(await G.subtle.wrapKey("raw",n,e,Rn(t)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),vy=o(async(t,e,r)=>{if(!me(e))throw new TypeError(fe(e,...oe));if(We(e,t,"decrypt","unwrapKey"),Wr(t,e),e.usages.includes("decrypt"))return new Uint8Array(await G.subtle.decrypt(Rn(t),e,r));if(e.usages.includes("unwrapKey")){let n=await G.subtle.unwrapKey("raw",r,e,Rn(t),...An);return new Uint8Array(await G.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function ki(t){switch(t){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new J(`Unsupported JWE Algorithm: ${t}`)}}var Lt,Fi=D(()=>{Y();Di();o(ki,"bitLength");Lt=o(t=>hr(new Uint8Array(ki(t)>>3)),"default")});var gd,Ty=D(()=>{gd=o((t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
57
57
  `);return`-----BEGIN ${e}-----
58
58
  ${r}
59
- -----END ${e}-----`},"default")});function Iy(t){let e=[],r=0;for(;r<t.length;){let n=Cy(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Cy(t){let e=0,r=t[0]&31;if(e++,r===31){for(r=0;t[e]>=128;)r=r*128+t[e]-128,e++;r=r*128+t[e]-128,e++}let n=0;if(t[e]<128)n=t[e],e++;else if(n===128){for(n=0;t[e+n]!==0||t[e+n+1]!==0;){if(n>t.byteLength)throw new TypeError("invalid indefinite form length");n++}let s=e+n+2;return{byteLength:s,contents:t.subarray(e,e+n),raw:t.subarray(0,s)}}else{let s=t[e]&127;e++,n=0;for(let a=0;a<s;a++)n=n*256+t[e],e++}let i=e+n;return{byteLength:i,contents:t.subarray(e,i),raw:t.subarray(0,i)}}function pP(t){let e=Iy(Iy(Cy(t).contents)[0].contents);return Rs(e[e[0].raw[0]===160?6:5].raw)}function fP(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=nd(e);return gd(pP(r),"PUBLIC KEY")}var Py,Ay,Ry,gr,Sy,Oy,Ny,bd,xy,Fs=D(()=>{xe();_t();De();Ty();Y();Et();Py=o(async(t,e,r)=>{if(!me(r))throw new TypeError(fe(r,...oe));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return gd(Rs(new Uint8Array(await G.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Ay=o(t=>Py("public","spki",t),"toSPKI"),Ry=o(t=>Py("private","pkcs8",t),"toPKCS8"),gr=o((t,e,r=0)=>{r===0&&(e.unshift(e.length),e.unshift(6));let n=t.indexOf(e[0],r);if(n===-1)return!1;let i=t.subarray(n,n+e.length);return i.length!==e.length?!1:i.every((s,a)=>s===e[a])||gr(t,e,n+1)},"findOid"),Sy=o(t=>{switch(!0){case gr(t,[42,134,72,206,61,3,1,7]):return"P-256";case gr(t,[43,129,4,0,34]):return"P-384";case gr(t,[43,129,4,0,35]):return"P-521";case gr(t,[43,101,110]):return"X25519";case gr(t,[43,101,111]):return"X448";case gr(t,[43,101,112]):return"Ed25519";case gr(t,[43,101,113]):return"Ed448";default:throw new J("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Oy=o(async(t,e,r,n,i)=>{var s;let a,c,u=new Uint8Array(atob(r.replace(t,"")).split("").map(d=>d.charCodeAt(0))),l=e==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=Sy(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:Sy(u)},c=l?["verify"]:["sign"];break;default:throw new J('Invalid or unsupported "alg" (Algorithm) value')}return G.subtle.importKey(e,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),Ny=o((t,e,r)=>Oy(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),bd=o((t,e,r)=>Oy(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");o(Iy,"getElement");o(Cy,"parseElement");o(pP,"spkiFromX509");o(fP,"getSPKI");xy=o((t,e,r)=>{let n;try{n=fP(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return bd(n,e,r)},"fromX509")});function hP(t){let e,r;switch(t.kty){case"oct":{switch(t.alg){case"HS256":case"HS384":case"HS512":e={name:"HMAC",hash:`SHA-${t.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new J(`${t.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":e={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":e={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":e={name:"PBKDF2"},r=["deriveBits"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new J('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var mP,_d,Ly=D(()=>{xe();Y();De();o(hP,"subtleMapping");mP=o(async t=>{var e,r;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=hP(t),s=[n,(e=t.ext)!==null&&e!==void 0?e:!1,(r=t.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return G.subtle.importKey("raw",pe(t.k),...s);let a={...t};return delete a.alg,delete a.use,G.subtle.importKey("jwk",a,...s)},"parse"),_d=mP});async function Dy(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return bd(t,e,r)}async function My(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return xy(t,e,r)}async function Uy(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ny(t,e,r)}async function br(t,e,r){var n;if(!se(t))throw new TypeError("JWK must be an object");switch(e||(e=t.alg),t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=t.ext!==!0),r?_d({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):pe(t.k);case"RSA":if(t.oth!==void 0)throw new J('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _d({...t,alg:e});default:throw new J('Unsupported "kty" (Key Type) Parameter value')}}var Hi=D(()=>{De();Fs();Ly();Y();Qe();o(Dy,"importSPKI");o(My,"importX509");o(Uy,"importPKCS8");o(br,"importJWK")});var yP,gP,bP,_r,qi=D(()=>{_t();Et();yP=o((t,e)=>{if(!(e instanceof Uint8Array)){if(!ud(e))throw new TypeError(cd(t,e,...oe,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${oe.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),gP=o((t,e,r)=>{if(!ud(e))throw new TypeError(cd(t,e,...oe));if(e.type==="secret")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),bP=o((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?yP(t,e):gP(t,e,r)},"checkKeyType"),_r=bP});async function _P(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(fe(r,"Uint8Array"));let s=parseInt(t.slice(1,4),10),a=await G.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await G.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await G.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Le(i,n,u,Is(i.length<<3)),d=new Uint8Array((await G.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function EP(t,e,r,n,i){let s;r instanceof Uint8Array?s=await G.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(We(r,t,"encrypt"),s=r);let a=new Uint8Array(await G.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var wP,$i,Ed=D(()=>{Pe();sd();ad();xe();yr();_t();Y();Et();o(_P,"cbcEncrypt");o(EP,"gcmEncrypt");wP=o(async(t,e,r,n,i)=>{if(!me(r)&&!(r instanceof Uint8Array))throw new TypeError(fe(r,...oe,"Uint8Array"));switch(Cs(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&In(r,parseInt(t.slice(-3),10)),_P(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&In(r,parseInt(t.slice(1,4),10)),EP(t,e,r,n,i);default:throw new J("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),$i=wP});async function ky(t,e,r,n){let i=t.slice(0,7);n||(n=Os(i));let{ciphertext:s,tag:a}=await $i(i,r,e,n,new Uint8Array(0));return{encryptedKey:s,iv:ce(n),tag:ce(a)}}async function Fy(t,e,r,n,i){let s=t.slice(0,7);return Ls(s,e,r,n,i,new Uint8Array(0))}var wd=D(()=>{Ed();ld();Ns();De();o(ky,"wrap");o(Fy,"unwrap")});async function vP(t,e,r,n,i){switch(_r(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new F("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new F("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!se(n.epk))throw new F('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Us(e))throw new J("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await br(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new F('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=pe(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new F('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=pe(n.apv)}let u=await Ms(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?ki(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new F("JWE Encrypted Key missing");return Ui(t.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new F("JWE Encrypted Key missing");return vy(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new F("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new F('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new F('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new F('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return _y(t,e,r,n.p2c,pe(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new F("JWE Encrypted Key missing");return Ui(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new F("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new F('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new F('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=pe(n.iv),a=pe(n.tag);return Fy(t,e,r,s,a)}default:throw new J('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Hy,qy=D(()=>{Ds();fd();md();yd();De();Y();Fi();Hi();qi();Qe();wd();o(vP,"decryptKeyManagement");Hy=vP});function TP(t,e,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let a of n.crit){if(!s.has(a))throw new J(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Dt,On=D(()=>{Y();o(TP,"validateCrit");Dt=TP});var SP,ji,vd=D(()=>{SP=o((t,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)},"validateAlgorithms"),ji=SP});async function Nn(t,e,r){var n;if(!se(t))throw new F("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new F("JOSE Header missing");if(typeof t.iv!="string")throw new F("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new F("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new F("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new F("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new F("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new F("JWE AAD incorrect type");if(t.header!==void 0&&!se(t.header))throw new F("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!se(t.unprotected))throw new F("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let v=pe(t.protected);i=JSON.parse(ge.decode(v))}catch{throw new F("JWE Protected Header is invalid")}if(!xt(i,t.header,t.unprotected))throw new F("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...t.header,...t.unprotected};if(Dt(F,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new J('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new F("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new F("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&ji("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&ji("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new pr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new pr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=pe(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let f;try{f=await Hy(a,e,d,s,r)}catch(v){if(v instanceof TypeError||v instanceof F||v instanceof J)throw v;f=Lt(c)}let h=pe(t.iv),y=pe(t.tag),b=ae.encode((n=t.protected)!==null&&n!==void 0?n:""),I;t.aad!==void 0?I=Le(b,ae.encode("."),ae.encode(t.aad)):I=b;let A=await Ls(c,f,pe(t.ciphertext),h,y,I);s.zip==="DEF"&&(A=await(r?.inflateRaw||ly)(A));let g={plaintext:A};return t.protected!==void 0&&(g.protectedHeader=i),t.aad!==void 0&&(g.additionalAuthenticatedData=pe(t.aad)),t.unprotected!==void 0&&(g.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(g.unprotectedHeader=t.header),p?{...g,key:e}:g}var Hs=D(()=>{De();ld();dd();Y();Pn();Qe();qy();Pe();Fi();On();vd();o(Nn,"flattenedDecrypt")});async function qs(t,e,r){if(t instanceof Uint8Array&&(t=ge.decode(t)),typeof t!="string")throw new F("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:a,4:c,length:u}=t.split(".");if(u!==5)throw new F("Invalid Compact JWE");let l=await Nn({ciphertext:a,iv:s||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},e,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...d,key:l.key}:d}var Td=D(()=>{Hs();Y();Pe();o(qs,"compactDecrypt")});async function $y(t,e,r){if(!se(t))throw new F("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(se))throw new F("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new F("JWE Recipients has no members");for(let n of t.recipients)try{return await Nn({aad:t.aad,ciphertext:t.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:t.iv,protected:t.protected,tag:t.tag,unprotected:t.unprotected},e,r)}catch{}throw new Wt}var jy=D(()=>{Hs();Y();Qe();o($y,"generalDecrypt")});var IP,Vy,By=D(()=>{xe();_t();De();Et();IP=o(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:ce(t)};if(!me(t))throw new TypeError(fe(t,...oe,"Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await G.subtle.exportKey("jwk",t);return s},"keyToJWK"),Vy=IP});async function Gy(t){return Ay(t)}async function Ky(t){return Ry(t)}async function $s(t){return Vy(t)}var Sd=D(()=>{Fs();Fs();By();o(Gy,"exportSPKI");o(Ky,"exportPKCS8");o($s,"exportJWK")});async function PP(t,e,r,n,i={}){let s,a,c;switch(_r(t,r,"encrypt"),t){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Us(r))throw new J("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await hy(r)).privateKey);let{x:p,y:f,crv:h,kty:y}=await $s(d),b=await Ms(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?ki(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:y}},y==="EC"&&(a.epk.y=f),u&&(a.apu=ce(u)),l&&(a.apv=ce(l)),t==="ECDH-ES"){c=b;break}c=n||Lt(e);let I=t.slice(-6);s=await Mi(I,b,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||Lt(e),s=await wy(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||Lt(e);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await by(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||Lt(e),s=await Mi(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||Lt(e);let{iv:u}=i;({encryptedKey:s,...a}=await ky(t,r,c,u));break}default:throw new J('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var js,Id=D(()=>{Ds();fd();md();yd();De();Fi();Y();Sd();qi();wd();o(PP,"encryptKeyManagement");js=PP});var Pd,Qt,Vs=D(()=>{De();Ed();dd();Ns();Id();Y();Pn();Pe();On();Pd=Symbol(),Qt=class{static{o(this,"FlattenedEncrypt")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new F("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!xt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Dt(F,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new J('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let y;({cek:c,encryptedKey:a,parameters:y}=await js(i,s,e,this._cek,this._keyManagementParameters)),y&&(r&&Pd in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...y}:this.setUnprotectedHeader(y):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...y}:this.setProtectedHeader(y))}this._iv||(this._iv=Os(s));let u,l,d;this._protectedHeader?l=ae.encode(ce(JSON.stringify(this._protectedHeader))):l=ae.encode(""),this._aad?(d=ce(this._aad),u=Le(l,ae.encode("."),ae.encode(d))):u=l;let p,f;if(n.zip==="DEF"){let y=await(r?.deflateRaw||dy)(this._plaintext);({ciphertext:p,tag:f}=await $i(s,y,c,this._iv,u))}else({ciphertext:p,tag:f}=await $i(s,this._plaintext,c,this._iv,u));let h={ciphertext:ce(p),iv:ce(this._iv),tag:ce(f)};return a&&(h.encrypted_key=ce(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ge.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var Ad,Bs,Jy=D(()=>{Vs();Y();Fi();Pn();Id();De();On();Ad=class{static{o(this,"IndividualRecipient")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}},Bs=class{static{o(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new Ad(this,e,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var r,n,i;if(!this._recipients.length)throw new F("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Qt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...e}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let s;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!xt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new F('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Dt(F,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=Lt(s),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let f={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let b=await new Qt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:f}).encrypt(l.key,{...l.options,...e,[Pd]:!0});c.ciphertext=b.ciphertext,c.iv=b.iv,c.tag=b.tag,b.aad&&(c.aad=b.aad),b.protected&&(c.protected=b.protected),b.unprotected&&(c.unprotected=b.unprotected),d.encrypted_key=b.encrypted_key,b.header&&(d.header=b.header);continue}let{encryptedKey:h,parameters:y}=await js(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),s,l.key,a,{p2c:f});d.encrypted_key=ce(h),(l.unprotectedHeader||y)&&(d.header={...l.unprotectedHeader,...y})}return c}}});function Vi(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new J(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var Rd=D(()=>{Y();o(Vi,"subtleDsa")});function Bi(t,e,r){if(me(e))return cy(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(fe(e,...oe));return G.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(fe(e,...oe,"Uint8Array"))}var Od=D(()=>{xe();yr();_t();Et();o(Bi,"getCryptoKey")});var AP,zy,Wy=D(()=>{Rd();xe();ks();Od();AP=o(async(t,e,r,n)=>{let i=await Bi(t,e,"verify");Wr(t,i);let s=Vi(t,i.algorithm);try{return await G.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),zy=AP});async function Cn(t,e,r){var n;if(!se(t))throw new ne("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new ne('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new ne("JWS Protected Header incorrect type");if(t.payload===void 0)throw new ne("JWS Payload missing");if(typeof t.signature!="string")throw new ne("JWS Signature missing or incorrect type");if(t.header!==void 0&&!se(t.header))throw new ne("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let I=pe(t.protected);i=JSON.parse(ge.decode(I))}catch{throw new ne("JWS Protected Header is invalid")}if(!xt(i,t.header))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...t.header},a=Dt(ne,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&ji("algorithms",r.algorithms);if(l&&!l.has(u))throw new pr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new ne("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new ne("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),_r(u,e,"verify");let p=Le(ae.encode((n=t.protected)!==null&&n!==void 0?n:""),ae.encode("."),typeof t.payload=="string"?ae.encode(t.payload):t.payload),f=pe(t.signature);if(!await zy(u,e,f,p))throw new zr;let y;c?y=pe(t.payload):typeof t.payload=="string"?y=ae.encode(t.payload):y=t.payload;let b={payload:y};return t.protected!==void 0&&(b.protectedHeader=i),t.header!==void 0&&(b.unprotectedHeader=t.header),d?{...b,key:e}:b}var Gs=D(()=>{De();Wy();Y();Pe();Pn();Qe();qi();On();vd();o(Cn,"flattenedVerify")});async function Ks(t,e,r){if(t instanceof Uint8Array&&(t=ge.decode(t)),typeof t!="string")throw new ne("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3)throw new ne("Invalid Compact JWS");let c=await Cn({payload:i,protected:n,signature:s},e,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...u,key:c.key}:u}var Nd=D(()=>{Gs();Y();Pe();o(Ks,"compactVerify")});async function Qy(t,e,r){if(!se(t))throw new ne("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(se))throw new ne("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await Cn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new zr}var Yy=D(()=>{Gs();Y();Qe();o(Qy,"generalVerify")});var xn,Cd=D(()=>{xn=o(t=>Math.floor(t.getTime()/1e3),"default")});var RP,Ln,xd=D(()=>{RP=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,Ln=o(t=>{let e=RP.exec(t);if(!e)throw new TypeError("Invalid time period format");let r=parseFloat(e[1]);switch(e[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var Zy,OP,Dn,Js=D(()=>{Y();Pe();Cd();xd();Qe();Zy=o(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),OP=o((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),Dn=o((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||Zy(t.typ)!==Zy(n)))throw new Oe('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ge.decode(e))}catch{}if(!se(i))throw new Ee("JWT Claims Set must be a top-level JSON object");let{requiredClaims:s=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&s.push("iat"),u!==void 0&&s.push("aud"),c!==void 0&&s.push("sub"),a!==void 0&&s.push("iss");for(let h of new Set(s.reverse()))if(!(h in i))throw new Oe(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new Oe('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new Oe('unexpected "sub" claim value',"sub","check_failed");if(u&&!OP(i.aud,typeof u=="string"?[u]:u))throw new Oe('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Ln(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=xn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new Oe('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new Oe('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>f+d)throw new Oe('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new Oe('"exp" claim must be a number',"exp","invalid");if(i.exp<=f-d)throw new Sn('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=f-i.iat,y=typeof l=="number"?l:Ln(l);if(h-d>y)throw new Sn('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new Oe('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function Xy(t,e,r){var n;let i=await Ks(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new Ee("JWTs MUST NOT use unencoded payload");let a={payload:Dn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var eg=D(()=>{Nd();Js();Y();o(Xy,"jwtVerify")});async function tg(t,e,r){let n=await qs(t,e,r),i=Dn(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Oe('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Oe('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Oe('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof e=="function"?{...a,key:n.key}:a}var rg=D(()=>{Td();Js();Y();o(tg,"jwtDecrypt")});var Mn,Ld=D(()=>{Vs();Mn=class{static{o(this,"CompactEncrypt")}constructor(e){this._flattened=new Qt(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this._flattened.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var NP,ng,ig=D(()=>{Rd();xe();ks();Od();NP=o(async(t,e,r)=>{let n=await Bi(t,e,"sign");Wr(t,n);let i=await G.subtle.sign(Vi(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),ng=NP});var Er,zs=D(()=>{De();ig();Pn();Y();Pe();qi();On();Er=class{static{o(this,"FlattenedSign")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ne("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!xt(this._protectedHeader,this._unprotectedHeader))throw new ne("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Dt(ne,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new ne('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new ne('JWS "alg" (Algorithm) Header Parameter missing or invalid');_r(a,e,"sign");let c=this._payload;s&&(c=ae.encode(ce(c)));let u;this._protectedHeader?u=ae.encode(ce(JSON.stringify(this._protectedHeader))):u=ae.encode("");let l=Le(u,ae.encode("."),c),d=await ng(a,e,l),p={signature:ce(d),payload:""};return s&&(p.payload=ge.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ge.decode(u)),p}}});var Un,Dd=D(()=>{zs();Un=class{static{o(this,"CompactSign")}constructor(e){this._flattened=new Er(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Md,Ws,og=D(()=>{zs();Y();Md=class{static{o(this,"IndividualSignature")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setProtectedHeader(e){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}},Ws=class{static{o(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new Md(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new ne("at least one signature must be added");let e={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new Er(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:s,...a}=await i.sign(n.key,n.options);if(r===0)e.payload=s;else if(e.payload!==s)throw new ne("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var wr,Qs=D(()=>{Cd();Qe();xd();wr=class{static{o(this,"ProduceJWT")}constructor(e){if(!se(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:e}:this._payload={...this._payload,nbf:xn(new Date)+Ln(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:xn(new Date)+Ln(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:xn(new Date)}:this._payload={...this._payload,iat:e},this}}});var Ys,sg=D(()=>{Dd();Y();Pe();Qs();Ys=class extends wr{static{o(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new Un(ae.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Ee("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var Zs,ag=D(()=>{Ld();Pe();Qs();Zs=class extends wr{static{o(this,"EncryptJWT")}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,r){let n=new Mn(ae.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(e,r)}}});async function Ud(t,e){if(!se(t))throw new TypeError("JWK must be an object");if(e??(e="sha256"),e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(t.kty){case"EC":vr(t.crv,'"crv" (Curve) Parameter'),vr(t.x,'"x" (X Coordinate) Parameter'),vr(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":vr(t.crv,'"crv" (Subtype of Key Pair) Parameter'),vr(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":vr(t.e,'"e" (Exponent) Parameter'),vr(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":vr(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new J('"kty" (Key Type) Parameter missing or unsupported')}let n=ae.encode(JSON.stringify(r));return ce(await Ts(e,n))}async function cg(t,e){e??(e="sha256");let r=await Ud(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var vr,ug=D(()=>{td();De();Y();Pe();Qe();vr=o((t,e)=>{if(typeof t!="string"||!t)throw new Ci(`${e} missing or invalid`)},"check");o(Ud,"calculateJwkThumbprint");o(cg,"calculateJwkThumbprintUri")});async function lg(t,e){let r={...t,...e?.header};if(!se(r.jwk))throw new ne('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await br({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new ne('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var dg=D(()=>{Hi();Qe();Y();o(lg,"EmbeddedJWK")});function CP(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new J('Unsupported "alg" value for a JSON Web Key Set')}}function kd(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(xP)}function xP(t){return se(t)}function LP(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function pg(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await br({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new fr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function fg(t){let e=new Gi(t);return async function(r,n){return e.getKey(r,n)}}var Gi,Fd=D(()=>{Hi();Y();Qe();o(CP,"getKtyFromAlg");o(kd,"isJWKSLike");o(xP,"isJWKLike");o(LP,"clone");Gi=class{static{o(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!kd(e))throw new fr("JSON Web Key Set malformed");this._jwks=LP(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=CP(n),a=this._jwks.keys.filter(l=>{let d=s===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Jr;if(u!==1){let l=new xi,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await pg(d,p,n)}catch{continue}},l}return pg(this._cached,c,n)}};o(pg,"importWithAlgCache");o(fg,"createLocalJWKSet")});var DP,hg,mg=D(()=>{Y();DP=o(async(t,e,r)=>{let n,i,s=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},e));let a=await fetch(t.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw s?new Li:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new Te("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new Te("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),hg=DP});function MP(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function yg(t,e){let r=new Hd(t,e);return async function(n,i){return r.getKey(n,i)}}var Hd,gg=D(()=>{mg();Y();Fd();o(MP,"isCloudflareWorkers");Hd=class extends Gi{static{o(this,"RemoteJWKSet")}constructor(e,r){if(super({keys:[]}),this._jwks=void 0,!(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}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,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(e,r)}catch(n){if(n instanceof Jr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&MP()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=hg(this._url,this._timeoutDuration,this._options).then(e=>{if(!kd(e))throw new fr("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}};o(yg,"createRemoteJWKSet")});var Xs,bg=D(()=>{De();Pe();Y();Js();Qs();Xs=class extends wr{static{o(this,"UnsecuredJWT")}encode(){let e=ce(JSON.stringify({alg:"none"})),r=ce(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new Ee("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3||s!=="")throw new Ee("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ge.decode(pe(n))),c.alg!=="none")throw new Error}catch{throw new Ee("Invalid Unsecured JWT")}return{payload:Dn(c,pe(i),r),header:c}}}});var qd={};Co(qd,{decode:()=>Ki,encode:()=>UP});var UP,Ki,ea=D(()=>{De();UP=ce,Ki=pe});function _g(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(ge.decode(Ki(e)));if(!se(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var Eg=D(()=>{ea();Pe();Qe();o(_g,"decodeProtectedHeader")});function wg(t){if(typeof t!="string")throw new Ee("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Ee("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Ee("Invalid JWT");if(!e)throw new Ee("JWTs must contain a payload");let n;try{n=Ki(e)}catch{throw new Ee("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ge.decode(n))}catch{throw new Ee("Failed to parse the decoded payload as JSON")}if(!se(i))throw new Ee("Invalid JWT Claims Set");return i}var vg=D(()=>{ea();Pe();Qe();Y();o(wg,"decodeJwt")});async function Tg(t,e){var r;let n,i,s;switch(t){case"HS256":case"HS384":case"HS512":n=parseInt(t.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},s=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(t.slice(-3),10),hr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(t.slice(1,4),10),i={name:"AES-KW",length:n},s=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(t.slice(1,4),10),i={name:"AES-GCM",length:n},s=["encrypt","decrypt"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return G.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,s)}function $d(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new J("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Sg(t,e){var r,n,i;let s,a;switch(t){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=e?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":s={name:c};break;default:throw new J("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=e?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{s={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":s={name:u};break;default:throw new J("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return G.subtle.generateKey(s,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var jd=D(()=>{xe();Y();Di();o(Tg,"generateSecret");o($d,"getModulusLengthOption");o(Sg,"generateKeyPair")});async function Ig(t,e){return Sg(t,e)}var Pg=D(()=>{jd();o(Ig,"generateKeyPair")});async function Ag(t,e){return Tg(t,e)}var Rg=D(()=>{jd();o(Ag,"generateSecret")});var ta={};Co(ta,{CompactEncrypt:()=>Mn,CompactSign:()=>Un,EmbeddedJWK:()=>lg,EncryptJWT:()=>Zs,FlattenedEncrypt:()=>Qt,FlattenedSign:()=>Er,GeneralEncrypt:()=>Bs,GeneralSign:()=>Ws,SignJWT:()=>Ys,UnsecuredJWT:()=>Xs,base64url:()=>qd,calculateJwkThumbprint:()=>Ud,calculateJwkThumbprintUri:()=>cg,compactDecrypt:()=>qs,compactVerify:()=>Ks,createLocalJWKSet:()=>fg,createRemoteJWKSet:()=>yg,decodeJwt:()=>wg,decodeProtectedHeader:()=>_g,errors:()=>id,exportJWK:()=>$s,exportPKCS8:()=>Ky,exportSPKI:()=>Gy,flattenedDecrypt:()=>Nn,flattenedVerify:()=>Cn,generalDecrypt:()=>$y,generalVerify:()=>Qy,generateKeyPair:()=>Ig,generateSecret:()=>Ag,importJWK:()=>br,importPKCS8:()=>Uy,importSPKI:()=>Dy,importX509:()=>My,jwtDecrypt:()=>tg,jwtVerify:()=>Xy});var ra=D(()=>{Td();Hs();jy();Jy();Nd();Gs();Yy();eg();rg();Ld();Vs();Dd();zs();og();sg();ag();ug();dg();Fd();gg();bg();Sd();Hi();Eg();vg();Y();Pg();Rg();ea()});var kn=_(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.fetchRetry=void 0;var kP=k();async function FP(t,e,r){for(let n=0;n<=t.retries;n++){let i=fetch(e,r);if(n===t.retries)return i;let s=await i;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,n)))}throw new kP.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(FP,"fetchRetry");na.fetchRetry=FP});var Fn=_(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.GcpServiceAccount=ct.fetchToken=ct.exchangeGgpJwtForIdToken=ct.exchangeFirebaseJwtForIdToken=ct.getTokenFromGcpServiceAccount=void 0;var Og=(ra(),xo(ta)),HP=k(),qP=kn();async function $P({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=t;return await new Og.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}o($P,"getTokenFromGcpServiceAccount");ct.getTokenFromGcpServiceAccount=$P;async function jP(t,e,r){return Bd(t,{token:e,returnSecureToken:!0},r)}o(jP,"exchangeFirebaseJwtForIdToken");ct.exchangeFirebaseJwtForIdToken=jP;async function VP(t,e,r){return Bd(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}o(VP,"exchangeGgpJwtForIdToken");ct.exchangeGgpJwtForIdToken=VP;async function Bd(t,e,r){let n=await(0,qP.fetchRetry)(r,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(n.status!==200){let s;try{let a=await n.text(),c=JSON.parse(a);s={cause:c.error??c}}catch{}throw new HP.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Bd,"fetchToken");ct.fetchToken=Bd;var Vd=class t{static{o(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:r}){this.#t=e,this.#e=r}static async init(e){let r=JSON.parse(e),n=await(0,Og.importPKCS8)(r.private_key.trim(),"RS256");return new t({serviceAccount:r,privateKey:n})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};ct.GcpServiceAccount=Vd});var oa=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.GoogleLogTransport=Yt.ZuploToGCPMap=Yt.GoogleCloudLoggingPlugin=void 0;var BP=k(),GP=Re(),Gd=ie(),Kd=Fn(),KP=zt(),Ng=Ct(),Jd=class extends KP.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ia(this.options)}};Yt.GoogleCloudLoggingPlugin=Jd;var JP="https://logging.googleapis.com/v2/entries:write?alt=json";Yt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var ia=class{static{o(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=Gd.Environment.instance.loggingEnvironmentType,this.#o=Gd.Environment.instance.loggingEnvironmentStage,this.#n=Gd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await Kd.GcpServiceAccount.init(this.#e)}log(e,r){if(!this.#t)throw new BP.SystemError("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n={allMessages:(0,Ng.makeErrorsSerializable)(e.messages)},i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:Yt.ZuploToGCPMap[e.level],timestamp:e.timestamp,trace:`projects/${i}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};e.rayId&&(s.labels.rayId=e.rayId);let a=(0,Ng.extractBestMessage)(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Kd.GcpServiceAccount.init(this.#e));let r=await(0,Kd.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(JP,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new GP.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Yt.GoogleLogTransport=ia});var zd=_(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.gcpLogFormat=Hn.GCP_LOG_FORMAT=void 0;var Cg=Ct(),zP=oa();Hn.GCP_LOG_FORMAT="gcp";function WP(t){let e={allMessages:(0,Cg.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Cg.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:zP.ZuploToGCPMap[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(i["logging.googleapis.com/labels"].rayId=t.rayId),i}o(WP,"gcpLogFormat");Hn.gcpLogFormat=WP});var Lg=_(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.ConsoleTransport=void 0;var xg=zd(),Wd=class{static{o(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;log(e){if(this.#t===xg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,xg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};sa.ConsoleTransport=Wd});var tp=_(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.DataDogTransport=qn.DataDogLoggingPlugin=void 0;var QP=Re(),Qd=ie(),YP=zt(),Dg=Ct(),ep=class extends YP.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new aa(this.options)}};qn.DataDogLoggingPlugin=ep;var Yd="__ddtags",Zd="__ddattr",Xd=o(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ZP=o(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(Xd(n)):r.push(`${Xd(n)}:${Xd(i.toString())}`)}),r.join(",")},"formatTags"),aa=class{static{o(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Qd.Environment.instance.loggingEnvironmentType,this.#i=Qd.Environment.instance.loggingEnvironmentStage,this.#r=Qd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n={},i=r.custom[Yd];i&&typeof i=="object"&&Object.assign(n,i);let s=[...e.messages],a=e.messages.findIndex(h=>h[Yd]!==void 0);a>-1&&(Object.assign(n,s[a][Yd]),s.splice(a,1));let c={},u=r.custom[Zd];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(h=>h[Zd]!==void 0);l>-1&&(Object.assign(c,s[l][Zd]),s.splice(l,1));let d=(0,Dg.makeErrorsSerializable)(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Dg.extractBestMessage)(d),service:e.loggingId,ddtags:ZP(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(f,c),this.batcher.enqueue(f),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new QP.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};qn.DataDogTransport=aa});var Ug=_(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.ProcessTransport=void 0;var Mg=zd(),rp=class{static{o(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===Mg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Mg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};ca.ProcessTransport=rp});var Fg=_(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.RemoteLogTransport=void 0;var XP=Re(),kg=ie(),eA=Ct(),tA=o(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;if(n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0)try{await fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,eA.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":kg.Environment.instance.systemUserAgent,"zp-dn":kg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),ua,np=class{static{o(this,"RemoteLogTransport")}constructor(e){ua||(ua=new XP.BatchDispatch("remote-log-transport",1,tA(e)))}log(e,r){ua.enqueue(e),r.waitUntil(ua.waitUntilFlushed())}};la.RemoteLogTransport=np});var Hg=_(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.unifiedFormatter=Qr.SeverityNumberOpenTelemetryMap=void 0;Qr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var rA=o((t,e)=>r=>{let n={};return n.deploymentName=t,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Qr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Qr.unifiedFormatter=rA});var $g=_(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.UnifiedLogTransport=void 0;var nA=Re(),qg=ie(),iA=Hg(),oA=o(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,iA.unifiedFormatter)(r,n);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":qg.Environment.instance.systemUserAgent,"zp-dn":qg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),da,ip=class{static{o(this,"UnifiedLogTransport")}constructor(e){da||(da=new nA.BatchDispatch("unified-log-transport",1,oA(e)))}async log(e,r){da.enqueue(e),r.waitUntil(da.waitUntilFlushed())}};pa.UnifiedLogTransport=ip});var zg=_(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.LogInitializer=void 0;var sA=or(),aA=Ot(),jg=Bl(),Vg=ie(),Bg=Km(),cA=zt(),uA=Jm(),Gg=zm(),Kg=Lg(),lA=tp(),dA=oa(),Jg=Ug(),pA=Fg(),fA=$g(),op=(0,sA.debug)("zuplo:logging"),sp=class t{static{o(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:r}){this.systemCoreLogger=e,this.userCoreLogger=r}static async init(e){let r=await t.setupSystemCoreLogger(Vg.Environment.instance,e),n=await t.setupUserCoreLogger(Vg.Environment.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;op("Gateway.setupSystemCoreLogger");let i=[],s=r.getService(jg.SYSTEM_LOGGER);return s?i.push(new Jg.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&i.push(new Kg.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new fA.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new Bg.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(e,r){op("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:s}=e,a=r.getService(jg.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new Jg.ProcessTransport(a.logger,e.logFormat)):e.isDeno&&n.push(new Kg.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new pA.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new dA.GoogleLogTransport({serviceAccountJson:i.GCP_USER_LOG_SVC_ACCT_JSON,logName:i.GCP_USER_LOG_NAME})),i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let c=i.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new lA.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return aA.plugins.forEach(c=>{c instanceof cA.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new Bg.CoreLogger(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,r,n,i,s){op("Gateway.createRequestLoggers");let a=new uA.LoggingContext(n,i,s),c=new Gg.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new Gg.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};fa.LogInitializer=sp});var cp=_(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.UserRouteConfiguration=void 0;var ap=class{static{o(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};ha.UserRouteConfiguration=ap});var lp=_(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.Router=Mt.RouterError=Mt.LookupResult=Mt.RouterEntry=void 0;var Wg=k(),hA=gt(),mA=cp(),ma=class{static{o(this,"RouterEntry")}constructor(e,r,n,i){this.fullPath=e,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};Mt.RouterEntry=ma;var Ji=class{static{o(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Mt.LookupResult=Ji;var ya=class extends Error{static{o(this,"RouterError")}constructor(e,r){super(e,r)}};Mt.RouterError=ya;var up=class{static{o(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof mA.UserRouteConfiguration||e instanceof hA.SystemRouteConfiguration))throw new Wg.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(s=>s.name===e.version)?.pathPrefix,i;"pathPattern"in e&&e.pathPattern?i=`${n??""}${e.pathPattern}`:i=`${n??""}${e.path}`;try{let s=new URLPattern({pathname:i}),a=new ma(i,s,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new ya(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(e,r){if(typeof e>"u")throw new Wg.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(e));if(n.length!==0)for(let i=0;i<n.length;i++){let s=n[i],c=s.urlPattern.exec({pathname:r});if(c!==null)return new Ji(s.config,s.executableHandler,c.pathname.groups)}}lookupByPathOnly(e){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:e});if(a!==null){let c=new Ji(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Mt.Router=up});var ga=_($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.getGlobalZuploEventContext=$n.setGlobalZuploEventContext=void 0;var dp;function yA(t){dp=t}o(yA,"setGlobalZuploEventContext");$n.setGlobalZuploEventContext=yA;function gA(){if(dp===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return dp}o(gA,"getGlobalZuploEventContext");$n.getGlobalZuploEventContext=gA});var Qg=_(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.normalizeIncomingRequestHeaders=void 0;var zi=Fr();function bA({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:r}){let n=new Headers(t);if(e){for(let[i]of t){let s=i.substring(0,3);zi.VENDOR_HEADER_PREFIXES.includes(s.toLowerCase())&&!zi.VENDOR_HEADERS_TO_ALLOW.includes(i.toLowerCase())&&n.delete(i)}n.delete(zi.X_REAL_IP_HEADER)}else zi.DISPATCH_HEADERS_TO_REMOVE.forEach(i=>{n.delete(i)});return r&&zi.INTERNAL_HEADERS_TO_REMOVE.forEach(i=>{n.delete(i)}),n}o(bA,"normalizeIncomingRequestHeaders");ba.normalizeIncomingRequestHeaders=bA});var qr=_(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.Gateway=void 0;var _A=or(),Yg=wm(),Zg=Om(),EA=Nm(),Xg=Cm(),eb=Mm(),Yr=Fr(),_a=$r(),tb=Gm(),kt=k(),Wi=Ot(),wA=zg(),vA=Gt(),TA=de(),SA=Ul(),IA=ar(),PA=En(),AA=Ke(),RA=lp(),pp=gt(),rb=cp(),OA=Je(),NA=ls(),Ea=ie(),CA=ga(),xA=Qg(),nb=Kr(),ib=yl(),Ut=(0,_A.debug)("zuplo:runtime"),LA=o(t=>{let e=t.findIndex(r=>r.name===pp.systemNoVersion.name);return e>-1?[...t.splice(e),pp.systemNoVersion]:[...t,pp.systemNoVersion]},"setupSystemNoVersion"),fp=class t{static{o(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(e,r,n,i){this.routeData=e,this.runtimeSettings=r,this.schemaValidator=i,Ut("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(e,r,n,i,s){if(Ut("Gateway.initialize"),!t.#e){await(0,Wi.initializeRuntime)(s);let a=await wA.LogInitializer.init(n),c=e(),u={...c,corsPolicies:(0,NA.parseCorsPolicies)(c.corsPolicies)},l=new t(u,r,a,i);t.#e=l}return t.#e}static purgeGatewayCache(){Ut("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new kt.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[PA.policyProcessor,SA.corsProcessor,IA.metricsProcessor];#i;setupRoutes=()=>{Ut("Gateway.setupRoutes");let e=this.routeData,r=LA(e.versions),n=new RA.Router(r);if(e.routes.length===0)return(0,Yg.registerBuildRoute)(n,this),(0,eb.registerPingRoute)(n,this),(0,Zg.registerCorsRoute)(n,this),(0,EA.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,tb.registerDevPortalLegacyRedirectRoute)(n,this),(0,tb.registerDevPortalV3Route)(n,this)),(0,Yg.registerBuildRoute)(n,this),(0,eb.registerPingRoute)(n,this),(0,Zg.registerCorsRoute)(n,this);for(let s of Wi.plugins)s instanceof Wi.SystemRuntimePlugin&&s.registerRoutes(n,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new kt.ConfigurationError(`Invalid state - No handler on route for path '${s.path}'`);let c=new vA.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new rb.UserRouteConfiguration(s);n.addRoute(u,c.execute)}),(0,Xg.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new kt.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=o((r,n,i)=>this.#o(r,n,i),"errorHandler");return e};errorHandler(e,r,n){try{return this.#i(e,r,n)}catch(i){return Ut("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){Ut("Gateway.internalErrorResponse");let i={};if(Ea.Environment.instance.isDeno){if(n instanceof kt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,nb.serializeError)(n.cause);"stack"in s&&(s.stack=(0,nb.cleanStack)(s.stack)),i={cause:s}}}return TA.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}async handleRequest(e,r){(0,CA.setGlobalZuploEventContext)(r);let n=e.headers.get(Yr.REQUEST_ID_HEADER)??e.headers.get(Yr.LEGACY_REQUEST_ID_HEADER),i=e.headers.get(Yr.RAY_ID_HEADER),s=(0,xA.normalizeIncomingRequestHeaders)({headers:e.headers,removeAllVendorHeadersExceptListed:Ea.Environment.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:Ea.Environment.instance.isDeno});n||(n=crypto.randomUUID(),s.set(Yr.REQUEST_ID_HEADER,n));let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let A=new Headers(a.headers);A.set(Yr.BODY_REMOVED_HEADER,"true"),a=new Request(a,{headers:A,body:null})}let c={},{userRequestLogger:u,systemRequestLogger:l}=this.#t.createRequestLoggers(n,i,r,c,a),d=new URL(a.url),p=d.pathname,f=this.#r.lookup(a.method,p);if(!f)throw new kt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let h=new _a.HeaderIncomingRequestProperties(e.headers),y=new AA.ZuploRequest(a,{params:f.params}),b=new _a.SystemZuploContext({logger:u,route:f.routeConfiguration,requestId:n,event:r,custom:c,incomingRequestProperties:h}),I=_a.ZuploContextExtensions.initialize(b,y);if(f.routeConfiguration===Xg.notFoundRouteConfiguration&&Wi.runtimeExtensions.value?.notFoundHandler!==void 0){let A=this.#r.lookupByPathOnly(p);I.pathOnlyMatches=A.map(g=>g.routeConfiguration).filter(g=>g instanceof rb.UserRouteConfiguration)}try{if(OA.SystemLogMap.addLogger(b,l),Ea.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,ib.isSystemRoute)(d):!d.pathname.startsWith("/__zuplo")){let v=await(0,Wi.invokeOnRequestExtensions)(y,b);if(v instanceof Response)return v;{let O=_a.ZuploContextExtensions.getContextExtensions(b);y=v,O.latestRequest=y}}(0,ib.isSystemRoute)(d)||u.debug(`Request received '${d.pathname}'`,{method:a.method,url:d.pathname,hostname:d.hostname,route:f.routeConfiguration.path});let A=f.executableHandler;DA(A,f,a),Ut("Gateway.handleRequest - call user handler");let g=await A(y,b);if(Ut("Gateway.handleRequest - user handler"),!(g instanceof Response))throw new kt.RuntimeError(`Invalid Response type from the request handler: ${typeof g}`);if(g.bodyUsed)throw new kt.RuntimeError("The response object has already been used. Return a new response instead.");if(g.headers.get(Yr.REQUEST_ID_HEADER)===null&&!g.webSocket){let v=new Headers(g.headers);return v.set(Yr.REQUEST_ID_HEADER,n),new Response(g.body,{status:g.status,statusText:g.statusText,headers:v,cf:g.cf})}else return g}catch(A){return Ut("Gateway - error executing handler",A),A instanceof kt.RuntimeError?(u.error(A),l.warn(A)):l.error(A),await this.#o(y,b,A)}}};wa.Gateway=fp;function DA(t,e,r){if(Ut("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new kt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new kt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}o(DA,"checkHandler")});var ob=_(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.invokeInboundPolicy=void 0;var MA=k(),UA=qr(),kA=En(),FA=o(async(t,e,r)=>{let n=UA.Gateway.instance.routeData.policies,i=(0,kA.getInboundPolicyInstances)([t],n);if(i.length===0)throw new MA.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return i[0].handler(e,r)},"invokeInboundPolicy");va.invokeInboundPolicy=FA});var $r=_(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.SystemZuploContext=ut.ZuploContextExtensions=ut.ResponseSentEvent=ut.ResponseSendingEvent=ut.HeaderIncomingRequestProperties=void 0;var be=Fr(),HA=k(),qA=ob(),hp=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(be.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(be.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(be.CF_IP_CITY_HEADER)??this.#e.get(be.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(be.CF_IP_CONTINENT_HEADER)??this.#e.get(be.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(be.CF_IP_COUNTRY_HEADER)??this.#e.get(be.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(be.CF_IP_LATITUDE_HEADER)??this.#e.get(be.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(be.CF_IP_LONGITUDE_HEADER)??this.#e.get(be.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(be.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(be.CF_POSTAL_CODE_HEADER)??this.#e.get(be.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(be.CF_METRO_CODE_HEADER)??this.#e.get(be.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(be.CF_IP_REGION_HEADER)??this.#e.get(be.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(be.CF_REGION_CODE_HEADER)??this.#e.get(be.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(be.CF_TIMEZONE_HEADER)??this.#e.get(be.ZP_TIMEZONE_HEADER)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}};ut.HeaderIncomingRequestProperties=hp;var mp=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};ut.ResponseSendingEvent=mp;var yp=class extends Event{static{o(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};ut.ResponseSentEvent=yp;var Qi=class t{static{o(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let n=new t(r);return t.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new HA.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,r,n)=>{for(let i of this.#t)await i(e,r,n)};onResponseSending=async(e,r,n)=>{let i=e;for(let s of this.#r)i=await s(e,r,n);return i}};ut.ZuploContextExtensions=Qi;var gp=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,event:i,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,qA.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Qi.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Qi.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,n){let i=o(s=>{try{typeof r=="function"?r(s):r.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,i,n)}};ut.SystemZuploContext=gp});var _p=_(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ContextData=void 0;var bp=class t{static{o(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let i=t.#e.get(e);i||(i=new Map),i.set(r,n),t.#e.set(e,i)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};Ta.ContextData=bp});var Yi=_(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.environment=Tr.isZuploReadableEnvVariableName=Tr.isRestrictedEnvVariableName=void 0;var $A=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function sb(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!$A.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}o(sb,"isRestrictedEnvVariableName");Tr.isRestrictedEnvVariableName=sb;function ab(t){return!!t.startsWith("ZUPLO_")}o(ab,"isZuploReadableEnvVariableName");Tr.isZuploReadableEnvVariableName=ab;var jA=new Proxy({},{get(t,e){if(sb(String(e))&&!ab(String(e)))return;let r=globalThis,n;return r.process?n=r.process.env[e]:n=r[e],n}});Tr.environment=jA});var Ep=_(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.externalServiceHandler=jn.externalServiceTunnelConfig=void 0;var VA=or(),Zr=k(),BA=wp(),Zi=ie(),wt=(0,VA.debug)("zuplo:runtime:external-service");function ub(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=Zi.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}o(ub,"getServiceAuth");async function GA(t){let e=ub();if(!e)throw wt("There is no external service auth configured for this zup."),new Zr.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw wt("Cannot call external service with Request object"),new Zr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(t).hostname,i={};i["CF-Access-Client-Id"]=e.clientId,i["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[n])s=`https://${e.customServiceMapping[n]}`;else if(Zi.Environment.instance.useSha256ServiceRouting){wt("Using sha256 service routing");let a=Zi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await lb(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw wt("Cannot use sha256 service routing, missing build variables"),new Zr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(GA,"externalServiceTunnelConfig");jn.externalServiceTunnelConfig=GA;async function KA(t,e){let r=ub();if(r)if(wt(`Using external service auth. ClientId: ${r.clientId})`),typeof t=="string"){let n=new URL(t),i=n.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),s.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(Zi.Environment.instance.useSha256ServiceRouting){wt("Using sha256 service routing");let d=Zi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await lb(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw wt("Cannot use sha256 service routing, missing build variables"),new Zr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);wt(`Calling external service: ${u.toString()}`);let l=await(0,BA.originalFetch)(u.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new Zr.RuntimeError("Could not connect to secure tunnel.");return l}else throw wt("Cannot call external service with Request object"),new Zr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw wt("There is no external service auth configured for this zup."),new Zr.RuntimeError("There are no external services configured for this zup.")}o(KA,"externalServiceHandler");jn.externalServiceHandler=KA;async function lb(t,e,r,n){let i=t.toLowerCase(),s=e.toLowerCase(),a=r.toLowerCase(),c=JA(n);wt(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await cb(`${s}-${i}`),l=await cb(`${s}-${a}-${c}`);return`${u}.${l}`}o(lb,"hashServiceName");async function cb(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}o(cb,"hashSegment");function JA(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}o(JA,"sanitizeEnvironmentType")});var wp=_(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.originalFetch=void 0;var zA=Ep(),db=new Map;db.set("service:",zA.externalServiceHandler);Vn.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=WA(e);if(typeof t=="string"){let n=new URL(t),i=db.get(n.protocol);return i?i(t,r):(0,Vn.originalFetch)(t,r)}else return(0,Vn.originalFetch)(t,r)};var WA=o(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let r=t;return r.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit")});var hb=_(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Handler=Bn.purgeGatewayCache=void 0;var QA=k(),fb=qr(),pb=ie(),YA=o(()=>{fb.Gateway.purgeGatewayCache()},"purgeGatewayCache");Bn.purgeGatewayCache=YA;var vp=class{static{o(this,"Handler")}routeLoader;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,s,a,c){this.routeLoader=e,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=s,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(e,r)=>{pb.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await fb.Gateway.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof QA.ConfigurationError&&(s=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:pb.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(e,r)}};Bn.Handler=vp});var bb=_(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.pathToRegexp=ke.tokensToRegexp=ke.regexpToFunction=ke.match=ke.tokensToFunction=ke.compile=ke.parse=void 0;function ZA(t){for(var e=[],r=0;r<t.length;){var n=t[r];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:r,value:t[r++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:r++,value:t[r++]});continue}if(n==="{"){e.push({type:"OPEN",index:r,value:t[r++]});continue}if(n==="}"){e.push({type:"CLOSE",index:r,value:t[r++]});continue}if(n===":"){for(var i="",s=r+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=t[s++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));e.push({type:"NAME",index:r,value:i}),r=s;continue}if(n==="("){var c=1,u="",s=r+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){u+=t[s++]+t[s++];continue}if(t[s]===")"){if(c--,c===0){s++;break}}else if(t[s]==="("&&(c++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));u+=t[s++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));e.push({type:"PATTERN",index:r,value:u}),r=s;continue}e.push({type:"CHAR",index:r,value:t[r++]})}return e.push({type:"END",index:r,value:""}),e}o(ZA,"lexer");function Tp(t,e){e===void 0&&(e={});for(var r=ZA(t),n=e.prefixes,i=n===void 0?"./":n,s="[^".concat(Gn(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(E){if(u<r.length&&r[u].type===E)return r[u++].value},"tryConsume"),p=o(function(E){var T=d(E);if(T!==void 0)return T;var C=r[u],w=C.type,P=C.index;throw new TypeError("Unexpected ".concat(w," at ").concat(P,", expected ").concat(E))},"mustConsume"),f=o(function(){for(var E="",T;T=d("CHAR")||d("ESCAPED_CHAR");)E+=T;return E},"consumeText");u<r.length;){var h=d("CHAR"),y=d("NAME"),b=d("PATTERN");if(y||b){var I=h||"";i.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:y||c++,prefix:I,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var A=h||d("ESCAPED_CHAR");if(A){l+=A;continue}l&&(a.push(l),l="");var g=d("OPEN");if(g){var I=f(),v=d("NAME")||"",O=d("PATTERN")||"",V=f();p("CLOSE"),a.push({name:v||(O?c++:""),pattern:v&&!O?s:O,prefix:I,suffix:V,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(Tp,"parse");ke.parse=Tp;function XA(t,e){return mb(Tp(t,e),e)}o(XA,"compile");ke.compile=XA;function mb(t,e){e===void 0&&(e={});var r=Sp(e),n=e.encode,i=n===void 0?function(u){return u}:n,s=e.validate,a=s===void 0?!0:s,c=t.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var f=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<f.length;b++){var I=i(f[b],p);if(a&&!c[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var I=i(String(f),p);if(a&&!c[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!h){var A=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(A))}}return l}}o(mb,"tokensToFunction");ke.tokensToFunction=mb;function e0(t,e){var r=[],n=Ip(t,r,e);return yb(n,r,e)}o(e0,"match");ke.match=e0;function yb(t,e,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(s){return s}:n;return function(s){var a=t.exec(s);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=o(function(f){if(a[f]===void 0)return"continue";var h=e[f-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[f].split(h.prefix+h.suffix).map(function(y){return i(y,h)}):l[h.name]=i(a[f],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(yb,"regexpToFunction");ke.regexpToFunction=yb;function Gn(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(Gn,"escapeString");function Sp(t){return t&&t.sensitive?"":"i"}o(Sp,"flags");function t0(t,e){if(!e)return t;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(t.source);i;)e.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(t.source);return t}o(t0,"regexpToRegexp");function r0(t,e,r){var n=t.map(function(i){return Ip(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Sp(r))}o(r0,"arrayToRegexp");function n0(t,e,r){return gb(Tp(t,r),e,r)}o(n0,"stringToRegexp");function gb(t,e,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,s=r.start,a=s===void 0?!0:s,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(P){return P}:l,p=r.delimiter,f=p===void 0?"/#?":p,h=r.endsWith,y=h===void 0?"":h,b="[".concat(Gn(y),"]|$"),I="[".concat(Gn(f),"]"),A=a?"^":"",g=0,v=t;g<v.length;g++){var O=v[g];if(typeof O=="string")A+=Gn(d(O));else{var V=Gn(d(O.prefix)),E=Gn(d(O.suffix));if(O.pattern)if(e&&e.push(O),V||E)if(O.modifier==="+"||O.modifier==="*"){var T=O.modifier==="*"?"?":"";A+="(?:".concat(V,"((?:").concat(O.pattern,")(?:").concat(E).concat(V,"(?:").concat(O.pattern,"))*)").concat(E,")").concat(T)}else A+="(?:".concat(V,"(").concat(O.pattern,")").concat(E,")").concat(O.modifier);else O.modifier==="+"||O.modifier==="*"?A+="((?:".concat(O.pattern,")").concat(O.modifier,")"):A+="(".concat(O.pattern,")").concat(O.modifier);else A+="(?:".concat(V).concat(E,")").concat(O.modifier)}}if(u)i||(A+="".concat(I,"?")),A+=r.endsWith?"(?=".concat(b,")"):"$";else{var C=t[t.length-1],w=typeof C=="string"?I.indexOf(C[C.length-1])>-1:C===void 0;i||(A+="(?:".concat(I,"(?=").concat(b,"))?")),w||(A+="(?=".concat(I,"|").concat(b,")"))}return new RegExp(A,Sp(r))}o(gb,"tokensToRegexp");ke.tokensToRegexp=gb;function Ip(t,e,r){return t instanceof RegExp?t0(t,e):Array.isArray(t)?r0(t,e,r):n0(t,e,r)}o(Ip,"pathToRegexp");ke.pathToRegexp=Ip});var Op=_(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.AwsV4Signer=Kn.AwsClient=void 0;var i0=or(),vb=k(),o0=(0,i0.debug)("zuplo:runtime"),Ap=new TextEncoder,_b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},s0=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Rp=class{static{o(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:r,sessionToken:n,service:i,region:s,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=s,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,r){let n=new Sa(Object.assign({url:e},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(e,r){o0("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:i,request:s}=await this.sign(e,r),a=fetch(i,s);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new vb.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};Kn.AwsClient=Rp;var Sa=class{static{o(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:r,headers:n,body:i,accessKeyId:s,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:h,allHeaders:y,singleEncode:b}){if(r==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=c;let I,A;(!u||!l)&&([I,A]=a0(this.url,this.headers)),this.service=u||I||"",this.region=l||A||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let g=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),g.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&g.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(O=>y||!s0.includes(O)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(O=>O+":"+(O==="host"?this.url.host:(this.headers.get(O)||"").replace(/\s+/g," "))).join(`
59
+ -----END ${e}-----`},"default")});function Iy(t){let e=[],r=0;for(;r<t.length;){let n=Cy(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Cy(t){let e=0,r=t[0]&31;if(e++,r===31){for(r=0;t[e]>=128;)r=r*128+t[e]-128,e++;r=r*128+t[e]-128,e++}let n=0;if(t[e]<128)n=t[e],e++;else if(n===128){for(n=0;t[e+n]!==0||t[e+n+1]!==0;){if(n>t.byteLength)throw new TypeError("invalid indefinite form length");n++}let s=e+n+2;return{byteLength:s,contents:t.subarray(e,e+n),raw:t.subarray(0,s)}}else{let s=t[e]&127;e++,n=0;for(let a=0;a<s;a++)n=n*256+t[e],e++}let i=e+n;return{byteLength:i,contents:t.subarray(e,i),raw:t.subarray(0,i)}}function pP(t){let e=Iy(Iy(Cy(t).contents)[0].contents);return Rs(e[e[0].raw[0]===160?6:5].raw)}function fP(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=nd(e);return gd(pP(r),"PUBLIC KEY")}var Py,Ay,Ry,gr,Sy,Oy,Ny,bd,xy,Fs=D(()=>{xe();_t();De();Ty();Y();Et();Py=o(async(t,e,r)=>{if(!me(r))throw new TypeError(fe(r,...oe));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return gd(Rs(new Uint8Array(await G.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Ay=o(t=>Py("public","spki",t),"toSPKI"),Ry=o(t=>Py("private","pkcs8",t),"toPKCS8"),gr=o((t,e,r=0)=>{r===0&&(e.unshift(e.length),e.unshift(6));let n=t.indexOf(e[0],r);if(n===-1)return!1;let i=t.subarray(n,n+e.length);return i.length!==e.length?!1:i.every((s,a)=>s===e[a])||gr(t,e,n+1)},"findOid"),Sy=o(t=>{switch(!0){case gr(t,[42,134,72,206,61,3,1,7]):return"P-256";case gr(t,[43,129,4,0,34]):return"P-384";case gr(t,[43,129,4,0,35]):return"P-521";case gr(t,[43,101,110]):return"X25519";case gr(t,[43,101,111]):return"X448";case gr(t,[43,101,112]):return"Ed25519";case gr(t,[43,101,113]):return"Ed448";default:throw new J("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Oy=o(async(t,e,r,n,i)=>{var s;let a,c,u=new Uint8Array(atob(r.replace(t,"")).split("").map(d=>d.charCodeAt(0))),l=e==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=Sy(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:Sy(u)},c=l?["verify"]:["sign"];break;default:throw new J('Invalid or unsupported "alg" (Algorithm) value')}return G.subtle.importKey(e,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),Ny=o((t,e,r)=>Oy(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),bd=o((t,e,r)=>Oy(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");o(Iy,"getElement");o(Cy,"parseElement");o(pP,"spkiFromX509");o(fP,"getSPKI");xy=o((t,e,r)=>{let n;try{n=fP(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return bd(n,e,r)},"fromX509")});function hP(t){let e,r;switch(t.kty){case"oct":{switch(t.alg){case"HS256":case"HS384":case"HS512":e={name:"HMAC",hash:`SHA-${t.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new J(`${t.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":e={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":e={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":e={name:"PBKDF2"},r=["deriveBits"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new J('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var mP,_d,Ly=D(()=>{xe();Y();De();o(hP,"subtleMapping");mP=o(async t=>{var e,r;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=hP(t),s=[n,(e=t.ext)!==null&&e!==void 0?e:!1,(r=t.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return G.subtle.importKey("raw",pe(t.k),...s);let a={...t};return delete a.alg,delete a.use,G.subtle.importKey("jwk",a,...s)},"parse"),_d=mP});async function Dy(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return bd(t,e,r)}async function My(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return xy(t,e,r)}async function Uy(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ny(t,e,r)}async function br(t,e,r){var n;if(!se(t))throw new TypeError("JWK must be an object");switch(e||(e=t.alg),t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=t.ext!==!0),r?_d({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):pe(t.k);case"RSA":if(t.oth!==void 0)throw new J('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _d({...t,alg:e});default:throw new J('Unsupported "kty" (Key Type) Parameter value')}}var Hi=D(()=>{De();Fs();Ly();Y();Qe();o(Dy,"importSPKI");o(My,"importX509");o(Uy,"importPKCS8");o(br,"importJWK")});var yP,gP,bP,_r,qi=D(()=>{_t();Et();yP=o((t,e)=>{if(!(e instanceof Uint8Array)){if(!ud(e))throw new TypeError(cd(t,e,...oe,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${oe.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),gP=o((t,e,r)=>{if(!ud(e))throw new TypeError(cd(t,e,...oe));if(e.type==="secret")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${oe.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),bP=o((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?yP(t,e):gP(t,e,r)},"checkKeyType"),_r=bP});async function _P(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(fe(r,"Uint8Array"));let s=parseInt(t.slice(1,4),10),a=await G.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await G.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await G.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Le(i,n,u,Is(i.length<<3)),d=new Uint8Array((await G.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function EP(t,e,r,n,i){let s;r instanceof Uint8Array?s=await G.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(We(r,t,"encrypt"),s=r);let a=new Uint8Array(await G.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var wP,$i,Ed=D(()=>{Pe();sd();ad();xe();yr();_t();Y();Et();o(_P,"cbcEncrypt");o(EP,"gcmEncrypt");wP=o(async(t,e,r,n,i)=>{if(!me(r)&&!(r instanceof Uint8Array))throw new TypeError(fe(r,...oe,"Uint8Array"));switch(Cs(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&In(r,parseInt(t.slice(-3),10)),_P(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&In(r,parseInt(t.slice(1,4),10)),EP(t,e,r,n,i);default:throw new J("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),$i=wP});async function ky(t,e,r,n){let i=t.slice(0,7);n||(n=Os(i));let{ciphertext:s,tag:a}=await $i(i,r,e,n,new Uint8Array(0));return{encryptedKey:s,iv:ce(n),tag:ce(a)}}async function Fy(t,e,r,n,i){let s=t.slice(0,7);return Ls(s,e,r,n,i,new Uint8Array(0))}var wd=D(()=>{Ed();ld();Ns();De();o(ky,"wrap");o(Fy,"unwrap")});async function vP(t,e,r,n,i){switch(_r(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new F("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new F("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!se(n.epk))throw new F('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Us(e))throw new J("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await br(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new F('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=pe(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new F('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=pe(n.apv)}let u=await Ms(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?ki(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new F("JWE Encrypted Key missing");return Ui(t.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new F("JWE Encrypted Key missing");return vy(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new F("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new F('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new F('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new F('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return _y(t,e,r,n.p2c,pe(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new F("JWE Encrypted Key missing");return Ui(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new F("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new F('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new F('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=pe(n.iv),a=pe(n.tag);return Fy(t,e,r,s,a)}default:throw new J('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Hy,qy=D(()=>{Ds();fd();md();yd();De();Y();Fi();Hi();qi();Qe();wd();o(vP,"decryptKeyManagement");Hy=vP});function TP(t,e,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let a of n.crit){if(!s.has(a))throw new J(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Dt,On=D(()=>{Y();o(TP,"validateCrit");Dt=TP});var SP,ji,vd=D(()=>{SP=o((t,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)},"validateAlgorithms"),ji=SP});async function Nn(t,e,r){var n;if(!se(t))throw new F("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new F("JOSE Header missing");if(typeof t.iv!="string")throw new F("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new F("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new F("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new F("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new F("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new F("JWE AAD incorrect type");if(t.header!==void 0&&!se(t.header))throw new F("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!se(t.unprotected))throw new F("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let v=pe(t.protected);i=JSON.parse(ge.decode(v))}catch{throw new F("JWE Protected Header is invalid")}if(!xt(i,t.header,t.unprotected))throw new F("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...t.header,...t.unprotected};if(Dt(F,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new J('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new F("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new F("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&ji("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&ji("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new pr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new pr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=pe(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let f;try{f=await Hy(a,e,d,s,r)}catch(v){if(v instanceof TypeError||v instanceof F||v instanceof J)throw v;f=Lt(c)}let h=pe(t.iv),y=pe(t.tag),b=ae.encode((n=t.protected)!==null&&n!==void 0?n:""),I;t.aad!==void 0?I=Le(b,ae.encode("."),ae.encode(t.aad)):I=b;let A=await Ls(c,f,pe(t.ciphertext),h,y,I);s.zip==="DEF"&&(A=await(r?.inflateRaw||ly)(A));let g={plaintext:A};return t.protected!==void 0&&(g.protectedHeader=i),t.aad!==void 0&&(g.additionalAuthenticatedData=pe(t.aad)),t.unprotected!==void 0&&(g.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(g.unprotectedHeader=t.header),p?{...g,key:e}:g}var Hs=D(()=>{De();ld();dd();Y();Pn();Qe();qy();Pe();Fi();On();vd();o(Nn,"flattenedDecrypt")});async function qs(t,e,r){if(t instanceof Uint8Array&&(t=ge.decode(t)),typeof t!="string")throw new F("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:a,4:c,length:u}=t.split(".");if(u!==5)throw new F("Invalid Compact JWE");let l=await Nn({ciphertext:a,iv:s||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},e,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...d,key:l.key}:d}var Td=D(()=>{Hs();Y();Pe();o(qs,"compactDecrypt")});async function $y(t,e,r){if(!se(t))throw new F("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(se))throw new F("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new F("JWE Recipients has no members");for(let n of t.recipients)try{return await Nn({aad:t.aad,ciphertext:t.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:t.iv,protected:t.protected,tag:t.tag,unprotected:t.unprotected},e,r)}catch{}throw new Wt}var jy=D(()=>{Hs();Y();Qe();o($y,"generalDecrypt")});var IP,Vy,By=D(()=>{xe();_t();De();Et();IP=o(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:ce(t)};if(!me(t))throw new TypeError(fe(t,...oe,"Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await G.subtle.exportKey("jwk",t);return s},"keyToJWK"),Vy=IP});async function Gy(t){return Ay(t)}async function Ky(t){return Ry(t)}async function $s(t){return Vy(t)}var Sd=D(()=>{Fs();Fs();By();o(Gy,"exportSPKI");o(Ky,"exportPKCS8");o($s,"exportJWK")});async function PP(t,e,r,n,i={}){let s,a,c;switch(_r(t,r,"encrypt"),t){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Us(r))throw new J("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await hy(r)).privateKey);let{x:p,y:f,crv:h,kty:y}=await $s(d),b=await Ms(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?ki(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:y}},y==="EC"&&(a.epk.y=f),u&&(a.apu=ce(u)),l&&(a.apv=ce(l)),t==="ECDH-ES"){c=b;break}c=n||Lt(e);let I=t.slice(-6);s=await Mi(I,b,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||Lt(e),s=await wy(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||Lt(e);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await by(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||Lt(e),s=await Mi(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||Lt(e);let{iv:u}=i;({encryptedKey:s,...a}=await ky(t,r,c,u));break}default:throw new J('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var js,Id=D(()=>{Ds();fd();md();yd();De();Fi();Y();Sd();qi();wd();o(PP,"encryptKeyManagement");js=PP});var Pd,Qt,Vs=D(()=>{De();Ed();dd();Ns();Id();Y();Pn();Pe();On();Pd=Symbol(),Qt=class{static{o(this,"FlattenedEncrypt")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new F("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!xt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Dt(F,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new J('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let y;({cek:c,encryptedKey:a,parameters:y}=await js(i,s,e,this._cek,this._keyManagementParameters)),y&&(r&&Pd in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...y}:this.setUnprotectedHeader(y):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...y}:this.setProtectedHeader(y))}this._iv||(this._iv=Os(s));let u,l,d;this._protectedHeader?l=ae.encode(ce(JSON.stringify(this._protectedHeader))):l=ae.encode(""),this._aad?(d=ce(this._aad),u=Le(l,ae.encode("."),ae.encode(d))):u=l;let p,f;if(n.zip==="DEF"){let y=await(r?.deflateRaw||dy)(this._plaintext);({ciphertext:p,tag:f}=await $i(s,y,c,this._iv,u))}else({ciphertext:p,tag:f}=await $i(s,this._plaintext,c,this._iv,u));let h={ciphertext:ce(p),iv:ce(this._iv),tag:ce(f)};return a&&(h.encrypted_key=ce(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ge.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var Ad,Bs,Jy=D(()=>{Vs();Y();Fi();Pn();Id();De();On();Ad=class{static{o(this,"IndividualRecipient")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}},Bs=class{static{o(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new Ad(this,e,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var r,n,i;if(!this._recipients.length)throw new F("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Qt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...e}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let s;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!xt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new F("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new F('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new F('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new F('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Dt(F,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new F('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=Lt(s),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let f={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let b=await new Qt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:f}).encrypt(l.key,{...l.options,...e,[Pd]:!0});c.ciphertext=b.ciphertext,c.iv=b.iv,c.tag=b.tag,b.aad&&(c.aad=b.aad),b.protected&&(c.protected=b.protected),b.unprotected&&(c.unprotected=b.unprotected),d.encrypted_key=b.encrypted_key,b.header&&(d.header=b.header);continue}let{encryptedKey:h,parameters:y}=await js(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),s,l.key,a,{p2c:f});d.encrypted_key=ce(h),(l.unprotectedHeader||y)&&(d.header={...l.unprotectedHeader,...y})}return c}}});function Vi(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new J(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var Rd=D(()=>{Y();o(Vi,"subtleDsa")});function Bi(t,e,r){if(me(e))return cy(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(fe(e,...oe));return G.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(fe(e,...oe,"Uint8Array"))}var Od=D(()=>{xe();yr();_t();Et();o(Bi,"getCryptoKey")});var AP,zy,Wy=D(()=>{Rd();xe();ks();Od();AP=o(async(t,e,r,n)=>{let i=await Bi(t,e,"verify");Wr(t,i);let s=Vi(t,i.algorithm);try{return await G.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),zy=AP});async function Cn(t,e,r){var n;if(!se(t))throw new ie("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new ie('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new ie("JWS Protected Header incorrect type");if(t.payload===void 0)throw new ie("JWS Payload missing");if(typeof t.signature!="string")throw new ie("JWS Signature missing or incorrect type");if(t.header!==void 0&&!se(t.header))throw new ie("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let I=pe(t.protected);i=JSON.parse(ge.decode(I))}catch{throw new ie("JWS Protected Header is invalid")}if(!xt(i,t.header))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...t.header},a=Dt(ie,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new ie('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new ie('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&ji("algorithms",r.algorithms);if(l&&!l.has(u))throw new pr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new ie("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new ie("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),_r(u,e,"verify");let p=Le(ae.encode((n=t.protected)!==null&&n!==void 0?n:""),ae.encode("."),typeof t.payload=="string"?ae.encode(t.payload):t.payload),f=pe(t.signature);if(!await zy(u,e,f,p))throw new zr;let y;c?y=pe(t.payload):typeof t.payload=="string"?y=ae.encode(t.payload):y=t.payload;let b={payload:y};return t.protected!==void 0&&(b.protectedHeader=i),t.header!==void 0&&(b.unprotectedHeader=t.header),d?{...b,key:e}:b}var Gs=D(()=>{De();Wy();Y();Pe();Pn();Qe();qi();On();vd();o(Cn,"flattenedVerify")});async function Ks(t,e,r){if(t instanceof Uint8Array&&(t=ge.decode(t)),typeof t!="string")throw new ie("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3)throw new ie("Invalid Compact JWS");let c=await Cn({payload:i,protected:n,signature:s},e,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof e=="function"?{...u,key:c.key}:u}var Nd=D(()=>{Gs();Y();Pe();o(Ks,"compactVerify")});async function Qy(t,e,r){if(!se(t))throw new ie("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(se))throw new ie("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await Cn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new zr}var Yy=D(()=>{Gs();Y();Qe();o(Qy,"generalVerify")});var xn,Cd=D(()=>{xn=o(t=>Math.floor(t.getTime()/1e3),"default")});var RP,Ln,xd=D(()=>{RP=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,Ln=o(t=>{let e=RP.exec(t);if(!e)throw new TypeError("Invalid time period format");let r=parseFloat(e[1]);switch(e[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var Zy,OP,Dn,Js=D(()=>{Y();Pe();Cd();xd();Qe();Zy=o(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),OP=o((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),Dn=o((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||Zy(t.typ)!==Zy(n)))throw new Oe('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ge.decode(e))}catch{}if(!se(i))throw new Ee("JWT Claims Set must be a top-level JSON object");let{requiredClaims:s=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&s.push("iat"),u!==void 0&&s.push("aud"),c!==void 0&&s.push("sub"),a!==void 0&&s.push("iss");for(let h of new Set(s.reverse()))if(!(h in i))throw new Oe(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new Oe('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new Oe('unexpected "sub" claim value',"sub","check_failed");if(u&&!OP(i.aud,typeof u=="string"?[u]:u))throw new Oe('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Ln(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=xn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new Oe('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new Oe('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>f+d)throw new Oe('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new Oe('"exp" claim must be a number',"exp","invalid");if(i.exp<=f-d)throw new Sn('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=f-i.iat,y=typeof l=="number"?l:Ln(l);if(h-d>y)throw new Sn('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new Oe('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function Xy(t,e,r){var n;let i=await Ks(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new Ee("JWTs MUST NOT use unencoded payload");let a={payload:Dn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var eg=D(()=>{Nd();Js();Y();o(Xy,"jwtVerify")});async function tg(t,e,r){let n=await qs(t,e,r),i=Dn(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Oe('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Oe('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Oe('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof e=="function"?{...a,key:n.key}:a}var rg=D(()=>{Td();Js();Y();o(tg,"jwtDecrypt")});var Mn,Ld=D(()=>{Vs();Mn=class{static{o(this,"CompactEncrypt")}constructor(e){this._flattened=new Qt(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this._flattened.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var NP,ng,ig=D(()=>{Rd();xe();ks();Od();NP=o(async(t,e,r)=>{let n=await Bi(t,e,"sign");Wr(t,n);let i=await G.subtle.sign(Vi(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),ng=NP});var Er,zs=D(()=>{De();ig();Pn();Y();Pe();qi();On();Er=class{static{o(this,"FlattenedSign")}constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new ie("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!xt(this._protectedHeader,this._unprotectedHeader))throw new ie("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Dt(ie,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new ie('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new ie('JWS "alg" (Algorithm) Header Parameter missing or invalid');_r(a,e,"sign");let c=this._payload;s&&(c=ae.encode(ce(c)));let u;this._protectedHeader?u=ae.encode(ce(JSON.stringify(this._protectedHeader))):u=ae.encode("");let l=Le(u,ae.encode("."),c),d=await ng(a,e,l),p={signature:ce(d),payload:""};return s&&(p.payload=ge.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ge.decode(u)),p}}});var Un,Dd=D(()=>{zs();Un=class{static{o(this,"CompactSign")}constructor(e){this._flattened=new Er(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Md,Ws,og=D(()=>{zs();Y();Md=class{static{o(this,"IndividualSignature")}constructor(e,r,n){this.parent=e,this.key=r,this.options=n}setProtectedHeader(e){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}},Ws=class{static{o(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new Md(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new ie("at least one signature must be added");let e={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new Er(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:s,...a}=await i.sign(n.key,n.options);if(r===0)e.payload=s;else if(e.payload!==s)throw new ie("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var wr,Qs=D(()=>{Cd();Qe();xd();wr=class{static{o(this,"ProduceJWT")}constructor(e){if(!se(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:e}:this._payload={...this._payload,nbf:xn(new Date)+Ln(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:xn(new Date)+Ln(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:xn(new Date)}:this._payload={...this._payload,iat:e},this}}});var Ys,sg=D(()=>{Dd();Y();Pe();Qs();Ys=class extends wr{static{o(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new Un(ae.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Ee("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var Zs,ag=D(()=>{Ld();Pe();Qs();Zs=class extends wr{static{o(this,"EncryptJWT")}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,r){let n=new Mn(ae.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(e,r)}}});async function Ud(t,e){if(!se(t))throw new TypeError("JWK must be an object");if(e??(e="sha256"),e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(t.kty){case"EC":vr(t.crv,'"crv" (Curve) Parameter'),vr(t.x,'"x" (X Coordinate) Parameter'),vr(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":vr(t.crv,'"crv" (Subtype of Key Pair) Parameter'),vr(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":vr(t.e,'"e" (Exponent) Parameter'),vr(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":vr(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new J('"kty" (Key Type) Parameter missing or unsupported')}let n=ae.encode(JSON.stringify(r));return ce(await Ts(e,n))}async function cg(t,e){e??(e="sha256");let r=await Ud(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var vr,ug=D(()=>{td();De();Y();Pe();Qe();vr=o((t,e)=>{if(typeof t!="string"||!t)throw new Ci(`${e} missing or invalid`)},"check");o(Ud,"calculateJwkThumbprint");o(cg,"calculateJwkThumbprintUri")});async function lg(t,e){let r={...t,...e?.header};if(!se(r.jwk))throw new ie('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await br({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new ie('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var dg=D(()=>{Hi();Qe();Y();o(lg,"EmbeddedJWK")});function CP(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new J('Unsupported "alg" value for a JSON Web Key Set')}}function kd(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(xP)}function xP(t){return se(t)}function LP(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function pg(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await br({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new fr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function fg(t){let e=new Gi(t);return async function(r,n){return e.getKey(r,n)}}var Gi,Fd=D(()=>{Hi();Y();Qe();o(CP,"getKtyFromAlg");o(kd,"isJWKSLike");o(xP,"isJWKLike");o(LP,"clone");Gi=class{static{o(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!kd(e))throw new fr("JSON Web Key Set malformed");this._jwks=LP(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=CP(n),a=this._jwks.keys.filter(l=>{let d=s===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Jr;if(u!==1){let l=new xi,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await pg(d,p,n)}catch{continue}},l}return pg(this._cached,c,n)}};o(pg,"importWithAlgCache");o(fg,"createLocalJWKSet")});var DP,hg,mg=D(()=>{Y();DP=o(async(t,e,r)=>{let n,i,s=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},e));let a=await fetch(t.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw s?new Li:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new Te("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new Te("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),hg=DP});function MP(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function yg(t,e){let r=new Hd(t,e);return async function(n,i){return r.getKey(n,i)}}var Hd,gg=D(()=>{mg();Y();Fd();o(MP,"isCloudflareWorkers");Hd=class extends Gi{static{o(this,"RemoteJWKSet")}constructor(e,r){if(super({keys:[]}),this._jwks=void 0,!(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}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,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(e,r)}catch(n){if(n instanceof Jr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&MP()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=hg(this._url,this._timeoutDuration,this._options).then(e=>{if(!kd(e))throw new fr("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}};o(yg,"createRemoteJWKSet")});var Xs,bg=D(()=>{De();Pe();Y();Js();Qs();Xs=class extends wr{static{o(this,"UnsecuredJWT")}encode(){let e=ce(JSON.stringify({alg:"none"})),r=ce(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new Ee("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3||s!=="")throw new Ee("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ge.decode(pe(n))),c.alg!=="none")throw new Error}catch{throw new Ee("Invalid Unsecured JWT")}return{payload:Dn(c,pe(i),r),header:c}}}});var qd={};Co(qd,{decode:()=>Ki,encode:()=>UP});var UP,Ki,ea=D(()=>{De();UP=ce,Ki=pe});function _g(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(ge.decode(Ki(e)));if(!se(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var Eg=D(()=>{ea();Pe();Qe();o(_g,"decodeProtectedHeader")});function wg(t){if(typeof t!="string")throw new Ee("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Ee("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Ee("Invalid JWT");if(!e)throw new Ee("JWTs must contain a payload");let n;try{n=Ki(e)}catch{throw new Ee("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ge.decode(n))}catch{throw new Ee("Failed to parse the decoded payload as JSON")}if(!se(i))throw new Ee("Invalid JWT Claims Set");return i}var vg=D(()=>{ea();Pe();Qe();Y();o(wg,"decodeJwt")});async function Tg(t,e){var r;let n,i,s;switch(t){case"HS256":case"HS384":case"HS512":n=parseInt(t.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},s=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(t.slice(-3),10),hr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(t.slice(1,4),10),i={name:"AES-KW",length:n},s=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(t.slice(1,4),10),i={name:"AES-GCM",length:n},s=["encrypt","decrypt"];break;default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return G.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,s)}function $d(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new J("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Sg(t,e){var r,n,i;let s,a;switch(t){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:$d(e)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=e?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":s={name:c};break;default:throw new J("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=e?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{s={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":s={name:u};break;default:throw new J("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new J('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return G.subtle.generateKey(s,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var jd=D(()=>{xe();Y();Di();o(Tg,"generateSecret");o($d,"getModulusLengthOption");o(Sg,"generateKeyPair")});async function Ig(t,e){return Sg(t,e)}var Pg=D(()=>{jd();o(Ig,"generateKeyPair")});async function Ag(t,e){return Tg(t,e)}var Rg=D(()=>{jd();o(Ag,"generateSecret")});var ta={};Co(ta,{CompactEncrypt:()=>Mn,CompactSign:()=>Un,EmbeddedJWK:()=>lg,EncryptJWT:()=>Zs,FlattenedEncrypt:()=>Qt,FlattenedSign:()=>Er,GeneralEncrypt:()=>Bs,GeneralSign:()=>Ws,SignJWT:()=>Ys,UnsecuredJWT:()=>Xs,base64url:()=>qd,calculateJwkThumbprint:()=>Ud,calculateJwkThumbprintUri:()=>cg,compactDecrypt:()=>qs,compactVerify:()=>Ks,createLocalJWKSet:()=>fg,createRemoteJWKSet:()=>yg,decodeJwt:()=>wg,decodeProtectedHeader:()=>_g,errors:()=>id,exportJWK:()=>$s,exportPKCS8:()=>Ky,exportSPKI:()=>Gy,flattenedDecrypt:()=>Nn,flattenedVerify:()=>Cn,generalDecrypt:()=>$y,generalVerify:()=>Qy,generateKeyPair:()=>Ig,generateSecret:()=>Ag,importJWK:()=>br,importPKCS8:()=>Uy,importSPKI:()=>Dy,importX509:()=>My,jwtDecrypt:()=>tg,jwtVerify:()=>Xy});var ra=D(()=>{Td();Hs();jy();Jy();Nd();Gs();Yy();eg();rg();Ld();Vs();Dd();zs();og();sg();ag();ug();dg();Fd();gg();bg();Sd();Hi();Eg();vg();Y();Pg();Rg();ea()});var kn=_(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.fetchRetry=void 0;var kP=k();async function FP(t,e,r){for(let n=0;n<=t.retries;n++){let i=fetch(e,r);if(n===t.retries)return i;let s=await i;if(s.status<500&&s.status!==429)return s;t?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status}),await new Promise(a=>setTimeout(a,t.retryDelayMs*Math.pow(2,n)))}throw new kP.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(FP,"fetchRetry");na.fetchRetry=FP});var Fn=_(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.GcpServiceAccount=ct.fetchToken=ct.exchangeGgpJwtForIdToken=ct.exchangeFirebaseJwtForIdToken=ct.getTokenFromGcpServiceAccount=void 0;var Og=(ra(),xo(ta)),HP=k(),qP=kn();async function $P({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=t;return await new Og.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}o($P,"getTokenFromGcpServiceAccount");ct.getTokenFromGcpServiceAccount=$P;async function jP(t,e,r){return Bd(t,{token:e,returnSecureToken:!0},r)}o(jP,"exchangeFirebaseJwtForIdToken");ct.exchangeFirebaseJwtForIdToken=jP;async function VP(t,e,r){return Bd(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}o(VP,"exchangeGgpJwtForIdToken");ct.exchangeGgpJwtForIdToken=VP;async function Bd(t,e,r){let n=await(0,qP.fetchRetry)(r,t,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(n.status!==200){let s;try{let a=await n.text(),c=JSON.parse(a);s={cause:c.error??c}}catch{}throw new HP.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Bd,"fetchToken");ct.fetchToken=Bd;var Vd=class t{static{o(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:r}){this.#t=e,this.#e=r}static async init(e){let r=JSON.parse(e),n=await(0,Og.importPKCS8)(r.private_key.trim(),"RS256");return new t({serviceAccount:r,privateKey:n})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};ct.GcpServiceAccount=Vd});var oa=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.GoogleLogTransport=Yt.ZuploToGCPMap=Yt.GoogleCloudLoggingPlugin=void 0;var BP=k(),GP=Re(),Gd=re(),Kd=Fn(),KP=zt(),Ng=Ct(),Jd=class extends KP.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ia(this.options)}};Yt.GoogleCloudLoggingPlugin=Jd;var JP="https://logging.googleapis.com/v2/entries:write?alt=json";Yt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var ia=class{static{o(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=Gd.Environment.instance.loggingEnvironmentType,this.#o=Gd.Environment.instance.loggingEnvironmentStage,this.#n=Gd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async init(){this.#t=await Kd.GcpServiceAccount.init(this.#e)}log(e,r){if(!this.#t)throw new BP.SystemError("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let n={allMessages:(0,Ng.makeErrorsSerializable)(e.messages)},i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:Yt.ZuploToGCPMap[e.level],timestamp:e.timestamp,trace:`projects/${i}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};e.rayId&&(s.labels.rayId=e.rayId);let a=(0,Ng.extractBestMessage)(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Kd.GcpServiceAccount.init(this.#e));let r=await(0,Kd.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(JP,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new GP.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Yt.GoogleLogTransport=ia});var zd=_(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.gcpLogFormat=Hn.GCP_LOG_FORMAT=void 0;var Cg=Ct(),zP=oa();Hn.GCP_LOG_FORMAT="gcp";function WP(t){let e={allMessages:(0,Cg.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Cg.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:zP.ZuploToGCPMap[t.level],timestamp:t.timestamp,"logging.googleapis.com/labels":{buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${t.requestId}`,allMessages:e.allMessages};return t.rayId&&(i["logging.googleapis.com/labels"].rayId=t.rayId),i}o(WP,"gcpLogFormat");Hn.gcpLogFormat=WP});var Lg=_(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.ConsoleTransport=void 0;var xg=zd(),Wd=class{static{o(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;log(e){if(this.#t===xg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,xg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,level:e.level,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId}])}};sa.ConsoleTransport=Wd});var tp=_(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.DataDogTransport=qn.DataDogLoggingPlugin=void 0;var QP=Re(),Qd=re(),YP=zt(),Dg=Ct(),ep=class extends YP.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new aa(this.options)}};qn.DataDogLoggingPlugin=ep;var Yd="__ddtags",Zd="__ddattr",Xd=o(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),ZP=o(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(Xd(n)):r.push(`${Xd(n)}:${Xd(i.toString())}`)}),r.join(",")},"formatTags"),aa=class{static{o(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Qd.Environment.instance.loggingEnvironmentType,this.#i=Qd.Environment.instance.loggingEnvironmentStage,this.#r=Qd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n={},i=r.custom[Yd];i&&typeof i=="object"&&Object.assign(n,i);let s=[...e.messages],a=e.messages.findIndex(h=>h[Yd]!==void 0);a>-1&&(Object.assign(n,s[a][Yd]),s.splice(a,1));let c={},u=r.custom[Zd];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(h=>h[Zd]!==void 0);l>-1&&(Object.assign(c,s[l][Zd]),s.splice(l,1));let d=(0,Dg.makeErrorsSerializable)(s),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Dg.extractBestMessage)(d),service:e.loggingId,ddtags:ZP(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(f,c),this.batcher.enqueue(f),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new QP.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};qn.DataDogTransport=aa});var Ug=_(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.ProcessTransport=void 0;var Mg=zd(),rp=class{static{o(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;log(e){if(this.#t===Mg.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Mg.gcpLogFormat)(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};ca.ProcessTransport=rp});var Fg=_(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.RemoteLogTransport=void 0;var XP=Re(),kg=re(),eA=Ct(),tA=o(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;if(n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0)try{await fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,eA.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":kg.Environment.instance.systemUserAgent,"zp-dn":kg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),ua,np=class{static{o(this,"RemoteLogTransport")}constructor(e){ua||(ua=new XP.BatchDispatch("remote-log-transport",1,tA(e)))}log(e,r){ua.enqueue(e),r.waitUntil(ua.waitUntilFlushed())}};la.RemoteLogTransport=np});var Hg=_(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.unifiedFormatter=Qr.SeverityNumberOpenTelemetryMap=void 0;Qr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var rA=o((t,e)=>r=>{let n={};return n.deploymentName=t,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Qr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Qr.unifiedFormatter=rA});var $g=_(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.UnifiedLogTransport=void 0;var nA=Re(),qg=re(),iA=Hg(),oA=o(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,iA.unifiedFormatter)(r,n);try{await fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":qg.Environment.instance.systemUserAgent,"zp-dn":qg.Environment.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),da,ip=class{static{o(this,"UnifiedLogTransport")}constructor(e){da||(da=new nA.BatchDispatch("unified-log-transport",1,oA(e)))}async log(e,r){da.enqueue(e),r.waitUntil(da.waitUntilFlushed())}};pa.UnifiedLogTransport=ip});var zg=_(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.LogInitializer=void 0;var sA=or(),aA=Ot(),jg=Bl(),Vg=re(),Bg=Km(),cA=zt(),uA=Jm(),Gg=zm(),Kg=Lg(),lA=tp(),dA=oa(),Jg=Ug(),pA=Fg(),fA=$g(),op=(0,sA.debug)("zuplo:logging"),sp=class t{static{o(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:r}){this.systemCoreLogger=e,this.userCoreLogger=r}static async init(e){let r=await t.setupSystemCoreLogger(Vg.Environment.instance,e),n=await t.setupUserCoreLogger(Vg.Environment.instance,e);return new t({systemCoreLogger:r,userCoreLogger:n})}static async setupSystemCoreLogger(e,r){let{build:n}=e;op("Gateway.setupSystemCoreLogger");let i=[],s=r.getService(jg.SYSTEM_LOGGER);return s?i.push(new Jg.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&i.push(new Kg.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new fA.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(i.map(async a=>{a.init&&await a.init()})),new Bg.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}static async setupUserCoreLogger(e,r){op("Gateway.setupUserCoreLogger");let n=[],{runtime:i,build:s}=e,a=r.getService(jg.SYSTEM_LOGGER);if(a&&a.captureUserLogs===!0?n.push(new Jg.ProcessTransport(a.logger,e.logFormat)):e.isDeno&&n.push(new Kg.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&n.push(new pA.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),i.GCP_USER_LOG_NAME&&i.GCP_USER_LOG_SVC_ACCT_JSON&&n.push(new dA.GoogleLogTransport({serviceAccountJson:i.GCP_USER_LOG_SVC_ACCT_JSON,logName:i.GCP_USER_LOG_NAME})),i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let c=i.ZUPLO_USER_LOGGER_DATA_DOG_URL;n.push(new lA.DataDogTransport({apiKey:i.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return aA.plugins.forEach(c=>{c instanceof cA.LogPlugin&&n.push(c.getTransport())}),await Promise.all(n.map(async c=>{c.init&&await c.init()})),new Bg.CoreLogger(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,n)}createRequestLoggers(e,r,n,i,s){op("Gateway.createRequestLoggers");let a=new uA.LoggingContext(n,i,s),c=new Gg.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new Gg.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};fa.LogInitializer=sp});var cp=_(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.UserRouteConfiguration=void 0;var ap=class{static{o(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};ha.UserRouteConfiguration=ap});var lp=_(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.Router=Mt.RouterError=Mt.LookupResult=Mt.RouterEntry=void 0;var Wg=k(),hA=gt(),mA=cp(),ma=class{static{o(this,"RouterEntry")}constructor(e,r,n,i){this.fullPath=e,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};Mt.RouterEntry=ma;var Ji=class{static{o(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Mt.LookupResult=Ji;var ya=class extends Error{static{o(this,"RouterError")}constructor(e,r){super(e,r)}};Mt.RouterError=ya;var up=class{static{o(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof mA.UserRouteConfiguration||e instanceof hA.SystemRouteConfiguration))throw new Wg.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(s=>s.name===e.version)?.pathPrefix,i;"pathPattern"in e&&e.pathPattern?i=`${n??""}${e.pathPattern}`:i=`${n??""}${e.path}`;try{let s=new URLPattern({pathname:i}),a=new ma(i,s,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new ya(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(e,r){if(typeof e>"u")throw new Wg.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(e));if(n.length!==0)for(let i=0;i<n.length;i++){let s=n[i],c=s.urlPattern.exec({pathname:r});if(c!==null)return new Ji(s.config,s.executableHandler,c.pathname.groups)}}lookupByPathOnly(e){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:e});if(a!==null){let c=new Ji(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Mt.Router=up});var ga=_($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.getGlobalZuploEventContext=$n.setGlobalZuploEventContext=void 0;var dp;function yA(t){dp=t}o(yA,"setGlobalZuploEventContext");$n.setGlobalZuploEventContext=yA;function gA(){if(dp===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return dp}o(gA,"getGlobalZuploEventContext");$n.getGlobalZuploEventContext=gA});var Qg=_(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.normalizeIncomingRequestHeaders=void 0;var zi=Fr();function bA({headers:t,removeAllVendorHeadersExceptListed:e,isDeno:r}){let n=new Headers(t);if(e){for(let[i]of t){let s=i.substring(0,3);zi.VENDOR_HEADER_PREFIXES.includes(s.toLowerCase())&&!zi.VENDOR_HEADERS_TO_ALLOW.includes(i.toLowerCase())&&n.delete(i)}n.delete(zi.X_REAL_IP_HEADER)}else zi.DISPATCH_HEADERS_TO_REMOVE.forEach(i=>{n.delete(i)});return r&&zi.INTERNAL_HEADERS_TO_REMOVE.forEach(i=>{n.delete(i)}),n}o(bA,"normalizeIncomingRequestHeaders");ba.normalizeIncomingRequestHeaders=bA});var qr=_(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.Gateway=void 0;var _A=or(),Yg=wm(),Zg=Om(),EA=Nm(),Xg=Cm(),eb=Mm(),Yr=Fr(),_a=$r(),tb=Gm(),kt=k(),Wi=Ot(),wA=zg(),vA=Gt(),TA=de(),SA=Ul(),IA=ar(),PA=En(),AA=Ke(),RA=lp(),pp=gt(),rb=cp(),OA=Je(),NA=ls(),Ea=re(),CA=ga(),xA=Qg(),nb=Kr(),ib=yl(),Ut=(0,_A.debug)("zuplo:runtime"),LA=o(t=>{let e=t.findIndex(r=>r.name===pp.systemNoVersion.name);return e>-1?[...t.splice(e),pp.systemNoVersion]:[...t,pp.systemNoVersion]},"setupSystemNoVersion"),fp=class t{static{o(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(e,r,n,i){this.routeData=e,this.runtimeSettings=r,this.schemaValidator=i,Ut("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=n}static async initialize(e,r,n,i,s){if(Ut("Gateway.initialize"),!t.#e){await(0,Wi.initializeRuntime)(s);let a=await wA.LogInitializer.init(n),c=e(),u={...c,corsPolicies:(0,NA.parseCorsPolicies)(c.corsPolicies)},l=new t(u,r,a,i);t.#e=l}return t.#e}static purgeGatewayCache(){Ut("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new kt.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[PA.policyProcessor,SA.corsProcessor,IA.metricsProcessor];#i;setupRoutes=()=>{Ut("Gateway.setupRoutes");let e=this.routeData,r=LA(e.versions),n=new RA.Router(r);if(e.routes.length===0)return(0,Yg.registerBuildRoute)(n,this),(0,eb.registerPingRoute)(n,this),(0,Zg.registerCorsRoute)(n,this),(0,EA.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;i&&((0,tb.registerDevPortalLegacyRedirectRoute)(n,this),(0,tb.registerDevPortalV3Route)(n,this)),(0,Yg.registerBuildRoute)(n,this),(0,eb.registerPingRoute)(n,this),(0,Zg.registerCorsRoute)(n,this);for(let s of Wi.plugins)s instanceof Wi.SystemRuntimePlugin&&s.registerRoutes(n,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new kt.ConfigurationError(`Invalid state - No handler on route for path '${s.path}'`);let c=new vA.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new rb.UserRouteConfiguration(s);n.addRoute(u,c.execute)}),(0,Xg.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new kt.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=o((r,n,i)=>this.#o(r,n,i),"errorHandler");return e};errorHandler(e,r,n){try{return this.#i(e,r,n)}catch(i){return Ut("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){Ut("Gateway.internalErrorResponse");let i={};if(Ea.Environment.instance.isDeno){if(n instanceof kt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,nb.serializeError)(n.cause);"stack"in s&&(s.stack=(0,nb.cleanStack)(s.stack)),i={cause:s}}}return TA.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}async handleRequest(e,r){(0,CA.setGlobalZuploEventContext)(r);let n=e.headers.get(Yr.REQUEST_ID_HEADER)??e.headers.get(Yr.LEGACY_REQUEST_ID_HEADER),i=e.headers.get(Yr.RAY_ID_HEADER),s=(0,xA.normalizeIncomingRequestHeaders)({headers:e.headers,removeAllVendorHeadersExceptListed:Ea.Environment.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed,isDeno:Ea.Environment.instance.isDeno});n||(n=crypto.randomUUID(),s.set(Yr.REQUEST_ID_HEADER,n));let a=new Request(e,{headers:s});if(["GET","HEAD"].includes(a.method)&&a.body){let A=new Headers(a.headers);A.set(Yr.BODY_REMOVED_HEADER,"true"),a=new Request(a,{headers:A,body:null})}let c={},{userRequestLogger:u,systemRequestLogger:l}=this.#t.createRequestLoggers(n,i,r,c,a),d=new URL(a.url),p=d.pathname,f=this.#r.lookup(a.method,p);if(!f)throw new kt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${p}'`);let h=new _a.HeaderIncomingRequestProperties(e.headers),y=new AA.ZuploRequest(a,{params:f.params}),b=new _a.SystemZuploContext({logger:u,route:f.routeConfiguration,requestId:n,event:r,custom:c,incomingRequestProperties:h}),I=_a.ZuploContextExtensions.initialize(b,y);if(f.routeConfiguration===Xg.notFoundRouteConfiguration&&Wi.runtimeExtensions.value?.notFoundHandler!==void 0){let A=this.#r.lookupByPathOnly(p);I.pathOnlyMatches=A.map(g=>g.routeConfiguration).filter(g=>g instanceof rb.UserRouteConfiguration)}try{if(OA.SystemLogMap.addLogger(b,l),Ea.Environment.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!(0,ib.isSystemRoute)(d):!d.pathname.startsWith("/__zuplo")){let v=await(0,Wi.invokeOnRequestExtensions)(y,b);if(v instanceof Response)return v;{let O=_a.ZuploContextExtensions.getContextExtensions(b);y=v,O.latestRequest=y}}(0,ib.isSystemRoute)(d)||u.debug(`Request received '${d.pathname}'`,{method:a.method,url:d.pathname,hostname:d.hostname,route:f.routeConfiguration.path});let A=f.executableHandler;DA(A,f,a),Ut("Gateway.handleRequest - call user handler");let g=await A(y,b);if(Ut("Gateway.handleRequest - user handler"),!(g instanceof Response))throw new kt.RuntimeError(`Invalid Response type from the request handler: ${typeof g}`);if(g.bodyUsed)throw new kt.RuntimeError("The response object has already been used. Return a new response instead.");if(g.headers.get(Yr.REQUEST_ID_HEADER)===null&&!g.webSocket){let v=new Headers(g.headers);return v.set(Yr.REQUEST_ID_HEADER,n),new Response(g.body,{status:g.status,statusText:g.statusText,headers:v,cf:g.cf})}else return g}catch(A){return Ut("Gateway - error executing handler",A),A instanceof kt.RuntimeError?(u.error(A),l.warn(A)):l.error(A),await this.#o(y,b,A)}}};wa.Gateway=fp;function DA(t,e,r){if(Ut("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new kt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new kt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}o(DA,"checkHandler")});var ob=_(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.invokeInboundPolicy=void 0;var MA=k(),UA=qr(),kA=En(),FA=o(async(t,e,r)=>{let n=UA.Gateway.instance.routeData.policies,i=(0,kA.getInboundPolicyInstances)([t],n);if(i.length===0)throw new MA.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);return i[0].handler(e,r)},"invokeInboundPolicy");va.invokeInboundPolicy=FA});var $r=_(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.SystemZuploContext=ut.ZuploContextExtensions=ut.ResponseSentEvent=ut.ResponseSendingEvent=ut.HeaderIncomingRequestProperties=void 0;var be=Fr(),HA=k(),qA=ob(),hp=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(be.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(be.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(be.CF_IP_CITY_HEADER)??this.#e.get(be.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(be.CF_IP_CONTINENT_HEADER)??this.#e.get(be.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(be.CF_IP_COUNTRY_HEADER)??this.#e.get(be.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(be.CF_IP_LATITUDE_HEADER)??this.#e.get(be.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(be.CF_IP_LONGITUDE_HEADER)??this.#e.get(be.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(be.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(be.CF_POSTAL_CODE_HEADER)??this.#e.get(be.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(be.CF_METRO_CODE_HEADER)??this.#e.get(be.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(be.CF_IP_REGION_HEADER)??this.#e.get(be.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(be.CF_REGION_CODE_HEADER)??this.#e.get(be.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(be.CF_TIMEZONE_HEADER)??this.#e.get(be.ZP_TIMEZONE_HEADER)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone}}};ut.HeaderIncomingRequestProperties=hp;var mp=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};ut.ResponseSendingEvent=mp;var yp=class extends Event{static{o(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};ut.ResponseSentEvent=yp;var Qi=class t{static{o(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let n=new t(r);return t.#e.set(e,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new HA.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,r,n)=>{for(let i of this.#t)await i(e,r,n)};onResponseSending=async(e,r,n)=>{let i=e;for(let s of this.#r)i=await s(e,r,n);return i}};ut.ZuploContextExtensions=Qi;var gp=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,event:i,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,qA.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Qi.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Qi.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,n){let i=o(s=>{try{typeof r=="function"?r(s):r.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,i,n)}};ut.SystemZuploContext=gp});var _p=_(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.ContextData=void 0;var bp=class t{static{o(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let i=t.#e.get(e);i||(i=new Map),i.set(r,n),t.#e.set(e,i)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};Ta.ContextData=bp});var Yi=_(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.environment=Tr.isZuploReadableEnvVariableName=Tr.isRestrictedEnvVariableName=void 0;var $A=re(),jA=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function sb(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!jA.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}o(sb,"isRestrictedEnvVariableName");Tr.isRestrictedEnvVariableName=sb;function ab(t){return!!t.startsWith("ZUPLO_")}o(ab,"isZuploReadableEnvVariableName");Tr.isZuploReadableEnvVariableName=ab;var VA=new Proxy({},{get(t,e){if(sb(String(e))&&!ab(String(e)))return;let r;return globalThis.process?r=globalThis.process.env[e]:r=$A.Environment.instance.runtime[String(e)],r}});Tr.environment=VA});var Ep=_(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.externalServiceHandler=jn.externalServiceTunnelConfig=void 0;var BA=or(),Zr=k(),GA=wp(),Zi=re(),wt=(0,BA.debug)("zuplo:runtime:external-service");function ub(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=Zi.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}o(ub,"getServiceAuth");async function KA(t){let e=ub();if(!e)throw wt("There is no external service auth configured for this zup."),new Zr.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw wt("Cannot call external service with Request object"),new Zr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(t).hostname,i={};i["CF-Access-Client-Id"]=e.clientId,i["CF-Access-Client-Secret"]=e.clientSecret;let s;if(e.customServiceMapping&&e.customServiceMapping[n])s=`https://${e.customServiceMapping[n]}`;else if(Zi.Environment.instance.useSha256ServiceRouting){wt("Using sha256 service routing");let a=Zi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await lb(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw wt("Cannot use sha256 service routing, missing build variables"),new Zr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(KA,"externalServiceTunnelConfig");jn.externalServiceTunnelConfig=KA;async function JA(t,e){let r=ub();if(r)if(wt(`Using external service auth. ClientId: ${r.clientId})`),typeof t=="string"){let n=new URL(t),i=n.hostname,s=e??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),s.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(Zi.Environment.instance.useSha256ServiceRouting){wt("Using sha256 service routing");let d=Zi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await lb(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw wt("Cannot use sha256 service routing, missing build variables"),new Zr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);wt(`Calling external service: ${u.toString()}`);let l=await(0,GA.originalFetch)(u.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new Zr.RuntimeError("Could not connect to secure tunnel.");return l}else throw wt("Cannot call external service with Request object"),new Zr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw wt("There is no external service auth configured for this zup."),new Zr.RuntimeError("There are no external services configured for this zup.")}o(JA,"externalServiceHandler");jn.externalServiceHandler=JA;async function lb(t,e,r,n){let i=t.toLowerCase(),s=e.toLowerCase(),a=r.toLowerCase(),c=zA(n);wt(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await cb(`${s}-${i}`),l=await cb(`${s}-${a}-${c}`);return`${u}.${l}`}o(lb,"hashServiceName");async function cb(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}o(cb,"hashSegment");function zA(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}o(zA,"sanitizeEnvironmentType")});var wp=_(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.originalFetch=void 0;var WA=Ep(),db=new Map;db.set("service:",WA.externalServiceHandler);Vn.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=QA(e);if(typeof t=="string"){let n=new URL(t),i=db.get(n.protocol);return i?i(t,r):(0,Vn.originalFetch)(t,r)}else return(0,Vn.originalFetch)(t,r)};var QA=o(t=>{if(!t||t instanceof Request)return t;let e=t;if(!e.zuplo)return t;let r=t;return r.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete t.zuplo,t},"transformInit")});var hb=_(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Handler=Bn.purgeGatewayCache=void 0;var YA=k(),fb=qr(),pb=re(),ZA=o(()=>{fb.Gateway.purgeGatewayCache()},"purgeGatewayCache");Bn.purgeGatewayCache=ZA;var vp=class{static{o(this,"Handler")}routeLoader;buildEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,s,a){this.routeLoader=e,this.buildEnvironment=r,this.runtimeSettings=n,this.serviceProvider=i,this.schemaValidations=s,this.runtimeInit=a}requestHandler=async(e,r,n)=>{pb.Environment.initialize(this.buildEnvironment,r);let i;try{i=await fb.Gateway.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(s){console.error("Error initializing gateway.",s);let a="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";s instanceof YA.ConfigurationError&&(a=s.message);let c={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:a,instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:pb.Environment.instance.isDeno?s.message:void 0};return new Response(JSON.stringify(c,null,2),{status:500,headers:{"content-type":"application/json"}})}return i.handleRequest(e,n)}};Bn.Handler=vp});var bb=_(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.pathToRegexp=ke.tokensToRegexp=ke.regexpToFunction=ke.match=ke.tokensToFunction=ke.compile=ke.parse=void 0;function XA(t){for(var e=[],r=0;r<t.length;){var n=t[r];if(n==="*"||n==="+"||n==="?"){e.push({type:"MODIFIER",index:r,value:t[r++]});continue}if(n==="\\"){e.push({type:"ESCAPED_CHAR",index:r++,value:t[r++]});continue}if(n==="{"){e.push({type:"OPEN",index:r,value:t[r++]});continue}if(n==="}"){e.push({type:"CLOSE",index:r,value:t[r++]});continue}if(n===":"){for(var i="",s=r+1;s<t.length;){var a=t.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=t[s++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));e.push({type:"NAME",index:r,value:i}),r=s;continue}if(n==="("){var c=1,u="",s=r+1;if(t[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<t.length;){if(t[s]==="\\"){u+=t[s++]+t[s++];continue}if(t[s]===")"){if(c--,c===0){s++;break}}else if(t[s]==="("&&(c++,t[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));u+=t[s++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));e.push({type:"PATTERN",index:r,value:u}),r=s;continue}e.push({type:"CHAR",index:r,value:t[r++]})}return e.push({type:"END",index:r,value:""}),e}o(XA,"lexer");function Tp(t,e){e===void 0&&(e={});for(var r=XA(t),n=e.prefixes,i=n===void 0?"./":n,s="[^".concat(Gn(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(E){if(u<r.length&&r[u].type===E)return r[u++].value},"tryConsume"),p=o(function(E){var T=d(E);if(T!==void 0)return T;var C=r[u],w=C.type,P=C.index;throw new TypeError("Unexpected ".concat(w," at ").concat(P,", expected ").concat(E))},"mustConsume"),f=o(function(){for(var E="",T;T=d("CHAR")||d("ESCAPED_CHAR");)E+=T;return E},"consumeText");u<r.length;){var h=d("CHAR"),y=d("NAME"),b=d("PATTERN");if(y||b){var I=h||"";i.indexOf(I)===-1&&(l+=I,I=""),l&&(a.push(l),l=""),a.push({name:y||c++,prefix:I,suffix:"",pattern:b||s,modifier:d("MODIFIER")||""});continue}var A=h||d("ESCAPED_CHAR");if(A){l+=A;continue}l&&(a.push(l),l="");var g=d("OPEN");if(g){var I=f(),v=d("NAME")||"",O=d("PATTERN")||"",V=f();p("CLOSE"),a.push({name:v||(O?c++:""),pattern:v&&!O?s:O,prefix:I,suffix:V,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(Tp,"parse");ke.parse=Tp;function e0(t,e){return mb(Tp(t,e),e)}o(e0,"compile");ke.compile=e0;function mb(t,e){e===void 0&&(e={});var r=Sp(e),n=e.encode,i=n===void 0?function(u){return u}:n,s=e.validate,a=s===void 0?!0:s,c=t.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<t.length;d++){var p=t[d];if(typeof p=="string"){l+=p;continue}var f=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<f.length;b++){var I=i(f[b],p);if(a&&!c[d].test(I))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var I=i(String(f),p);if(a&&!c[d].test(I))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(I,'"'));l+=p.prefix+I+p.suffix;continue}if(!h){var A=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(A))}}return l}}o(mb,"tokensToFunction");ke.tokensToFunction=mb;function t0(t,e){var r=[],n=Ip(t,r,e);return yb(n,r,e)}o(t0,"match");ke.match=t0;function yb(t,e,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(s){return s}:n;return function(s){var a=t.exec(s);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=o(function(f){if(a[f]===void 0)return"continue";var h=e[f-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[f].split(h.prefix+h.suffix).map(function(y){return i(y,h)}):l[h.name]=i(a[f],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(yb,"regexpToFunction");ke.regexpToFunction=yb;function Gn(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(Gn,"escapeString");function Sp(t){return t&&t.sensitive?"":"i"}o(Sp,"flags");function r0(t,e){if(!e)return t;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(t.source);i;)e.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(t.source);return t}o(r0,"regexpToRegexp");function n0(t,e,r){var n=t.map(function(i){return Ip(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),Sp(r))}o(n0,"arrayToRegexp");function i0(t,e,r){return gb(Tp(t,r),e,r)}o(i0,"stringToRegexp");function gb(t,e,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,s=r.start,a=s===void 0?!0:s,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(P){return P}:l,p=r.delimiter,f=p===void 0?"/#?":p,h=r.endsWith,y=h===void 0?"":h,b="[".concat(Gn(y),"]|$"),I="[".concat(Gn(f),"]"),A=a?"^":"",g=0,v=t;g<v.length;g++){var O=v[g];if(typeof O=="string")A+=Gn(d(O));else{var V=Gn(d(O.prefix)),E=Gn(d(O.suffix));if(O.pattern)if(e&&e.push(O),V||E)if(O.modifier==="+"||O.modifier==="*"){var T=O.modifier==="*"?"?":"";A+="(?:".concat(V,"((?:").concat(O.pattern,")(?:").concat(E).concat(V,"(?:").concat(O.pattern,"))*)").concat(E,")").concat(T)}else A+="(?:".concat(V,"(").concat(O.pattern,")").concat(E,")").concat(O.modifier);else O.modifier==="+"||O.modifier==="*"?A+="((?:".concat(O.pattern,")").concat(O.modifier,")"):A+="(".concat(O.pattern,")").concat(O.modifier);else A+="(?:".concat(V).concat(E,")").concat(O.modifier)}}if(u)i||(A+="".concat(I,"?")),A+=r.endsWith?"(?=".concat(b,")"):"$";else{var C=t[t.length-1],w=typeof C=="string"?I.indexOf(C[C.length-1])>-1:C===void 0;i||(A+="(?:".concat(I,"(?=").concat(b,"))?")),w||(A+="(?=".concat(I,"|").concat(b,")"))}return new RegExp(A,Sp(r))}o(gb,"tokensToRegexp");ke.tokensToRegexp=gb;function Ip(t,e,r){return t instanceof RegExp?r0(t,e):Array.isArray(t)?n0(t,e,r):i0(t,e,r)}o(Ip,"pathToRegexp");ke.pathToRegexp=Ip});var Op=_(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.AwsV4Signer=Kn.AwsClient=void 0;var o0=or(),vb=k(),s0=(0,o0.debug)("zuplo:runtime"),Ap=new TextEncoder,_b={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},a0=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Rp=class{static{o(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:r,sessionToken:n,service:i,region:s,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=s,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,r){let n=new Sa(Object.assign({url:e},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(e,r){s0("AWS fetch",e);for(let n=0;n<=this.retries;n++){let{url:i,request:s}=await this.sign(e,r),a=fetch(i,s);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new vb.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};Kn.AwsClient=Rp;var Sa=class{static{o(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:r,headers:n,body:i,accessKeyId:s,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:h,allHeaders:y,singleEncode:b}){if(r==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=c;let I,A;(!u||!l)&&([I,A]=c0(this.url,this.headers)),this.service=u||I||"",this.region=l||A||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let g=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),g.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&g.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(O=>y||!a0.includes(O)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(O=>O+":"+(O==="host"?this.url.host:(this.headers.get(O)||"").replace(/\s+/g," "))).join(`
60
60
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!g.has("X-Amz-Expires")&&g.set("X-Amz-Expires","86400"),g.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),g.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),g.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=wb(this.encodedPath);let v=new Set;this.encodedSearch=[...this.url.searchParams].filter(([O])=>{if(!O)return!1;if(this.service==="s3"){if(v.has(O))return!1;v.add(O)}return!0}).map(O=>O.map(V=>wb(encodeURIComponent(V)))).sort(([O,V],[E,T])=>O<E?-1:O>E?1:V<T?-1:V>T?1:0).map(O=>O.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let i=await Xi("AWS4"+this.secretAccessKey,e),s=await Xi(i,this.region),a=await Xi(s,this.service);n=await Xi(a,"aws4_request"),this.cache.set(r,n)}return Pp(await Xi(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Pp(await Eb(await this.canonicalString()))].join(`
61
61
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
62
62
  `,this.signedHeaders,await this.hexBodyHash()].join(`
63
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new vb.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Pp(await Eb(this.body||""))}return e}};Kn.AwsV4Signer=Sa;async function Xi(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Ap.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Ap.encode(e))}o(Xi,"hmac");async function Eb(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Ap.encode(t):t)}o(Eb,"hash");function Pp(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}o(Pp,"buf2hex");function wb(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}o(wb,"encodeRfc3986");function a0(t,e){let{hostname:r,pathname:n}=t,i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(i||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?s="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in _b?[_b[s],a]:[s,a]}o(a0,"guessServiceRegion")});var Tb=_(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.convertStringToUtf8Array=Ft.convertUtf8ArrayToString=Ft.base64Encode=Ft.base64Decode=void 0;function c0(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}o(c0,"b64ToUint6");function u0(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,i=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(i),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=c0(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<i;)s[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return s}o(u0,"base64Decode");Ft.base64Decode=u0;function Ia(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}o(Ia,"uint6ToB64");function l0(t){let e=2,r="",n=t.length,i=0;for(let s=0;s<n;s++)e=s%3,i|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(Ia(i>>>18&63),Ia(i>>>12&63),Ia(i>>>6&63),Ia(i&63)),i=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}o(l0,"base64Encode");Ft.base64Encode=l0;function d0(t){let e="",r,n=t.length;for(let i=0;i<n;i++)r=t[i],e+=String.fromCodePoint(r>251&&r<254&&i+5<n?(r-252)*1073741824+(t[++i]-128<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>247&&r<252&&i+4<n?(r-248<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>239&&r<248&&i+3<n?(r-240<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>223&&r<240&&i+2<n?(r-224<<12)+(t[++i]-128<<6)+t[++i]-128:r>191&&r<224&&i+1<n?(r-192<<6)+t[++i]-128:r);return e}o(d0,"convertUtf8ArrayToString");Ft.convertUtf8ArrayToString=d0;function p0(t){let e,r=t.length,n=0;for(let c=0;c<r;c++)e=t.codePointAt(c),e>=65536&&c++,n+=e<128?1:e<2048?2:e<65536?3:e<2097152?4:e<67108864?5:6;let i=new Uint8Array(n),s=0,a=0;for(;s<n;)e=t.codePointAt(a),e<128?i[s++]=e:e<2048?(i[s++]=192+(e>>>6),i[s++]=128+(e&63)):e<65536?(i[s++]=224+(e>>>12),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63)):e<2097152?(i[s++]=240+(e>>>18),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):e<67108864?(i[s++]=248+(e>>>24),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):(i[s++]=252+(e>>>30),i[s++]=128+(e>>>24&63),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++),a++;return i}o(p0,"convertStringToUtf8Array");Ft.convertStringToUtf8Array=p0});var Sb=_(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.toCLFDate=void 0;function Jn(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}o(Jn,"numberToString");function f0(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",i=Jn(Math.floor(r/60)),s=Jn(r%60);return`${n}${i}${s}`}o(f0,"getCLFOffset");function h0(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Jn(t.getDate()),n=e[t.getMonth()],i=t.getFullYear(),s=Jn(t.getHours()),a=Jn(t.getMinutes()),c=Jn(t.getSeconds()),u=f0(t);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(h0,"toCLFDate");Pa.toCLFDate=h0});var Cb=_(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getResponse=Sr.awsLambdaHandler=Sr.AwsLambdaHandlerExtensions=void 0;var m0=or(),Ib=bb(),eo=k(),y0=Kt(),g0=Op(),Ab=Tb(),Rb=Sb(),Pb=(0,m0.debug)("zuplo:runtime"),b0="X-Amzn-Trace-Id",_0="x-amzn-errortype",Ob=[],E0=o(async(t,e,r)=>{let n=r;for await(let i of Ob)n=await i(t,e,r);return n},"onSendingAwsLambdaEvent"),et=class extends eo.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(b0)??void 0,this.errorType=r.get(_0)??void 0}};Sr.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:t=>{Ob.push(t)}};async function w0(t,e){let{accessKeyId:r,secretAccessKey:n,region:i,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new eo.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new eo.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new eo.ConfigurationError("region is not set in the handler options");if(!s)throw new eo.ConfigurationError("functionName is not set in the handler options");let l=new g0.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Pb(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,f]=await S0(t,{binaryMediaTypes:u}),{options:h}=e.route.handler,y;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?y=T0(t,e):y=await v0(t,e,{useAwsResourcePathStyle:c}),Pb("Calling onSendingAwsLambdaEvent hook");let b=await E0(t,e,y);b.body=p,b.isBase64Encoded=f;let I=await l.fetch(d,{body:JSON.stringify(b)});try{return Nb(I)}catch(A){if(A instanceof et){let g=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&A.traceId?{AMZN_TRACE_ID_HEADER:A.traceId}:void 0;return y0.HttpProblems.internalServerError(t,e,void 0,g)}throw A}}o(w0,"awsLambdaHandler");Sr.awsLambdaHandler=w0;async function Nb(t){let e;try{e=await t.json()}catch{throw new et("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new et(e.message,t.headers):new et(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new et(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new et(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[i,s]of Object.entries(e.headers))r.set(i,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new et(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new et(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new et("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new et("Response was set to base64 encoded but body was not a string",t.headers);n=(0,Ab.base64Decode)(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new et(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let i=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(i).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}o(Nb,"getResponse");Sr.getResponse=Nb;async function v0(t,e,{useAwsResourcePathStyle:r}){let n={},i={};t.headers.forEach((l,d)=>{n[d]=l,i[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:i,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:(0,Rb.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:P0(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}o(v0,"buildEventVersion1");function T0(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:(0,Rb.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}o(T0,"buildEventVersion2");async function S0(t,{binaryMediaTypes:e}){let r,n=!1,i=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&i&&I0(e,i)){let s=await t.arrayBuffer();r=(0,Ab.base64Encode)(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}o(S0,"getBodyResult");function I0(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(I0,"matchesContentType");function P0(t,e=!1){if(!e)return t;let r=(0,Ib.parse)(t),n=(0,Ib.compile)(t),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(P0,"getResourcePath")});var Wn=_(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.getHandlerUserLogFunction=zn.logBadGatewayResponses=void 0;var A0=Je(),R0=ie(),O0=[502,503,504];async function N0(t,e){if(O0.includes(t.status)){let r=A0.SystemLogMap.getLogger(e),i=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:i,headers:s})}}o(N0,"logBadGatewayResponses");zn.logBadGatewayResponses=N0;var Np;function C0(t){if(Np===void 0){let r=R0.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Np=r}return t.log[Np]}o(C0,"getHandlerUserLogFunction");zn.getHandlerUserLogFunction=C0});var Lb=_(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.openApiSpecHandler=void 0;var xb=k(),x0=de(),Cp=ie(),L0=Wn();async function D0(t,e){let r=Cp.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=Cp.Environment.instance,i=e.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new xb.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=M0(s);if(!a.isValid)throw new xb.ConfigurationError(a.error);let c;Cp.Environment.instance.isLocalDevelopment?c=`${n}/${s.substring(1)}`:c=`${n}/${r}${s.substring(1)}`;let u=await fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return x0.HttpProblems.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json"},status:u.status,statusText:u.statusText});return(0,L0.logBadGatewayResponses)(l,e),l}o(D0,"openApiSpecHandler");Aa.openApiSpecHandler=D0;var M0=o(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath")});var Db=_(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.redirectHandler=void 0;var U0=k();async function k0(t,e){let r=e.route.handler.options;if(!r.location)throw new U0.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(k0,"redirectHandler");Ra.redirectHandler=k0});var Ub=_(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.urlForwardHandler=void 0;var F0=k(),Mb=Wn();function H0(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}o(H0,"join");async function q0(t,e){let r=(0,Mb.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1;if(!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new F0.ConfigurationError("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),c=n.__rewriteFunction(t,s),u=H0(c,a.pathname),l=i?`${u}${a.search}`:u.toString(),d=Date.now();r(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),f=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),(0,Mb.logBadGatewayResponses)(p,e),p}o(q0,"urlForwardHandler");Oa.urlForwardHandler=q0});var Fb=_(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.urlRewriteHandler=void 0;var $0=k(),kb=Wn(),j0=o((t,e)=>{let r=new URL(t),n=new URL(e);for(let[i,s]of n.searchParams.entries())r.searchParams.append(i,s);return r.toString()},"addQuery");async function V0(t,e){let r=(0,kb.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new $0.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=i?j0(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),(0,kb.logBadGatewayResponses)(d,e),d}o(V0,"urlRewriteHandler");Na.urlRewriteHandler=V0});var qb=_(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.webSocketHandler=void 0;var Hb=k(),B0=Ep(),G0=Kt(),K0=ie(),J0=Wn();async function z0(t,e){let r=K0.Environment.instance,n=e.route.handler.options,i=(0,J0.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new Hb.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return G0.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Hb.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno){let p=new Headers(t.headers);if(c.startsWith("service:")){let h=await(0,B0.externalServiceTunnelConfig)(c),y=new URL(c);c=new URL(`${h.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let I in h.tunnelHeaders)p.set(I,h.tunnelHeaders[I])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let h=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${h}`}}catch{}let f=JSON.stringify({url:c});return new Response(f,{headers:p})}c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(f)}let d=Date.now()-u;return i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}o(z0,"webSocketHandler");Ca.webSocketHandler=z0});var $b=_(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.webSocketPolicyProcessor=Qn.getWebSocketPolicyFunctions=void 0;var W0=k(),Q0=o((t,e)=>t.map((n,i)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${i+1}, export name: ${n.export}`;throw new W0.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");Qn.getWebSocketPolicyFunctions=Q0;var Y0=o(async(t,e,r,n,i,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,i),a===void 0)return}}return a},"webSocketPolicyProcessor");Qn.webSocketPolicyProcessor=Y0});var Vb=_(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.webSocketPipelineHandler=void 0;var xp=k(),Z0=Kt(),X0=ie(),eR=Wn(),Lp=$b();function jb(t,e,r,n,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let c=o(async u=>{let l=await(0,Lp.webSocketPolicyProcessor)(u,t,e,r,n,i);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(c)}catch(a){n.log.error(a)}})}o(jb,"wireUpListeners");async function tR(t,e){let r=X0.Environment.instance,n=e.route.handler.options,i=(0,eR.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new xp.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return Z0.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new xp.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno)throw new xp.ConfigurationError("Websocket pipeline handler is currently not supported on working-copy environments");c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let A=await l.text(),g=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${A}'`;throw new Error(g)}let d=new WebSocketPair,[p,f]=Object.values(d),h=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${h}ms`);let y=l.webSocket;y.accept(),f.accept();let b=n.policies&&n.policies.inbound?(0,Lp.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],I=n.policies&&n.policies.outbound?(0,Lp.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return jb(f,y,t,e,b),jb(y,f,t,e,I),new Response(null,{status:101,webSocket:p})}o(tR,"webSocketPipelineHandler");xa.webSocketPipelineHandler=tR});var Bb=_(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.DynaTraceLoggingPlugin=void 0;var rR=Re(),Dp=ie(),nR=Kr(),iR=zt(),oR=Ct(),Mp=class extends iR.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Up(this.options)}};La.DynaTraceLoggingPlugin=Mp;var Up=class{static{o(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#n=Dp.Environment.instance.loggingEnvironmentType,this.#i=Dp.Environment.instance.loggingEnvironmentStage,this.#r=Dp.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,oR.stringifyNonString)((0,nR.serializeError)(n)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#r,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new rR.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var Gb=_(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.LokiLoggingPlugin=void 0;var sR=Re(),kp=ie(),aR=Kr(),cR=zt(),uR=Ct(),Fp=class extends cR.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new qp(this.options)}};Da.LokiLoggingPlugin=Fp;var Hp=class{static{o(this,"LokiStream")}constructor(e,r,n,i,s){this.level=e,this.environment=r,this.environmentType=n,this.environmentStage=i,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function lR(t,e){return btoa(`${t}:${e}`)}o(lR,"createBasicDigest");var qp=class{static{o(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=lR(e.username,e.password),this.#n=kp.Environment.instance.loggingEnvironmentType,this.#i=kp.Environment.instance.loggingEnvironmentStage,this.#r=kp.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n=new Hp(e.level,this.#r,this.#n,this.#i,e.requestId);e.messages.forEach(i=>{let s={stream:n,message:(0,uR.stringifyNonString)((0,aR.serializeError)(i)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=e=>{let r={streams:[]};return e.forEach(n=>{let i=r.streams.find(s=>s.stream.equals(n.stream));i||(i={stream:n.stream,values:[]},r.streams.push(i)),i.values.push([n.nanoSecondEpoch,n.message])}),r};#s=async e=>{if(e.length===0)return;let r=this.#o(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new sR.BatchDispatch("loki-log-transport",10,this.#s)}});var Kb=_(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.SumoLogicLoggingPlugin=void 0;var dR=Re(),$p=ie(),pR=Kr(),fR=zt(),hR=Ct(),jp=class extends fR.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Vp(this.options)}};Ma.SumoLogicLoggingPlugin=jp;var Vp=class{static{o(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#i=e.category,this.#o=e.name,this.#r=$p.Environment.instance.loggingEnvironmentType,this.#n=$p.Environment.instance.loggingEnvironmentStage,this.#t=$p.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,hR.stringifyNonString)((0,pR.serializeError)(n)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#r,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let r=e.map(i=>JSON.stringify(i)).join(`
64
- `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#o&&n.set("X-Sumo-Name",this.#o),this.#i&&n.set("X-Sumo-Category",this.#i),await fetch(this.#e,{method:"POST",body:r,headers:n})};batcher=new dR.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var zb=_(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.VMWareLogInsightTransport=Yn.VMWareLogInsightLoggingPlugin=void 0;var mR=k(),yR=Re(),Bp=ie(),gR=zt(),Jb=Ct(),bR="d3a5b78f823648f5b1df4fe269d41172",Gp=class extends gR.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ua(this.options)}};Yn.VMWareLogInsightLoggingPlugin=Gp;var Ua=class{static{o(this,"VMWareLogInsightTransport")}constructor(e){let r;try{r=new URL(e.url),r.pathname==="/"&&(r.pathname=`/api/v1/events/ingest/${e.agentId??bR}`)}catch{throw new mR.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.toString(),this.#n=Bp.Environment.instance.loggingEnvironmentType,this.#i=Bp.Environment.instance.loggingEnvironmentStage,this.#r=Bp.Environment.instance.deploymentName,this.#o=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;#s;log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=(0,Jb.messagesToMultilineText)(e.messages);this.#t?.forEach(s=>{n=n.replaceAll(s[0],s[1])});let i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#i},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&i.fields.push({name:"request_ray_id",content:e.rayId}),this.#r&&i.fields.push({name:"environment",content:this.#r}),this.#s&&i.fields.push(...this.#s),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,Jb.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#o&&(i=this.#o(i)),i}#a=async e=>{if(e.length===0)return;let r=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(r.status!==200)try{let n=await r.text();console.error("Error logging to Log Insight",n)}catch(n){console.error(n)}};batcher=new yR.BatchDispatch("vmware-log-insights-log-transport",10,this.#a)};Yn.VMWareLogInsightTransport=Ua});var Qb=_(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.AWSLogTransport=Zn.AWSLoggingPlugin=void 0;var _R=Op(),ER=Re(),Wb=ie(),wR=Kr(),vR=zt(),TR=Ct(),Kp=class extends vR.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ka(this.options)}};Zn.AWSLoggingPlugin=Kp;var ka=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new ER.BatchDispatch("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:r,logGroupName:n,secretAccessKey:i,region:s}){this.awsClient=new _R.AwsClient({accessKeyId:e,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=Wb.Environment.instance.loggingEnvironmentType,this.environment=Wb.Environment.instance.deploymentName}log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,TR.stringifyNonString)((0,wR.serializeError)(n)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}};Zn.AWSLogTransport=ka});var Yb=_(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.AWSLoggingPlugin=Fe.VMWareLogInsightLoggingPlugin=Fe.SumoLogicLoggingPlugin=Fe.LokiLoggingPlugin=Fe.GoogleCloudLoggingPlugin=Fe.DynaTraceLoggingPlugin=Fe.DataDogLoggingPlugin=void 0;var SR=tp();Object.defineProperty(Fe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return SR.DataDogLoggingPlugin}});var IR=Bb();Object.defineProperty(Fe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return IR.DynaTraceLoggingPlugin}});var PR=oa();Object.defineProperty(Fe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return PR.GoogleCloudLoggingPlugin}});var AR=Gb();Object.defineProperty(Fe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return AR.LokiLoggingPlugin}});var RR=Kb();Object.defineProperty(Fe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return RR.SumoLogicLoggingPlugin}});var OR=zb();Object.defineProperty(Fe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return OR.VMWareLogInsightLoggingPlugin}});var NR=Qb();Object.defineProperty(Fe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return NR.AWSLoggingPlugin}})});var Zb=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.DataDogMetricsError=Ir.DataDogMetricsTransport=Ir.DataDogMetricsPlugin=void 0;var CR=Je(),xR=Re(),LR=es(),Jp=new WeakMap,DR={tags:[]},zp=class extends LR.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Fa(this.options)}static setContext(e,r){let n=Jp.get(e);n||(n=DR);let i=Object.assign({...n},r);Jp.set(e,i)}};Ir.DataDogMetricsPlugin=zp;var Fa=class{static{o(this,"DataDogMetricsTransport")}#e;#t;#r;#n;#i;#o=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#n=e.tags??[]}pushMetrics(e,r){this.#o===void 0&&(this.#o=new xR.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,CR.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),i=this.#n.concat(Jp.get(r)?.tags??[]);if(this.#i.country&&i.push(`country:${e.country}`),this.#i.httpMethod&&i.push(`httpMethod:${e.method}`),this.#i.statusCode&&i.push(`statusCode:${e.statusCode}`),this.#i.path){let s=e.systemRouteName||e.routePath;i.push(`path:${s}`)}this.#r.latency&&this.#o.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:i}),this.#r.requestContentLength&&e.requestContentLength&&this.#o.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:i}),this.#r.responseContentLength&&e.responseContentLength&&this.#o.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:i}),r.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=JSON.stringify({series:e}),n=await fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!n.ok)throw new Ha(await n.text())}};Ir.DataDogMetricsTransport=Fa;var Ha=class t extends Error{static{o(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Ir.DataDogMetricsError=Ha});var Xb=_(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.DynaTraceMetricsError=Pr.DynaTraceMetricsTransport=Pr.DynatraceMetricsPlugin=void 0;var MR=Je(),UR=Re(),kR=es(),Wp=new WeakMap,FR={dimensions:[]},Qp=class extends kR.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new qa(this.options)}static setContext(e,r){let n=Wp.get(e);n||(n=FR);let i=Object.assign({...n},r);Wp.set(e,i)}};Pr.DynatraceMetricsPlugin=Qp;var qa=class{static{o(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#r;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#n===void 0&&(this.#n=new UR.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,MR.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),i=this.dimensions.concat(Wp.get(r)?.dimensions??[]);if(this.#r.country&&i.push(`country="${e.country}"`),this.#r.httpMethod&&i.push(`http_method="${e.method}"`),this.#r.statusCode&&i.push(`status_code="${e.statusCode}"`),this.#r.path){let a=e.systemRouteName||e.routePath;i.push(`path="${a}"`)}let s=i.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${n}`),r.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=e.join(`
65
- `),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new $a(await n.text())}};Pr.DynaTraceMetricsTransport=qa;var $a=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Pr.DynaTraceMetricsError=$a});var e_=_(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.DynatraceMetricsPlugin=Xn.DataDogMetricsPlugin=void 0;var HR=Zb();Object.defineProperty(Xn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return HR.DataDogMetricsPlugin}});var qR=Xb();Object.defineProperty(Xn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return qR.DynatraceMetricsPlugin}})});var t_=_(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.AuditLogDataStaxProvider=void 0;var Yp=class{static{o(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};ja.AuditLogDataStaxProvider=Yp});var n_=_(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.AuditLogPlugin=void 0;var $R=Ot(),jR=Re(),Zp=class extends $R.SystemRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Xp(e,this.#e,this.#t)}};Va.AuditLogPlugin=Zp;var r_=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),VR={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Xp=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...VR};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,e.addRequestHook(this.#o),this.#r=new jR.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async e=>{await this.#t.writeLogBatch(e)};#i=async(e,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?r_(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?r_(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let i=new Date,s=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(f=>{r.log.error(f)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var i_=_(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.StripeSignatureVerificationError=ei.StripeError=void 0;var Ba=class extends Error{static{o(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}};ei.StripeError=Ba;var ef=class extends Ba{static{o(this,"StripeSignatureVerificationError")}header;payload;constructor(e,r,n={}){super(n),this.header=e,this.payload=r}};ei.StripeSignatureVerificationError=ef});var s_=_(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.computeHMACSignatureAsync=ti.constructEventAsync=void 0;var Xr=i_(),BR="v1",GR=300;async function KR(t,e,r,n=GR,i){return await zR(t,e,r,n,i),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}o(KR,"constructEventAsync");ti.constructEventAsync=KR;function JR(t,e){return`${e.timestamp}.${t}`}o(JR,"makeHMACContent");async function zR(t,e,r,n,i){let{decodedHeader:s,decodedPayload:a,details:c,suspectPayloadType:u}=WR(t,e,BR),l=/\s/.test(r),d=await o_(JR(a,c),r);return QR(a,s,c,d,n,u,l,i)}o(zR,"verifyHeaderAsync");function WR(t,e,r){if(!t)throw new Xr.StripeSignatureVerificationError(e,t,{message:"No webhook payload was provided."});let n=typeof t!="string"&&!(t instanceof Uint8Array),i=new TextDecoder("utf8"),s=t instanceof Uint8Array?i.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Xr.StripeSignatureVerificationError(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?i.decode(e):e,c=YR(a,r);if(!c||c.timestamp===-1)throw new Xr.StripeSignatureVerificationError(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!c.signatures.length)throw new Xr.StripeSignatureVerificationError(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:c,suspectPayloadType:n}}o(WR,"parseEventDetails");function QR(t,e,r,n,i,s,a,c){let u=!!r.signatures.filter(f=>ZR(f,n)).length,l=`
63
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new vb.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Pp(await Eb(this.body||""))}return e}};Kn.AwsV4Signer=Sa;async function Xi(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Ap.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Ap.encode(e))}o(Xi,"hmac");async function Eb(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Ap.encode(t):t)}o(Eb,"hash");function Pp(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}o(Pp,"buf2hex");function wb(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}o(wb,"encodeRfc3986");function c0(t,e){let{hostname:r,pathname:n}=t,i=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(i||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?s="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in _b?[_b[s],a]:[s,a]}o(c0,"guessServiceRegion")});var Tb=_(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.convertStringToUtf8Array=Ft.convertUtf8ArrayToString=Ft.base64Encode=Ft.base64Decode=void 0;function u0(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}o(u0,"b64ToUint6");function l0(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,i=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(i),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=u0(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<i;)s[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return s}o(l0,"base64Decode");Ft.base64Decode=l0;function Ia(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}o(Ia,"uint6ToB64");function d0(t){let e=2,r="",n=t.length,i=0;for(let s=0;s<n;s++)e=s%3,i|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(Ia(i>>>18&63),Ia(i>>>12&63),Ia(i>>>6&63),Ia(i&63)),i=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}o(d0,"base64Encode");Ft.base64Encode=d0;function p0(t){let e="",r,n=t.length;for(let i=0;i<n;i++)r=t[i],e+=String.fromCodePoint(r>251&&r<254&&i+5<n?(r-252)*1073741824+(t[++i]-128<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>247&&r<252&&i+4<n?(r-248<<24)+(t[++i]-128<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>239&&r<248&&i+3<n?(r-240<<18)+(t[++i]-128<<12)+(t[++i]-128<<6)+t[++i]-128:r>223&&r<240&&i+2<n?(r-224<<12)+(t[++i]-128<<6)+t[++i]-128:r>191&&r<224&&i+1<n?(r-192<<6)+t[++i]-128:r);return e}o(p0,"convertUtf8ArrayToString");Ft.convertUtf8ArrayToString=p0;function f0(t){let e,r=t.length,n=0;for(let c=0;c<r;c++)e=t.codePointAt(c),e>=65536&&c++,n+=e<128?1:e<2048?2:e<65536?3:e<2097152?4:e<67108864?5:6;let i=new Uint8Array(n),s=0,a=0;for(;s<n;)e=t.codePointAt(a),e<128?i[s++]=e:e<2048?(i[s++]=192+(e>>>6),i[s++]=128+(e&63)):e<65536?(i[s++]=224+(e>>>12),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63)):e<2097152?(i[s++]=240+(e>>>18),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):e<67108864?(i[s++]=248+(e>>>24),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++):(i[s++]=252+(e>>>30),i[s++]=128+(e>>>24&63),i[s++]=128+(e>>>18&63),i[s++]=128+(e>>>12&63),i[s++]=128+(e>>>6&63),i[s++]=128+(e&63),a++),a++;return i}o(f0,"convertStringToUtf8Array");Ft.convertStringToUtf8Array=f0});var Sb=_(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.toCLFDate=void 0;function Jn(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}o(Jn,"numberToString");function h0(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",i=Jn(Math.floor(r/60)),s=Jn(r%60);return`${n}${i}${s}`}o(h0,"getCLFOffset");function m0(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Jn(t.getDate()),n=e[t.getMonth()],i=t.getFullYear(),s=Jn(t.getHours()),a=Jn(t.getMinutes()),c=Jn(t.getSeconds()),u=h0(t);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(m0,"toCLFDate");Pa.toCLFDate=m0});var Cb=_(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getResponse=Sr.awsLambdaHandler=Sr.AwsLambdaHandlerExtensions=void 0;var y0=or(),Ib=bb(),eo=k(),g0=Kt(),b0=Op(),Ab=Tb(),Rb=Sb(),Pb=(0,y0.debug)("zuplo:runtime"),_0="X-Amzn-Trace-Id",E0="x-amzn-errortype",Ob=[],w0=o(async(t,e,r)=>{let n=r;for await(let i of Ob)n=await i(t,e,r);return n},"onSendingAwsLambdaEvent"),et=class extends eo.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(_0)??void 0,this.errorType=r.get(E0)??void 0}};Sr.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:t=>{Ob.push(t)}};async function v0(t,e){let{accessKeyId:r,secretAccessKey:n,region:i,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new eo.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new eo.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new eo.ConfigurationError("region is not set in the handler options");if(!s)throw new eo.ConfigurationError("functionName is not set in the handler options");let l=new b0.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Pb(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,f]=await I0(t,{binaryMediaTypes:u}),{options:h}=e.route.handler,y;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?y=S0(t,e):y=await T0(t,e,{useAwsResourcePathStyle:c}),Pb("Calling onSendingAwsLambdaEvent hook");let b=await w0(t,e,y);b.body=p,b.isBase64Encoded=f;let I=await l.fetch(d,{body:JSON.stringify(b)});try{return Nb(I)}catch(A){if(A instanceof et){let g=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&A.traceId?{AMZN_TRACE_ID_HEADER:A.traceId}:void 0;return g0.HttpProblems.internalServerError(t,e,void 0,g)}throw A}}o(v0,"awsLambdaHandler");Sr.awsLambdaHandler=v0;async function Nb(t){let e;try{e=await t.json()}catch{throw new et("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new et(e.message,t.headers):new et(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new et(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new et(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[i,s]of Object.entries(e.headers))r.set(i,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new et(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new et(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new et("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new et("Response was set to base64 encoded but body was not a string",t.headers);n=(0,Ab.base64Decode)(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new et(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let i=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(i).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}o(Nb,"getResponse");Sr.getResponse=Nb;async function T0(t,e,{useAwsResourcePathStyle:r}){let n={},i={};t.headers.forEach((l,d)=>{n[d]=l,i[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]=[d];let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:i,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:(0,Rb.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:A0(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}o(T0,"buildEventVersion1");function S0(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:(0,Rb.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}o(S0,"buildEventVersion2");async function I0(t,{binaryMediaTypes:e}){let r,n=!1,i=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&i&&P0(e,i)){let s=await t.arrayBuffer();r=(0,Ab.base64Encode)(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}o(I0,"getBodyResult");function P0(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(P0,"matchesContentType");function A0(t,e=!1){if(!e)return t;let r=(0,Ib.parse)(t),n=(0,Ib.compile)(t),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(A0,"getResourcePath")});var Wn=_(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.getHandlerUserLogFunction=zn.logBadGatewayResponses=void 0;var R0=Je(),O0=re(),N0=[502,503,504];async function C0(t,e){if(N0.includes(t.status)){let r=R0.SystemLogMap.getLogger(e),i=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:i,headers:s})}}o(C0,"logBadGatewayResponses");zn.logBadGatewayResponses=C0;var Np;function x0(t){if(Np===void 0){let r=O0.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Np=r}return t.log[Np]}o(x0,"getHandlerUserLogFunction");zn.getHandlerUserLogFunction=x0});var Lb=_(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.openApiSpecHandler=void 0;var xb=k(),L0=de(),Cp=re(),D0=Wn();async function M0(t,e){let r=Cp.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=Cp.Environment.instance,i=e.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new xb.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=U0(s);if(!a.isValid)throw new xb.ConfigurationError(a.error);let c;Cp.Environment.instance.isLocalDevelopment?c=`${n}/${s.substring(1)}`:c=`${n}/${r}${s.substring(1)}`;let u=await fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return L0.HttpProblems.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json"},status:u.status,statusText:u.statusText});return(0,D0.logBadGatewayResponses)(l,e),l}o(M0,"openApiSpecHandler");Aa.openApiSpecHandler=M0;var U0=o(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath")});var Db=_(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.redirectHandler=void 0;var k0=k();async function F0(t,e){let r=e.route.handler.options;if(!r.location)throw new k0.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(F0,"redirectHandler");Ra.redirectHandler=F0});var Ub=_(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.urlForwardHandler=void 0;var H0=k(),Mb=Wn();function q0(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}o(q0,"join");async function $0(t,e){let r=(0,Mb.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1;if(!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new H0.ConfigurationError("Invalid options for this route");let s={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(t.url),c=n.__rewriteFunction(t,s),u=q0(c,a.pathname),l=i?`${u}${a.search}`:u.toString(),d=Date.now();r(`URL Forwarding to '${l}'`);let p=await fetch(l,{method:t.method,body:t.body,headers:t.headers}),f=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),(0,Mb.logBadGatewayResponses)(p,e),p}o($0,"urlForwardHandler");Oa.urlForwardHandler=$0});var Fb=_(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.urlRewriteHandler=void 0;var j0=k(),kb=Wn(),V0=o((t,e)=>{let r=new URL(t),n=new URL(e);for(let[i,s]of n.searchParams.entries())r.searchParams.append(i,s);return r.toString()},"addQuery");async function B0(t,e){let r=(0,kb.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new j0.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=i?V0(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),(0,kb.logBadGatewayResponses)(d,e),d}o(B0,"urlRewriteHandler");Na.urlRewriteHandler=B0});var qb=_(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.webSocketHandler=void 0;var Hb=k(),G0=Ep(),K0=Kt(),J0=re(),z0=Wn();async function W0(t,e){let r=J0.Environment.instance,n=e.route.handler.options,i=(0,z0.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new Hb.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return K0.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Hb.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno){let p=new Headers(t.headers);if(c.startsWith("service:")){let h=await(0,G0.externalServiceTunnelConfig)(c),y=new URL(c);c=new URL(`${h.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let I in h.tunnelHeaders)p.set(I,h.tunnelHeaders[I])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let h=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${h}`}}catch{}let f=JSON.stringify({url:c});return new Response(f,{headers:p})}c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let p=await l.text(),f=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(f)}let d=Date.now()-u;return i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${d}ms`),new Response(null,{status:101,webSocket:l.webSocket})}o(W0,"webSocketHandler");Ca.webSocketHandler=W0});var $b=_(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.webSocketPolicyProcessor=Qn.getWebSocketPolicyFunctions=void 0;var Q0=k(),Y0=o((t,e)=>t.map((n,i)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${i+1}, export name: ${n.export}`;throw new Q0.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");Qn.getWebSocketPolicyFunctions=Y0;var Z0=o(async(t,e,r,n,i,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,i),a===void 0)return}}return a},"webSocketPolicyProcessor");Qn.webSocketPolicyProcessor=Z0});var Vb=_(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.webSocketPipelineHandler=void 0;var xp=k(),X0=Kt(),eR=re(),tR=Wn(),Lp=$b();function jb(t,e,r,n,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let c=o(async u=>{let l=await(0,Lp.webSocketPolicyProcessor)(u,t,e,r,n,i);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(c)}catch(a){n.log.error(a)}})}o(jb,"wireUpListeners");async function rR(t,e){let r=eR.Environment.instance,n=e.route.handler.options,i=(0,tR.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new xp.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return X0.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new xp.ConfigurationError("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},c=n.__rewriteFunction(t,a),u=Date.now();if(i(`Attempting WebSocket connection to '${c}'`),r.isDeno)throw new xp.ConfigurationError("Websocket pipeline handler is currently not supported on working-copy environments");c=c.replace(/^(ws)/,"http");let l=await fetch(c,{method:t.method,headers:t.headers,body:t.body});if(l.status!==101||!l.webSocket){let A=await l.text(),g=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${A}'`;throw new Error(g)}let d=new WebSocketPair,[p,f]=Object.values(d),h=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${h}ms`);let y=l.webSocket;y.accept(),f.accept();let b=n.policies&&n.policies.inbound?(0,Lp.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],I=n.policies&&n.policies.outbound?(0,Lp.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return jb(f,y,t,e,b),jb(y,f,t,e,I),new Response(null,{status:101,webSocket:p})}o(rR,"webSocketPipelineHandler");xa.webSocketPipelineHandler=rR});var Bb=_(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.DynaTraceLoggingPlugin=void 0;var nR=Re(),Dp=re(),iR=Kr(),oR=zt(),sR=Ct(),Mp=class extends oR.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Up(this.options)}};La.DynaTraceLoggingPlugin=Mp;var Up=class{static{o(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#n=Dp.Environment.instance.loggingEnvironmentType,this.#i=Dp.Environment.instance.loggingEnvironmentStage,this.#r=Dp.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,sR.stringifyNonString)((0,iR.serializeError)(n)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.environment":this.#r,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=async e=>{e.length!==0&&await fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new nR.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var Gb=_(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.LokiLoggingPlugin=void 0;var aR=Re(),kp=re(),cR=Kr(),uR=zt(),lR=Ct(),Fp=class extends uR.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new qp(this.options)}};Da.LokiLoggingPlugin=Fp;var Hp=class{static{o(this,"LokiStream")}constructor(e,r,n,i,s){this.level=e,this.environment=r,this.environmentType=n,this.environmentStage=i,this.requestId=s}job="zuplo";level;environment;environmentType;environmentStage;requestId;equals=e=>this.level===e.level&&this.requestId===e.requestId};function dR(t,e){return btoa(`${t}:${e}`)}o(dR,"createBasicDigest");var qp=class{static{o(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=dR(e.username,e.password),this.#n=kp.Environment.instance.loggingEnvironmentType,this.#i=kp.Environment.instance.loggingEnvironmentStage,this.#r=kp.Environment.instance.deploymentName}#e;#t;#r;#n;#i;log(e,r){let n=new Hp(e.level,this.#r,this.#n,this.#i,e.requestId);e.messages.forEach(i=>{let s={stream:n,message:(0,lR.stringifyNonString)((0,cR.serializeError)(i)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(s)}),r.waitUntil(this.batcher.waitUntilFlushed())}#o=e=>{let r={streams:[]};return e.forEach(n=>{let i=r.streams.find(s=>s.stream.equals(n.stream));i||(i={stream:n.stream,values:[]},r.streams.push(i)),i.values.push([n.nanoSecondEpoch,n.message])}),r};#s=async e=>{if(e.length===0)return;let r=this.#o(e);await fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#t}`}})};batcher=new aR.BatchDispatch("loki-log-transport",10,this.#s)}});var Kb=_(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.SumoLogicLoggingPlugin=void 0;var pR=Re(),$p=re(),fR=Kr(),hR=zt(),mR=Ct(),jp=class extends hR.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Vp(this.options)}};Ma.SumoLogicLoggingPlugin=jp;var Vp=class{static{o(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#i=e.category,this.#o=e.name,this.#r=$p.Environment.instance.loggingEnvironmentType,this.#n=$p.Environment.instance.loggingEnvironmentStage,this.#t=$p.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,mR.stringifyNonString)((0,fR.serializeError)(n)),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#r,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let r=e.map(i=>JSON.stringify(i)).join(`
64
+ `),n=new Headers({"content-type":"application/json; charset=utf-8"});this.#o&&n.set("X-Sumo-Name",this.#o),this.#i&&n.set("X-Sumo-Category",this.#i),await fetch(this.#e,{method:"POST",body:r,headers:n})};batcher=new pR.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var zb=_(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.VMWareLogInsightTransport=Yn.VMWareLogInsightLoggingPlugin=void 0;var yR=k(),gR=Re(),Bp=re(),bR=zt(),Jb=Ct(),_R="d3a5b78f823648f5b1df4fe269d41172",Gp=class extends bR.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ua(this.options)}};Yn.VMWareLogInsightLoggingPlugin=Gp;var Ua=class{static{o(this,"VMWareLogInsightTransport")}constructor(e){let r;try{r=new URL(e.url),r.pathname==="/"&&(r.pathname=`/api/v1/events/ingest/${e.agentId??_R}`)}catch{throw new yR.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.toString(),this.#n=Bp.Environment.instance.loggingEnvironmentType,this.#i=Bp.Environment.instance.loggingEnvironmentStage,this.#r=Bp.Environment.instance.deploymentName,this.#o=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;#s;log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=(0,Jb.messagesToMultilineText)(e.messages);this.#t?.forEach(s=>{n=n.replaceAll(s[0],s[1])});let i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#i},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&i.fields.push({name:"request_ray_id",content:e.rayId}),this.#r&&i.fields.push({name:"environment",content:this.#r}),this.#s&&i.fields.push(...this.#s),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,Jb.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#o&&(i=this.#o(i)),i}#a=async e=>{if(e.length===0)return;let r=await fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(r.status!==200)try{let n=await r.text();console.error("Error logging to Log Insight",n)}catch(n){console.error(n)}};batcher=new gR.BatchDispatch("vmware-log-insights-log-transport",10,this.#a)};Yn.VMWareLogInsightTransport=Ua});var Qb=_(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.AWSLogTransport=Zn.AWSLoggingPlugin=void 0;var ER=Op(),wR=Re(),Wb=re(),vR=Kr(),TR=zt(),SR=Ct(),Kp=class extends TR.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ka(this.options)}};Zn.AWSLoggingPlugin=Kp;var ka=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new wR.BatchDispatch("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}})});constructor({accessKeyId:e,logStreamName:r,logGroupName:n,secretAccessKey:i,region:s}){this.awsClient=new ER.AwsClient({accessKeyId:e,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=Wb.Environment.instance.loggingEnvironmentType,this.environment=Wb.Environment.instance.deploymentName}log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,SR.stringifyNonString)((0,vR.serializeError)(n)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}};Zn.AWSLogTransport=ka});var Yb=_(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.AWSLoggingPlugin=Fe.VMWareLogInsightLoggingPlugin=Fe.SumoLogicLoggingPlugin=Fe.LokiLoggingPlugin=Fe.GoogleCloudLoggingPlugin=Fe.DynaTraceLoggingPlugin=Fe.DataDogLoggingPlugin=void 0;var IR=tp();Object.defineProperty(Fe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return IR.DataDogLoggingPlugin}});var PR=Bb();Object.defineProperty(Fe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return PR.DynaTraceLoggingPlugin}});var AR=oa();Object.defineProperty(Fe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return AR.GoogleCloudLoggingPlugin}});var RR=Gb();Object.defineProperty(Fe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return RR.LokiLoggingPlugin}});var OR=Kb();Object.defineProperty(Fe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return OR.SumoLogicLoggingPlugin}});var NR=zb();Object.defineProperty(Fe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return NR.VMWareLogInsightLoggingPlugin}});var CR=Qb();Object.defineProperty(Fe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return CR.AWSLoggingPlugin}})});var Zb=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.DataDogMetricsError=Ir.DataDogMetricsTransport=Ir.DataDogMetricsPlugin=void 0;var xR=Je(),LR=Re(),DR=es(),Jp=new WeakMap,MR={tags:[]},zp=class extends DR.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Fa(this.options)}static setContext(e,r){let n=Jp.get(e);n||(n=MR);let i=Object.assign({...n},r);Jp.set(e,i)}};Ir.DataDogMetricsPlugin=zp;var Fa=class{static{o(this,"DataDogMetricsTransport")}#e;#t;#r;#n;#i;#o=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#n=e.tags??[]}pushMetrics(e,r){this.#o===void 0&&(this.#o=new LR.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,xR.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),i=this.#n.concat(Jp.get(r)?.tags??[]);if(this.#i.country&&i.push(`country:${e.country}`),this.#i.httpMethod&&i.push(`httpMethod:${e.method}`),this.#i.statusCode&&i.push(`statusCode:${e.statusCode}`),this.#i.path){let s=e.systemRouteName||e.routePath;i.push(`path:${s}`)}this.#r.latency&&this.#o.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:n,value:e.durationMs}],tags:i}),this.#r.requestContentLength&&e.requestContentLength&&this.#o.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:n,value:e.requestContentLength}],tags:i}),this.#r.responseContentLength&&e.responseContentLength&&this.#o.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:n,value:e.responseContentLength}],tags:i}),r.waitUntil(this.#o.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=JSON.stringify({series:e}),n=await fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!n.ok)throw new Ha(await n.text())}};Ir.DataDogMetricsTransport=Fa;var Ha=class t extends Error{static{o(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Ir.DataDogMetricsError=Ha});var Xb=_(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.DynaTraceMetricsError=Pr.DynaTraceMetricsTransport=Pr.DynatraceMetricsPlugin=void 0;var UR=Je(),kR=Re(),FR=es(),Wp=new WeakMap,HR={dimensions:[]},Qp=class extends FR.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new qa(this.options)}static setContext(e,r){let n=Wp.get(e);n||(n=HR);let i=Object.assign({...n},r);Wp.set(e,i)}};Pr.DynatraceMetricsPlugin=Qp;var qa=class{static{o(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#r;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#n===void 0&&(this.#n=new kR.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,UR.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),i=this.dimensions.concat(Wp.get(r)?.dimensions??[]);if(this.#r.country&&i.push(`country="${e.country}"`),this.#r.httpMethod&&i.push(`http_method="${e.method}"`),this.#r.statusCode&&i.push(`status_code="${e.statusCode}"`),this.#r.path){let a=e.systemRouteName||e.routePath;i.push(`path="${a}"`)}let s=i.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${n}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${n}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${n}`),r.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;let r=e.join(`
65
+ `),n=await fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!n.ok)throw new $a(await n.text())}};Pr.DynaTraceMetricsTransport=qa;var $a=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Pr.DynaTraceMetricsError=$a});var e_=_(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.DynatraceMetricsPlugin=Xn.DataDogMetricsPlugin=void 0;var qR=Zb();Object.defineProperty(Xn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return qR.DataDogMetricsPlugin}});var $R=Xb();Object.defineProperty(Xn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return $R.DynatraceMetricsPlugin}})});var t_=_(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.AuditLogDataStaxProvider=void 0;var Yp=class{static{o(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async r=>{await fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))}};ja.AuditLogDataStaxProvider=Yp});var n_=_(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.AuditLogPlugin=void 0;var jR=Ot(),VR=Re(),Zp=class extends jR.SystemRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Xp(e,this.#e,this.#t)}};Va.AuditLogPlugin=Zp;var r_=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),BR={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Xp=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...BR};n?.requestFilter&&(i.requestFilter=n.requestFilter),n?.include?.request&&Object.assign(i,n.include.request),n?.include?.response&&Object.assign(i,n.include.response),this.#e=i,e.addRequestHook(this.#o),this.#r=new VR.BatchDispatch("audit-log",10,this.#n)}#e;#t;#r;#n=async e=>{await this.#t.writeLogBatch(e)};#i=async(e,r,n,i,s,a)=>{try{let c={timestamp:i,durationMs:s,routePath:n.route.path,requestId:n.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?r_(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?r_(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#r.enqueue(c),n.waitUntil(this.#r.waitUntilFlushed())}catch(c){n.log.error(c)}};#o=async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let i=new Date,s=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,r,i,l-s,u.user?.sub).catch(f=>{r.log.error(f)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var i_=_(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.StripeSignatureVerificationError=ei.StripeError=void 0;var Ba=class extends Error{static{o(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}};ei.StripeError=Ba;var ef=class extends Ba{static{o(this,"StripeSignatureVerificationError")}header;payload;constructor(e,r,n={}){super(n),this.header=e,this.payload=r}};ei.StripeSignatureVerificationError=ef});var s_=_(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.computeHMACSignatureAsync=ti.constructEventAsync=void 0;var Xr=i_(),GR="v1",KR=300;async function JR(t,e,r,n=KR,i){return await WR(t,e,r,n,i),t instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(t)):JSON.parse(t)}o(JR,"constructEventAsync");ti.constructEventAsync=JR;function zR(t,e){return`${e.timestamp}.${t}`}o(zR,"makeHMACContent");async function WR(t,e,r,n,i){let{decodedHeader:s,decodedPayload:a,details:c,suspectPayloadType:u}=QR(t,e,GR),l=/\s/.test(r),d=await o_(zR(a,c),r);return YR(a,s,c,d,n,u,l,i)}o(WR,"verifyHeaderAsync");function QR(t,e,r){if(!t)throw new Xr.StripeSignatureVerificationError(e,t,{message:"No webhook payload was provided."});let n=typeof t!="string"&&!(t instanceof Uint8Array),i=new TextDecoder("utf8"),s=t instanceof Uint8Array?i.decode(t):t;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new Xr.StripeSignatureVerificationError(e,t,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?i.decode(e):e,c=ZR(a,r);if(!c||c.timestamp===-1)throw new Xr.StripeSignatureVerificationError(a,s,{message:"Unable to extract timestamp and signatures from header"});if(!c.signatures.length)throw new Xr.StripeSignatureVerificationError(a,s,{message:"No signatures found with expected scheme"});return{decodedPayload:s,decodedHeader:a,details:c,suspectPayloadType:n}}o(QR,"parseEventDetails");function YR(t,e,r,n,i,s,a,c){let u=!!r.signatures.filter(f=>XR(f,n)).length,l=`
66
66
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
67
67
 
68
68
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!u)throw s?new Xr.StripeSignatureVerificationError(e,t,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -71,23 +71,23 @@ Signature verification is impossible without access to the original signed mater
71
71
  `+d}):new Xr.StripeSignatureVerificationError(e,t,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
72
72
  If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
73
73
  `+l+`
74
- `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Xr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(QR,"validateComputedSignature");function YR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(YR,"parseHeader");function ZR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(ZR,"secureCompare");async function o_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=tf[s[c]];return a.join("")}o(o_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=o_;var tf=new Array(256);for(let t=0;t<tf.length;t++)tf[t]=t.toString(16).padStart(2,"0")});var lt=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.optionValidator=void 0;var ri=k(),XR=at();function eO(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,XR.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(eO,"optionValidator");Ga.optionValidator=eO});var nf=_(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.StripeWebhookVerificationInboundPolicy=void 0;var tO=_n(),rO=de(),nO=s_(),iO=lt(),rf=class extends tO.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,iO.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,nO.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),rO.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Ka.StripeWebhookVerificationInboundPolicy=rf});var c_=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.isStripeWebhookEvent=void 0;var a_=at();function oO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,a_.isString)(t.id)&&"type"in t&&(0,a_.isString)(t.type)}o(oO,"isStripeWebhookEvent");Ja.isStripeWebhookEvent=oO});var u_=_(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.MeteringPlugin=void 0;var sO=Ot(),of=class extends sO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};za.MeteringPlugin=of});var cf=_(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var sf=k(),aO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i}};af.default=aO});var d_=_(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.deleteConsumer=Ar.createConsumerInvite=Ar.createConsumer=void 0;var uf=k(),lf=Je(),df=ie(),pf=kn(),ff="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l_="My API Key";async function cO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=df.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,ff);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new uf.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(cO,"createConsumer");Ar.createConsumer=cO;async function uO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=df.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,ff);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new uf.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(uO,"createConsumerInvite");Ar.createConsumerInvite=uO;async function lO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=df.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,ff);i.searchParams.set("with-api-key","true");let s=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new uf.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(lO,"deleteConsumer");Ar.deleteConsumer=lO});var Wa=_(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getSubscription=Or.updateSubscription=Or.createSubscription=void 0;var Rr=k(),hf=Je(),mf=ie(),yf=kn(),gf=at();async function dO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c,metadata:u}){let l={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:u},{authApiJWT:d,meteringServiceUrl:p}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(d))throw new Rr.SystemError("No Zuplo JWT token set.");let f=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${p}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!f.ok){let h="Error creating monetization subscription.",y;try{y=await f.json()}catch{y={status:f.status,statusText:f.statusText}}throw t.log.error(h,y),new Rr.RuntimeError(h)}t.log.info("Successfully created monetization subscription.",l)}o(dO,"createSubscription");Or.createSubscription=dO;async function pO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Rr.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(pO,"updateSubscription");Or.updateSubscription=pO;async function fO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Rr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}return c.data[0]}o(fO,"getSubscription");Or.getSubscription=fO});var bf=_(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.stripeStatusToMeteringStatus=void 0;function hO(t){return t.replaceAll("_","-")}o(hO,"stripeStatusToMeteringStatus");Qa.stripeStatusToMeteringStatus=hO});var p_=_(to=>{"use strict";var mO=to&&to.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(to,"__esModule",{value:!0});var en=de(),yO=mO(cf()),_f=d_(),gO=Wa(),bO=bf();async function _O(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u,l,d;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,u=await(0,_f.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await yO.default.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,_f.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!u)return en.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=(0,bO.stripeStatusToMeteringStatus)(r.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}}),await(0,gO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f})}catch(p){return await(0,_f.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),en.HttpProblems.internalServerError(t,e,{detail:p.message})}return en.HttpProblems.ok(t,e)}o(_O,"onCustomerSubscriptionCreated");to.default=_O});var h_=_(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ef=de(),f_=Wa();async function EO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,f_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,f_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),Ef.HttpProblems.ok(t,e)}o(EO,"onCustomerSubscriptionDeleted");wf.default=EO});var m_=_(no=>{"use strict";var wO=no&&no.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(no,"__esModule",{value:!0});var ro=de(),vO=wO(cf()),Ya=Wa(),TO=bf();async function SO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,TO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),ro.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await vO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),ro.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),ro.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(SO,"onCustomerSubscriptionUpdated");no.default=SO});var g_=_(ni=>{"use strict";var Tf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Za=Yi(),Xa=k(),IO=Gt(),PO=nf(),y_=de(),AO=ar(),RO=En(),OO=Sl(),NO=gt(),CO=ie(),xO=c_(),LO=lt(),DO=u_(),MO=Tf(p_()),UO=Tf(h_()),kO=Tf(m_()),vf=class extends DO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!CO.Environment.instance.build.ACCOUNT_NAME)throw new Xa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!FO(p))throw new Xa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,xO.isStripeWebhookEvent)(f))return y_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,MO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,kO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,UO.default)(c,u,f,{meteringBucketId:l});default:return y_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,RO.createInternalPolicyProcessor)({inboundPolicies:[new PO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,LO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new IO.Pipeline({processors:[AO.metricsProcessor,i],handler:n,gateway:r}),a=new NO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:OO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=vf;function FO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(FO,"isMetricsRegion")});var v_=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var b_=k(),HO=Re(),__=Jt(),w_=new WeakMap,E_={},Sf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){w_.set(e,r)}};ii.AmberfloMeteringPolicy=Sf;async function qO(t,e,r,n){if(!r.statusCodes)throw new b_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,__.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=w_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new b_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,__.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=E_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new HO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let I=r.url??"https://app.amberflo.io/ingest",A=await fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),E_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o(qO,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=qO});var If=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.sha256=void 0;async function $O(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o($O,"sha256");ec.sha256=$O});var Zt=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.getPolicyCacheName=void 0;var jO=If(),T_=new Map;async function VO(t,e){let r,n=T_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,jO.sha256)(JSON.stringify({policyName:t,options:e}))}`,T_.set(t,r)),r}o(VO,"getPolicyCacheName");tc.getPolicyCacheName=VO});var Rf=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ApiKeyInboundPolicy=void 0;var BO=Zt(),GO=Bt(),S_=Yi(),Pf=k(),KO=Kt(),I_=Je(),Af=ie(),JO=kn(),P_="key-metadata-cache-type";function zO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(zO,"getKeyValue");async function WO(t,e,r,n){if(!r.bucketName)if(S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?t:KO.HttpProblems.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=zO(a,i);if(!c||c==="")return s("No key present");let u=await QO(c),l=await(0,BO.getPolicyCacheName)(n,i),d=new GO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==P_&&I_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,JO.fetchRetry)({retryDelayMs:5,retries:2,logger:I_.SystemLogMap.getLogger(e)},`${Af.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Af.Environment.instance.deploymentName??"unknown","User-Agent":Af.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),A=JSON.parse(I);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Pf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:P_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(WO,"ApiKeyInboundPolicy");rc.ApiKeyInboundPolicy=WO;async function QO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(QO,"hashValue")});var A_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ApiAuthKeyInboundPolicy=void 0;var YO=Rf();nc.ApiAuthKeyInboundPolicy=YO.ApiKeyInboundPolicy});var Xt=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.OpenIdJwtInboundPolicy=void 0;var Nf=(ra(),xo(ta)),Cf=k(),ZO=de(),Of={},XO=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Cf.ConfigurationError("Invalid State - jwkUrl not set");Of[e.jwkUrl]||(Of[e.jwkUrl]=(0,Nf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Nf.jwtVerify)(t,Of[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),eN=o(async(t,e)=>{let r;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Nf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),tN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>ZO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?XO:eN,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ic.OpenIdJwtInboundPolicy=tN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.Auth0JwtInboundPolicy=void 0;var rN=Xt(),nN=o(async(t,e,r,n)=>(0,rN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");oc.Auth0JwtInboundPolicy=nN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BasicAuthInboundPolicy=void 0;var iN=de(),oN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>iN.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");sc.BasicAuthInboundPolicy=oN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CachingInboundPolicy=void 0;var sN=Zt(),aN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function cN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(cN,"digestMessage");var uN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await cN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function lN(t,e,r,n){let i=await(0,sN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await uN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);aN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(lN,"CachingInboundPolicy");ac.CachingInboundPolicy=lN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ChangeMethodInboundPolicy=void 0;var dN=k(),pN=Ke(),fN=o(async(t,e,r,n)=>{if(!r.method)throw new dN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new pN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");cc.ChangeMethodInboundPolicy=fN});var x_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.ClearHeadersInboundPolicy=void 0;var hN=Ke(),mN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new hN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");uc.ClearHeadersInboundPolicy=mN});var L_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.ClearHeadersOutboundPolicy=void 0;var yN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");lc.ClearHeadersOutboundPolicy=yN});var D_=_(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.ClerkJwtInboundPolicy=void 0;var gN=Xt(),bN=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,gN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");dc.ClerkJwtInboundPolicy=bN});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CognitoJwtInboundPolicy=void 0;var M_=k(),_N=Xt(),EN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new M_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new M_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,_N.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");pc.CognitoJwtInboundPolicy=EN});var F_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.CompositeInboundPolicy=void 0;var wN=k(),vN=qr(),k_=En(),TN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new wN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=vN.Gateway.instance,s=(0,k_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,k_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");fc.CompositeInboundPolicy=TN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.CurityPhantomTokenInboundPolicy=void 0;var SN=Zt(),IN=Bt(),hc=de(),PN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return hc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=AN(i);if(!s)return hc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,SN.getPolicyCacheName)(n,r),c=new IN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),hc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):hc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");mc.CurityPhantomTokenInboundPolicy=PN;function AN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(AN,"getToken")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.FirebaseJwtInboundPolicy=void 0;var RN=lt(),ON=Xt(),NN=o(async(t,e,r,n)=>((0,RN.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,ON.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");yc.FirebaseJwtInboundPolicy=NN});var $_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.FormDataToJsonInboundPolicy=void 0;var CN=Ke(),xN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new CN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");gc.FormDataToJsonInboundPolicy=xN});var j_=_(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.GeoFilterInboundPolicy=void 0;var LN=k(),DN=de(),oi="__unknown__",MN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");bc.GeoFilterInboundPolicy=MN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),DN.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new LN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var V_=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.JWTScopeValidationInboundPolicy=void 0;var UN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");_c.JWTScopeValidationInboundPolicy=UN});var G_=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.MockApiInboundPolicy=void 0;var kN=de(),FN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return xf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return xf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return B_(a[c])}else return a.length>0?B_(a[0]):xf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ec.MockApiInboundPolicy=FN;function B_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(B_,"generateResponse");var xf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return kN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Q_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var HN=k(),qN=Re(),$N="Incoming",jN={logRequestBody:!0,logResponseBody:!0};function K_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(K_,"headersToObject");function J_(){return new Date().toISOString()}o(J_,"timestamp");var Lf=new WeakMap,VN={};function BN(t,e){let r=Lf.get(t);r||(r=VN);let n=Object.assign({...r},e);Lf.set(t,n)}o(BN,"setMoesifContext");ci.setMoesifContext=BN;async function z_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(z_,"readBody");var GN={},Df;function W_(){if(!Df)throw new HN.RuntimeError("Invalid State - no _lastLogger");return Df}o(W_,"getLastLogger");function KN(t){let e=GN[t];return e||(e=new qN.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);W_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||W_().error({status:i.status,body:await i.text()})})),e}o(KN,"getDispatcher");async function JN(t,e,r,n){Df=e.log;let i=J_(),s=Object.assign(jN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await z_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=KN(s.applicationId),d=t.headers.get("true-client-ip"),p=Lf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:K_(t.headers)},h=s.logResponseBody?await z_(c,e):void 0,y={time:J_(),status:c.status,headers:K_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:$N};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(JN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=JN});var X_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var Y_=Je(),Z_=ie();async function zN(t,e,r,n){let i=Y_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(zN,"loadSubscription");ui.loadSubscription=zN;async function WN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c=Y_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(WN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=WN});var eE=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.compareMeters=Nr.parseAllowedSubscriptionStatuses=Nr.validateMeters=void 0;var tn=k(),QN=Jt(),YN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function ZN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new tn.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(ZN,"validateMeters");Nr.validateMeters=ZN;function XN(t,e){if(t)try{if(t.length===0)throw new tn.ConfigurationError("Must set valid subscription statuses");let r=(0,QN.parseValueToStringArray)(t),n=[];for(let i of r)YN.has(i)||n.push(i);if(n.length>0)throw new tn.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(XN,"parseAllowedSubscriptionStatuses");Nr.parseAllowedSubscriptionStatuses=XN;function eC(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(eC,"compareMeters");Nr.compareMeters=eC});var nE=_(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MonetizationInboundPolicy=void 0;var rn=Fr(),nn=_p(),wc=Yi(),tE=k(),tC=_n(),on=de(),rC=Jt(),nC=lt(),rE=X_(),io=eE(),Mf=class extends tC.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return nn.ContextData.get(e,rn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,io.validateMeters)(r,"setMeters"),nn.ContextData.set(e,rn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,nC.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,i=(0,rC.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=nn.ContextData.get(r,rn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,io.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,io.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,I,A)=>{let g=nn.ContextData.get(A,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=nn.ContextData.get(A,rn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,io.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,io.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,rE.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:on.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,rE.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),nn.ContextData.set(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=nn.ContextData.get(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),on.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),on.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),on.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].available<=0&&!n)return on.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};vc.MonetizationInboundPolicy=Mf});var iE=_(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.OktaJwtInboundPolicy=void 0;var iC=Xt(),oC=o(async(t,e,r,n)=>(0,iC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Tc.OktaJwtInboundPolicy=oC});var oE=_(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.PropelAuthJwtInboundPolicy=void 0;var sC=(ra(),xo(ta)),aC=Xt(),Uf,cC=o(async(t,e,r,n)=>{if(!Uf)try{Uf=await(0,sC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,aC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Uf,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Sc.PropelAuthJwtInboundPolicy=cC});var sE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var oo=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=oo;var so=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=so;function uC(t,e){if((0,Ye.isUndefined)(t))throw new oo(e)}o(uC,"throwIfUndefined");Z.throwIfUndefined=uC;function kf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new oo(e)}o(kf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=kf;function lC(t,e){if(kf(t,e),!(0,Ye.isString)(t))throw new so(e,"string")}o(lC,"throwIfNotString");Z.throwIfNotString=lC;function dC(t,e){if(kf(t,e),!(0,Ye.isNumber)(t))throw new so(e,"number")}o(dC,"throwIfNotNumber");Z.throwIfNotNumber=dC;var ao=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=ao;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function pC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new ao(t,e,r)}o(pC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=pC;function Ic(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new ao(t,e,r)}o(Ic,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=Ic;function fC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(fC,"throwIfOptionNotString");Z.throwIfOptionNotString=fC;function hC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(hC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=hC;function mC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(mC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=mC;function yC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(yC,"throwIfStateUndefined");Z.throwIfStateUndefined=yC;function Pc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Pc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Pc;function gC(t,e){if(Pc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(gC,"throwIfStateNotString");Z.throwIfStateNotString=gC;function bC(t,e){if(Pc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(bC,"throwIfStateNotNumber");Z.throwIfStateNotNumber=bC;function _C(t,e){if(Pc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(_C,"throwIfStateNotObject");Z.throwIfStateNotObject=_C});var aE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Ff=k(),Ac=sE(),Hf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ac.throwIfNotString)(e,"redisClientUrl"),(0,Ac.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ac.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Ff.SystemError("Redis client failed with 401: Unauthorized"):new Ff.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=Hf;var qf=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ac.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Ff.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=qf});var $f=_(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.RETRY_AFTER_HEADER=Ae.wrapUserFunction=Ae.getCountAndUpdateExpiry=Ae.getRedisClient=Ae.getAll=Ae.getUser=Ae.getIP=Ae.getRealIP=void 0;var Cr=k(),Rc=ie(),cE=aE(),uE=at(),EC=o(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Ae.getRealIP=EC;var wC=o(async t=>({key:`ip-${(0,Ae.getRealIP)(t)}`}),"getIP");Ae.getIP=wC;var vC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Ae.getUser=vC;var TC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Ae.getAll=TC;var Oc;function SC(t,e){let r;if(Oc)return Oc;if(Rc.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new cE.InMemoryRedisClient,Oc=r,r;let{authApiJWT:n,redisURL:i}=Rc.Environment.instance;if(!(0,uE.isString)(i))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,uE.isString)(n))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=cE.StandardRedisClient.initialize(i,n,Rc.Environment.instance.deploymentName??"unknown",Rc.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Oc=r,r}o(SC,"getRedisClient");Ae.getRedisClient=SC;async function IC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(IC,"getCountAndUpdateExpiry");Ae.getCountAndUpdateExpiry=IC;function PC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Cr.RuntimeError(u)}return c},"outerFunction")}o(PC,"wrapUserFunction");Ae.wrapUserFunction=PC;Ae.RETRY_AFTER_HEADER="Retry-After"});var dE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.AsyncRateLimitInboundPolicy=void 0;var AC=or(),RC=Zt(),OC=de(),NC=Je(),CC=ie(),xC=Bt(),sn=$f(),lE=(0,AC.debug)("zuplo:policies:RateLimitInboundPolicy"),LC=o(async(t,e,r,n)=>{let i=NC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[sn.RETRY_AFTER_HEADER]=T.toString()),OC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,sn.getRedisClient)(n,i),b=`bucket/${CC.Environment.instance.build.BUILD_ID}/${n}/${l}`,I=await(0,RC.getPolicyCacheName)(n,r),A=new xC.MemoryZoneReadThroughCache(I,e),g=(0,sn.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),v;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),lE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),v=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){lE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>v??E),t},"AsyncRateLimitInboundPolicy");Nc.AsyncRateLimitInboundPolicy=LC});var fE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RateLimitInboundPolicy=void 0;var DC=or(),MC=k(),UC=de(),kC=Je(),FC=ie(),HC=dE(),an=$f(),pE=(0,DC.debug)("zuplo:policies:RateLimitInboundPolicy"),qC="strict",$C=o(async(t,e,r,n)=>{if((r.mode??qC)==="async")return(0,HC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=kC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new MC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[an.RETRY_AFTER_HEADER]=d.toString()),UC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,an.wrapUserFunction)(r,n),user:an.getUser,ip:an.getIP,all:an.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",I=(0,an.getRedisClient)(n,a),g=`bucket/${FC.Environment.instance.build.BUILD_ID}/${n}/${f}`,v=await(0,an.getCountAndUpdateExpiry)(g,y,I,a,e.requestId);return v.count>h?(pE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,v.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;pE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Cc.RateLimitInboundPolicy=$C});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.ReadmeMetricsInboundPolicy=void 0;var jC=Re(),jf=ie(),hE=Jt(),Vf;function mE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(mE,"headersToNameValuePairs");function VC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(VC,"queryToNameValueParis");function BC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(BC,"parseIntOrUndefined");var yE={};async function GC(t,e,r,n){let i=new Date,s=Date.now();return Vf||(Vf={name:"zuplo",version:jf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${jf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:jf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Vf,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:mE(t.headers),queryString:VC(t.query)},response:{status:a.status,statusText:a.statusText,headers:mE(a.headers),content:{size:BC(t.headers.get("content-length"))}}}]}}},d=yE[r.apiKey];if(!d){let p=r.apiKey;d=new jC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),yE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(GC,"ReadmeMetricsInboundPolicy");xc.ReadmeMetricsInboundPolicy=GC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.RemoveHeadersInboundPolicy=void 0;var KC=k(),JC=Ke(),zC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new KC.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new JC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Lc.RemoveHeadersInboundPolicy=zC});var _E=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RemoveHeadersOutboundPolicy=void 0;var WC=k(),QC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new WC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Dc.RemoveHeadersOutboundPolicy=QC});var EE=_(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.RemoveQueryParamsInboundPolicy=void 0;var YC=k(),ZC=Ke(),XC=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new YC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new ZC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");Mc.RemoveQueryParamsInboundPolicy=XC});var wE=_(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.ReplaceStringOutboundPolicy=void 0;var ex=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Uc.ReplaceStringOutboundPolicy=ex});var TE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.RequestSizeLimitInboundPolicy=void 0;var vE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),tx=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?vE():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?vE():t},"RequestSizeLimitInboundPolicy");kc.RequestSizeLimitInboundPolicy=tx});var Fc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function rx(t,e,r){return`_${cn(t+"_"+e+"_"+r)}`}o(rx,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=rx;function nx(t,e,r,n){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(nx,"getIdForParameterSchema");pt.getIdForParameterSchema=nx;function ix(t,e,r){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${cn(r.toLowerCase())}`}o(ix,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=ix;function ox(t,e){return`_${cn(t)}__${cn(e)}`}o(ox,"getIdForRefSchema");pt.getIdForRefSchema=ox;function cn(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(cn,"sanitizedIdentifierName");pt.sanitizedIdentifierName=cn});var co=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var sx=qr(),ax=Fc(),cx=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");je.getParametersForOperation=cx;var ux=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,ax.getIdForParameterSchema)(r,n,i,u.name),p=sx.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=ux;var lx=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=lx;var dx=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=dx;var px=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=px;var fx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=fx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleBodyValidation=void 0;var hx=qr(),Hc=de(),mx=Fc(),tt=co();async function yx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Hc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,mx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=hx.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Hc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(yx,"handleBodyValidation");qc.handleBodyValidation=yx});var IE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.handleHeadersValidation=void 0;var gx=de(),uo=co();function bx(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,uo.getParametersForOperation)(t),s=(0,uo.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=gx.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,uo.shouldLog)(r.validateHeaders)&&(0,uo.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,uo.shouldReject)(r.validateHeaders))return c}}o(bx,"handleHeadersValidation");$c.handleHeadersValidation=bx});var PE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.handlePathParameterValidation=void 0;var _x=de(),lo=co();function Ex(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=_x.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validatePathParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validatePathParameters))return a}}o(Ex,"handlePathParameterValidation");jc.handlePathParameterValidation=Ex});var AE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.handleQueryParameterValidation=void 0;var wx=de(),po=co();function vx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,po.getParametersForOperation)(t),i=(0,po.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=wx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,po.shouldLog)(r.validateQueryParameters)&&(0,po.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,po.shouldReject)(r.validateQueryParameters))return a}}o(vx,"handleQueryParameterValidation");Vc.handleQueryParameterValidation=vx});var RE=_(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy=void 0;var Tx=SE(),Sx=IE(),Ix=PE(),Px=AE(),Ax=o(async(t,e,r)=>{let n=(0,Px.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Ix.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,Sx.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,Tx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");un.RequestValidationInboundPolicy=Ax;un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy});var OE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.RequireOriginInboundPolicy=void 0;var Rx=k(),Ox=de(),Nx=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Rx.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Ox.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");Bc.RequireOriginInboundPolicy=Nx});var NE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetBodyInboundPolicy=void 0;var Cx=Ke(),xx=o(async(t,e,r)=>new Cx.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Gc.SetBodyInboundPolicy=xx});var xE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetHeadersInboundPolicy=void 0;var CE=k(),Lx=Ke(),Dx=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Lx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Kc.SetHeadersInboundPolicy=Dx});var DE=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SetHeadersOutboundPolicy=void 0;var LE=k(),Mx=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Jc.SetHeadersOutboundPolicy=Mx});var UE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SetQueryParamsInboundPolicy=void 0;var ME=k(),Ux=Ke(),kx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new Ux.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");zc.SetQueryParamsInboundPolicy=kx});var kE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.SetStatusOutboundPolicy=void 0;var Fx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Wc.SetStatusOutboundPolicy=Fx});var FE=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.SleepInboundPolicy=void 0;var Hx=k(),qx=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),$x=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new Hx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await qx(r.sleepInMs),t},"SleepInboundPolicy");Qc.SleepInboundPolicy=$x});var qE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.SupabaseJwtInboundPolicy=void 0;var HE=k(),jx=de(),Vx=Ke(),Bx=lt(),Gx=Xt(),Kx=o(async(t,e,r,n)=>{(0,Bx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,Gx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Vx.ZuploRequest))throw new HE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new HE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?jx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Yc.SupabaseJwtInboundPolicy=Kx});var jE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var Jx=Zt(),zx=Bt(),$E=k(),Wx=kn(),Qx=lt(),Yx=o(async(t,e,r,n)=>{(0,Qx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,Jx.getPolicyCacheName)(n,r),s=new zx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Zx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Zc.UpstreamAzureAdServiceAuthInboundPolicy=Yx;async function Zx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Wx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new $E.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new $E.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Zx,"getAccessToken")});var BE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var Xx=Zt(),eL=Bt(),tL=k(),Bf=Fn(),rL=lt(),VE="https://accounts.google.com/o/oauth2/token",Gf,nL=o(async(t,e,r,n)=>{(0,rL.optionValidator)(r,n).required("serviceAccountJson","string"),Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,Xx.getPolicyCacheName)(n,r),a=new eL.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:VE,payload:i}),l=await(0,Bf.exchangeGgpJwtForIdToken)(VE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new tL.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Xc.UpstreamFirebaseAdminAuthInboundPolicy=nL});var GE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.UpstreamFirebaseUserAuthInboundPolicy=void 0;var iL=Zt(),oL=Bt(),pi=k(),sL=If(),Kf=Fn(),aL=Jt(),cL=lt(),uL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",lL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Jf,dL=o(async(t,e,r,n)=>{if((0,cL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(lL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Jf||(Jf=await Kf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,aL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,iL.getPolicyCacheName)(n,r),c=new oL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,sL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Kf.getTokenFromGcpServiceAccount)({serviceAccount:Jf,audience:uL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Kf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");eu.UpstreamFirebaseUserAuthInboundPolicy=dL});var JE=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.UpstreamGcpJwtInboundPolicy=void 0;var KE=Fn(),pL=lt(),zf,fL=o(async(t,e,r,n)=>{(0,pL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),zf||(zf=await KE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,KE.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");tu.UpstreamGcpJwtInboundPolicy=fL});var WE=_(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.UpstreamGcpServiceAuthInboundPolicy=void 0;var hL=Zt(),mL=Xu(),yL=Bt(),fo=k(),Wf=Fn(),gL=Jt(),bL=lt(),zE="https://www.googleapis.com/oauth2/v4/token",Qf,_L=o(async(t,e,r,n)=>{(0,bL.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qf||(Qf=await Wf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new fo.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,gL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof fo.ConfigurationError?new fo.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,hL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new mL.MemoryCache(s):a=new yL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Wf.getTokenFromGcpServiceAccount)({serviceAccount:Qf,audience:zE,payload:i}),l=await(0,Wf.exchangeGgpJwtForIdToken)(zE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");ru.UpstreamGcpServiceAuthInboundPolicy=_L});var YE=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.ValidateJsonSchemaInbound=void 0;var EL=k(),QE=de(),wL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return QE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new EL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return QE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nu.ValidateJsonSchemaInbound=wL});var ew=_((JJ,XE)=>{"use strict";var vL=Object.defineProperty,TL=Object.getOwnPropertyNames,B=o((t,e)=>vL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[TL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Yf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),ZE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Yf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,v){v=Object.assign({},r,v);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
74
+ `+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-r.timestamp;if(i>0&&p>i)throw new Xr.StripeSignatureVerificationError(e,t,{message:"Timestamp outside the tolerance zone"});return!0}o(YR,"validateComputedSignature");function ZR(t,e){return typeof t!="string"?null:t.split(",").reduce((r,n)=>{let i=n.split("=");return i[0]==="t"&&(r.timestamp=parseInt(i[1],10)),i[0]===e&&r.signatures.push(i[1]),r},{timestamp:-1,signatures:[]})}o(ZR,"parseHeader");function XR(t,e){if(t.length!==e.length)return!1;let r=t.length,n=0;for(let i=0;i<r;++i)n|=t.charCodeAt(i)^e.charCodeAt(i);return n===0}o(XR,"secureCompare");async function o_(t,e){let r=new TextEncoder,n=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign("hmac",n,r.encode(t)),s=new Uint8Array(i),a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=tf[s[c]];return a.join("")}o(o_,"computeHMACSignatureAsync");ti.computeHMACSignatureAsync=o_;var tf=new Array(256);for(let t=0;t<tf.length;t++)tf[t]=t.toString(16).padStart(2,"0")});var lt=_(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.optionValidator=void 0;var ri=k(),eO=at();function tO(t,e,r="policy"){let n=`${r} '${e}'`;if(!(0,eO.isObject)(t))throw new ri.ConfigurationError(`Options on ${n} is expected to be an object. Received the type '${typeof t}'.`);let i=o((c,u,l)=>{let d=t[c];if(!(l&&d===void 0)){if(d===void 0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(u==="array"&&Array.isArray(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be an array. Received type ${typeof d}.`);if(typeof d!==u)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be of type ${u}. Received type ${typeof d}.`);if(typeof d=="string"&&d.length===0)throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof d=="number"&&isNaN(d))throw new ri.ConfigurationError(`Value of '${String(c)}' on ${n} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),s=o((c,u)=>(i(c,u,!0),{optional:s,required:a}),"optional"),a=o((c,u)=>(i(c,u,!1),{optional:s,required:a}),"required");return{optional:s,required:a}}o(tO,"optionValidator");Ga.optionValidator=tO});var nf=_(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.StripeWebhookVerificationInboundPolicy=void 0;var rO=_n(),nO=de(),iO=s_(),oO=lt(),rf=class extends rO.InboundPolicy{static{o(this,"StripeWebhookVerificationInboundPolicy")}async handler(e,r){(0,oO.optionValidator)(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let n=e.headers.get("stripe-signature");try{let i=await e.clone().text();await(0,iO.constructEventAsync)(i,n,this.options.signingSecret)}catch(i){let s=i.message;if(i.type&&i.type==="StripeSignatureVerificationError"){let a=i.message,u=/Note:(.*)/g.exec(a);s=u?u[1].trim():a}return r.log.error("Error validating stripe webhook",s),nO.HttpProblems.badRequest(e,r,{title:"Webhook Error",detail:s})}return e}};Ka.StripeWebhookVerificationInboundPolicy=rf});var c_=_(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.isStripeWebhookEvent=void 0;var a_=at();function sO(t){return t!==null&&typeof t=="object"&&"id"in t&&(0,a_.isString)(t.id)&&"type"in t&&(0,a_.isString)(t.type)}o(sO,"isStripeWebhookEvent");Ja.isStripeWebhookEvent=sO});var u_=_(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.MeteringPlugin=void 0;var aO=Ot(),of=class extends aO.SystemRuntimePlugin{static{o(this,"MeteringPlugin")}};za.MeteringPlugin=of});var cf=_(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var sf=k(),cO={getSubscription:async({subscriptionId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/subscriptions/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving subscription from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getCustomer:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/customers/${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i},getUpcomingInvoice:async({customerId:t,stripeSecretKey:e,logger:r})=>{let n=await fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${t}`,{headers:{Authorization:`Bearer ${e}`}}),i=await n.json();if(n.status!==200){let s="Error retrieving customer upcoming invoice from Stripe API.";throw r.error(s,i),new sf.RuntimeError(s)}return i}};af.default=cO});var d_=_(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.deleteConsumer=Ar.createConsumerInvite=Ar.createConsumer=void 0;var uf=k(),lf=Je(),df=re(),pf=kn(),ff="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",l_="My API Key";async function uO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,managerSub:s,context:a}){let{authApiJWT:c}=df.Environment.instance,u=new URL(`/v1/buckets/${t}/consumers`,ff);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[{sub:s,email:i}]},p=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new uf.RuntimeError(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:r}),l}o(uO,"createConsumer");Ar.createConsumer=uO;async function lO({apiKeyBucketName:t,stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n,managerEmail:i,context:s}){let{authApiJWT:a}=df.Environment.instance,c=new URL(`/v1/buckets/${t}/consumers`,ff);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:l_,tags:{subscriptionExternalId:e,planExternalIds:[r]},metadata:{stripeSubscriptionId:e,stripeProductId:r,stripeCustomerId:n},managers:[i]},d=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(s)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw s.log.error(f,p),new uf.RuntimeError(f)}return s.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:r}),u}o(lO,"createConsumerInvite");Ar.createConsumerInvite=lO;async function dO({apiKeyBucketName:t,consumerId:e,context:r}){let{authApiJWT:n}=df.Environment.instance,i=new URL(`/v1/buckets/${t}/consumers/${e}`,ff);i.searchParams.set("with-api-key","true");let s=await(0,pf.fetchRetry)({retryDelayMs:5,retries:2,logger:lf.SystemLogMap.getLogger(r)},i.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({})});if(s.status!==204){let a=await s.json(),c="Error invalidating API Key Consumer";throw r.log.error(c,a),new uf.RuntimeError(c)}return r.log.info(`Successfully invalidated API Key Consumer '${e}`),e}o(dO,"deleteConsumer");Ar.deleteConsumer=dO});var Wa=_(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getSubscription=Or.updateSubscription=Or.createSubscription=void 0;var Rr=k(),hf=Je(),mf=re(),yf=kn(),gf=at();async function pO({context:t,stripeSubscriptionId:e,stripeProductId:r,customerKey:n,meteringBucketId:i,meteringBucketRegion:s,customerExternalId:a,subscriptionStatus:c,metadata:u}){let l={status:c,type:"periodic",renewalStrategy:"monthly",region:s,subscriptionExternalId:e,planExternalIds:[r],customerKey:n,customerExternalId:a,metadata:u},{authApiJWT:d,meteringServiceUrl:p}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(d))throw new Rr.SystemError("No Zuplo JWT token set.");let f=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${p}/internal/v1/metering/${i}/subscriptions`,{headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"POST",body:JSON.stringify(l)});if(!f.ok){let h="Error creating monetization subscription.",y;try{y=await f.json()}catch{y={status:f.status,statusText:f.statusText}}throw t.log.error(h,y),new Rr.RuntimeError(h)}t.log.info("Successfully created monetization subscription.",l)}o(pO,"createSubscription");Or.createSubscription=pO;async function fO({context:t,meteringSubscriptionId:e,meteringBucketId:r,requestBody:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${r}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","zp-rid":t.requestId},method:"PATCH",body:JSON.stringify(n)});if(!a.ok){let c=`Error updating monetization subscription with: '${JSON.stringify(n)}'.`,u;try{u=await a.json()}catch{u={status:a.status,statusText:a.statusText}}throw t.log.error(c,u),new Rr.RuntimeError(c)}t.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(n)}'.`)}o(fO,"updateSubscription");Or.updateSubscription=fO;async function hO({context:t,stripeSubscriptionId:e,stripeCustomerId:r,meteringBucketId:n}){let{authApiJWT:i,meteringServiceUrl:s}=mf.Environment.instance;if(!(0,gf.isNonEmptyString)(i))throw new Rr.SystemError("No Zuplo JWT token set.");let a=await(0,yf.fetchRetry)({retryDelayMs:5,retries:2,logger:hf.SystemLogMap.getLogger(t)},`${s}/internal/v1/metering/${n}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":t.requestId},method:"GET"});if(!a.ok){let u="Error retrieving the monetization subscription.",l;try{l=await a.json()}catch{l={status:a.status,statusText:a.statusText}}throw t.log.error(u,l),new Rr.RuntimeError(u,l)}let c=await a.json();if(c.data.length===0){let u="Subscription was not found and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}if(c.data[0].customerExternalId!==r){let u="A subscription was not found for the customer provided and the event was ignored by Zuplo.";throw t.log.error(u),new Rr.RuntimeError(u)}return c.data[0]}o(hO,"getSubscription");Or.getSubscription=hO});var bf=_(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.stripeStatusToMeteringStatus=void 0;function mO(t){return t.replaceAll("_","-")}o(mO,"stripeStatusToMeteringStatus");Qa.stripeStatusToMeteringStatus=mO});var p_=_(to=>{"use strict";var yO=to&&to.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(to,"__esModule",{value:!0});var en=de(),gO=yO(cf()),_f=d_(),bO=Wa(),_O=bf();async function EO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.plan;if(!s||!s.product)return e.log.warn(`Invalid Stripe API result. Expected event '${r.id}' to have a plan data.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=r.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let c=s.product,u,l,d;if(r.data.object.metadata&&r.data.object.metadata.zuplo_created_by_email&&r.data.object.metadata.zuplo_created_by_sub)l=r.data.object.metadata.zuplo_created_by_email,d=r.data.object.metadata.zuplo_created_by_sub,u=await(0,_f.createConsumer)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await gO.default.getCustomer({logger:e.log,stripeSecretKey:n.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),en.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await(0,_f.createConsumerInvite)({apiKeyBucketName:n.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:i,stripeCustomerId:a,managerEmail:p.email,context:e})}if(!u)return en.HttpProblems.internalServerError(t,e,{detail:"No API Key Consumer was created, skipping creation of subscription"});try{let p=(0,_O.stripeStatusToMeteringStatus)(r.data.object.status),f;l&&d&&(f={subscriber:{sub:d,email:l}}),await(0,bO.createSubscription)({context:e,stripeProductId:c,stripeSubscriptionId:i,customerKey:u,meteringBucketId:n.meteringBucketId,meteringBucketRegion:n.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f})}catch(p){return await(0,_f.deleteConsumer)({apiKeyBucketName:n.apiKeyBucketName,consumerId:u,context:e}),en.HttpProblems.internalServerError(t,e,{detail:p.message})}return en.HttpProblems.ok(t,e)}o(EO,"onCustomerSubscriptionCreated");to.default=EO});var h_=_(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ef=de(),f_=Wa();async function wO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to have '.data.object.id' be the subscription ID.`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),Ef.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});let a=await(0,f_.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId});return await(0,f_.updateSubscription)({context:e,meteringSubscriptionId:a.id,meteringBucketId:n.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}}),Ef.HttpProblems.ok(t,e)}o(wO,"onCustomerSubscriptionDeleted");wf.default=wO});var m_=_(no=>{"use strict";var vO=no&&no.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(no,"__esModule",{value:!0});var ro=de(),TO=vO(cf()),Ya=Wa(),SO=bf();async function IO(t,e,r,n){let i=r.data.object.id;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected event '${r.id}' to include '.data.object.id' as the subscription ID.`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let s=r.data.object.customer;if(!s)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${r.id}'`),ro.HttpProblems.badRequest(t,e,{detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(r.data.previous_attributes){let a=r.data.previous_attributes;if(a.status&&a.status!==r.data.object.status){e.log.debug(`Processing subscription status change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=(0,SO.stripeStatusToMeteringStatus)(r.data.object.status);return await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds}}),ro.HttpProblems.ok(t,e)}if(a.plan&&a.plan.product!==r.data.object.plan.product){e.log.debug(`Processing subscription plan change from Stripe event '${r.id}'.`);let c=await(0,Ya.getSubscription)({context:e,stripeSubscriptionId:i,stripeCustomerId:s,meteringBucketId:n.meteringBucketId}),u=r.data.object.plan.product,d=(await TO.default.getUpcomingInvoice({customerId:s,logger:e.log,stripeSecretKey:n.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===u),p=0;return d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${r.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await(0,Ya.updateSubscription)({context:e,meteringSubscriptionId:c.id,meteringBucketId:n.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}}),ro.HttpProblems.ok(t,e)}}return e.log.warn(`This update event '${r.id}' is not supported by Stripe metering plugin webhook.`),ro.HttpProblems.badRequest(t,e,{detail:"This update event is not supported by Stripe metering plugin webhook."})}o(IO,"onCustomerSubscriptionUpdated");no.default=IO});var g_=_(ni=>{"use strict";var Tf=ni&&ni.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ni,"__esModule",{value:!0});ni.StripeMonetizationPlugin=void 0;var Za=Yi(),Xa=k(),PO=Gt(),AO=nf(),y_=de(),RO=ar(),OO=En(),NO=Sl(),CO=gt(),xO=re(),LO=c_(),DO=lt(),MO=u_(),UO=Tf(p_()),kO=Tf(h_()),FO=Tf(m_()),vf=class extends MO.MeteringPlugin{static{o(this,"StripeMonetizationPlugin")}options;constructor(e){super(),this.options=e}registerRoutes(e,r){let n=o(async(c,u)=>{if(this.options.__testMode===!0)return u.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:l,apiKeyBucketName:d}=this.options;if(!l)if(Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)l=Za.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!d)if(Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)d=Za.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Xa.ConfigurationError("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!xO.Environment.instance.build.ACCOUNT_NAME)throw new Xa.SystemError("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let p=this.options.meteringBucketRegion??"us-central1";if(!HO(p))throw new Xa.ConfigurationError(`StripeMonetizationPlugin - The value '${p}' on the property 'meteringBucketRegion' is invalid.`);let f=await c.json();if(!(0,LO.isStripeWebhookEvent)(f))return y_.HttpProblems.badRequest(c,u,{detail:"The received body was not in the expected format."});switch(u.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await(0,UO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await(0,FO.default)(c,u,f,{meteringBucketId:l,apiKeyBucketName:d,meteringBucketRegion:p,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await(0,kO.default)(c,u,f,{meteringBucketId:l});default:return y_.HttpProblems.badRequest(c,u,{detail:"Event is not supported by Stripe monetization plugin webhook."})}},"stripeWebhookHandler"),i=(0,OO.createInternalPolicyProcessor)({inboundPolicies:[new AO.StripeWebhookVerificationInboundPolicy({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});(0,DO.optionValidator)(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let s=new PO.Pipeline({processors:[RO.metricsProcessor,i],handler:n,gateway:r}),a=new CO.SystemRouteConfiguration({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:NO.SystemRouteName.StripePlugin});e.addRoute(a,s.execute)}};ni.StripeMonetizationPlugin=vf;function HO(t){return t!==null&&typeof t=="string"&&["us-central1","europe-west4"].includes(t)}o(HO,"isMetricsRegion")});var v_=_(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.AmberfloMeteringInboundPolicy=ii.AmberfloMeteringPolicy=void 0;var b_=k(),qO=Re(),__=Jt(),w_=new WeakMap,E_={},Sf=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){w_.set(e,r)}};ii.AmberfloMeteringPolicy=Sf;async function $O(t,e,r,n){if(!r.statusCodes)throw new b_.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=(0,__.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=w_.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new b_.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,__.getValueFromRequestUser)(t.user,r.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': customerId cannot be undefined`);return}let l=a?.meterApiName??r.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterApiName cannot be undefined`);return}let d=a?.meterValue??r.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${n}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(r.dimensions??{},a?.dimensions)},f=E_[r.apiKey];if(!f){let h=r.apiKey,y=t.headers.get("zm-test-id")??"";f=new qO.BatchDispatch("amberflo-ingest-meter",10,async b=>{try{let I=r.url??"https://app.amberflo.io/ingest",A=await fetch(I,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":y}});A.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${A.status}: ${await A.text()}`)}catch(I){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${I.message}`),I}}),E_[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),t}o($O,"AmberfloMeteringInboundPolicy");ii.AmberfloMeteringInboundPolicy=$O});var If=_(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.sha256=void 0;async function jO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}o(jO,"sha256");ec.sha256=jO});var Zt=_(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.getPolicyCacheName=void 0;var VO=If(),T_=new Map;async function BO(t,e){let r,n=T_.get(t);return n!==void 0?r=n:(r=`zuplo-policy-${await(0,VO.sha256)(JSON.stringify({policyName:t,options:e}))}`,T_.set(t,r)),r}o(BO,"getPolicyCacheName");tc.getPolicyCacheName=BO});var Rf=_(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ApiKeyInboundPolicy=void 0;var GO=Zt(),KO=Bt(),S_=Yi(),Pf=k(),JO=Kt(),I_=Je(),Af=re(),zO=kn(),P_="key-metadata-cache-type";function WO(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(WO,"getKeyValue");async function QO(t,e,r,n){if(!r.bucketName)if(S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=S_.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - no bucketName property provided`);let i={authHeader:r.authHeader??"authorization",authScheme:r.authScheme??"Bearer",bucketName:r.bucketName,cacheTtlSeconds:r.cacheTtlSeconds??60,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:r.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(i.cacheTtlSeconds<60)throw new Pf.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(I=>i.allowUnauthenticatedRequests?t:JO.HttpProblems.unauthorized(t,e,{detail:I}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=WO(a,i);if(!c||c==="")return s("No key present");let u=await YO(c),l=await(0,GO.getPolicyCacheName)(n,i),d=new KO.MemoryZoneReadThroughCache(l,e),p=await d.get(u);if(p&&p.isValid===!0)return t.user=p.user,t;if(p&&!p.isValid)return p.typeId!==P_&&I_.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${p.typeId}'`,p),s("Authorization Failed");let f={key:c},h=await(0,zO.fetchRetry)({retryDelayMs:5,retries:2,logger:I_.SystemLogMap.getLogger(e)},`${Af.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Af.Environment.instance.deploymentName??"unknown","User-Agent":Af.Environment.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(h.status!==200){try{let I=await h.text(),A=JSON.parse(I);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new Pf.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${h.status}`)}let y=await h.json(),b={isValid:!0,typeId:P_,user:{sub:y.name,data:y.metadata}};return t.user=b.user,d.put(u,b,i.cacheTtlSeconds),t}o(QO,"ApiKeyInboundPolicy");rc.ApiKeyInboundPolicy=QO;async function YO(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(YO,"hashValue")});var A_=_(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ApiAuthKeyInboundPolicy=void 0;var ZO=Rf();nc.ApiAuthKeyInboundPolicy=ZO.ApiKeyInboundPolicy});var Xt=_(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.OpenIdJwtInboundPolicy=void 0;var Nf=(ra(),xo(ta)),Cf=k(),XO=de(),Of={},eN=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new Cf.ConfigurationError("Invalid State - jwkUrl not set");Of[e.jwkUrl]||(Of[e.jwkUrl]=(0,Nf.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,Nf.jwtVerify)(t,Of[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),tN=o(async(t,e)=>{let r;if(e.secret===void 0)throw new Error("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let s=new TextEncoder().encode(e.secret);r=new Uint8Array(s)}else r=e.secret;let{payload:n}=await(0,Nf.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),rN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(f=>XO.HttpProblems.unauthorized(t,e,{detail:f}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new Cf.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?eN:tN,l=await o(async()=>{if(!i)return a("No authorization header");if(i.toLowerCase().indexOf(s)!==0)return a("Invalid bearer token format for authorization header");let f=i.substring(s.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await c(f,r)}catch(h){let y=new URL(t.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,h):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return r.allowUnauthenticatedRequests===!0?t:l;let d=r.subPropertyName??"sub",p=l[d];return p?(t.user={sub:p,data:l},t):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");ic.OpenIdJwtInboundPolicy=rN});var R_=_(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.Auth0JwtInboundPolicy=void 0;var nN=Xt(),iN=o(async(t,e,r,n)=>(0,nN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");oc.Auth0JwtInboundPolicy=iN});var O_=_(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BasicAuthInboundPolicy=void 0;var oN=de(),sN=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>oN.HttpProblems.unauthorized(t,e,{detail:l}),"unauthorizedResponse"),c=await o(async()=>{if(!n)return await s("No Authorization header");if(n.toLowerCase().indexOf(i)!==0)return await s("Invalid Basic token format for Authorization header");let l=n.substring(i.length);if(!l||l.length===0)return await s("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await s("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let f=d.substring(0,p),h=d.substring(p+1),y=r.accounts.find(b=>b.username===f&&b.password===h);return y||await s("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return r.allowUnauthenticatedRequests?t:c;let u=c.username;return t.user={sub:u,data:c.data},t},"BasicAuthInboundPolicy");sc.BasicAuthInboundPolicy=sN});var N_=_(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.CachingInboundPolicy=void 0;var aN=Zt(),cN=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function uN(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}o(uN,"digestMessage");var lN=o(async(t,e)=>{let r=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],n=[];for(let[d,p]of t.headers.entries())r.includes(d)&&n.push({key:d.toLowerCase(),value:p});n.sort((d,p)=>d.key.localeCompare(p.key));let i=await uN(JSON.stringify(n)),s=new URL(t.url),a=new URLSearchParams(s.searchParams);a.set("_z-hdr-dgst",i);let c=e.cacheHttpMethods?.includes(t.method.toUpperCase())&&t.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",t.method);let u=`${s.origin}${s.pathname}?${a}`;return new Request(u,{method:c?"GET":t.method})},"createCacheKeyRequest");async function dN(t,e,r,n){let i=await(0,aN.getPolicyCacheName)(n,r),s=await caches.open(i),a=r?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await lN(t,r),u=await s.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=r.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(t.method.toUpperCase()))return;let f=r?.expirationSecondsTtl??60,h=new Response(p.body,p);cN.forEach(y=>h.headers.delete(y)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(s.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${n}': "${d.message}"`,d)}}),t)}o(dN,"CachingInboundPolicy");ac.CachingInboundPolicy=dN});var C_=_(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.ChangeMethodInboundPolicy=void 0;var pN=k(),fN=Ke(),hN=o(async(t,e,r,n)=>{if(!r.method)throw new pN.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new fN.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");cc.ChangeMethodInboundPolicy=hN});var x_=_(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.ClearHeadersInboundPolicy=void 0;var mN=Ke(),yN=o(async(t,e,r)=>{let n=[...r.exclude??[]],i=new Headers;return n.forEach(a=>{let c=t.headers.get(a);c&&i.set(a,c)}),new mN.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");uc.ClearHeadersInboundPolicy=yN});var L_=_(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.ClearHeadersOutboundPolicy=void 0;var gN=o(async(t,e,r,n)=>{let i=[...n.exclude??[]],s=new Headers;return i.forEach(c=>{let u=t.headers.get(c);u&&s.set(c,u)}),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})},"ClearHeadersOutboundPolicy");lc.ClearHeadersOutboundPolicy=gN});var D_=_(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.ClerkJwtInboundPolicy=void 0;var bN=Xt(),_N=o(async(t,e,r,n)=>{let i=new URL(r.frontendApiUrl.startsWith("https://")||r.frontendApiUrl.startsWith("http://")?r.frontendApiUrl:`https://${r.frontendApiUrl}`),s=new URL(i);return s.pathname="/.well-known/jwks.json",(0,bN.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");dc.ClerkJwtInboundPolicy=_N});var U_=_(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.CognitoJwtInboundPolicy=void 0;var M_=k(),EN=Xt(),wN=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new M_.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new M_.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,EN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,jwkUrl:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"CognitoJwtInboundPolicy");pc.CognitoJwtInboundPolicy=wN});var F_=_(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});fc.CompositeInboundPolicy=void 0;var vN=k(),TN=qr(),k_=En(),SN=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new vN.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=TN.Gateway.instance,s=(0,k_.getInboundPolicyInstances)(r.policies,i?.routeData.policies);return(0,k_.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");fc.CompositeInboundPolicy=SN});var H_=_(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});mc.CurityPhantomTokenInboundPolicy=void 0;var IN=Zt(),PN=Bt(),hc=de(),AN=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization");if(!i)return hc.HttpProblems.unauthorized(t,e,{detail:"No authorization header"});let s=RN(i);if(!s)return hc.HttpProblems.unauthorized(t,e,{detail:"Failed to parse token from Authorization header"});let a=await(0,IN.getPolicyCacheName)(n,r),c=new PN.MemoryZoneReadThroughCache(a,e),u=await c.get(s);if(!u){let l=await fetch(r.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${r.clientId}:${r.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+s+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(s,u,r.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),hc.HttpProblems.internalServerError(t,e,{detail:"Problem encountered authorizing the HTTP request"})):hc.HttpProblems.unauthorized(t,e)}return t.headers.set("Authorization",`Bearer ${u}`),t},"CurityPhantomTokenInboundPolicy");mc.CurityPhantomTokenInboundPolicy=AN;function RN(t){return t.split(" ")[0]==="Bearer"?t.split(" ")[1]:null}o(RN,"getToken")});var q_=_(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.FirebaseJwtInboundPolicy=void 0;var ON=lt(),NN=Xt(),CN=o(async(t,e,r,n)=>((0,ON.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,NN.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://securetoken.google.com/${r.projectId}`,audience:r.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)),"FirebaseJwtInboundPolicy");yc.FirebaseJwtInboundPolicy=CN});var $_=_(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.FormDataToJsonInboundPolicy=void 0;var xN=Ke(),LN=o(async(t,e,r)=>{let n="application/x-www-form-urlencoded",i="multipart/form-data",s=t.headers.get("content-type")?.toLowerCase();if(!s||![i,n].includes(s))return r&&r.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${n}' or ${i}`,{status:400,statusText:"Bad Request"}):t;let a=await t.formData();if(r&&r.optionalHoneypotName&&a.get(r.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(t.headers);return u.set("content-type","application/json"),u.delete("content-length"),new xN.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");gc.FormDataToJsonInboundPolicy=LN});var j_=_(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.GeoFilterInboundPolicy=void 0;var DN=k(),MN=de(),oi="__unknown__",UN=o(async(t,e,r,n)=>{let i={allow:{countries:ai(r.allow?.countries,"allow.countries",n),regionCodes:ai(r.allow?.regionCodes,"allow.regionCode",n),asns:ai(r.allow?.asns,"allow.asOrganization",n)},block:{countries:ai(r.block?.countries,"block.countries",n),regionCodes:ai(r.block?.regionCodes,"block.regionCode",n),asns:ai(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??oi,a=e.incomingRequestProperties.regionCode?.toLowerCase()??oi,c=e.incomingRequestProperties.asn?.toString()??oi,u=i.ignoreUnknown&&s===oi,l=i.ignoreUnknown&&a===oi,d=i.ignoreUnknown&&c===oi,p=i.allow.countries,f=i.allow.regionCodes,h=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return si(t,e,n,s,a,c);let y=i.block.countries,b=i.block.regionCodes,I=i.block.asns;return y.length>0&&y.includes(s)&&!u||b.length>0&&b.includes(a)&&!l||I.length>0&&I.includes(c)&&!d?si(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");bc.GeoFilterInboundPolicy=UN;function si(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),MN.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(si,"blockedResponse");function ai(t,e,r){if(typeof t=="string")return t.split(",").map(n=>n.trim().toLowerCase());if(typeof t>"u")return[];if(Array.isArray(t))return t.map(n=>n.trim().toLowerCase());throw new DN.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(ai,"toLowerStringArray")});var V_=_(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.JWTScopeValidationInboundPolicy=void 0;var kN=o(async(t,e,r)=>{let n=t.user?.data.scope.split(" ")||[];if(!o((s,a)=>a.every(c=>s.includes(c)),"scopeChecker")(n,r.scopes)){let s={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${r.scopes}`};return new Response(JSON.stringify(s),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return t},"JWTScopeValidationInboundPolicy");_c.JWTScopeValidationInboundPolicy=kN});var G_=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.MockApiInboundPolicy=void 0;var FN=de(),HN=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return xf(n,t,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let s=Object.keys(i),a=[];if(s.length===0)return xf(n,t,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(s.forEach(c=>{i[c].content&&Object.keys(i[c].content).forEach(l=>{let d=i[c].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:c,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(c=>!(r.responsePrefixFilter&&!c.responseName.startsWith(r.responsePrefixFilter)||r.contentType&&c.contentName!==r.contentType||r.exampleName&&c.exampleName!==r.exampleName)),r.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return B_(a[c])}else return a.length>0?B_(a[0]):xf(n,t,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");Ec.MockApiInboundPolicy=HN;function B_(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.set("Content-Type",t.contentName),t.responseName){case"1XX":return new Response(e,{status:100,headers:r});case"2XX":return new Response(e,{status:200,headers:r});case"3XX":return new Response(e,{status:300,headers:r});case"4XX":return new Response(e,{status:400,headers:r});case"5XX":case"default":return new Response(e,{status:500,headers:r});default:return new Response(e,{status:Number(t.responseName),headers:r})}}o(B_,"generateResponse");var xf=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return FN.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Q_=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.MoesifInboundPolicy=ci.setMoesifContext=void 0;var qN=k(),$N=Re(),jN="Incoming",VN={logRequestBody:!0,logResponseBody:!0};function K_(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(K_,"headersToObject");function J_(){return new Date().toISOString()}o(J_,"timestamp");var Lf=new WeakMap,BN={};function GN(t,e){let r=Lf.get(t);r||(r=BN);let n=Object.assign({...r},e);Lf.set(t,n)}o(GN,"setMoesifContext");ci.setMoesifContext=GN;async function z_(t,e){let r=t.headers.get("content-type");if(r&&r.indexOf("json")!==0)try{return await t.clone().json()}catch(i){e.log.error(i)}let n=await t.clone().text();return e.log.debug({textBody:n}),n}o(z_,"readBody");var KN={},Df;function W_(){if(!Df)throw new qN.RuntimeError("Invalid State - no _lastLogger");return Df}o(W_,"getLastLogger");function JN(t){let e=KN[t];return e||(e=new $N.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);W_().debug("posting",n);let i=await fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":t},body:n});i.ok||W_().error({status:i.status,body:await i.text()})})),e}o(JN,"getDispatcher");async function zN(t,e,r,n){Df=e.log;let i=J_(),s=Object.assign(VN,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await z_(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=JN(s.applicationId),d=t.headers.get("true-client-ip"),p=Lf.get(e)??{},f={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:K_(t.headers)},h=s.logResponseBody?await z_(c,e):void 0,y={time:J_(),status:c.status,headers:K_(c.headers),body:h},b={request:f,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:jN};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),t}o(zN,"MoesifInboundPolicy");ci.MoesifInboundPolicy=zN});var X_=_(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.consumeSubcriptionQuotas=ui.loadSubscription=void 0;var Y_=Je(),Z_=re();async function WN(t,e,r,n){let i=Y_.SystemLogMap.getLogger(t),{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c;try{let l=await fetch(`${a}/internal/v1/metering/${n}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error loading subscription. ${l.status} - ${p}`),i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){i.error(`MonetizationInboundPolicy '${r}' - Error loading subscription`,l)}return c&&c.data&&c.data.length>0?c.data[0]:void 0}o(WN,"loadSubscription");ui.loadSubscription=WN;async function QN(t,e,r,n,i){let{authApiJWT:s,meteringServiceUrl:a}=Z_.Environment.instance,c=Y_.SystemLogMap.getLogger(t);try{let u=await fetch(`${a}/internal/v1/metering/${n}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${s}`,"zp-rid":t.requestId},method:"POST",body:JSON.stringify({meters:i})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){t.log.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${r}' - Error updating subscription quota.`,u)}}o(QN,"consumeSubcriptionQuotas");ui.consumeSubcriptionQuotas=QN});var eE=_(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.compareMeters=Nr.parseAllowedSubscriptionStatuses=Nr.validateMeters=void 0;var tn=k(),YN=Jt(),ZN=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function XN(t,e){try{let r=[];for(let n in t)typeof t[n]!="number"&&!(Number.isInteger(t[n])&&/^-?\d+$/.test(t[n].toString()))&&r.push(n);if(r.length>0)throw new tn.ConfigurationError(r.length>1?`The values found in these properties are not integers : ${r.join(", ")}`:`The value in property '${r[0]}' is not an integer`)}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${r.message}`):r}}o(XN,"validateMeters");Nr.validateMeters=XN;function eC(t,e){if(t)try{if(t.length===0)throw new tn.ConfigurationError("Must set valid subscription statuses");let r=(0,YN.parseValueToStringArray)(t),n=[];for(let i of r)ZN.has(i)||n.push(i);if(n.length>0)throw new tn.ConfigurationError(`Found the following invalid statuses: ${n.join(", ")}`);return t}catch(r){throw r instanceof tn.ConfigurationError?new tn.ConfigurationError(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${r.message}`):r}else return["active","incomplete","trialing"]}o(eC,"parseAllowedSubscriptionStatuses");Nr.parseAllowedSubscriptionStatuses=eC;function tC(t,e){let r={},n={};for(let i in e)t.hasOwnProperty(i)?r[i]=e[i]:n[i]=e[i];return{metersInSubscription:r,metersNotInSubscription:n}}o(tC,"compareMeters");Nr.compareMeters=tC});var nE=_(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.MonetizationInboundPolicy=void 0;var rn=Fr(),nn=_p(),wc=Yi(),tE=k(),rC=_n(),on=de(),nC=Jt(),iC=lt(),rE=X_(),io=eE(),Mf=class extends rC.InboundPolicy{static{o(this,"MonetizationInboundPolicy")}static getSubscription(e){return nn.ContextData.get(e,rn.METERING_SUBSCRIPTION_CONTEXT_DATA)}static setMeters(e,r){(0,io.validateMeters)(r,"setMeters"),nn.ContextData.set(e,rn.DYNAMIC_METERS_CONTEXT_DATA,r)}async handler(e,r){(0,iC.optionValidator)(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let n=this.options.allowRequestsOverQuota??!1,i=(0,nC.statusCodesStringToNumberArray)(this.options.meterOnStatusCodes),s=nn.ContextData.get(r,rn.DYNAMIC_METERS_CONTEXT_DATA),a={...this.options.meters,...s};(0,io.validateMeters)(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=(0,io.parseAllowedSubscriptionStatuses)(this.options.allowedSubscriptionStatuses,this.policyName);r.addResponseSendingFinalHook(async(b,I,A)=>{let g=nn.ContextData.get(A,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if((this.options.allowRequestsWithoutSubscription??!1)&&!g){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let O=nn.ContextData.get(A,rn.DYNAMIC_METERS_CONTEXT_DATA),V={...this.options.meters,...O};if((0,io.validateMeters)(V,this.policyName),i.includes(b.status)&&g&&V){A.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${g.id}' with meters '${JSON.stringify(V)} on response status '${b.status}'`);let{metersInSubscription:E,metersNotInSubscription:T}=(0,io.compareMeters)(g.meters,V);if(T&&Object.keys(T).length>0){let C=Object.keys(T);A.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${C}'`)}await(0,rE.consumeSubcriptionQuotas)(A,g.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return c?e:on.HttpProblems.unauthorized(e,r,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=wc.environment.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new tE.ConfigurationError(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await(0,rE.loadSubscription)(r,d,this.policyName,this.options.bucketId);if(!p)return r.log.warn("No valid subscription found"),c?e:on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return r.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),on.HttpProblems.unauthorized(e,r,{detail:"No valid subscription found"});u.includes(p.status)&&(r.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),nn.ContextData.set(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA,p));let f=nn.ContextData.get(r,rn.METERING_SUBSCRIPTION_CONTEXT_DATA);if(!f)return c?e:(r.log.warn("Subscription is not available for user"),on.HttpProblems.paymentRequired(e,r,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return r.log.error(`Quota is not set up for subscription '${f.id}'`),on.HttpProblems.tooManyRequests(e,r,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let y=Object.keys(a).filter(b=>!Object.keys(f.meters).includes(b));if(y.length>0)return r.log.warn(`The following policy meters are not present in the subscription: ${y.join(", ")}`),on.HttpProblems.tooManyRequests(e,r,{detail:`The following policy meters are not present in the subscription: ${y.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(f.meters[b].available<=0&&!n)return on.HttpProblems.tooManyRequests(e,r,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};vc.MonetizationInboundPolicy=Mf});var iE=_(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.OktaJwtInboundPolicy=void 0;var oC=Xt(),sC=o(async(t,e,r,n)=>(0,oC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");Tc.OktaJwtInboundPolicy=sC});var oE=_(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.PropelAuthJwtInboundPolicy=void 0;var aC=(ra(),xo(ta)),cC=Xt(),Uf,uC=o(async(t,e,r,n)=>{if(!Uf)try{Uf=await(0,aC.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,cC.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Uf,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Sc.PropelAuthJwtInboundPolicy=uC});var sE=_(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.throwIfStateNotObject=Z.throwIfStateNotNumber=Z.throwIfStateNotString=Z.throwIfStateUndefinedOrNull=Z.throwIfStateUndefined=Z.throwIfOptionNotObject=Z.throwIfOptionNotNumber=Z.throwIfOptionNotString=Z.throwIfOptionUndefinedOrNull=Z.throwIfOptionUndefined=Z.OptionTypeError=Z.OptionUndefinedError=Z.throwIfNotNumber=Z.throwIfNotString=Z.throwIfUndefinedOrNull=Z.throwIfUndefined=Z.ArgumentTypeError=Z.ArgumentUndefinedError=Z.ValidationError=void 0;var Ye=at(),dt=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};Z.ValidationError=dt;var oo=class extends dt{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};Z.ArgumentUndefinedError=oo;var so=class extends dt{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};Z.ArgumentTypeError=so;function lC(t,e){if((0,Ye.isUndefined)(t))throw new oo(e)}o(lC,"throwIfUndefined");Z.throwIfUndefined=lC;function kf(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new oo(e)}o(kf,"throwIfUndefinedOrNull");Z.throwIfUndefinedOrNull=kf;function dC(t,e){if(kf(t,e),!(0,Ye.isString)(t))throw new so(e,"string")}o(dC,"throwIfNotString");Z.throwIfNotString=dC;function pC(t,e){if(kf(t,e),!(0,Ye.isNumber)(t))throw new so(e,"number")}o(pC,"throwIfNotNumber");Z.throwIfNotNumber=pC;var ao=class extends dt{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};Z.OptionUndefinedError=ao;var li=class extends dt{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};Z.OptionTypeError=li;function fC(t,e,r,n){if((0,Ye.isUndefined)(n))throw new ao(t,e,r)}o(fC,"throwIfOptionUndefined");Z.throwIfOptionUndefined=fC;function Ic(t,e,r,n){if((0,Ye.isUndefinedOrNull)(n))throw new ao(t,e,r)}o(Ic,"throwIfOptionUndefinedOrNull");Z.throwIfOptionUndefinedOrNull=Ic;function hC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isString)(n))throw new li(t,e,r,"string")}o(hC,"throwIfOptionNotString");Z.throwIfOptionNotString=hC;function mC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isNumber)(n))throw new li(t,e,r,"number")}o(mC,"throwIfOptionNotNumber");Z.throwIfOptionNotNumber=mC;function yC(t,e,r,n){if(Ic(t,e,r,n),!(0,Ye.isObject)(n))throw new li(t,e,r,"object")}o(yC,"throwIfOptionNotObject");Z.throwIfOptionNotObject=yC;function gC(t,e){if((0,Ye.isUndefined)(t))throw new dt(e)}o(gC,"throwIfStateUndefined");Z.throwIfStateUndefined=gC;function Pc(t,e){if((0,Ye.isUndefinedOrNull)(t))throw new dt(e)}o(Pc,"throwIfStateUndefinedOrNull");Z.throwIfStateUndefinedOrNull=Pc;function bC(t,e){if(Pc(t,e),!(0,Ye.isString)(t))throw new dt(e);return!0}o(bC,"throwIfStateNotString");Z.throwIfStateNotString=bC;function _C(t,e){if(Pc(t,e),!(0,Ye.isNumber)(t))throw new dt(e);return!0}o(_C,"throwIfStateNotNumber");Z.throwIfStateNotNumber=_C;function EC(t,e){if(Pc(t,e),!(0,Ye.isObject)(t))throw new dt(e);return!0}o(EC,"throwIfStateNotObject");Z.throwIfStateNotObject=EC});var aE=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.InMemoryRedisClient=di.StandardRedisClient=void 0;var Ff=k(),Ac=sE(),Hf=class t{static{o(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,r,n,i){this.redisClientUrl=e,this.clientAuthToken=r,this.deploymentName=n,this.userAgent=i}static initialize(e,r,n,i){return(0,Ac.throwIfNotString)(e,"redisClientUrl"),(0,Ac.throwIfNotString)(r,"clientAuthToken"),t.instance||(t.instance=new t(e,r,n,i)),t.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:r,method:n,requestId:i}){(0,Ac.throwIfNotString)(e,"url");let s=await fetch(`${this.redisClientUrl}${e}`,{method:n,body:r,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":i,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=s.headers.get("Content-Type")?.includes("application/json")?await s.json():await s.text();if(s.ok)return a;throw s.status===401?new Ff.SystemError("Redis client failed with 401: Unauthorized"):new Ff.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};di.StandardRedisClient=Hf;var qf=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ac.throwIfNotString)(e,"url"),n==="POST"&&e==="/rate-limit"){let{incrBy:i,expire:s,key:a}=JSON.parse(r),c=Date.now()+s*1e3,u=this.keyValueStore.get(a);u?Date.now()>u.expiresAt?this.keyValueStore.set(a,{value:i,expiresAt:c}):this.keyValueStore.set(a,{value:u.value+i,expiresAt:u.expiresAt}):this.keyValueStore.set(a,{value:i,expiresAt:c});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new Ff.SystemError("The in-memory redis client only supports /rate-limit calls")}};di.InMemoryRedisClient=qf});var $f=_(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.RETRY_AFTER_HEADER=Ae.wrapUserFunction=Ae.getCountAndUpdateExpiry=Ae.getRedisClient=Ae.getAll=Ae.getUser=Ae.getIP=Ae.getRealIP=void 0;var Cr=k(),Rc=re(),cE=aE(),uE=at(),wC=o(t=>{let e=t.headers.get("x-real-ip")??t.headers.get("true-client-ip")??t.headers.get("cf-connecting-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP");Ae.getRealIP=wC;var vC=o(async t=>({key:`ip-${(0,Ae.getRealIP)(t)}`}),"getIP");Ae.getIP=vC;var TC=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser");Ae.getUser=TC;var SC=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");Ae.getAll=SC;var Oc;function IC(t,e){let r;if(Oc)return Oc;if(Rc.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new cE.InMemoryRedisClient,Oc=r,r;let{authApiJWT:n,redisURL:i}=Rc.Environment.instance;if(!(0,uE.isString)(i))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,uE.isString)(n))throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=cE.StandardRedisClient.initialize(i,n,Rc.Environment.instance.deploymentName??"unknown",Rc.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Cr.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Oc=r,r}o(IC,"getRedisClient");Ae.getRedisClient=IC;async function PC(t,e,r,n,i){let s=Math.floor(e*60);return await r.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:s,key:t}),requestId:i})}o(PC,"getCountAndUpdateExpiry");Ae.getCountAndUpdateExpiry=PC;function AC(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=t.identifier.module[t.identifier.export],!r||typeof r!="function")throw new Cr.ConfigurationError(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return o(async(i,s,a)=>{let c=await r(i,s,a);if(!c.key){let u=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(c,null,2)}'`;throw s.log.error(u),new Cr.RuntimeError(u)}return c},"outerFunction")}o(AC,"wrapUserFunction");Ae.wrapUserFunction=AC;Ae.RETRY_AFTER_HEADER="Retry-After"});var dE=_(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.AsyncRateLimitInboundPolicy=void 0;var RC=or(),OC=Zt(),NC=de(),CC=Je(),xC=re(),LC=Bt(),sn=$f(),lE=(0,RC.debug)("zuplo:policies:RateLimitInboundPolicy"),DC=o(async(t,e,r,n)=>{let i=CC.SystemLogMap.getLogger(e),s=o((E,T)=>{let C={};return(!E||E==="retry-after")&&(C[sn.RETRY_AFTER_HEADER]=T.toString()),NC.HttpProblems.tooManyRequests(t,e,void 0,C)},"rateLimited"),c={function:(0,sn.wrapUserFunction)(r,n),user:sn.getUser,ip:sn.getIP,all:sn.getAll}[r.rateLimitBy],u=await c(t,e,n),l=u.key,d=u.requestsAllowed??r.requestsAllowed,p=u.timeWindowMinutes??r.timeWindowMinutes,f=r.headerMode??"retry-after",h=(0,sn.getRedisClient)(n,i),b=`bucket/${xC.Environment.instance.build.BUILD_ID}/${n}/${l}`,I=await(0,OC.getPolicyCacheName)(n,r),A=new LC.MemoryZoneReadThroughCache(I,e),g=(0,sn.getCountAndUpdateExpiry)(b,p,h,i,e.requestId),v;o(async()=>{let E=await g;if(E.count>d){let T=Date.now()+E.ttlSeconds*1e3;A.put(b,T,E.ttlSeconds),lE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${b}' (async mode)`),v=s(f,E.ttlSeconds)}},"asyncCheck")();let V=await A.get(b);if(V!==void 0&&V>Date.now()){lE(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${b}' (async mode)`);let E=Math.round((V-Date.now())/1e3);return s(f,E)}return e.addResponseSendingHook(async E=>v??E),t},"AsyncRateLimitInboundPolicy");Nc.AsyncRateLimitInboundPolicy=DC});var fE=_(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.RateLimitInboundPolicy=void 0;var MC=or(),UC=k(),kC=de(),FC=Je(),HC=re(),qC=dE(),an=$f(),pE=(0,MC.debug)("zuplo:policies:RateLimitInboundPolicy"),$C="strict",jC=o(async(t,e,r,n)=>{if((r.mode??$C)==="async")return(0,qC.AsyncRateLimitInboundPolicy)(t,e,r,n);let s=Date.now(),a=FC.SystemLogMap.getLogger(e),c=o((l,d)=>{if(r.throwOnFailure)throw new UC.SystemError(l,{cause:d});a.error(l,d)},"throwOrLog"),u=o((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[an.RETRY_AFTER_HEADER]=d.toString()),kC.HttpProblems.tooManyRequests(t,e,void 0,p)},"rateLimited");try{let d={function:(0,an.wrapUserFunction)(r,n),user:an.getUser,ip:an.getIP,all:an.getAll}[r.rateLimitBy],p=await d(t,e,n),f=p.key,h=p.requestsAllowed??r.requestsAllowed,y=p.timeWindowMinutes??r.timeWindowMinutes,b=r.headerMode??"retry-after",I=(0,an.getRedisClient)(n,a),g=`bucket/${HC.Environment.instance.build.BUILD_ID}/${n}/${f}`,v=await(0,an.getCountAndUpdateExpiry)(g,y,I,a,e.requestId);return v.count>h?(pE(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${g}' (strict mode)`),u(b,v.ttlSeconds)):t}catch(l){return c(l.message,l),t}finally{let l=Date.now()-s;pE(`RateLimitInboundPolicy '${n}' - latency ${l}ms`)}},"RateLimitInboundPolicy");Cc.RateLimitInboundPolicy=jC});var gE=_(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.ReadmeMetricsInboundPolicy=void 0;var VC=Re(),jf=re(),hE=Jt(),Vf;function mE(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(mE,"headersToNameValuePairs");function BC(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(BC,"queryToNameValueParis");function GC(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(GC,"parseIntOrUndefined");var yE={};async function KC(t,e,r,n){let i=new Date,s=Date.now();return Vf||(Vf={name:"zuplo",version:jf.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${jf.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,hE.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:jf.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Vf,entries:[{startedDateTime:i.toISOString(),time:Date.now()-s,request:{method:t.method,url:r.useFullRequestPath?new URL(t.url).pathname:e.route.path,httpVersion:"2",headers:mE(t.headers),queryString:BC(t.query)},response:{status:a.status,statusText:a.statusText,headers:mE(a.headers),content:{size:GC(t.headers.get("content-length"))}}}]}}},d=yE[r.apiKey];if(!d){let p=r.apiKey;d=new VC.BatchDispatch("readme-metering-inbound-policy",10,async f=>{try{let h=r.url??"https://metrics.readme.io/request",y=await fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});y.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${n}'. ${y.status}: '${await y.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${h.message}'`),h}}),yE[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(KC,"ReadmeMetricsInboundPolicy");xc.ReadmeMetricsInboundPolicy=KC});var bE=_(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});Lc.RemoveHeadersInboundPolicy=void 0;var JC=k(),zC=Ke(),WC=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new JC.ConfigurationError(`RemoveHeadersInboundPolicy '${n}' options.headers must be a non-empty string array of header names`);let s=new Headers(t.headers);return i.forEach(c=>{s.delete(c)}),new zC.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Lc.RemoveHeadersInboundPolicy=WC});var _E=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RemoveHeadersOutboundPolicy=void 0;var QC=k(),YC=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new QC.ConfigurationError(`RemoveHeadersOutboundPolicy '${i}' options.headers must be a non-empty string array of header names`);let a=new Headers(t.headers);return s.forEach(u=>{a.delete(u)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"RemoveHeadersOutboundPolicy");Dc.RemoveHeadersOutboundPolicy=YC});var EE=_(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.RemoveQueryParamsInboundPolicy=void 0;var ZC=k(),XC=Ke(),ex=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new ZC.ConfigurationError(`RemoveQueryParamsInboundPolicy '${n}' options.params must be a non-empty string array of header names`);let s=new URL(t.url);return i.forEach(c=>{s.searchParams.delete(c)}),new XC.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");Mc.RemoveQueryParamsInboundPolicy=ex});var wE=_(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.ReplaceStringOutboundPolicy=void 0;var tx=o(async(t,e,r,n)=>{let i=await t.text(),s=n.mode==="regexp"?new RegExp(n.match,"gm"):n.match,a=i.replaceAll(s,n.replaceWith);return new Response(a,{headers:t.headers,status:t.status,statusText:t.statusText})},"ReplaceStringOutboundPolicy");Uc.ReplaceStringOutboundPolicy=tx});var TE=_(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.RequestSizeLimitInboundPolicy=void 0;var vE=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),rx=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?vE():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?vE():t},"RequestSizeLimitInboundPolicy");kc.RequestSizeLimitInboundPolicy=rx});var Fc=_(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.sanitizedIdentifierName=pt.getIdForRefSchema=pt.getIdForRequestBodySchema=pt.getIdForParameterSchema=pt.getRawOperationDataIdentifierName=void 0;function nx(t,e,r){return`_${cn(t+"_"+e+"_"+r)}`}o(nx,"getRawOperationDataIdentifierName");pt.getRawOperationDataIdentifierName=nx;function ix(t,e,r,n){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(ix,"getIdForParameterSchema");pt.getIdForParameterSchema=ix;function ox(t,e,r){return`_${cn(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${cn(r.toLowerCase())}`}o(ox,"getIdForRequestBodySchema");pt.getIdForRequestBodySchema=ox;function sx(t,e){return`_${cn(t)}__${cn(e)}`}o(sx,"getIdForRefSchema");pt.getIdForRefSchema=sx;function cn(t){let e=[];for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n>="0".charCodeAt(0)&&n<="9".charCodeAt(0)||n>="A".charCodeAt(0)&&n<="Z".charCodeAt(0)||n>="a".charCodeAt(0)&&n<="z".charCodeAt(0)?e.push(t.charAt(r)):e.push("_")}return e.join("")}o(cn,"sanitizedIdentifierName");pt.sanitizedIdentifierName=cn});var co=_(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.getErrorsFromValidator=je.shouldReject=je.shouldLog=je.logErrors=je.validateParameters=je.getParametersForOperation=void 0;var ax=qr(),cx=Fc(),ux=o(t=>{let e=t.route.raw();return e.parameters?e.parameters.map(n=>({name:n.name,location:n.in,required:n.required,deprecated:n.deprecated,allowEmptyValue:n.allowEmptyValue})):[]},"getParametersForOperation");je.getParametersForOperation=ux;var lx=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{let l=u.required||i==="path";if(l&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=(0,cx.getIdForParameterSchema)(r,n,i,u.name),p=ax.Gateway.instance.schemaValidator[d],f=p(e[u.name]),h=(0,je.getErrorsFromValidator)(p.errors);f||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");je.validateParameters=lx;var dx=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");je.logErrors=dx;var px=o(t=>t==="log-only"||t==="reject-and-log","shouldLog");je.shouldLog=px;var fx=o(t=>t==="reject-only"||t==="reject-and-log","shouldReject");je.shouldReject=fx;var hx=o(t=>t?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");je.getErrorsFromValidator=hx});var SE=_(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.handleBodyValidation=void 0;var mx=qr(),Hc=de(),yx=Fc(),tt=co();async function gx(t,e,r){if(!r.validateBody||r.validateBody==="none")return;let n;try{n=await e.clone().json()}catch(h){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=Hc.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${h}`});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",y,[n],h),(0,tt.shouldReject)(r.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}let i=e.headers.get("Content-Type"),s=i.indexOf(";");s>-1&&(i=i.substring(0,s));let a=(0,yx.getIdForRequestBodySchema)(t.route.path,e.method,i),c=mx.Gateway.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Hc.HttpProblems.badRequest(e,t,{detail:h});return(0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",h,[n],[h]),(0,tt.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,tt.getErrorsFromValidator)(l),f=Hc.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,tt.shouldLog)(r.validateBody)&&(0,tt.logErrors)(t,r.logLevel??"info",d,[n],p),(0,tt.shouldReject)(r.validateBody))return f}o(gx,"handleBodyValidation");qc.handleBodyValidation=gx});var IE=_($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.handleHeadersValidation=void 0;var bx=de(),uo=co();function _x(t,e,r){if(!r.validateHeaders||r.validateHeaders==="none")return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,uo.getParametersForOperation)(t),s=(0,uo.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=bx.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,uo.shouldLog)(r.validateHeaders)&&(0,uo.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,uo.shouldReject)(r.validateHeaders))return c}}o(_x,"handleHeadersValidation");$c.handleHeadersValidation=_x});var PE=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.handlePathParameterValidation=void 0;var Ex=de(),lo=co();function wx(t,e,r){if(!r.validatePathParameters||r.validatePathParameters==="none")return;let n=(0,lo.getParametersForOperation)(t),i=(0,lo.validateParameters)(n.filter(s=>s.location==="path"),e.params,t.route.path,e.method.toLowerCase(),"path");if(!i.isValid){let s="Path parameters validation failed",a=Ex.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,lo.shouldLog)(r.validatePathParameters)&&(0,lo.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,lo.shouldReject)(r.validatePathParameters))return a}}o(wx,"handlePathParameterValidation");jc.handlePathParameterValidation=wx});var AE=_(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.handleQueryParameterValidation=void 0;var vx=de(),po=co();function Tx(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters==="none")return;let n=(0,po.getParametersForOperation)(t),i=(0,po.validateParameters)(n.filter(s=>s.location==="query"),e.query,t.route.path,e.method.toLowerCase(),"query");if(!i.isValid){let s="Query parameters validation failed",a=vx.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,po.shouldLog)(r.validateQueryParameters)&&(0,po.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,po.shouldReject)(r.validateQueryParameters))return a}}o(Tx,"handleQueryParameterValidation");Vc.handleQueryParameterValidation=Tx});var RE=_(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy=void 0;var Sx=SE(),Ix=IE(),Px=PE(),Ax=AE(),Rx=o(async(t,e,r)=>{let n=(0,Ax.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,Px.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,Ix.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,Sx.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");un.RequestValidationInboundPolicy=Rx;un.SchemaBasedRequestValidation=un.RequestValidationInboundPolicy});var OE=_(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.RequireOriginInboundPolicy=void 0;var Ox=k(),Nx=de(),Cx=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new Ox.ConfigurationError(`RequireOriginInboundPolicy '${n}' configuration error - no allowed origins specified`);let i=typeof r.origins=="string"?r.origins.split(","):r.origins;i=i.map(a=>a.trim());let s=t.headers.get("origin");if(!s||!i.includes(s)){let a=r.failureDetail??"Forbidden";return Nx.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");Bc.RequireOriginInboundPolicy=Cx});var NE=_(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.SetBodyInboundPolicy=void 0;var xx=Ke(),Lx=o(async(t,e,r)=>new xx.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Gc.SetBodyInboundPolicy=Lx});var xE=_(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.SetHeadersInboundPolicy=void 0;var CE=k(),Dx=Ke(),Mx=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' options.headers must be a valid array of { name, value }`);let s=new Headers(t.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new CE.ConfigurationError(`SetHeadersInboundPolicy '${n}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.has(c.name)||u)&&s.set(c.name,c.value)}),new Dx.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Kc.SetHeadersInboundPolicy=Mx});var DE=_(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.SetHeadersOutboundPolicy=void 0;var LE=k(),Ux=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' options.headers must be a valid array of { name, value }`);let a=new Headers(t.headers);return s.forEach(u=>{if(!u.name||u.name.length===0)throw new LE.ConfigurationError(`SetHeadersOutboundPolicy '${i}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(t.body,{headers:a,status:t.status,statusText:t.statusText})},"SetHeadersOutboundPolicy");Jc.SetHeadersOutboundPolicy=Ux});var UE=_(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.SetQueryParamsInboundPolicy=void 0;var ME=k(),kx=Ke(),Fx=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' options.params must be a valid array of { name, value }`);let s=new URL(t.url);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new ME.ConfigurationError(`SetQueryParamsInboundPolicy '${n}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!s.searchParams.has(c.name)||u)&&s.searchParams.set(c.name,c.value)}),new kx.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");zc.SetQueryParamsInboundPolicy=Fx});var kE=_(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.SetStatusOutboundPolicy=void 0;var Hx=o(async(t,e,r,n,i)=>{if(!n.status||isNaN(n.status)||n.status<100||n.status>599)throw new Error(`Invalid SetStatusOutboundPolicy '${i}' - status must be a valid number between 100 and 599, not '${n.status}'`);return new Response(t.body,{headers:t.headers,status:n.status,statusText:n.statusText??t.statusText})},"SetStatusOutboundPolicy");Wc.SetStatusOutboundPolicy=Hx});var FE=_(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.SleepInboundPolicy=void 0;var qx=k(),$x=o(async t=>new Promise(r=>{setTimeout(r,t)}),"sleep"),jx=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new qx.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await $x(r.sleepInMs),t},"SleepInboundPolicy");Qc.SleepInboundPolicy=jx});var qE=_(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.SupabaseJwtInboundPolicy=void 0;var HE=k(),Vx=de(),Bx=Ke(),Gx=lt(),Kx=Xt(),Jx=o(async(t,e,r,n)=>{(0,Gx.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,Kx.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof Bx.ZuploRequest))throw new HE.SystemError("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=r.requiredClaims;if(!a)return s;let c=t.user?.data.app_metadata;if(!c)throw new HE.RuntimeError(`SupabaseJwtInboundPolicy policy '${n}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?Vx.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Yc.SupabaseJwtInboundPolicy=Jx});var jE=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var zx=Zt(),Wx=Bt(),$E=k(),Qx=kn(),Yx=lt(),Zx=o(async(t,e,r,n)=>{(0,Yx.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=await(0,zx.getPolicyCacheName)(n,r),s=new Wx.MemoryZoneReadThroughCache(i,e),a=await s.get(n);if(!a){let c=await Xx(r,e);s.put(n,c.access_token,c.expires_in-(r.expirationOffsetSeconds??300)),a=c.access_token}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Zc.UpstreamAzureAdServiceAuthInboundPolicy=Zx;async function Xx(t,e){let r=new URLSearchParams({client_id:t.activeDirectoryClientId,scope:`${t.activeDirectoryClientId}/.default`,client_secret:t.activeDirectoryClientSecret,grant_type:"client_credentials"}),n=await(0,Qx.fetchRetry)({retries:t.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${t.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:r});if(n.status!==200){try{let s=await n.text();e.log.error("Could not get token from Azure AD",s)}catch{}throw new $E.RuntimeError("Could not get token from Azure AD")}let i=await n.json();if(i&&typeof i=="object"&&"access_token"in i&&typeof i.access_token=="string"&&"expires_in"in i&&typeof i.expires_in=="number")return{access_token:i.access_token,expires_in:i.expires_in};throw new $E.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(Xx,"getAccessToken")});var BE=_(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var eL=Zt(),tL=Bt(),rL=k(),Bf=Fn(),nL=lt(),VE="https://accounts.google.com/o/oauth2/token",Gf,iL=o(async(t,e,r,n)=>{(0,nL.optionValidator)(r,n).required("serviceAccountJson","string"),Gf||(Gf=await Bf.GcpServiceAccount.init(r.serviceAccountJson));let i={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},s=await(0,eL.getPolicyCacheName)(n,r),a=new tL.MemoryZoneReadThroughCache(s,e),c=await a.get(n);if(!c){let u=await(0,Bf.getTokenFromGcpServiceAccount)({serviceAccount:Gf,audience:VE,payload:i}),l=await(0,Bf.exchangeGgpJwtForIdToken)(VE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new rL.RuntimeError("Invalid OAuth response from Firebase");c=l.access_token,a.put(n,c,(l.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Xc.UpstreamFirebaseAdminAuthInboundPolicy=iL});var GE=_(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.UpstreamFirebaseUserAuthInboundPolicy=void 0;var oL=Zt(),sL=Bt(),pi=k(),aL=If(),Kf=Fn(),cL=Jt(),uL=lt(),lL="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",dL=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Jf,pL=o(async(t,e,r,n)=>{if((0,uL.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new pi.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let p in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,p)){if(dL.indexOf(p)!==-1)throw new pi.ConfigurationError(`Developer claim "${p}" is reserved and cannot be specified.`);i[p]=r.developerClaims[p]}}Jf||(Jf=await Kf.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");s=t.user?.sub}else if(r.userIdPropertyPath){if(!t.user)throw new pi.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,cL.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new pi.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=await(0,oL.getPolicyCacheName)(n,r),c=new sL.MemoryZoneReadThroughCache(a,e),u={uid:s,claims:i},l=await(0,aL.sha256)(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await(0,Kf.getTokenFromGcpServiceAccount)({serviceAccount:Jf,audience:lL,payload:u}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,h=await(0,Kf.exchangeFirebaseJwtForIdToken)(f,p,{retries:r.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new pi.RuntimeError("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${d}`),t},"UpstreamFirebaseUserAuthInboundPolicy");eu.UpstreamFirebaseUserAuthInboundPolicy=pL});var JE=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.UpstreamGcpJwtInboundPolicy=void 0;var KE=Fn(),fL=lt(),zf,hL=o(async(t,e,r,n)=>{(0,fL.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),zf||(zf=await KE.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,KE.getTokenFromGcpServiceAccount)({serviceAccount:zf,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");tu.UpstreamGcpJwtInboundPolicy=hL});var WE=_(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.UpstreamGcpServiceAuthInboundPolicy=void 0;var mL=Zt(),yL=Xu(),gL=Bt(),fo=k(),Wf=Fn(),bL=Jt(),_L=lt(),zE="https://www.googleapis.com/oauth2/v4/token",Qf,EL=o(async(t,e,r,n)=>{(0,_L.optionValidator)(r,n).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Qf||(Qf=await Wf.GcpServiceAccount.init(r.serviceAccountJson));let i={};if(r.scopes&&r.audience)throw new fo.ConfigurationError("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(r.scopes)try{let u=(0,bL.parseValueToStringArray)(r.scopes);i.scope=u.join(" ")}catch(u){throw u instanceof fo.ConfigurationError?new fo.ConfigurationError(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}r.audience&&(i.target_audience=`${r.audience}`);let s=await(0,mL.getPolicyCacheName)(n,r),a;r.useMemoryCacheOnly?a=new yL.MemoryCache(s):a=new gL.MemoryZoneReadThroughCache(s,e);let c=await a.get(n);if(!c){let u=await(0,Wf.getTokenFromGcpServiceAccount)({serviceAccount:Qf,audience:zE,payload:i}),l=await(0,Wf.exchangeGgpJwtForIdToken)(zE,u,{retries:r.tokenRetries??3,retryDelayMs:10});if(r.audience){if(!l.id_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new fo.RuntimeError("Invalid token response from GCP");c=l.access_token}a.put(n,c,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${c}`),t},"UpstreamGcpServiceAuthInboundPolicy");ru.UpstreamGcpServiceAuthInboundPolicy=EL});var YE=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.ValidateJsonSchemaInbound=void 0;var wL=k(),QE=de(),vL=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return QE.HttpProblems.badRequest(t,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(r.validator(i))return t;let{errors:a}=r.validator;if(!a)throw new wL.SystemError("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return QE.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nu.ValidateJsonSchemaInbound=vL});var ew=_((WJ,XE)=>{"use strict";var TL=Object.defineProperty,SL=Object.getOwnPropertyNames,B=o((t,e)=>TL(t,"name",{value:e,configurable:!0}),"__name"),vt=o((t,e)=>o(function(){return e||(0,t[SL(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require"),"__commonJS"),Yf=vt({"node_modules/fast-xml-parser/src/util.js"(t){"use strict";var e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",n="["+e+"]["+r+"]*",i=new RegExp("^"+n+"$"),s=B(function(c,u){let l=[],d=u.exec(c);for(;d;){let p=[];p.startIndex=u.lastIndex-d[0].length;let f=d.length;for(let h=0;h<f;h++)p.push(d[h]);l.push(p),d=u.exec(c)}return l},"getAllMatches"),a=B(function(c){let u=i.exec(c);return!(u===null||typeof u>"u")},"isName");t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,u,l){if(u){let d=Object.keys(u),p=d.length;for(let f=0;f<p;f++)l==="strict"?c[d[f]]=[u[d[f]]]:c[d[f]]=u[d[f]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=n}}),ZE=vt({"node_modules/fast-xml-parser/src/validator.js"(t){"use strict";var e=Yf(),r={allowBooleanAttributes:!1,unpairedTags:[]};t.validate=function(g,v){v=Object.assign({},r,v);let O=[],V=!1,E=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let T=0;T<g.length;T++)if(g[T]==="<"&&g[T+1]==="?"){if(T+=2,T=i(g,T),T.err)return T}else if(g[T]==="<"){let C=T;if(T++,g[T]==="!"){T=s(g,T);continue}else{let w=!1;g[T]==="/"&&(w=!0,T++);let P="";for(;T<g.length&&g[T]!==">"&&g[T]!==" "&&g[T]!==" "&&g[T]!==`
75
75
  `&&g[T]!=="\r";T++)P+=g[T];if(P=P.trim(),P[P.length-1]==="/"&&(P=P.substring(0,P.length-1),T--),!b(P)){let j;return P.trim().length===0?j="Invalid space after '<'.":j="Tag '"+P+"' is an invalid name.",h("InvalidTag",j,I(g,T))}let L=u(g,T);if(L===!1)return h("InvalidAttr","Attributes for '"+P+"' have open quote.",I(g,T));let te=L.value;if(T=L.index,te[te.length-1]==="/"){let j=T-te.length;te=te.substring(0,te.length-1);let M=d(te,v);if(M===!0)V=!0;else return h(M.err.code,M.err.msg,I(g,j+M.err.line))}else if(w)if(L.tagClosed){if(te.trim().length>0)return h("InvalidTag","Closing tag '"+P+"' can't have attributes or invalid starting.",I(g,C));{let j=O.pop();if(P!==j.tagName){let M=I(g,j.tagStartPos);return h("InvalidTag","Expected closing tag '"+j.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+P+"'.",I(g,C))}O.length==0&&(E=!0)}}else return h("InvalidTag","Closing tag '"+P+"' doesn't have proper closing.",I(g,T));else{let j=d(te,v);if(j!==!0)return h(j.err.code,j.err.msg,I(g,T-te.length+j.err.line));if(E===!0)return h("InvalidXml","Multiple possible root nodes found.",I(g,T));v.unpairedTags.indexOf(P)!==-1||O.push({tagName:P,tagStartPos:C}),V=!0}for(T++;T<g.length;T++)if(g[T]==="<")if(g[T+1]==="!"){T++,T=s(g,T);continue}else if(g[T+1]==="?"){if(T=i(g,++T),T.err)return T}else break;else if(g[T]==="&"){let j=f(g,T);if(j==-1)return h("InvalidChar","char '&' is not expected.",I(g,T));T=j}else if(E===!0&&!n(g[T]))return h("InvalidXml","Extra text at the end",I(g,T));g[T]==="<"&&T--}}else{if(n(g[T]))continue;return h("InvalidChar","char '"+g[T]+"' is not expected.",I(g,T))}if(V){if(O.length==1)return h("InvalidTag","Unclosed tag '"+O[0].tagName+"'.",I(g,O[0].tagStartPos));if(O.length>0)return h("InvalidXml","Invalid '"+JSON.stringify(O.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return h("InvalidXml","Start tag expected.",1);return!0};function n(g){return g===" "||g===" "||g===`
76
- `||g==="\r"}o(n,"isWhiteSpace"),B(n,"isWhiteSpace");function i(g,v){let O=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let V=g.substr(O,v-O);if(v>5&&V==="xml")return h("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"readPI"),B(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let O=1;for(v+=8;v<g.length;v++)if(g[v]==="<")O++;else if(g[v]===">"&&(O--,O===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"readCommentAndCDATA"),B(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let O="",V="",E=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)V===""?V=g[v]:V!==g[v]||(V="");else if(g[v]===">"&&V===""){E=!0;break}O+=g[v]}return V!==""?!1:{value:O,index:v,tagClosed:E}}o(u,"readAttributeStr"),B(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let O=e.getAllMatches(g,l),V={};for(let E=0;E<O.length;E++){if(O[E][1].length===0)return h("InvalidAttr","Attribute '"+O[E][2]+"' has no space in starting.",A(O[E]));if(O[E][3]!==void 0&&O[E][4]===void 0)return h("InvalidAttr","Attribute '"+O[E][2]+"' is without value.",A(O[E]));if(O[E][3]===void 0&&!v.allowBooleanAttributes)return h("InvalidAttr","boolean attribute '"+O[E][2]+"' is not allowed.",A(O[E]));let T=O[E][2];if(!y(T))return h("InvalidAttr","Attribute '"+T+"' is an invalid name.",A(O[E]));if(!V.hasOwnProperty(T))V[T]=1;else return h("InvalidAttr","Attribute '"+T+"' is repeated.",A(O[E]))}return!0}o(d,"validateAttributeString"),B(d,"validateAttributeString");function p(g,v){let O=/\d/;for(g[v]==="x"&&(v++,O=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(O))break}return-1}o(p,"validateNumberAmpersand"),B(p,"validateNumberAmpersand");function f(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let O=0;for(;v<g.length;v++,O++)if(!(g[v].match(/\w/)&&O<20)){if(g[v]===";")break;return-1}return v}o(f,"validateAmpersand"),B(f,"validateAmpersand");function h(g,v,O){return{err:{code:g,msg:v,line:O.line||O,col:O.col}}}o(h,"getErrorObject"),B(h,"getErrorObject");function y(g){return e.isName(g)}o(y,"validateAttrName"),B(y,"validateAttrName");function b(g){return e.isName(g)}o(b,"validateTagName"),B(b,"validateTagName");function I(g,v){let O=g.substring(0,v).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}o(I,"getLineNumberForPosition"),B(I,"getLineNumberForPosition");function A(g){return g.startIndex+g[1].length}o(A,"getPositionFromMatch"),B(A,"getPositionFromMatch")}}),SL=vt({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=B(function(n){return Object.assign({},e,n)},"buildOptions");t.buildOptions=r,t.defaultOptions=e}}),IL=vt({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var r=class{static{o(this,"XmlNode")}static{B(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};e.exports=r}}),PL=vt({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var r=Yf();function n(p,f){let h={};if(p[f+3]==="O"&&p[f+4]==="C"&&p[f+5]==="T"&&p[f+6]==="Y"&&p[f+7]==="P"&&p[f+8]==="E"){f=f+9;let y=1,b=!1,I=!1,A="";for(;f<p.length;f++)if(p[f]==="<"&&!I){if(b&&a(p,f))f+=7,[entityName,val,f]=i(p,f+1),val.indexOf("&")===-1&&(h[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&c(p,f))f+=8;else if(b&&u(p,f))f+=8;else if(b&&l(p,f))f+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,A=""}else if(p[f]===">"){if(I?p[f-1]==="-"&&p[f-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[f]==="["?b=!0:A+=p[f];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:h,i:f}}o(n,"readDocType"),B(n,"readDocType");function i(p,f){let h="";for(;f<p.length&&p[f]!=="'"&&p[f]!=='"';f++)h+=p[f];if(h=h.trim(),h.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[f++],b="";for(;f<p.length&&p[f]!==y;f++)b+=p[f];return[h,b,f]}o(i,"readEntityExp"),B(i,"readEntityExp");function s(p,f){return p[f+1]==="!"&&p[f+2]==="-"&&p[f+3]==="-"}o(s,"isComment"),B(s,"isComment");function a(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="N"&&p[f+4]==="T"&&p[f+5]==="I"&&p[f+6]==="T"&&p[f+7]==="Y"}o(a,"isEntity"),B(a,"isEntity");function c(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="L"&&p[f+4]==="E"&&p[f+5]==="M"&&p[f+6]==="E"&&p[f+7]==="N"&&p[f+8]==="T"}o(c,"isElement"),B(c,"isElement");function u(p,f){return p[f+1]==="!"&&p[f+2]==="A"&&p[f+3]==="T"&&p[f+4]==="T"&&p[f+5]==="L"&&p[f+6]==="I"&&p[f+7]==="S"&&p[f+8]==="T"}o(u,"isAttlist"),B(u,"isAttlist");function l(p,f){return p[f+1]==="!"&&p[f+2]==="N"&&p[f+3]==="O"&&p[f+4]==="T"&&p[f+5]==="A"&&p[f+6]==="T"&&p[f+7]==="I"&&p[f+8]==="O"&&p[f+9]==="N"}o(l,"isNotation"),B(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"validateEntityName"),B(d,"validateEntityName"),e.exports=n}}),AL=vt({"../../node_modules/strnum/strnum.js"(t,e){var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],f=d[2],h=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&f.length>0&&p&&l[2]!==".")return c;if(!u.leadingZeros&&f.length>0&&!p&&l[1]!==".")return c;{let b=Number(l),I=""+b;return I.search(/[eE]/)!==-1||y?u.eNotation?b:c:l.indexOf(".")!==-1?I==="0"&&h===""||I===h||p&&I==="-"+h?b:c:f?h===I||p+h===I?b:c:l===I||l===p+I?b:c}}else return c}}o(s,"toNumber"),B(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"trimZeros"),B(a,"trimZeros"),e.exports=s}}),RL=vt({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var r=Yf(),n=IL(),i=PL(),s=AL(),a=class{static{o(this,"OrderedObjParser")}static{B(this,"OrderedObjParser")}constructor(E){this.options=E,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=c,this.parseXml=f,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=h}};function c(E){let T=Object.keys(E);for(let C=0;C<T.length;C++){let w=T[C];this.lastEntities[w]={regex:new RegExp("&"+w+";","g"),val:E[w]}}}o(c,"addExternalEntities"),B(c,"addExternalEntities");function u(E,T,C,w,P,L,te){if(E!==void 0&&(this.options.trimValues&&!w&&(E=E.trim()),E.length>0)){te||(E=this.replaceEntitiesValue(E));let j=this.options.tagValueProcessor(T,E,C,P,L);return j==null?E:typeof j!=typeof E||j!==E?j:this.options.trimValues?V(E,this.options.parseTagValue,this.options.numberParseOptions):E.trim()===E?V(E,this.options.parseTagValue,this.options.numberParseOptions):E}}o(u,"parseTextData"),B(u,"parseTextData");function l(E){if(this.options.removeNSPrefix){let T=E.split(":"),C=E.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(E=C+T[1])}return E}o(l,"resolveNameSpace"),B(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(E,T,C){if(!this.options.ignoreAttributes&&typeof E=="string"){let w=r.getAllMatches(E,d),P=w.length,L={};for(let te=0;te<P;te++){let j=this.resolveNameSpace(w[te][1]),M=w[te][4],_e=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(_e=this.options.transformAttributeName(_e)),_e==="__proto__"&&(_e="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let le=this.options.attributeValueProcessor(j,M,T);le==null?L[_e]=M:typeof le!=typeof M||le!==M?L[_e]=le:L[_e]=V(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[_e]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=L,te}return L}}o(p,"buildAttributesMap"),B(p,"buildAttributesMap");var f=B(function(E){E=E.replace(/\r\n?/g,`
77
- `);let T=new n("!xml"),C=T,w="",P="";for(let L=0;L<E.length;L++)if(E[L]==="<")if(E[L+1]==="/"){let j=g(E,">",L,"Closing Tag is not closed."),M=E.substring(L+2,j).trim();if(this.options.removeNSPrefix){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&(w=this.saveTextToParentTag(w,C,P));let _e=P.substring(P.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let le=0;_e&&this.options.unpairedTags.indexOf(_e)!==-1?(le=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):le=P.lastIndexOf("."),P=P.substring(0,le),C=this.tagsNodeStack.pop(),w="",L=j}else if(E[L+1]==="?"){let j=v(E,L,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(w=this.saveTextToParentTag(w,C,P),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let M=new n(j.tagName);M.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(M[":@"]=this.buildAttributesMap(j.tagExp,P,j.tagName)),this.addChild(C,M,P)}L=j.closeIndex+1}else if(E.substr(L+1,3)==="!--"){let j=g(E,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let M=E.substring(L+4,j-2);w=this.saveTextToParentTag(w,C,P),C.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}L=j}else if(E.substr(L+1,2)==="!D"){let j=i(E,L);this.docTypeEntities=j.entities,L=j.i}else if(E.substr(L+1,2)==="!["){let j=g(E,"]]>",L,"CDATA is not closed.")-2,M=E.substring(L+9,j);w=this.saveTextToParentTag(w,C,P);let _e=this.parseTextData(M,C.tagname,P,!0,!1,!0,!0);_e==null&&(_e=""),this.options.cdataPropName?C.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):C.add(this.options.textNodeName,_e),L=j+2}else{let j=v(E,L,this.options.removeNSPrefix),M=j.tagName,_e=j.rawTagName,le=j.tagExp,yt=j.attrExpPresent,xh=j.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&w&&C.tagname!=="!xml"&&(w=this.saveTextToParentTag(w,C,P,!1));let Lh=C;if(Lh&&this.options.unpairedTags.indexOf(Lh.tagname)!==-1&&(C=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),M!==T.tagname&&(P+=P?"."+M:M),this.isItStopNode(this.options.stopNodes,P,M)){let st="";if(le.length>0&&le.lastIndexOf("/")===le.length-1)L=j.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)L=j.closeIndex;else{let Ku=this.readStopNodeData(E,_e,xh+1);if(!Ku)throw new Error(`Unexpected end of ${_e}`);L=Ku.i,st=Ku.tagContent}let Gu=new n(M);M!==le&&yt&&(Gu[":@"]=this.buildAttributesMap(le,P,M)),st&&(st=this.parseTextData(st,M,P,!0,yt,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),Gu.add(this.options.textNodeName,st),this.addChild(C,Gu,P)}else{if(le.length>0&&le.lastIndexOf("/")===le.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),P=P.substr(0,P.length-1),le=M):le=le.substr(0,le.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let st=new n(M);M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),P=P.substr(0,P.lastIndexOf("."))}else{let st=new n(M);this.tagsNodeStack.push(C),M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),C=st}w="",L=xh}}else w+=E[L];return T.child},"parseXml");function h(E,T,C){let w=this.options.updateTag(T.tagname,C,T[":@"]);w===!1||(typeof w=="string"&&(T.tagname=w),E.addChild(T))}o(h,"addChild"),B(h,"addChild");var y=B(function(E){if(this.options.processEntities){for(let T in this.docTypeEntities){let C=this.docTypeEntities[T];E=E.replace(C.regx,C.val)}for(let T in this.lastEntities){let C=this.lastEntities[T];E=E.replace(C.regex,C.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let C=this.htmlEntities[T];E=E.replace(C.regex,C.val)}E=E.replace(this.ampEntity.regex,this.ampEntity.val)}return E},"replaceEntitiesValue");function b(E,T,C,w){return E&&(w===void 0&&(w=Object.keys(T.child).length===0),E=this.parseTextData(E,T.tagname,C,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,w),E!==void 0&&E!==""&&T.add(this.options.textNodeName,E),E=""),E}o(b,"saveTextToParentTag"),B(b,"saveTextToParentTag");function I(E,T,C){let w="*."+C;for(let P in E){let L=E[P];if(w===L||T===L)return!0}return!1}o(I,"isItStopNode"),B(I,"isItStopNode");function A(E,T,C=">"){let w,P="";for(let L=T;L<E.length;L++){let te=E[L];if(w)te===w&&(w="");else if(te==='"'||te==="'")w=te;else if(te===C[0])if(C[1]){if(E[L+1]===C[1])return{data:P,index:L}}else return{data:P,index:L};else te===" "&&(te=" ");P+=te}}o(A,"tagExpWithClosingIndex"),B(A,"tagExpWithClosingIndex");function g(E,T,C,w){let P=E.indexOf(T,C);if(P===-1)throw new Error(w);return P+T.length-1}o(g,"findClosingIndex"),B(g,"findClosingIndex");function v(E,T,C,w=">"){let P=A(E,T+1,w);if(!P)return;let L=P.data,te=P.index,j=L.search(/\s/),M=L,_e=!0;j!==-1&&(M=L.substring(0,j),L=L.substring(j+1).trimStart());let le=M;if(C){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1),_e=M!==P.data.substr(yt+1))}return{tagName:M,tagExp:L,closeIndex:te,attrExpPresent:_e,rawTagName:le}}o(v,"readTagExp"),B(v,"readTagExp");function O(E,T,C){let w=C,P=1;for(;C<E.length;C++)if(E[C]==="<")if(E[C+1]==="/"){let L=g(E,">",C,`${T} is not closed`);if(E.substring(C+2,L).trim()===T&&(P--,P===0))return{tagContent:E.substring(w,C),i:L};C=L}else if(E[C+1]==="?")C=g(E,"?>",C+1,"StopNode is not closed.");else if(E.substr(C+1,3)==="!--")C=g(E,"-->",C+3,"StopNode is not closed.");else if(E.substr(C+1,2)==="![")C=g(E,"]]>",C,"StopNode is not closed.")-2;else{let L=v(E,C,">");L&&((L&&L.tagName)===T&&L.tagExp[L.tagExp.length-1]!=="/"&&P++,C=L.closeIndex)}}o(O,"readStopNodeData"),B(O,"readStopNodeData");function V(E,T,C){if(T&&typeof E=="string"){let w=E.trim();return w==="true"?!0:w==="false"?!1:s(E,C)}else return r.isExist(E)?E:""}o(V,"parseValue"),B(V,"parseValue"),e.exports=a}}),OL=vt({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,c){return r(a,c)}o(e,"prettify"),B(e,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let f=a[p],h=n(f),y="";if(u===void 0?y=h:y=u+"."+h,h===c.textNodeName)l===void 0?l=f[h]:l+=""+f[h];else{if(h===void 0)continue;if(f[h]){let b=r(f[h],c,y),I=s(b,c);f[":@"]?i(b,f[":@"],y,c):Object.keys(b).length===1&&b[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?b=b[c.textNodeName]:Object.keys(b).length===0&&(c.alwaysCreateTextNode?b[c.textNodeName]="":b=""),d[h]!==void 0&&d.hasOwnProperty(h)?(Array.isArray(d[h])||(d[h]=[d[h]]),d[h].push(b)):c.isArray(h,y,I)?d[h]=[b]:d[h]=b}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"compress"),B(r,"compress");function n(a){let c=Object.keys(a);for(let u=0;u<c.length;u++){let l=c[u];if(l!==":@")return l}}o(n,"propName"),B(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let f=0;f<p;f++){let h=d[f];l.isArray(h,u+"."+h,!0,!0)?a[h]=[c[h]]:a[h]=c[h]}}}o(i,"assignAttributes"),B(i,"assignAttributes");function s(a,c){let{textNodeName:u}=c,l=Object.keys(a).length;return!!(l===0||l===1&&(a[u]||typeof a[u]=="boolean"||a[u]===0))}o(s,"isLeafTag"),B(s,"isLeafTag"),t.prettify=e}}),NL=vt({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:r}=SL(),n=RL(),{prettify:i}=OL(),s=ZE(),a=class{static{o(this,"XMLParser2")}static{B(this,"XMLParser")}constructor(c){this.externalEntities={},this.options=r(c)}parse(c,u){if(typeof c!="string")if(c.toString)c=c.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(u){u===!0&&(u={});let p=s.validate(c,u);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new n(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(c);return this.options.preserveOrder||d===void 0?d:i(d,this.options)}addEntity(c,u){if(u.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(c.indexOf("&")!==-1||c.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(u==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[c]=u}};e.exports=a}}),CL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var r=`
78
- `;function n(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=r),i(l,d,"",p)}o(n,"toXml"),B(n,"toXml");function i(l,d,p,f){let h="",y=!1;for(let b=0;b<l.length;b++){let I=l[b],A=s(I);if(A===void 0)continue;let g="";if(p.length===0?g=A:g=`${p}.${A}`,A===d.textNodeName){let T=I[A];c(g,d)||(T=d.tagValueProcessor(A,T),T=u(T,d)),y&&(h+=f),h+=T,y=!1;continue}else if(A===d.cdataPropName){y&&(h+=f),h+=`<![CDATA[${I[A][0][d.textNodeName]}]]>`,y=!1;continue}else if(A===d.commentPropName){h+=f+`<!--${I[A][0][d.textNodeName]}-->`,y=!0;continue}else if(A[0]==="?"){let T=a(I[":@"],d),C=A==="?xml"?"":f,w=I[A][0][d.textNodeName];w=w.length!==0?" "+w:"",h+=C+`<${A}${w}${T}?>`,y=!0;continue}let v=f;v!==""&&(v+=d.indentBy);let O=a(I[":@"],d),V=f+`<${A}${O}`,E=i(I[A],d,g,v);d.unpairedTags.indexOf(A)!==-1?d.suppressUnpairedNode?h+=V+">":h+=V+"/>":(!E||E.length===0)&&d.suppressEmptyNode?h+=V+"/>":E&&E.endsWith(">")?h+=V+`>${E}${f}</${A}>`:(h+=V+">",E&&f!==""&&(E.includes("/>")||E.includes("</"))?h+=f+d.indentBy+E+f:h+=E,h+=`</${A}>`),y=!0}return h}o(i,"arrToStr"),B(i,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let f=d[p];if(l.hasOwnProperty(f)&&f!==":@")return f}}o(s,"propName"),B(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let f in l){if(!l.hasOwnProperty(f))continue;let h=d.attributeValueProcessor(f,l[f]);h=u(h,d),h===!0&&d.suppressBooleanAttributes?p+=` ${f.substr(d.attributeNamePrefix.length)}`:p+=` ${f.substr(d.attributeNamePrefix.length)}="${h}"`}return p}o(a,"attr_to_str"),B(a,"attr_to_str");function c(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let f in d.stopNodes)if(d.stopNodes[f]===l||d.stopNodes[f]==="*."+p)return!0;return!1}o(c,"isStopNode"),B(c,"isStopNode");function u(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let f=d.entities[p];l=l.replace(f.regex,f.val)}return l}o(u,"replaceEntitiesValue"),B(u,"replaceEntitiesValue"),e.exports=n}}),xL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var r=CL(),n={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(u,l){return l},attributeValueProcessor:function(u,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function i(u){this.options=Object.assign({},n,u),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=c),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
76
+ `||g==="\r"}o(n,"isWhiteSpace"),B(n,"isWhiteSpace");function i(g,v){let O=v;for(;v<g.length;v++)if(g[v]=="?"||g[v]==" "){let V=g.substr(O,v-O);if(v>5&&V==="xml")return h("InvalidXml","XML declaration allowed only at the start of the document.",I(g,v));if(g[v]=="?"&&g[v+1]==">"){v++;break}else continue}return v}o(i,"readPI"),B(i,"readPI");function s(g,v){if(g.length>v+5&&g[v+1]==="-"&&g[v+2]==="-"){for(v+=3;v<g.length;v++)if(g[v]==="-"&&g[v+1]==="-"&&g[v+2]===">"){v+=2;break}}else if(g.length>v+8&&g[v+1]==="D"&&g[v+2]==="O"&&g[v+3]==="C"&&g[v+4]==="T"&&g[v+5]==="Y"&&g[v+6]==="P"&&g[v+7]==="E"){let O=1;for(v+=8;v<g.length;v++)if(g[v]==="<")O++;else if(g[v]===">"&&(O--,O===0))break}else if(g.length>v+9&&g[v+1]==="["&&g[v+2]==="C"&&g[v+3]==="D"&&g[v+4]==="A"&&g[v+5]==="T"&&g[v+6]==="A"&&g[v+7]==="["){for(v+=8;v<g.length;v++)if(g[v]==="]"&&g[v+1]==="]"&&g[v+2]===">"){v+=2;break}}return v}o(s,"readCommentAndCDATA"),B(s,"readCommentAndCDATA");var a='"',c="'";function u(g,v){let O="",V="",E=!1;for(;v<g.length;v++){if(g[v]===a||g[v]===c)V===""?V=g[v]:V!==g[v]||(V="");else if(g[v]===">"&&V===""){E=!0;break}O+=g[v]}return V!==""?!1:{value:O,index:v,tagClosed:E}}o(u,"readAttributeStr"),B(u,"readAttributeStr");var l=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function d(g,v){let O=e.getAllMatches(g,l),V={};for(let E=0;E<O.length;E++){if(O[E][1].length===0)return h("InvalidAttr","Attribute '"+O[E][2]+"' has no space in starting.",A(O[E]));if(O[E][3]!==void 0&&O[E][4]===void 0)return h("InvalidAttr","Attribute '"+O[E][2]+"' is without value.",A(O[E]));if(O[E][3]===void 0&&!v.allowBooleanAttributes)return h("InvalidAttr","boolean attribute '"+O[E][2]+"' is not allowed.",A(O[E]));let T=O[E][2];if(!y(T))return h("InvalidAttr","Attribute '"+T+"' is an invalid name.",A(O[E]));if(!V.hasOwnProperty(T))V[T]=1;else return h("InvalidAttr","Attribute '"+T+"' is repeated.",A(O[E]))}return!0}o(d,"validateAttributeString"),B(d,"validateAttributeString");function p(g,v){let O=/\d/;for(g[v]==="x"&&(v++,O=/[\da-fA-F]/);v<g.length;v++){if(g[v]===";")return v;if(!g[v].match(O))break}return-1}o(p,"validateNumberAmpersand"),B(p,"validateNumberAmpersand");function f(g,v){if(v++,g[v]===";")return-1;if(g[v]==="#")return v++,p(g,v);let O=0;for(;v<g.length;v++,O++)if(!(g[v].match(/\w/)&&O<20)){if(g[v]===";")break;return-1}return v}o(f,"validateAmpersand"),B(f,"validateAmpersand");function h(g,v,O){return{err:{code:g,msg:v,line:O.line||O,col:O.col}}}o(h,"getErrorObject"),B(h,"getErrorObject");function y(g){return e.isName(g)}o(y,"validateAttrName"),B(y,"validateAttrName");function b(g){return e.isName(g)}o(b,"validateTagName"),B(b,"validateTagName");function I(g,v){let O=g.substring(0,v).split(/\r?\n/);return{line:O.length,col:O[O.length-1].length+1}}o(I,"getLineNumberForPosition"),B(I,"getLineNumberForPosition");function A(g){return g.startIndex+g[1].length}o(A,"getPositionFromMatch"),B(A,"getPositionFromMatch")}}),IL=vt({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(t){var e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,i){return i},attributeValueProcessor:function(n,i){return i},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,i,s){return n}},r=B(function(n){return Object.assign({},e,n)},"buildOptions");t.buildOptions=r,t.defaultOptions=e}}),PL=vt({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(t,e){"use strict";var r=class{static{o(this,"XmlNode")}static{B(this,"XmlNode")}constructor(n){this.tagname=n,this.child=[],this[":@"]={}}add(n,i){n==="__proto__"&&(n="#__proto__"),this.child.push({[n]:i})}addChild(n){n.tagname==="__proto__"&&(n.tagname="#__proto__"),n[":@"]&&Object.keys(n[":@"]).length>0?this.child.push({[n.tagname]:n.child,":@":n[":@"]}):this.child.push({[n.tagname]:n.child})}};e.exports=r}}),AL=vt({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(t,e){var r=Yf();function n(p,f){let h={};if(p[f+3]==="O"&&p[f+4]==="C"&&p[f+5]==="T"&&p[f+6]==="Y"&&p[f+7]==="P"&&p[f+8]==="E"){f=f+9;let y=1,b=!1,I=!1,A="";for(;f<p.length;f++)if(p[f]==="<"&&!I){if(b&&a(p,f))f+=7,[entityName,val,f]=i(p,f+1),val.indexOf("&")===-1&&(h[d(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(b&&c(p,f))f+=8;else if(b&&u(p,f))f+=8;else if(b&&l(p,f))f+=9;else if(s)I=!0;else throw new Error("Invalid DOCTYPE");y++,A=""}else if(p[f]===">"){if(I?p[f-1]==="-"&&p[f-2]==="-"&&(I=!1,y--):y--,y===0)break}else p[f]==="["?b=!0:A+=p[f];if(y!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:h,i:f}}o(n,"readDocType"),B(n,"readDocType");function i(p,f){let h="";for(;f<p.length&&p[f]!=="'"&&p[f]!=='"';f++)h+=p[f];if(h=h.trim(),h.indexOf(" ")!==-1)throw new Error("External entites are not supported");let y=p[f++],b="";for(;f<p.length&&p[f]!==y;f++)b+=p[f];return[h,b,f]}o(i,"readEntityExp"),B(i,"readEntityExp");function s(p,f){return p[f+1]==="!"&&p[f+2]==="-"&&p[f+3]==="-"}o(s,"isComment"),B(s,"isComment");function a(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="N"&&p[f+4]==="T"&&p[f+5]==="I"&&p[f+6]==="T"&&p[f+7]==="Y"}o(a,"isEntity"),B(a,"isEntity");function c(p,f){return p[f+1]==="!"&&p[f+2]==="E"&&p[f+3]==="L"&&p[f+4]==="E"&&p[f+5]==="M"&&p[f+6]==="E"&&p[f+7]==="N"&&p[f+8]==="T"}o(c,"isElement"),B(c,"isElement");function u(p,f){return p[f+1]==="!"&&p[f+2]==="A"&&p[f+3]==="T"&&p[f+4]==="T"&&p[f+5]==="L"&&p[f+6]==="I"&&p[f+7]==="S"&&p[f+8]==="T"}o(u,"isAttlist"),B(u,"isAttlist");function l(p,f){return p[f+1]==="!"&&p[f+2]==="N"&&p[f+3]==="O"&&p[f+4]==="T"&&p[f+5]==="A"&&p[f+6]==="T"&&p[f+7]==="I"&&p[f+8]==="O"&&p[f+9]==="N"}o(l,"isNotation"),B(l,"isNotation");function d(p){if(r.isName(p))return p;throw new Error(`Invalid entity name ${p}`)}o(d,"validateEntityName"),B(d,"validateEntityName"),e.exports=n}}),RL=vt({"../../node_modules/strnum/strnum.js"(t,e){var r=/^[-+]?0x[a-fA-F0-9]+$/,n=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var i={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function s(c,u={}){if(u=Object.assign({},i,u),!c||typeof c!="string")return c;let l=c.trim();if(u.skipLike!==void 0&&u.skipLike.test(l))return c;if(u.hex&&r.test(l))return Number.parseInt(l,16);{let d=n.exec(l);if(d){let p=d[1],f=d[2],h=a(d[3]),y=d[4]||d[6];if(!u.leadingZeros&&f.length>0&&p&&l[2]!==".")return c;if(!u.leadingZeros&&f.length>0&&!p&&l[1]!==".")return c;{let b=Number(l),I=""+b;return I.search(/[eE]/)!==-1||y?u.eNotation?b:c:l.indexOf(".")!==-1?I==="0"&&h===""||I===h||p&&I==="-"+h?b:c:f?h===I||p+h===I?b:c:l===I||l===p+I?b:c}}else return c}}o(s,"toNumber"),B(s,"toNumber");function a(c){return c&&c.indexOf(".")!==-1&&(c=c.replace(/0+$/,""),c==="."?c="0":c[0]==="."?c="0"+c:c[c.length-1]==="."&&(c=c.substr(0,c.length-1))),c}o(a,"trimZeros"),B(a,"trimZeros"),e.exports=s}}),OL=vt({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(t,e){"use strict";var r=Yf(),n=PL(),i=AL(),s=RL(),a=class{static{o(this,"OrderedObjParser")}static{B(this,"OrderedObjParser")}constructor(E){this.options=E,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"}},this.addExternalEntities=c,this.parseXml=f,this.parseTextData=u,this.resolveNameSpace=l,this.buildAttributesMap=p,this.isItStopNode=I,this.replaceEntitiesValue=y,this.readStopNodeData=O,this.saveTextToParentTag=b,this.addChild=h}};function c(E){let T=Object.keys(E);for(let C=0;C<T.length;C++){let w=T[C];this.lastEntities[w]={regex:new RegExp("&"+w+";","g"),val:E[w]}}}o(c,"addExternalEntities"),B(c,"addExternalEntities");function u(E,T,C,w,P,L,te){if(E!==void 0&&(this.options.trimValues&&!w&&(E=E.trim()),E.length>0)){te||(E=this.replaceEntitiesValue(E));let j=this.options.tagValueProcessor(T,E,C,P,L);return j==null?E:typeof j!=typeof E||j!==E?j:this.options.trimValues?V(E,this.options.parseTagValue,this.options.numberParseOptions):E.trim()===E?V(E,this.options.parseTagValue,this.options.numberParseOptions):E}}o(u,"parseTextData"),B(u,"parseTextData");function l(E){if(this.options.removeNSPrefix){let T=E.split(":"),C=E.charAt(0)==="/"?"/":"";if(T[0]==="xmlns")return"";T.length===2&&(E=C+T[1])}return E}o(l,"resolveNameSpace"),B(l,"resolveNameSpace");var d=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p(E,T,C){if(!this.options.ignoreAttributes&&typeof E=="string"){let w=r.getAllMatches(E,d),P=w.length,L={};for(let te=0;te<P;te++){let j=this.resolveNameSpace(w[te][1]),M=w[te][4],_e=this.options.attributeNamePrefix+j;if(j.length)if(this.options.transformAttributeName&&(_e=this.options.transformAttributeName(_e)),_e==="__proto__"&&(_e="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let le=this.options.attributeValueProcessor(j,M,T);le==null?L[_e]=M:typeof le!=typeof M||le!==M?L[_e]=le:L[_e]=V(M,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(L[_e]=!0)}if(!Object.keys(L).length)return;if(this.options.attributesGroupName){let te={};return te[this.options.attributesGroupName]=L,te}return L}}o(p,"buildAttributesMap"),B(p,"buildAttributesMap");var f=B(function(E){E=E.replace(/\r\n?/g,`
77
+ `);let T=new n("!xml"),C=T,w="",P="";for(let L=0;L<E.length;L++)if(E[L]==="<")if(E[L+1]==="/"){let j=g(E,">",L,"Closing Tag is not closed."),M=E.substring(L+2,j).trim();if(this.options.removeNSPrefix){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&(w=this.saveTextToParentTag(w,C,P));let _e=P.substring(P.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let le=0;_e&&this.options.unpairedTags.indexOf(_e)!==-1?(le=P.lastIndexOf(".",P.lastIndexOf(".")-1),this.tagsNodeStack.pop()):le=P.lastIndexOf("."),P=P.substring(0,le),C=this.tagsNodeStack.pop(),w="",L=j}else if(E[L+1]==="?"){let j=v(E,L,!1,"?>");if(!j)throw new Error("Pi Tag is not closed.");if(w=this.saveTextToParentTag(w,C,P),!(this.options.ignoreDeclaration&&j.tagName==="?xml"||this.options.ignorePiTags)){let M=new n(j.tagName);M.add(this.options.textNodeName,""),j.tagName!==j.tagExp&&j.attrExpPresent&&(M[":@"]=this.buildAttributesMap(j.tagExp,P,j.tagName)),this.addChild(C,M,P)}L=j.closeIndex+1}else if(E.substr(L+1,3)==="!--"){let j=g(E,"-->",L+4,"Comment is not closed.");if(this.options.commentPropName){let M=E.substring(L+4,j-2);w=this.saveTextToParentTag(w,C,P),C.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}L=j}else if(E.substr(L+1,2)==="!D"){let j=i(E,L);this.docTypeEntities=j.entities,L=j.i}else if(E.substr(L+1,2)==="!["){let j=g(E,"]]>",L,"CDATA is not closed.")-2,M=E.substring(L+9,j);w=this.saveTextToParentTag(w,C,P);let _e=this.parseTextData(M,C.tagname,P,!0,!1,!0,!0);_e==null&&(_e=""),this.options.cdataPropName?C.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):C.add(this.options.textNodeName,_e),L=j+2}else{let j=v(E,L,this.options.removeNSPrefix),M=j.tagName,_e=j.rawTagName,le=j.tagExp,yt=j.attrExpPresent,xh=j.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),C&&w&&C.tagname!=="!xml"&&(w=this.saveTextToParentTag(w,C,P,!1));let Lh=C;if(Lh&&this.options.unpairedTags.indexOf(Lh.tagname)!==-1&&(C=this.tagsNodeStack.pop(),P=P.substring(0,P.lastIndexOf("."))),M!==T.tagname&&(P+=P?"."+M:M),this.isItStopNode(this.options.stopNodes,P,M)){let st="";if(le.length>0&&le.lastIndexOf("/")===le.length-1)L=j.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)L=j.closeIndex;else{let Ku=this.readStopNodeData(E,_e,xh+1);if(!Ku)throw new Error(`Unexpected end of ${_e}`);L=Ku.i,st=Ku.tagContent}let Gu=new n(M);M!==le&&yt&&(Gu[":@"]=this.buildAttributesMap(le,P,M)),st&&(st=this.parseTextData(st,M,P,!0,yt,!0,!0)),P=P.substr(0,P.lastIndexOf(".")),Gu.add(this.options.textNodeName,st),this.addChild(C,Gu,P)}else{if(le.length>0&&le.lastIndexOf("/")===le.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),P=P.substr(0,P.length-1),le=M):le=le.substr(0,le.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let st=new n(M);M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),P=P.substr(0,P.lastIndexOf("."))}else{let st=new n(M);this.tagsNodeStack.push(C),M!==le&&yt&&(st[":@"]=this.buildAttributesMap(le,P,M)),this.addChild(C,st,P),C=st}w="",L=xh}}else w+=E[L];return T.child},"parseXml");function h(E,T,C){let w=this.options.updateTag(T.tagname,C,T[":@"]);w===!1||(typeof w=="string"&&(T.tagname=w),E.addChild(T))}o(h,"addChild"),B(h,"addChild");var y=B(function(E){if(this.options.processEntities){for(let T in this.docTypeEntities){let C=this.docTypeEntities[T];E=E.replace(C.regx,C.val)}for(let T in this.lastEntities){let C=this.lastEntities[T];E=E.replace(C.regex,C.val)}if(this.options.htmlEntities)for(let T in this.htmlEntities){let C=this.htmlEntities[T];E=E.replace(C.regex,C.val)}E=E.replace(this.ampEntity.regex,this.ampEntity.val)}return E},"replaceEntitiesValue");function b(E,T,C,w){return E&&(w===void 0&&(w=Object.keys(T.child).length===0),E=this.parseTextData(E,T.tagname,C,!1,T[":@"]?Object.keys(T[":@"]).length!==0:!1,w),E!==void 0&&E!==""&&T.add(this.options.textNodeName,E),E=""),E}o(b,"saveTextToParentTag"),B(b,"saveTextToParentTag");function I(E,T,C){let w="*."+C;for(let P in E){let L=E[P];if(w===L||T===L)return!0}return!1}o(I,"isItStopNode"),B(I,"isItStopNode");function A(E,T,C=">"){let w,P="";for(let L=T;L<E.length;L++){let te=E[L];if(w)te===w&&(w="");else if(te==='"'||te==="'")w=te;else if(te===C[0])if(C[1]){if(E[L+1]===C[1])return{data:P,index:L}}else return{data:P,index:L};else te===" "&&(te=" ");P+=te}}o(A,"tagExpWithClosingIndex"),B(A,"tagExpWithClosingIndex");function g(E,T,C,w){let P=E.indexOf(T,C);if(P===-1)throw new Error(w);return P+T.length-1}o(g,"findClosingIndex"),B(g,"findClosingIndex");function v(E,T,C,w=">"){let P=A(E,T+1,w);if(!P)return;let L=P.data,te=P.index,j=L.search(/\s/),M=L,_e=!0;j!==-1&&(M=L.substring(0,j),L=L.substring(j+1).trimStart());let le=M;if(C){let yt=M.indexOf(":");yt!==-1&&(M=M.substr(yt+1),_e=M!==P.data.substr(yt+1))}return{tagName:M,tagExp:L,closeIndex:te,attrExpPresent:_e,rawTagName:le}}o(v,"readTagExp"),B(v,"readTagExp");function O(E,T,C){let w=C,P=1;for(;C<E.length;C++)if(E[C]==="<")if(E[C+1]==="/"){let L=g(E,">",C,`${T} is not closed`);if(E.substring(C+2,L).trim()===T&&(P--,P===0))return{tagContent:E.substring(w,C),i:L};C=L}else if(E[C+1]==="?")C=g(E,"?>",C+1,"StopNode is not closed.");else if(E.substr(C+1,3)==="!--")C=g(E,"-->",C+3,"StopNode is not closed.");else if(E.substr(C+1,2)==="![")C=g(E,"]]>",C,"StopNode is not closed.")-2;else{let L=v(E,C,">");L&&((L&&L.tagName)===T&&L.tagExp[L.tagExp.length-1]!=="/"&&P++,C=L.closeIndex)}}o(O,"readStopNodeData"),B(O,"readStopNodeData");function V(E,T,C){if(T&&typeof E=="string"){let w=E.trim();return w==="true"?!0:w==="false"?!1:s(E,C)}else return r.isExist(E)?E:""}o(V,"parseValue"),B(V,"parseValue"),e.exports=a}}),NL=vt({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(t){"use strict";function e(a,c){return r(a,c)}o(e,"prettify"),B(e,"prettify");function r(a,c,u){let l,d={};for(let p=0;p<a.length;p++){let f=a[p],h=n(f),y="";if(u===void 0?y=h:y=u+"."+h,h===c.textNodeName)l===void 0?l=f[h]:l+=""+f[h];else{if(h===void 0)continue;if(f[h]){let b=r(f[h],c,y),I=s(b,c);f[":@"]?i(b,f[":@"],y,c):Object.keys(b).length===1&&b[c.textNodeName]!==void 0&&!c.alwaysCreateTextNode?b=b[c.textNodeName]:Object.keys(b).length===0&&(c.alwaysCreateTextNode?b[c.textNodeName]="":b=""),d[h]!==void 0&&d.hasOwnProperty(h)?(Array.isArray(d[h])||(d[h]=[d[h]]),d[h].push(b)):c.isArray(h,y,I)?d[h]=[b]:d[h]=b}}}return typeof l=="string"?l.length>0&&(d[c.textNodeName]=l):l!==void 0&&(d[c.textNodeName]=l),d}o(r,"compress"),B(r,"compress");function n(a){let c=Object.keys(a);for(let u=0;u<c.length;u++){let l=c[u];if(l!==":@")return l}}o(n,"propName"),B(n,"propName");function i(a,c,u,l){if(c){let d=Object.keys(c),p=d.length;for(let f=0;f<p;f++){let h=d[f];l.isArray(h,u+"."+h,!0,!0)?a[h]=[c[h]]:a[h]=c[h]}}}o(i,"assignAttributes"),B(i,"assignAttributes");function s(a,c){let{textNodeName:u}=c,l=Object.keys(a).length;return!!(l===0||l===1&&(a[u]||typeof a[u]=="boolean"||a[u]===0))}o(s,"isLeafTag"),B(s,"isLeafTag"),t.prettify=e}}),CL=vt({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(t,e){var{buildOptions:r}=IL(),n=OL(),{prettify:i}=NL(),s=ZE(),a=class{static{o(this,"XMLParser2")}static{B(this,"XMLParser")}constructor(c){this.externalEntities={},this.options=r(c)}parse(c,u){if(typeof c!="string")if(c.toString)c=c.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(u){u===!0&&(u={});let p=s.validate(c,u);if(p!==!0)throw Error(`${p.err.msg}:${p.err.line}:${p.err.col}`)}let l=new n(this.options);l.addExternalEntities(this.externalEntities);let d=l.parseXml(c);return this.options.preserveOrder||d===void 0?d:i(d,this.options)}addEntity(c,u){if(u.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(c.indexOf("&")!==-1||c.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(u==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[c]=u}};e.exports=a}}),xL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(t,e){var r=`
78
+ `;function n(l,d){let p="";return d.format&&d.indentBy.length>0&&(p=r),i(l,d,"",p)}o(n,"toXml"),B(n,"toXml");function i(l,d,p,f){let h="",y=!1;for(let b=0;b<l.length;b++){let I=l[b],A=s(I);if(A===void 0)continue;let g="";if(p.length===0?g=A:g=`${p}.${A}`,A===d.textNodeName){let T=I[A];c(g,d)||(T=d.tagValueProcessor(A,T),T=u(T,d)),y&&(h+=f),h+=T,y=!1;continue}else if(A===d.cdataPropName){y&&(h+=f),h+=`<![CDATA[${I[A][0][d.textNodeName]}]]>`,y=!1;continue}else if(A===d.commentPropName){h+=f+`<!--${I[A][0][d.textNodeName]}-->`,y=!0;continue}else if(A[0]==="?"){let T=a(I[":@"],d),C=A==="?xml"?"":f,w=I[A][0][d.textNodeName];w=w.length!==0?" "+w:"",h+=C+`<${A}${w}${T}?>`,y=!0;continue}let v=f;v!==""&&(v+=d.indentBy);let O=a(I[":@"],d),V=f+`<${A}${O}`,E=i(I[A],d,g,v);d.unpairedTags.indexOf(A)!==-1?d.suppressUnpairedNode?h+=V+">":h+=V+"/>":(!E||E.length===0)&&d.suppressEmptyNode?h+=V+"/>":E&&E.endsWith(">")?h+=V+`>${E}${f}</${A}>`:(h+=V+">",E&&f!==""&&(E.includes("/>")||E.includes("</"))?h+=f+d.indentBy+E+f:h+=E,h+=`</${A}>`),y=!0}return h}o(i,"arrToStr"),B(i,"arrToStr");function s(l){let d=Object.keys(l);for(let p=0;p<d.length;p++){let f=d[p];if(l.hasOwnProperty(f)&&f!==":@")return f}}o(s,"propName"),B(s,"propName");function a(l,d){let p="";if(l&&!d.ignoreAttributes)for(let f in l){if(!l.hasOwnProperty(f))continue;let h=d.attributeValueProcessor(f,l[f]);h=u(h,d),h===!0&&d.suppressBooleanAttributes?p+=` ${f.substr(d.attributeNamePrefix.length)}`:p+=` ${f.substr(d.attributeNamePrefix.length)}="${h}"`}return p}o(a,"attr_to_str"),B(a,"attr_to_str");function c(l,d){l=l.substr(0,l.length-d.textNodeName.length-1);let p=l.substr(l.lastIndexOf(".")+1);for(let f in d.stopNodes)if(d.stopNodes[f]===l||d.stopNodes[f]==="*."+p)return!0;return!1}o(c,"isStopNode"),B(c,"isStopNode");function u(l,d){if(l&&l.length>0&&d.processEntities)for(let p=0;p<d.entities.length;p++){let f=d.entities[p];l=l.replace(f.regex,f.val)}return l}o(u,"replaceEntitiesValue"),B(u,"replaceEntitiesValue"),e.exports=n}}),LL=vt({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(t,e){"use strict";var r=xL(),n={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(u,l){return l},attributeValueProcessor:function(u,l){return l},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function i(u){this.options=Object.assign({},n,u),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=c),this.processTextOrObjNode=s,this.options.format?(this.indentate=a,this.tagEndChar=`>
79
79
  `,this.newLine=`
80
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}o(i,"Builder"),B(i,"Builder"),i.prototype.build=function(u){return this.options.preserveOrder?r(u,this.options):(Array.isArray(u)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(u={[this.options.arrayNodeName]:u}),this.j2x(u,0).val)},i.prototype.j2x=function(u,l){let d="",p="";for(let f in u)if(Object.prototype.hasOwnProperty.call(u,f))if(typeof u[f]>"u")this.isAttribute(f)&&(p+="");else if(u[f]===null)this.isAttribute(f)?p+="":f[0]==="?"?p+=this.indentate(l)+"<"+f+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+f+"/"+this.tagEndChar;else if(u[f]instanceof Date)p+=this.buildTextValNode(u[f],f,"",l);else if(typeof u[f]!="object"){let h=this.isAttribute(f);if(h)d+=this.buildAttrPairStr(h,""+u[f]);else if(f===this.options.textNodeName){let y=this.options.tagValueProcessor(f,""+u[f]);p+=this.replaceEntitiesValue(y)}else p+=this.buildTextValNode(u[f],f,"",l)}else if(Array.isArray(u[f])){let h=u[f].length,y="";for(let b=0;b<h;b++){let I=u[f][b];typeof I>"u"||(I===null?f[0]==="?"?p+=this.indentate(l)+"<"+f+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+f+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?y+=this.j2x(I,l+1).val:y+=this.processTextOrObjNode(I,f,l):y+=this.buildTextValNode(I,f,"",l))}this.options.oneListGroup&&(y=this.buildObjectNode(y,f,"",l)),p+=y}else if(this.options.attributesGroupName&&f===this.options.attributesGroupName){let h=Object.keys(u[f]),y=h.length;for(let b=0;b<y;b++)d+=this.buildAttrPairStr(h[b],""+u[f][h[b]])}else p+=this.processTextOrObjNode(u[f],f,l);return{attrStr:d,val:p}},i.prototype.buildAttrPairStr=function(u,l){return l=this.options.attributeValueProcessor(u,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+u:" "+u+'="'+l+'"'};function s(u,l,d){let p=this.j2x(u,d+1);return u[this.options.textNodeName]!==void 0&&Object.keys(u).length===1?this.buildTextValNode(u[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}o(s,"processTextOrObjNode"),B(s,"processTextOrObjNode"),i.prototype.buildObjectNode=function(u,l,d,p){if(u==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let f="</"+l+this.tagEndChar,h="";return l[0]==="?"&&(h="?",f=""),(d||d==="")&&u.indexOf("<")===-1?this.indentate(p)+"<"+l+d+h+">"+u+f:this.options.commentPropName!==!1&&l===this.options.commentPropName&&h.length===0?this.indentate(p)+`<!--${u}-->`+this.newLine:this.indentate(p)+"<"+l+d+h+this.tagEndChar+u+this.indentate(p)+f}},i.prototype.closeTag=function(u){let l="";return this.options.unpairedTags.indexOf(u)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${u}`,l},i.prototype.buildTextValNode=function(u,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${u}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${u}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let f=this.options.tagValueProcessor(l,u);return f=this.replaceEntitiesValue(f),f===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+f+"</"+l+this.tagEndChar}},i.prototype.replaceEntitiesValue=function(u){if(u&&u.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];u=u.replace(d.regex,d.val)}return u};function a(u){return this.options.indentBy.repeat(u)}o(a,"indentate"),B(a,"indentate");function c(u){return u.startsWith(this.options.attributeNamePrefix)&&u!==this.options.textNodeName?u.substr(this.attrPrefixLen):!1}o(c,"isAttribute"),B(c,"isAttribute"),e.exports=i}}),LL=ZE(),DL=NL(),ML=xL();XE.exports={XMLParser:DL,XMLValidator:LL,XMLBuilder:ML}});var tw=_(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});iu.XmlToJsonOutboundPolicy=void 0;var UL=k(),kL=_n(),FL=ew(),HL=Jt(),qL=lt(),Zf=class extends kL.OutboundPolicy{static{o(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,r){super(e,r),(0,qL.optionValidator)(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?(0,HL.statusCodesStringToNumberArray)(e.parseOnStatusCodes):void 0,this.parser=new FL.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,r,n){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let i;try{let c=await e.text();i=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw n.log.error(u,c),new UL.RuntimeError(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:s})}};iu.XmlToJsonOutboundPolicy=Zf});var rw=_(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.ServiceProviderImpl=void 0;var $L=k(),Xf=class{static{o(this,"ServiceProviderImpl")}services=new Map;addService(e,r){if(this.services.get(e))throw new $L.SystemError(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};ou.ServiceProviderImpl=Xf});var iw=_(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.BackgroundDispatcher=fi.BatchDispatch=void 0;var nw=Re();Object.defineProperty(fi,"BatchDispatch",{enumerable:!0,get:function(){return nw.BatchDispatch}});var jL=ga(),eh=class{static{o(this,"BackgroundDispatcher")}#e;constructor(e,r){if(!r||r.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new nw.BatchDispatch(r.name??"",r.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),(0,jL.getGlobalZuploEventContext)().waitUntil(this.#e.waitUntilFlushed())}};fi.BackgroundDispatcher=eh});var ow=_(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.BackgroundLoader=void 0;var VL=ga(),th=class{static{o(this,"BackgroundLoader")}#e=new Map;#t;#r;#n=new Map;constructor(e,r){this.#t=e,this.#r=r*1e3}#i(e){let r=this.#e.get(e);r&&(r.expiry=new Date(Date.now()+this.#r))}#o(e){return e.expiry<=new Date}async get(e){let r=this.#e.get(e);return r&&!this.#o(r)?(this.#s(e),r.data):this.#a(e)}async#s(e){let r=this.#n.get(e);if(r!==void 0)return r.wrap();let n=this.#a(e);return this.#n.set(e,new ho(n)),await new ho(n).wrap(),this.#n.delete(e),n}async#a(e){let r=this.#n.get(e);if(r===void 0){let n=this.#t(e);r=new ho(n),this.#i(e);let i=await r.wrap();this.#e.set(e,{data:i,expiry:new Date(Date.now()+this.#r)})}return r.wrap()}};su.BackgroundLoader=th;var ho=class{static{o(this,"WrappedPromise")}#e;#t=[];#r;#n;constructor(e){(0,VL.getGlobalZuploEventContext)().waitUntil(e),this.#e=e,this.#e.then(n=>{this.#t.forEach(i=>i.resolve(n)),this.#r=n}).catch(n=>{this.#t.forEach(i=>i.reject(n)),this.#n=n})}async wrap(){if(this.#n)throw this.#n;if(this.#r)return this.#r;let e=this;return new Promise((n,i)=>{e.#t.push({resolve:n,reject:i})})}}});var _w=_(m=>{"use strict";var BL=m&&m.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=m&&m.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&BL(e,t,r)},GL=m&&m.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(m,"__esModule",{value:!0});m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.MonetizationInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.OutboundPolicy=m.InboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.RuntimeError=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.BackgroundLoader=m.BackgroundDispatcher=m.BatchDispatch=m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.XmlToJsonOutboundPolicy=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=void 0;Hh();var KL=Bt();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return KL.MemoryZoneReadThroughCache}});var JL=rl();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return JL.ZoneCache}});var sw=$r();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return sw.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return sw.ResponseSentEvent}});var zL=_p();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return zL.ContextData}});var nh=Yi();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return nh.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return nh.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return nh.isZuploReadableEnvVariableName}});var aw=k();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return aw.ConfigurationError}});Object.defineProperty(m,"RuntimeError",{enumerable:!0,get:function(){return aw.RuntimeError}});var WL=wp();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return WL.originalFetch}});var cw=hb();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return cw.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return cw.purgeGatewayCache}});var uw=Cb();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return uw.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return uw.awsLambdaHandler}});var QL=Lb();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return QL.openApiSpecHandler}});var YL=Db();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return YL.redirectHandler}});var ZL=Ub();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return ZL.urlForwardHandler}});var XL=Fb();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return XL.urlRewriteHandler}});var eD=qb();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return eD.webSocketHandler}});var tD=Vb();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return tD.webSocketPipelineHandler}});var rD=Il();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return rD.HttpStatusCode}});rh(Yb(),m);rh(e_(),m);var nD=t_();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return nD.AuditLogDataStaxProvider}});var iD=n_();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return iD.AuditLogPlugin}});rh(g_(),m);var lw=_n();Object.defineProperty(m,"InboundPolicy",{enumerable:!0,get:function(){return lw.InboundPolicy}});Object.defineProperty(m,"OutboundPolicy",{enumerable:!0,get:function(){return lw.OutboundPolicy}});var dw=v_();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return dw.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return dw.AmberfloMeteringPolicy}});var oD=A_();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return oD.ApiAuthKeyInboundPolicy}});var sD=Rf();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return sD.ApiKeyInboundPolicy}});var aD=R_();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return aD.Auth0JwtInboundPolicy}});var cD=O_();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return cD.BasicAuthInboundPolicy}});var uD=N_();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return uD.CachingInboundPolicy}});var lD=C_();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return lD.ChangeMethodInboundPolicy}});var dD=x_();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return dD.ClearHeadersInboundPolicy}});var pD=L_();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return pD.ClearHeadersOutboundPolicy}});var fD=D_();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return fD.ClerkJwtInboundPolicy}});var hD=U_();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return hD.CognitoJwtInboundPolicy}});var mD=F_();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return mD.CompositeInboundPolicy}});var yD=H_();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return yD.CurityPhantomTokenInboundPolicy}});var gD=q_();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return gD.FirebaseJwtInboundPolicy}});var bD=$_();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return bD.FormDataToJsonInboundPolicy}});var _D=j_();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return _D.GeoFilterInboundPolicy}});var ED=V_();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return ED.JWTScopeValidationInboundPolicy}});var wD=G_();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return wD.MockApiInboundPolicy}});var pw=Q_();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return pw.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return pw.setMoesifContext}});var vD=nE();Object.defineProperty(m,"MonetizationInboundPolicy",{enumerable:!0,get:function(){return vD.MonetizationInboundPolicy}});var TD=iE();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return TD.OktaJwtInboundPolicy}});var SD=Xt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return SD.OpenIdJwtInboundPolicy}});var ID=oE();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return ID.PropelAuthJwtInboundPolicy}});var fw=fE();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return fw.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return fw.RateLimitInboundPolicy}});var PD=gE();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return PD.ReadmeMetricsInboundPolicy}});var AD=bE();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return AD.RemoveHeadersInboundPolicy}});var RD=_E();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return RD.RemoveHeadersOutboundPolicy}});var OD=EE();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return OD.RemoveQueryParamsInboundPolicy}});var ND=wE();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return ND.ReplaceStringOutboundPolicy}});var CD=TE();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return CD.RequestSizeLimitInboundPolicy}});var hw=RE();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return hw.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return hw.SchemaBasedRequestValidation}});var xD=OE();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return xD.RequireOriginInboundPolicy}});var LD=NE();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return LD.SetBodyInboundPolicy}});var DD=xE();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return DD.SetHeadersInboundPolicy}});var MD=DE();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return MD.SetHeadersOutboundPolicy}});var UD=UE();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return UD.SetQueryParamsInboundPolicy}});var kD=kE();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return kD.SetStatusOutboundPolicy}});var FD=FE();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return FD.SleepInboundPolicy}});var HD=nf();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return HD.StripeWebhookVerificationInboundPolicy}});var qD=qE();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return qD.SupabaseJwtInboundPolicy}});var $D=jE();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return $D.UpstreamAzureAdServiceAuthInboundPolicy}});var jD=BE();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return jD.UpstreamFirebaseAdminAuthInboundPolicy}});var VD=GE();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return VD.UpstreamFirebaseUserAuthInboundPolicy}});var BD=JE();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return BD.UpstreamGcpJwtInboundPolicy}});var GD=WE();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return GD.UpstreamGcpServiceAuthInboundPolicy}});var KD=YE();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return KD.ValidateJsonSchemaInbound}});var JD=tw();Object.defineProperty(m,"XmlToJsonOutboundPolicy",{enumerable:!0,get:function(){return JD.XmlToJsonOutboundPolicy}});var zD=de();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return zD.HttpProblems}});var WD=Go();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return WD.ProblemResponseFormatter}});var QD=Ke();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return QD.ZuploRequest}});var YD=Vr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return YD.SystemRouteName}});var mw=lp();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return mw.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return mw.Router}});var yw=ml();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return yw.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return yw.serialize}});var ZD=rw();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return ZD.ServiceProviderImpl}});var gw=Bl();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return gw.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return gw.SYSTEM_LOGGER}});var XD=Al();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return GL(XD).default}});var e1=Je();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return e1.SystemLogMap}});var mo=Fc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return mo.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return mo.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return mo.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return mo.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return mo.sanitizedIdentifierName}});var bw=iw();Object.defineProperty(m,"BatchDispatch",{enumerable:!0,get:function(){return bw.BatchDispatch}});Object.defineProperty(m,"BackgroundDispatcher",{enumerable:!0,get:function(){return bw.BackgroundDispatcher}});var t1=ow();Object.defineProperty(m,"BackgroundLoader",{enumerable:!0,get:function(){return t1.BackgroundLoader}})});var Ew=_(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.BaseCryptoBeta=hi.supportedDigests=void 0;hi.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var ih=class{static{o(this,"BaseCryptoBeta")}};hi.BaseCryptoBeta=ih});var ww=_(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.WorkerCryptoBeta=void 0;var oh=Ew(),r1=k(),sh=class extends oh.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!oh.supportedDigests.includes(e.toLowerCase()))throw new r1.RuntimeError(`Algorithm ${e} is not supported. Try using ${oh.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};au.WorkerCryptoBeta=sh});var vw=_(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});cu.BaseKeyValueStore=void 0;var ah=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};cu.BaseKeyValueStore=ah});var Sw=_(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.WorkerKeyValueStore=void 0;var Tw=k(),n1=vw(),ch=class extends n1.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=globalThis.ZUPLO_KV;if(!n)throw new Tw.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=n}put(e,r,n){if(typeof e!="string")throw new Tw.ConfigurationError("value must be of type string");return this.#e.put(e,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(e,r){return this.#e.get(e,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};uu.WorkerKeyValueStore=ch});var Kt=_(Tt=>{"use strict";var i1=Tt&&Tt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),o1=Tt&&Tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&i1(e,t,r)};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.KeyValueStore=Tt.CryptoBeta=void 0;o1(_w(),Tt);var s1=ww();Object.defineProperty(Tt,"CryptoBeta",{enumerable:!0,get:function(){return s1.WorkerCryptoBeta}});var a1=Sw();Object.defineProperty(Tt,"KeyValueStore",{enumerable:!0,get:function(){return a1.WorkerKeyValueStore}})});var hM={};Co(hM,{GraphQLComplexityLimitInboundPolicy:()=>rv,GraphQLDisableIntrospectionInboundPolicy:()=>iv});module.exports=xo(hM);var Pi=Mh(Kt());function X(t,e){if(!!!t)throw new Error(e)}o(X,"devAssert");function Ne(t){return typeof t=="object"&&t!==null}o(Ne,"isObjectLike");function Ht(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(Ht,"invariant");var c1=/\r\n|[\n\r]/g;function mi(t,e){let r=0,n=1;for(let i of t.body.matchAll(c1)){if(typeof i.index=="number"||Ht(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(mi,"getLocation");function uh(t){return lu(t.source,mi(t.source,t.start))}o(uh,"printLocation");function lu(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?r:0,u=e.column+c,l=`${t.name}:${a}:${u}
80
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}o(i,"Builder"),B(i,"Builder"),i.prototype.build=function(u){return this.options.preserveOrder?r(u,this.options):(Array.isArray(u)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(u={[this.options.arrayNodeName]:u}),this.j2x(u,0).val)},i.prototype.j2x=function(u,l){let d="",p="";for(let f in u)if(Object.prototype.hasOwnProperty.call(u,f))if(typeof u[f]>"u")this.isAttribute(f)&&(p+="");else if(u[f]===null)this.isAttribute(f)?p+="":f[0]==="?"?p+=this.indentate(l)+"<"+f+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+f+"/"+this.tagEndChar;else if(u[f]instanceof Date)p+=this.buildTextValNode(u[f],f,"",l);else if(typeof u[f]!="object"){let h=this.isAttribute(f);if(h)d+=this.buildAttrPairStr(h,""+u[f]);else if(f===this.options.textNodeName){let y=this.options.tagValueProcessor(f,""+u[f]);p+=this.replaceEntitiesValue(y)}else p+=this.buildTextValNode(u[f],f,"",l)}else if(Array.isArray(u[f])){let h=u[f].length,y="";for(let b=0;b<h;b++){let I=u[f][b];typeof I>"u"||(I===null?f[0]==="?"?p+=this.indentate(l)+"<"+f+"?"+this.tagEndChar:p+=this.indentate(l)+"<"+f+"/"+this.tagEndChar:typeof I=="object"?this.options.oneListGroup?y+=this.j2x(I,l+1).val:y+=this.processTextOrObjNode(I,f,l):y+=this.buildTextValNode(I,f,"",l))}this.options.oneListGroup&&(y=this.buildObjectNode(y,f,"",l)),p+=y}else if(this.options.attributesGroupName&&f===this.options.attributesGroupName){let h=Object.keys(u[f]),y=h.length;for(let b=0;b<y;b++)d+=this.buildAttrPairStr(h[b],""+u[f][h[b]])}else p+=this.processTextOrObjNode(u[f],f,l);return{attrStr:d,val:p}},i.prototype.buildAttrPairStr=function(u,l){return l=this.options.attributeValueProcessor(u,""+l),l=this.replaceEntitiesValue(l),this.options.suppressBooleanAttributes&&l==="true"?" "+u:" "+u+'="'+l+'"'};function s(u,l,d){let p=this.j2x(u,d+1);return u[this.options.textNodeName]!==void 0&&Object.keys(u).length===1?this.buildTextValNode(u[this.options.textNodeName],l,p.attrStr,d):this.buildObjectNode(p.val,l,p.attrStr,d)}o(s,"processTextOrObjNode"),B(s,"processTextOrObjNode"),i.prototype.buildObjectNode=function(u,l,d,p){if(u==="")return l[0]==="?"?this.indentate(p)+"<"+l+d+"?"+this.tagEndChar:this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar;{let f="</"+l+this.tagEndChar,h="";return l[0]==="?"&&(h="?",f=""),(d||d==="")&&u.indexOf("<")===-1?this.indentate(p)+"<"+l+d+h+">"+u+f:this.options.commentPropName!==!1&&l===this.options.commentPropName&&h.length===0?this.indentate(p)+`<!--${u}-->`+this.newLine:this.indentate(p)+"<"+l+d+h+this.tagEndChar+u+this.indentate(p)+f}},i.prototype.closeTag=function(u){let l="";return this.options.unpairedTags.indexOf(u)!==-1?this.options.suppressUnpairedNode||(l="/"):this.options.suppressEmptyNode?l="/":l=`></${u}`,l},i.prototype.buildTextValNode=function(u,l,d,p){if(this.options.cdataPropName!==!1&&l===this.options.cdataPropName)return this.indentate(p)+`<![CDATA[${u}]]>`+this.newLine;if(this.options.commentPropName!==!1&&l===this.options.commentPropName)return this.indentate(p)+`<!--${u}-->`+this.newLine;if(l[0]==="?")return this.indentate(p)+"<"+l+d+"?"+this.tagEndChar;{let f=this.options.tagValueProcessor(l,u);return f=this.replaceEntitiesValue(f),f===""?this.indentate(p)+"<"+l+d+this.closeTag(l)+this.tagEndChar:this.indentate(p)+"<"+l+d+">"+f+"</"+l+this.tagEndChar}},i.prototype.replaceEntitiesValue=function(u){if(u&&u.length>0&&this.options.processEntities)for(let l=0;l<this.options.entities.length;l++){let d=this.options.entities[l];u=u.replace(d.regex,d.val)}return u};function a(u){return this.options.indentBy.repeat(u)}o(a,"indentate"),B(a,"indentate");function c(u){return u.startsWith(this.options.attributeNamePrefix)&&u!==this.options.textNodeName?u.substr(this.attrPrefixLen):!1}o(c,"isAttribute"),B(c,"isAttribute"),e.exports=i}}),DL=ZE(),ML=CL(),UL=LL();XE.exports={XMLParser:ML,XMLValidator:DL,XMLBuilder:UL}});var tw=_(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});iu.XmlToJsonOutboundPolicy=void 0;var kL=k(),FL=_n(),HL=ew(),qL=Jt(),$L=lt(),Zf=class extends FL.OutboundPolicy{static{o(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,r){super(e,r),(0,$L.optionValidator)(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?(0,qL.statusCodesStringToNumberArray)(e.parseOnStatusCodes):void 0,this.parser=new HL.XMLParser({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,r,n){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let i;try{let c=await e.text();i=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw n.log.error(u,c),new kL.RuntimeError(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:s})}};iu.XmlToJsonOutboundPolicy=Zf});var rw=_(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.ServiceProviderImpl=void 0;var jL=k(),Xf=class{static{o(this,"ServiceProviderImpl")}services=new Map;addService(e,r){if(this.services.get(e))throw new jL.SystemError(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};ou.ServiceProviderImpl=Xf});var iw=_(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.BackgroundDispatcher=fi.BatchDispatch=void 0;var nw=Re();Object.defineProperty(fi,"BatchDispatch",{enumerable:!0,get:function(){return nw.BatchDispatch}});var VL=ga(),eh=class{static{o(this,"BackgroundDispatcher")}#e;constructor(e,r){if(!r||r.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new nw.BatchDispatch(r.name??"",r.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),(0,VL.getGlobalZuploEventContext)().waitUntil(this.#e.waitUntilFlushed())}};fi.BackgroundDispatcher=eh});var ow=_(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.BackgroundLoader=void 0;var BL=ga(),th=class{static{o(this,"BackgroundLoader")}#e=new Map;#t;#r;#n=new Map;constructor(e,r){this.#t=e,this.#r=r*1e3}#i(e){let r=this.#e.get(e);r&&(r.expiry=new Date(Date.now()+this.#r))}#o(e){return e.expiry<=new Date}async get(e){let r=this.#e.get(e);return r&&!this.#o(r)?(this.#s(e),r.data):this.#a(e)}async#s(e){let r=this.#n.get(e);if(r!==void 0)return r.wrap();let n=this.#a(e);return this.#n.set(e,new ho(n)),await new ho(n).wrap(),this.#n.delete(e),n}async#a(e){let r=this.#n.get(e);if(r===void 0){let n=this.#t(e);r=new ho(n),this.#i(e);let i=await r.wrap();this.#e.set(e,{data:i,expiry:new Date(Date.now()+this.#r)})}return r.wrap()}};su.BackgroundLoader=th;var ho=class{static{o(this,"WrappedPromise")}#e;#t=[];#r;#n;constructor(e){(0,BL.getGlobalZuploEventContext)().waitUntil(e),this.#e=e,this.#e.then(n=>{this.#t.forEach(i=>i.resolve(n)),this.#r=n}).catch(n=>{this.#t.forEach(i=>i.reject(n)),this.#n=n})}async wrap(){if(this.#n)throw this.#n;if(this.#r)return this.#r;let e=this;return new Promise((n,i)=>{e.#t.push({resolve:n,reject:i})})}}});var _w=_(m=>{"use strict";var GL=m&&m.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=m&&m.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&GL(e,t,r)},KL=m&&m.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(m,"__esModule",{value:!0});m.OpenIdJwtInboundPolicy=m.OktaJwtInboundPolicy=m.MonetizationInboundPolicy=m.setMoesifContext=m.MoesifInboundPolicy=m.MockApiInboundPolicy=m.JWTScopeValidationInboundPolicy=m.GeoFilterInboundPolicy=m.FormDataToJsonInboundPolicy=m.FirebaseJwtInboundPolicy=m.CurityPhantomTokenInboundPolicy=m.CompositeInboundPolicy=m.CognitoJwtInboundPolicy=m.ClerkJwtInboundPolicy=m.ClearHeadersOutboundPolicy=m.ClearHeadersInboundPolicy=m.ChangeMethodInboundPolicy=m.CachingInboundPolicy=m.BasicAuthInboundPolicy=m.Auth0JwtInboundPolicy=m.ApiKeyInboundPolicy=m.ApiAuthKeyInboundPolicy=m.AmberfloMeteringPolicy=m.AmberfloMeteringInboundPolicy=m.OutboundPolicy=m.InboundPolicy=m.AuditLogPlugin=m.AuditLogDataStaxProvider=m.HttpStatusCode=m.webSocketPipelineHandler=m.webSocketHandler=m.urlRewriteHandler=m.urlForwardHandler=m.redirectHandler=m.openApiSpecHandler=m.awsLambdaHandler=m.AwsLambdaHandlerExtensions=m.purgeGatewayCache=m.Handler=m.originalFetch=m.RuntimeError=m.ConfigurationError=m.isZuploReadableEnvVariableName=m.isRestrictedEnvVariableName=m.environment=m.ContextData=m.ResponseSentEvent=m.ResponseSendingEvent=m.ZoneCache=m.MemoryZoneReadThroughCache=void 0;m.BackgroundLoader=m.BackgroundDispatcher=m.BatchDispatch=m.sanitizedIdentifierName=m.getRawOperationDataIdentifierName=m.getIdForRequestBodySchema=m.getIdForRefSchema=m.getIdForParameterSchema=m.SystemLogMap=m.httpStatuses=m.SYSTEM_LOGGER=m.API_KEY=m.ServiceProviderImpl=m.serialize=m.ContentTypes=m.Router=m.LookupResult=m.SystemRouteName=m.ZuploRequest=m.ProblemResponseFormatter=m.HttpProblems=m.XmlToJsonOutboundPolicy=m.ValidateJsonSchemaInbound=m.UpstreamGcpServiceAuthInboundPolicy=m.UpstreamGcpJwtInboundPolicy=m.UpstreamFirebaseUserAuthInboundPolicy=m.UpstreamFirebaseAdminAuthInboundPolicy=m.UpstreamAzureAdServiceAuthInboundPolicy=m.SupabaseJwtInboundPolicy=m.StripeWebhookVerificationInboundPolicy=m.SleepInboundPolicy=m.SetStatusOutboundPolicy=m.SetQueryParamsInboundPolicy=m.SetHeadersOutboundPolicy=m.SetHeadersInboundPolicy=m.SetBodyInboundPolicy=m.RequireOriginInboundPolicy=m.SchemaBasedRequestValidation=m.RequestValidationInboundPolicy=m.RequestSizeLimitInboundPolicy=m.ReplaceStringOutboundPolicy=m.RemoveQueryParamsInboundPolicy=m.RemoveHeadersOutboundPolicy=m.RemoveHeadersInboundPolicy=m.ReadmeMetricsInboundPolicy=m.RateLimitInboundPolicy=m.BasicRateLimitInboundPolicy=m.PropelAuthJwtInboundPolicy=void 0;Hh();var JL=Bt();Object.defineProperty(m,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return JL.MemoryZoneReadThroughCache}});var zL=rl();Object.defineProperty(m,"ZoneCache",{enumerable:!0,get:function(){return zL.ZoneCache}});var sw=$r();Object.defineProperty(m,"ResponseSendingEvent",{enumerable:!0,get:function(){return sw.ResponseSendingEvent}});Object.defineProperty(m,"ResponseSentEvent",{enumerable:!0,get:function(){return sw.ResponseSentEvent}});var WL=_p();Object.defineProperty(m,"ContextData",{enumerable:!0,get:function(){return WL.ContextData}});var nh=Yi();Object.defineProperty(m,"environment",{enumerable:!0,get:function(){return nh.environment}});Object.defineProperty(m,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return nh.isRestrictedEnvVariableName}});Object.defineProperty(m,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return nh.isZuploReadableEnvVariableName}});var aw=k();Object.defineProperty(m,"ConfigurationError",{enumerable:!0,get:function(){return aw.ConfigurationError}});Object.defineProperty(m,"RuntimeError",{enumerable:!0,get:function(){return aw.RuntimeError}});var QL=wp();Object.defineProperty(m,"originalFetch",{enumerable:!0,get:function(){return QL.originalFetch}});var cw=hb();Object.defineProperty(m,"Handler",{enumerable:!0,get:function(){return cw.Handler}});Object.defineProperty(m,"purgeGatewayCache",{enumerable:!0,get:function(){return cw.purgeGatewayCache}});var uw=Cb();Object.defineProperty(m,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return uw.AwsLambdaHandlerExtensions}});Object.defineProperty(m,"awsLambdaHandler",{enumerable:!0,get:function(){return uw.awsLambdaHandler}});var YL=Lb();Object.defineProperty(m,"openApiSpecHandler",{enumerable:!0,get:function(){return YL.openApiSpecHandler}});var ZL=Db();Object.defineProperty(m,"redirectHandler",{enumerable:!0,get:function(){return ZL.redirectHandler}});var XL=Ub();Object.defineProperty(m,"urlForwardHandler",{enumerable:!0,get:function(){return XL.urlForwardHandler}});var eD=Fb();Object.defineProperty(m,"urlRewriteHandler",{enumerable:!0,get:function(){return eD.urlRewriteHandler}});var tD=qb();Object.defineProperty(m,"webSocketHandler",{enumerable:!0,get:function(){return tD.webSocketHandler}});var rD=Vb();Object.defineProperty(m,"webSocketPipelineHandler",{enumerable:!0,get:function(){return rD.webSocketPipelineHandler}});var nD=Il();Object.defineProperty(m,"HttpStatusCode",{enumerable:!0,get:function(){return nD.HttpStatusCode}});rh(Yb(),m);rh(e_(),m);var iD=t_();Object.defineProperty(m,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return iD.AuditLogDataStaxProvider}});var oD=n_();Object.defineProperty(m,"AuditLogPlugin",{enumerable:!0,get:function(){return oD.AuditLogPlugin}});rh(g_(),m);var lw=_n();Object.defineProperty(m,"InboundPolicy",{enumerable:!0,get:function(){return lw.InboundPolicy}});Object.defineProperty(m,"OutboundPolicy",{enumerable:!0,get:function(){return lw.OutboundPolicy}});var dw=v_();Object.defineProperty(m,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return dw.AmberfloMeteringInboundPolicy}});Object.defineProperty(m,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return dw.AmberfloMeteringPolicy}});var sD=A_();Object.defineProperty(m,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return sD.ApiAuthKeyInboundPolicy}});var aD=Rf();Object.defineProperty(m,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return aD.ApiKeyInboundPolicy}});var cD=R_();Object.defineProperty(m,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return cD.Auth0JwtInboundPolicy}});var uD=O_();Object.defineProperty(m,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return uD.BasicAuthInboundPolicy}});var lD=N_();Object.defineProperty(m,"CachingInboundPolicy",{enumerable:!0,get:function(){return lD.CachingInboundPolicy}});var dD=C_();Object.defineProperty(m,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return dD.ChangeMethodInboundPolicy}});var pD=x_();Object.defineProperty(m,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return pD.ClearHeadersInboundPolicy}});var fD=L_();Object.defineProperty(m,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return fD.ClearHeadersOutboundPolicy}});var hD=D_();Object.defineProperty(m,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return hD.ClerkJwtInboundPolicy}});var mD=U_();Object.defineProperty(m,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return mD.CognitoJwtInboundPolicy}});var yD=F_();Object.defineProperty(m,"CompositeInboundPolicy",{enumerable:!0,get:function(){return yD.CompositeInboundPolicy}});var gD=H_();Object.defineProperty(m,"CurityPhantomTokenInboundPolicy",{enumerable:!0,get:function(){return gD.CurityPhantomTokenInboundPolicy}});var bD=q_();Object.defineProperty(m,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return bD.FirebaseJwtInboundPolicy}});var _D=$_();Object.defineProperty(m,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return _D.FormDataToJsonInboundPolicy}});var ED=j_();Object.defineProperty(m,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return ED.GeoFilterInboundPolicy}});var wD=V_();Object.defineProperty(m,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return wD.JWTScopeValidationInboundPolicy}});var vD=G_();Object.defineProperty(m,"MockApiInboundPolicy",{enumerable:!0,get:function(){return vD.MockApiInboundPolicy}});var pw=Q_();Object.defineProperty(m,"MoesifInboundPolicy",{enumerable:!0,get:function(){return pw.MoesifInboundPolicy}});Object.defineProperty(m,"setMoesifContext",{enumerable:!0,get:function(){return pw.setMoesifContext}});var TD=nE();Object.defineProperty(m,"MonetizationInboundPolicy",{enumerable:!0,get:function(){return TD.MonetizationInboundPolicy}});var SD=iE();Object.defineProperty(m,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return SD.OktaJwtInboundPolicy}});var ID=Xt();Object.defineProperty(m,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return ID.OpenIdJwtInboundPolicy}});var PD=oE();Object.defineProperty(m,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return PD.PropelAuthJwtInboundPolicy}});var fw=fE();Object.defineProperty(m,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return fw.RateLimitInboundPolicy}});Object.defineProperty(m,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return fw.RateLimitInboundPolicy}});var AD=gE();Object.defineProperty(m,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return AD.ReadmeMetricsInboundPolicy}});var RD=bE();Object.defineProperty(m,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return RD.RemoveHeadersInboundPolicy}});var OD=_E();Object.defineProperty(m,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return OD.RemoveHeadersOutboundPolicy}});var ND=EE();Object.defineProperty(m,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return ND.RemoveQueryParamsInboundPolicy}});var CD=wE();Object.defineProperty(m,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return CD.ReplaceStringOutboundPolicy}});var xD=TE();Object.defineProperty(m,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return xD.RequestSizeLimitInboundPolicy}});var hw=RE();Object.defineProperty(m,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return hw.RequestValidationInboundPolicy}});Object.defineProperty(m,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return hw.SchemaBasedRequestValidation}});var LD=OE();Object.defineProperty(m,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return LD.RequireOriginInboundPolicy}});var DD=NE();Object.defineProperty(m,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return DD.SetBodyInboundPolicy}});var MD=xE();Object.defineProperty(m,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return MD.SetHeadersInboundPolicy}});var UD=DE();Object.defineProperty(m,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return UD.SetHeadersOutboundPolicy}});var kD=UE();Object.defineProperty(m,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return kD.SetQueryParamsInboundPolicy}});var FD=kE();Object.defineProperty(m,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return FD.SetStatusOutboundPolicy}});var HD=FE();Object.defineProperty(m,"SleepInboundPolicy",{enumerable:!0,get:function(){return HD.SleepInboundPolicy}});var qD=nf();Object.defineProperty(m,"StripeWebhookVerificationInboundPolicy",{enumerable:!0,get:function(){return qD.StripeWebhookVerificationInboundPolicy}});var $D=qE();Object.defineProperty(m,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return $D.SupabaseJwtInboundPolicy}});var jD=jE();Object.defineProperty(m,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return jD.UpstreamAzureAdServiceAuthInboundPolicy}});var VD=BE();Object.defineProperty(m,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return VD.UpstreamFirebaseAdminAuthInboundPolicy}});var BD=GE();Object.defineProperty(m,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return BD.UpstreamFirebaseUserAuthInboundPolicy}});var GD=JE();Object.defineProperty(m,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return GD.UpstreamGcpJwtInboundPolicy}});var KD=WE();Object.defineProperty(m,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return KD.UpstreamGcpServiceAuthInboundPolicy}});var JD=YE();Object.defineProperty(m,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return JD.ValidateJsonSchemaInbound}});var zD=tw();Object.defineProperty(m,"XmlToJsonOutboundPolicy",{enumerable:!0,get:function(){return zD.XmlToJsonOutboundPolicy}});var WD=de();Object.defineProperty(m,"HttpProblems",{enumerable:!0,get:function(){return WD.HttpProblems}});var QD=Go();Object.defineProperty(m,"ProblemResponseFormatter",{enumerable:!0,get:function(){return QD.ProblemResponseFormatter}});var YD=Ke();Object.defineProperty(m,"ZuploRequest",{enumerable:!0,get:function(){return YD.ZuploRequest}});var ZD=Vr();Object.defineProperty(m,"SystemRouteName",{enumerable:!0,get:function(){return ZD.SystemRouteName}});var mw=lp();Object.defineProperty(m,"LookupResult",{enumerable:!0,get:function(){return mw.LookupResult}});Object.defineProperty(m,"Router",{enumerable:!0,get:function(){return mw.Router}});var yw=ml();Object.defineProperty(m,"ContentTypes",{enumerable:!0,get:function(){return yw.ContentTypes}});Object.defineProperty(m,"serialize",{enumerable:!0,get:function(){return yw.serialize}});var XD=rw();Object.defineProperty(m,"ServiceProviderImpl",{enumerable:!0,get:function(){return XD.ServiceProviderImpl}});var gw=Bl();Object.defineProperty(m,"API_KEY",{enumerable:!0,get:function(){return gw.API_KEY}});Object.defineProperty(m,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return gw.SYSTEM_LOGGER}});var e1=Al();Object.defineProperty(m,"httpStatuses",{enumerable:!0,get:function(){return KL(e1).default}});var t1=Je();Object.defineProperty(m,"SystemLogMap",{enumerable:!0,get:function(){return t1.SystemLogMap}});var mo=Fc();Object.defineProperty(m,"getIdForParameterSchema",{enumerable:!0,get:function(){return mo.getIdForParameterSchema}});Object.defineProperty(m,"getIdForRefSchema",{enumerable:!0,get:function(){return mo.getIdForRefSchema}});Object.defineProperty(m,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return mo.getIdForRequestBodySchema}});Object.defineProperty(m,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return mo.getRawOperationDataIdentifierName}});Object.defineProperty(m,"sanitizedIdentifierName",{enumerable:!0,get:function(){return mo.sanitizedIdentifierName}});var bw=iw();Object.defineProperty(m,"BatchDispatch",{enumerable:!0,get:function(){return bw.BatchDispatch}});Object.defineProperty(m,"BackgroundDispatcher",{enumerable:!0,get:function(){return bw.BackgroundDispatcher}});var r1=ow();Object.defineProperty(m,"BackgroundLoader",{enumerable:!0,get:function(){return r1.BackgroundLoader}})});var Ew=_(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.BaseCryptoBeta=hi.supportedDigests=void 0;hi.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var ih=class{static{o(this,"BaseCryptoBeta")}};hi.BaseCryptoBeta=ih});var ww=_(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.WorkerCryptoBeta=void 0;var oh=Ew(),n1=k(),sh=class extends oh.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!oh.supportedDigests.includes(e.toLowerCase()))throw new n1.RuntimeError(`Algorithm ${e} is not supported. Try using ${oh.supportedDigests.join(", ")}`);let n=new TextEncoder().encode(r),i=await crypto.subtle.digest(e,n);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}};au.WorkerCryptoBeta=sh});var vw=_(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});cu.BaseKeyValueStore=void 0;var ah=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};cu.BaseKeyValueStore=ah});var Sw=_(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.WorkerKeyValueStore=void 0;var Tw=k(),i1=vw(),o1=re(),ch=class extends i1.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let r=o1.Environment.instance.runtime.ZUPLO_KV;if(!r)throw new Tw.FeatureNotEnabledError("The Key Value Store feature is not enabled for this project.");this.#e=r}put(e,r,n){if(typeof e!="string")throw new Tw.ConfigurationError("value must be of type string");return this.#e.put(e,r,n?{expirationTtl:n.expirationSecondsTtl}:void 0)}get(e,r){return this.#e.get(e,{type:"text",cacheTtl:r?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};uu.WorkerKeyValueStore=ch});var Kt=_(Tt=>{"use strict";var s1=Tt&&Tt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),a1=Tt&&Tt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&s1(e,t,r)};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.KeyValueStore=Tt.CryptoBeta=void 0;a1(_w(),Tt);var c1=ww();Object.defineProperty(Tt,"CryptoBeta",{enumerable:!0,get:function(){return c1.WorkerCryptoBeta}});var u1=Sw();Object.defineProperty(Tt,"KeyValueStore",{enumerable:!0,get:function(){return u1.WorkerKeyValueStore}})});var yM={};Co(yM,{GraphQLComplexityLimitInboundPolicy:()=>rv,GraphQLDisableIntrospectionInboundPolicy:()=>iv});module.exports=xo(yM);var Pi=Mh(Kt());function X(t,e){if(!!!t)throw new Error(e)}o(X,"devAssert");function Ne(t){return typeof t=="object"&&t!==null}o(Ne,"isObjectLike");function Ht(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(Ht,"invariant");var l1=/\r\n|[\n\r]/g;function mi(t,e){let r=0,n=1;for(let i of t.body.matchAll(l1)){if(typeof i.index=="number"||Ht(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(mi,"getLocation");function uh(t){return lu(t.source,mi(t.source,t.start))}o(uh,"printLocation");function lu(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,s=t.locationOffset.line-1,a=e.line+s,c=e.line===1?r:0,u=e.column+c,l=`${t.name}:${a}:${u}
81
81
  `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let f=Math.floor(u/80),h=u%80,y=[];for(let b=0;b<p.length;b+=80)y.push(p.slice(b,b+80));return l+Iw([[`${a} |`,y[0]],...y.slice(1,f+1).map(b=>["|",b]),["|","^".padStart(h)],["|",y[f+1]]])}return l+Iw([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(lu,"printSourceLocation");function Iw(t){let e=t.filter(([n,i])=>i!==void 0),r=Math.max(...e.map(([n])=>n.length));return e.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
82
- `)}o(Iw,"printPrefixedLines");function u1(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}o(u1,"toNormalizedOptions");var $=class t extends Error{static{o(this,"GraphQLError")}constructor(e,...r){var n,i,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=u1(r);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=Pw(Array.isArray(a)?a:a?[a]:void 0);let f=Pw((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(f==null||(i=f[0])===null||i===void 0?void 0:i.source),this.positions=u??f?.map(y=>y.start),this.locations=u&&c?u.map(y=>mi(c,y)):f?.map(y=>mi(y.source,y.start));let h=Ne(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??h)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(e+=`
82
+ `)}o(Iw,"printPrefixedLines");function d1(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}o(d1,"toNormalizedOptions");var $=class t extends Error{static{o(this,"GraphQLError")}constructor(e,...r){var n,i,s;let{nodes:a,source:c,positions:u,path:l,originalError:d,extensions:p}=d1(r);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=Pw(Array.isArray(a)?a:a?[a]:void 0);let f=Pw((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(f==null||(i=f[0])===null||i===void 0?void 0:i.source),this.positions=u??f?.map(y=>y.start),this.locations=u&&c?u.map(y=>mi(c,y)):f?.map(y=>mi(y.source,y.start));let h=Ne(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??h)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(e+=`
83
83
 
84
84
  `+uh(r.loc));else if(this.source&&this.locations)for(let r of this.locations)e+=`
85
85
 
86
- `+lu(this.source,r);return e}toJSON(){let e={message:this.message};return this.locations!=null&&(e.locations=this.locations),this.path!=null&&(e.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(e.extensions=this.extensions),e}};function Pw(t){return t===void 0||t.length===0?void 0:t}o(Pw,"undefinedIfEmpty");function we(t,e,r){return new $(`Syntax Error: ${r}`,{source:t,positions:[e]})}o(we,"syntaxError");var yo=class{static{o(this,"Location")}constructor(e,r,n){this.start=e.start,this.end=r.end,this.startToken=e,this.endToken=r,this.source=n}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}},yi=class{static{o(this,"Token")}constructor(e,r,n,i,s,a){this.kind=e,this.start=r,this.end=n,this.line=i,this.column=s,this.value=a,this.prev=null,this.next=null}get[Symbol.toStringTag](){return"Token"}toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}},lh={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},l1=new Set(Object.keys(lh));function go(t){let e=t?.kind;return typeof e=="string"&&l1.has(e)}o(go,"isNode");var ft;(function(t){t.QUERY="query",t.MUTATION="mutation",t.SUBSCRIPTION="subscription"})(ft||(ft={}));var ee;(function(t){t.QUERY="QUERY",t.MUTATION="MUTATION",t.SUBSCRIPTION="SUBSCRIPTION",t.FIELD="FIELD",t.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",t.FRAGMENT_SPREAD="FRAGMENT_SPREAD",t.INLINE_FRAGMENT="INLINE_FRAGMENT",t.VARIABLE_DEFINITION="VARIABLE_DEFINITION",t.SCHEMA="SCHEMA",t.SCALAR="SCALAR",t.OBJECT="OBJECT",t.FIELD_DEFINITION="FIELD_DEFINITION",t.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",t.INTERFACE="INTERFACE",t.UNION="UNION",t.ENUM="ENUM",t.ENUM_VALUE="ENUM_VALUE",t.INPUT_OBJECT="INPUT_OBJECT",t.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(ee||(ee={}));var S;(function(t){t.NAME="Name",t.DOCUMENT="Document",t.OPERATION_DEFINITION="OperationDefinition",t.VARIABLE_DEFINITION="VariableDefinition",t.SELECTION_SET="SelectionSet",t.FIELD="Field",t.ARGUMENT="Argument",t.FRAGMENT_SPREAD="FragmentSpread",t.INLINE_FRAGMENT="InlineFragment",t.FRAGMENT_DEFINITION="FragmentDefinition",t.VARIABLE="Variable",t.INT="IntValue",t.FLOAT="FloatValue",t.STRING="StringValue",t.BOOLEAN="BooleanValue",t.NULL="NullValue",t.ENUM="EnumValue",t.LIST="ListValue",t.OBJECT="ObjectValue",t.OBJECT_FIELD="ObjectField",t.DIRECTIVE="Directive",t.NAMED_TYPE="NamedType",t.LIST_TYPE="ListType",t.NON_NULL_TYPE="NonNullType",t.SCHEMA_DEFINITION="SchemaDefinition",t.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",t.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",t.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",t.FIELD_DEFINITION="FieldDefinition",t.INPUT_VALUE_DEFINITION="InputValueDefinition",t.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",t.UNION_TYPE_DEFINITION="UnionTypeDefinition",t.ENUM_TYPE_DEFINITION="EnumTypeDefinition",t.ENUM_VALUE_DEFINITION="EnumValueDefinition",t.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",t.DIRECTIVE_DEFINITION="DirectiveDefinition",t.SCHEMA_EXTENSION="SchemaExtension",t.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",t.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",t.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",t.UNION_TYPE_EXTENSION="UnionTypeExtension",t.ENUM_TYPE_EXTENSION="EnumTypeExtension",t.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(S||(S={}));function du(t){return t===9||t===32}o(du,"isWhiteSpace");function gi(t){return t>=48&&t<=57}o(gi,"isDigit");function Aw(t){return t>=97&&t<=122||t>=65&&t<=90}o(Aw,"isLetter");function bo(t){return Aw(t)||t===95}o(bo,"isNameStart");function pu(t){return Aw(t)||gi(t)||t===95}o(pu,"isNameContinue");function Rw(t){var e;let r=Number.MAX_SAFE_INTEGER,n=null,i=-1;for(let a=0;a<t.length;++a){var s;let c=t[a],u=d1(c);u!==c.length&&(n=(s=n)!==null&&s!==void 0?s:a,i=a,a!==0&&u<r&&(r=u))}return t.map((a,c)=>c===0?a:a.slice(r)).slice((e=n)!==null&&e!==void 0?e:0,i+1)}o(Rw,"dedentBlockStringLines");function d1(t){let e=0;for(;e<t.length&&du(t.charCodeAt(e));)++e;return e}o(d1,"leadingWhitespace");function Ow(t,e){let r=t.replace(/"""/g,'\\"""'),n=r.split(/\r\n|[\n\r]/g),i=n.length===1,s=n.length>1&&n.slice(1).every(h=>h.length===0||du(h.charCodeAt(0))),a=r.endsWith('\\"""'),c=t.endsWith('"')&&!a,u=t.endsWith("\\"),l=c||u,d=!(e!=null&&e.minimize)&&(!i||t.length>70||l||s||a),p="",f=i&&du(t.charCodeAt(0));return(d&&!f||s)&&(p+=`
86
+ `+lu(this.source,r);return e}toJSON(){let e={message:this.message};return this.locations!=null&&(e.locations=this.locations),this.path!=null&&(e.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(e.extensions=this.extensions),e}};function Pw(t){return t===void 0||t.length===0?void 0:t}o(Pw,"undefinedIfEmpty");function we(t,e,r){return new $(`Syntax Error: ${r}`,{source:t,positions:[e]})}o(we,"syntaxError");var yo=class{static{o(this,"Location")}constructor(e,r,n){this.start=e.start,this.end=r.end,this.startToken=e,this.endToken=r,this.source=n}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}},yi=class{static{o(this,"Token")}constructor(e,r,n,i,s,a){this.kind=e,this.start=r,this.end=n,this.line=i,this.column=s,this.value=a,this.prev=null,this.next=null}get[Symbol.toStringTag](){return"Token"}toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}},lh={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},p1=new Set(Object.keys(lh));function go(t){let e=t?.kind;return typeof e=="string"&&p1.has(e)}o(go,"isNode");var ft;(function(t){t.QUERY="query",t.MUTATION="mutation",t.SUBSCRIPTION="subscription"})(ft||(ft={}));var ee;(function(t){t.QUERY="QUERY",t.MUTATION="MUTATION",t.SUBSCRIPTION="SUBSCRIPTION",t.FIELD="FIELD",t.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",t.FRAGMENT_SPREAD="FRAGMENT_SPREAD",t.INLINE_FRAGMENT="INLINE_FRAGMENT",t.VARIABLE_DEFINITION="VARIABLE_DEFINITION",t.SCHEMA="SCHEMA",t.SCALAR="SCALAR",t.OBJECT="OBJECT",t.FIELD_DEFINITION="FIELD_DEFINITION",t.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",t.INTERFACE="INTERFACE",t.UNION="UNION",t.ENUM="ENUM",t.ENUM_VALUE="ENUM_VALUE",t.INPUT_OBJECT="INPUT_OBJECT",t.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(ee||(ee={}));var S;(function(t){t.NAME="Name",t.DOCUMENT="Document",t.OPERATION_DEFINITION="OperationDefinition",t.VARIABLE_DEFINITION="VariableDefinition",t.SELECTION_SET="SelectionSet",t.FIELD="Field",t.ARGUMENT="Argument",t.FRAGMENT_SPREAD="FragmentSpread",t.INLINE_FRAGMENT="InlineFragment",t.FRAGMENT_DEFINITION="FragmentDefinition",t.VARIABLE="Variable",t.INT="IntValue",t.FLOAT="FloatValue",t.STRING="StringValue",t.BOOLEAN="BooleanValue",t.NULL="NullValue",t.ENUM="EnumValue",t.LIST="ListValue",t.OBJECT="ObjectValue",t.OBJECT_FIELD="ObjectField",t.DIRECTIVE="Directive",t.NAMED_TYPE="NamedType",t.LIST_TYPE="ListType",t.NON_NULL_TYPE="NonNullType",t.SCHEMA_DEFINITION="SchemaDefinition",t.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",t.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",t.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",t.FIELD_DEFINITION="FieldDefinition",t.INPUT_VALUE_DEFINITION="InputValueDefinition",t.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",t.UNION_TYPE_DEFINITION="UnionTypeDefinition",t.ENUM_TYPE_DEFINITION="EnumTypeDefinition",t.ENUM_VALUE_DEFINITION="EnumValueDefinition",t.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",t.DIRECTIVE_DEFINITION="DirectiveDefinition",t.SCHEMA_EXTENSION="SchemaExtension",t.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",t.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",t.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",t.UNION_TYPE_EXTENSION="UnionTypeExtension",t.ENUM_TYPE_EXTENSION="EnumTypeExtension",t.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(S||(S={}));function du(t){return t===9||t===32}o(du,"isWhiteSpace");function gi(t){return t>=48&&t<=57}o(gi,"isDigit");function Aw(t){return t>=97&&t<=122||t>=65&&t<=90}o(Aw,"isLetter");function bo(t){return Aw(t)||t===95}o(bo,"isNameStart");function pu(t){return Aw(t)||gi(t)||t===95}o(pu,"isNameContinue");function Rw(t){var e;let r=Number.MAX_SAFE_INTEGER,n=null,i=-1;for(let a=0;a<t.length;++a){var s;let c=t[a],u=f1(c);u!==c.length&&(n=(s=n)!==null&&s!==void 0?s:a,i=a,a!==0&&u<r&&(r=u))}return t.map((a,c)=>c===0?a:a.slice(r)).slice((e=n)!==null&&e!==void 0?e:0,i+1)}o(Rw,"dedentBlockStringLines");function f1(t){let e=0;for(;e<t.length&&du(t.charCodeAt(e));)++e;return e}o(f1,"leadingWhitespace");function Ow(t,e){let r=t.replace(/"""/g,'\\"""'),n=r.split(/\r\n|[\n\r]/g),i=n.length===1,s=n.length>1&&n.slice(1).every(h=>h.length===0||du(h.charCodeAt(0))),a=r.endsWith('\\"""'),c=t.endsWith('"')&&!a,u=t.endsWith("\\"),l=c||u,d=!(e!=null&&e.minimize)&&(!i||t.length>70||l||s||a),p="",f=i&&du(t.charCodeAt(0));return(d&&!f||s)&&(p+=`
87
87
  `),p+=r,(d||l)&&(p+=`
88
- `),'"""'+p+'"""'}o(Ow,"printBlockString");var R;(function(t){t.SOF="<SOF>",t.EOF="<EOF>",t.BANG="!",t.DOLLAR="$",t.AMP="&",t.PAREN_L="(",t.PAREN_R=")",t.SPREAD="...",t.COLON=":",t.EQUALS="=",t.AT="@",t.BRACKET_L="[",t.BRACKET_R="]",t.BRACE_L="{",t.PIPE="|",t.BRACE_R="}",t.NAME="Name",t.INT="Int",t.FLOAT="Float",t.STRING="String",t.BLOCK_STRING="BlockString",t.COMMENT="Comment"})(R||(R={}));var Eo=class{static{o(this,"Lexer")}constructor(e){let r=new yi(R.SOF,0,0,0,0);this.source=e,this.lastToken=r,this.token=r,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let e=this.token;if(e.kind!==R.EOF)do if(e.next)e=e.next;else{let r=p1(this,e.end);e.next=r,r.prev=e,e=r}while(e.kind===R.COMMENT);return e}};function Cw(t){return t===R.BANG||t===R.DOLLAR||t===R.AMP||t===R.PAREN_L||t===R.PAREN_R||t===R.SPREAD||t===R.COLON||t===R.EQUALS||t===R.AT||t===R.BRACKET_L||t===R.BRACKET_R||t===R.BRACE_L||t===R.PIPE||t===R.BRACE_R}o(Cw,"isPunctuatorTokenKind");function bi(t){return t>=0&&t<=55295||t>=57344&&t<=1114111}o(bi,"isUnicodeScalarValue");function fu(t,e){return xw(t.charCodeAt(e))&&Lw(t.charCodeAt(e+1))}o(fu,"isSupplementaryCodePoint");function xw(t){return t>=55296&&t<=56319}o(xw,"isLeadingSurrogate");function Lw(t){return t>=56320&&t<=57343}o(Lw,"isTrailingSurrogate");function ln(t,e){let r=t.source.body.codePointAt(e);if(r===void 0)return R.EOF;if(r>=32&&r<=126){let n=String.fromCodePoint(r);return n==='"'?`'"'`:`"${n}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}o(ln,"printCodePointAt");function Se(t,e,r,n,i){let s=t.line,a=1+r-t.lineStart;return new yi(e,r,n,s,a,i)}o(Se,"createToken");function p1(t,e){let r=t.source.body,n=r.length,i=e;for(;i<n;){let s=r.charCodeAt(i);switch(s){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++t.line,t.lineStart=i;continue;case 13:r.charCodeAt(i+1)===10?i+=2:++i,++t.line,t.lineStart=i;continue;case 35:return f1(t,i);case 33:return Se(t,R.BANG,i,i+1);case 36:return Se(t,R.DOLLAR,i,i+1);case 38:return Se(t,R.AMP,i,i+1);case 40:return Se(t,R.PAREN_L,i,i+1);case 41:return Se(t,R.PAREN_R,i,i+1);case 46:if(r.charCodeAt(i+1)===46&&r.charCodeAt(i+2)===46)return Se(t,R.SPREAD,i,i+3);break;case 58:return Se(t,R.COLON,i,i+1);case 61:return Se(t,R.EQUALS,i,i+1);case 64:return Se(t,R.AT,i,i+1);case 91:return Se(t,R.BRACKET_L,i,i+1);case 93:return Se(t,R.BRACKET_R,i,i+1);case 123:return Se(t,R.BRACE_L,i,i+1);case 124:return Se(t,R.PIPE,i,i+1);case 125:return Se(t,R.BRACE_R,i,i+1);case 34:return r.charCodeAt(i+1)===34&&r.charCodeAt(i+2)===34?_1(t,i):m1(t,i)}if(gi(s)||s===45)return h1(t,i,s);if(bo(s))return E1(t,i);throw we(t.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:bi(s)||fu(r,i)?`Unexpected character: ${ln(t,i)}.`:`Invalid character: ${ln(t,i)}.`)}return Se(t,R.EOF,n,n)}o(p1,"readNextToken");function f1(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(s===10||s===13)break;if(bi(s))++i;else if(fu(r,i))i+=2;else break}return Se(t,R.COMMENT,e,i,r.slice(e+1,i))}o(f1,"readComment");function h1(t,e,r){let n=t.source.body,i=e,s=r,a=!1;if(s===45&&(s=n.charCodeAt(++i)),s===48){if(s=n.charCodeAt(++i),gi(s))throw we(t.source,i,`Invalid number, unexpected digit after 0: ${ln(t,i)}.`)}else i=dh(t,i,s),s=n.charCodeAt(i);if(s===46&&(a=!0,s=n.charCodeAt(++i),i=dh(t,i,s),s=n.charCodeAt(i)),(s===69||s===101)&&(a=!0,s=n.charCodeAt(++i),(s===43||s===45)&&(s=n.charCodeAt(++i)),i=dh(t,i,s),s=n.charCodeAt(i)),s===46||bo(s))throw we(t.source,i,`Invalid number, expected digit but got: ${ln(t,i)}.`);return Se(t,a?R.FLOAT:R.INT,e,i,n.slice(e,i))}o(h1,"readNumber");function dh(t,e,r){if(!gi(r))throw we(t.source,e,`Invalid number, expected digit but got: ${ln(t,e)}.`);let n=t.source.body,i=e+1;for(;gi(n.charCodeAt(i));)++i;return i}o(dh,"readDigits");function m1(t,e){let r=t.source.body,n=r.length,i=e+1,s=i,a="";for(;i<n;){let c=r.charCodeAt(i);if(c===34)return a+=r.slice(s,i),Se(t,R.STRING,e,i+1,a);if(c===92){a+=r.slice(s,i);let u=r.charCodeAt(i+1)===117?r.charCodeAt(i+2)===123?y1(t,i):g1(t,i):b1(t,i);a+=u.value,i+=u.size,s=i;continue}if(c===10||c===13)break;if(bi(c))++i;else if(fu(r,i))i+=2;else throw we(t.source,i,`Invalid character within String: ${ln(t,i)}.`)}throw we(t.source,i,"Unterminated string.")}o(m1,"readString");function y1(t,e){let r=t.source.body,n=0,i=3;for(;i<12;){let s=r.charCodeAt(e+i++);if(s===125){if(i<5||!bi(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|_o(s),n<0)break}throw we(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+i)}".`)}o(y1,"readEscapedUnicodeVariableWidth");function g1(t,e){let r=t.source.body,n=Nw(r,e+2);if(bi(n))return{value:String.fromCodePoint(n),size:6};if(xw(n)&&r.charCodeAt(e+6)===92&&r.charCodeAt(e+7)===117){let i=Nw(r,e+8);if(Lw(i))return{value:String.fromCodePoint(n,i),size:12}}throw we(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+6)}".`)}o(g1,"readEscapedUnicodeFixedWidth");function Nw(t,e){return _o(t.charCodeAt(e))<<12|_o(t.charCodeAt(e+1))<<8|_o(t.charCodeAt(e+2))<<4|_o(t.charCodeAt(e+3))}o(Nw,"read16BitHexCode");function _o(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:-1}o(_o,"readHexDigit");function b1(t,e){let r=t.source.body;switch(r.charCodeAt(e+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
89
- `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw we(t.source,e,`Invalid character escape sequence: "${r.slice(e,e+2)}".`)}o(b1,"readEscapedCharacter");function _1(t,e){let r=t.source.body,n=r.length,i=t.lineStart,s=e+3,a=s,c="",u=[];for(;s<n;){let l=r.charCodeAt(s);if(l===34&&r.charCodeAt(s+1)===34&&r.charCodeAt(s+2)===34){c+=r.slice(a,s),u.push(c);let d=Se(t,R.BLOCK_STRING,e,s+3,Rw(u).join(`
90
- `));return t.line+=u.length-1,t.lineStart=i,d}if(l===92&&r.charCodeAt(s+1)===34&&r.charCodeAt(s+2)===34&&r.charCodeAt(s+3)===34){c+=r.slice(a,s),a=s+1,s+=4;continue}if(l===10||l===13){c+=r.slice(a,s),u.push(c),l===13&&r.charCodeAt(s+1)===10?s+=2:++s,c="",a=s,i=s;continue}if(bi(l))++s;else if(fu(r,s))s+=2;else throw we(t.source,s,`Invalid character within String: ${ln(t,s)}.`)}throw we(t.source,s,"Unterminated string.")}o(_1,"readBlockString");function E1(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(pu(s))++i;else break}return Se(t,R.NAME,e,i,r.slice(e,i))}o(E1,"readName");function U(t){return hu(t,[])}o(U,"inspect");function hu(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return w1(t,e);default:return String(t)}}o(hu,"formatValue");function w1(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(v1(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:hu(n,r)}else if(Array.isArray(t))return S1(t,r);return T1(t,r)}o(w1,"formatObjectValue");function v1(t){return typeof t.toJSON=="function"}o(v1,"isJSONable");function T1(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+I1(t)+"]":"{ "+r.map(([i,s])=>i+": "+hu(s,e)).join(", ")+" }"}o(T1,"formatObject");function S1(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let s=0;s<r;++s)i.push(hu(t[s],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}o(S1,"formatArray");function I1(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}o(I1,"getObjectTag");var rt=globalThis.process&&globalThis.process.env.NODE_ENV==="production"?o(function(e,r){return e instanceof r},"instanceOf"):o(function(e,r){if(e instanceof r)return!0;if(typeof e=="object"&&e!==null){var n;let i=r.prototype[Symbol.toStringTag],s=Symbol.toStringTag in e?e[Symbol.toStringTag]:(n=e.constructor)===null||n===void 0?void 0:n.name;if(i===s){let a=U(e);throw new Error(`Cannot use ${i} "${a}" from another module or realm.
88
+ `),'"""'+p+'"""'}o(Ow,"printBlockString");var R;(function(t){t.SOF="<SOF>",t.EOF="<EOF>",t.BANG="!",t.DOLLAR="$",t.AMP="&",t.PAREN_L="(",t.PAREN_R=")",t.SPREAD="...",t.COLON=":",t.EQUALS="=",t.AT="@",t.BRACKET_L="[",t.BRACKET_R="]",t.BRACE_L="{",t.PIPE="|",t.BRACE_R="}",t.NAME="Name",t.INT="Int",t.FLOAT="Float",t.STRING="String",t.BLOCK_STRING="BlockString",t.COMMENT="Comment"})(R||(R={}));var Eo=class{static{o(this,"Lexer")}constructor(e){let r=new yi(R.SOF,0,0,0,0);this.source=e,this.lastToken=r,this.token=r,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let e=this.token;if(e.kind!==R.EOF)do if(e.next)e=e.next;else{let r=h1(this,e.end);e.next=r,r.prev=e,e=r}while(e.kind===R.COMMENT);return e}};function Cw(t){return t===R.BANG||t===R.DOLLAR||t===R.AMP||t===R.PAREN_L||t===R.PAREN_R||t===R.SPREAD||t===R.COLON||t===R.EQUALS||t===R.AT||t===R.BRACKET_L||t===R.BRACKET_R||t===R.BRACE_L||t===R.PIPE||t===R.BRACE_R}o(Cw,"isPunctuatorTokenKind");function bi(t){return t>=0&&t<=55295||t>=57344&&t<=1114111}o(bi,"isUnicodeScalarValue");function fu(t,e){return xw(t.charCodeAt(e))&&Lw(t.charCodeAt(e+1))}o(fu,"isSupplementaryCodePoint");function xw(t){return t>=55296&&t<=56319}o(xw,"isLeadingSurrogate");function Lw(t){return t>=56320&&t<=57343}o(Lw,"isTrailingSurrogate");function ln(t,e){let r=t.source.body.codePointAt(e);if(r===void 0)return R.EOF;if(r>=32&&r<=126){let n=String.fromCodePoint(r);return n==='"'?`'"'`:`"${n}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}o(ln,"printCodePointAt");function Se(t,e,r,n,i){let s=t.line,a=1+r-t.lineStart;return new yi(e,r,n,s,a,i)}o(Se,"createToken");function h1(t,e){let r=t.source.body,n=r.length,i=e;for(;i<n;){let s=r.charCodeAt(i);switch(s){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++t.line,t.lineStart=i;continue;case 13:r.charCodeAt(i+1)===10?i+=2:++i,++t.line,t.lineStart=i;continue;case 35:return m1(t,i);case 33:return Se(t,R.BANG,i,i+1);case 36:return Se(t,R.DOLLAR,i,i+1);case 38:return Se(t,R.AMP,i,i+1);case 40:return Se(t,R.PAREN_L,i,i+1);case 41:return Se(t,R.PAREN_R,i,i+1);case 46:if(r.charCodeAt(i+1)===46&&r.charCodeAt(i+2)===46)return Se(t,R.SPREAD,i,i+3);break;case 58:return Se(t,R.COLON,i,i+1);case 61:return Se(t,R.EQUALS,i,i+1);case 64:return Se(t,R.AT,i,i+1);case 91:return Se(t,R.BRACKET_L,i,i+1);case 93:return Se(t,R.BRACKET_R,i,i+1);case 123:return Se(t,R.BRACE_L,i,i+1);case 124:return Se(t,R.PIPE,i,i+1);case 125:return Se(t,R.BRACE_R,i,i+1);case 34:return r.charCodeAt(i+1)===34&&r.charCodeAt(i+2)===34?w1(t,i):g1(t,i)}if(gi(s)||s===45)return y1(t,i,s);if(bo(s))return v1(t,i);throw we(t.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:bi(s)||fu(r,i)?`Unexpected character: ${ln(t,i)}.`:`Invalid character: ${ln(t,i)}.`)}return Se(t,R.EOF,n,n)}o(h1,"readNextToken");function m1(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(s===10||s===13)break;if(bi(s))++i;else if(fu(r,i))i+=2;else break}return Se(t,R.COMMENT,e,i,r.slice(e+1,i))}o(m1,"readComment");function y1(t,e,r){let n=t.source.body,i=e,s=r,a=!1;if(s===45&&(s=n.charCodeAt(++i)),s===48){if(s=n.charCodeAt(++i),gi(s))throw we(t.source,i,`Invalid number, unexpected digit after 0: ${ln(t,i)}.`)}else i=dh(t,i,s),s=n.charCodeAt(i);if(s===46&&(a=!0,s=n.charCodeAt(++i),i=dh(t,i,s),s=n.charCodeAt(i)),(s===69||s===101)&&(a=!0,s=n.charCodeAt(++i),(s===43||s===45)&&(s=n.charCodeAt(++i)),i=dh(t,i,s),s=n.charCodeAt(i)),s===46||bo(s))throw we(t.source,i,`Invalid number, expected digit but got: ${ln(t,i)}.`);return Se(t,a?R.FLOAT:R.INT,e,i,n.slice(e,i))}o(y1,"readNumber");function dh(t,e,r){if(!gi(r))throw we(t.source,e,`Invalid number, expected digit but got: ${ln(t,e)}.`);let n=t.source.body,i=e+1;for(;gi(n.charCodeAt(i));)++i;return i}o(dh,"readDigits");function g1(t,e){let r=t.source.body,n=r.length,i=e+1,s=i,a="";for(;i<n;){let c=r.charCodeAt(i);if(c===34)return a+=r.slice(s,i),Se(t,R.STRING,e,i+1,a);if(c===92){a+=r.slice(s,i);let u=r.charCodeAt(i+1)===117?r.charCodeAt(i+2)===123?b1(t,i):_1(t,i):E1(t,i);a+=u.value,i+=u.size,s=i;continue}if(c===10||c===13)break;if(bi(c))++i;else if(fu(r,i))i+=2;else throw we(t.source,i,`Invalid character within String: ${ln(t,i)}.`)}throw we(t.source,i,"Unterminated string.")}o(g1,"readString");function b1(t,e){let r=t.source.body,n=0,i=3;for(;i<12;){let s=r.charCodeAt(e+i++);if(s===125){if(i<5||!bi(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|_o(s),n<0)break}throw we(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+i)}".`)}o(b1,"readEscapedUnicodeVariableWidth");function _1(t,e){let r=t.source.body,n=Nw(r,e+2);if(bi(n))return{value:String.fromCodePoint(n),size:6};if(xw(n)&&r.charCodeAt(e+6)===92&&r.charCodeAt(e+7)===117){let i=Nw(r,e+8);if(Lw(i))return{value:String.fromCodePoint(n,i),size:12}}throw we(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+6)}".`)}o(_1,"readEscapedUnicodeFixedWidth");function Nw(t,e){return _o(t.charCodeAt(e))<<12|_o(t.charCodeAt(e+1))<<8|_o(t.charCodeAt(e+2))<<4|_o(t.charCodeAt(e+3))}o(Nw,"read16BitHexCode");function _o(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:-1}o(_o,"readHexDigit");function E1(t,e){let r=t.source.body;switch(r.charCodeAt(e+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
89
+ `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw we(t.source,e,`Invalid character escape sequence: "${r.slice(e,e+2)}".`)}o(E1,"readEscapedCharacter");function w1(t,e){let r=t.source.body,n=r.length,i=t.lineStart,s=e+3,a=s,c="",u=[];for(;s<n;){let l=r.charCodeAt(s);if(l===34&&r.charCodeAt(s+1)===34&&r.charCodeAt(s+2)===34){c+=r.slice(a,s),u.push(c);let d=Se(t,R.BLOCK_STRING,e,s+3,Rw(u).join(`
90
+ `));return t.line+=u.length-1,t.lineStart=i,d}if(l===92&&r.charCodeAt(s+1)===34&&r.charCodeAt(s+2)===34&&r.charCodeAt(s+3)===34){c+=r.slice(a,s),a=s+1,s+=4;continue}if(l===10||l===13){c+=r.slice(a,s),u.push(c),l===13&&r.charCodeAt(s+1)===10?s+=2:++s,c="",a=s,i=s;continue}if(bi(l))++s;else if(fu(r,s))s+=2;else throw we(t.source,s,`Invalid character within String: ${ln(t,s)}.`)}throw we(t.source,s,"Unterminated string.")}o(w1,"readBlockString");function v1(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(pu(s))++i;else break}return Se(t,R.NAME,e,i,r.slice(e,i))}o(v1,"readName");function U(t){return hu(t,[])}o(U,"inspect");function hu(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return T1(t,e);default:return String(t)}}o(hu,"formatValue");function T1(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(S1(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:hu(n,r)}else if(Array.isArray(t))return P1(t,r);return I1(t,r)}o(T1,"formatObjectValue");function S1(t){return typeof t.toJSON=="function"}o(S1,"isJSONable");function I1(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+A1(t)+"]":"{ "+r.map(([i,s])=>i+": "+hu(s,e)).join(", ")+" }"}o(I1,"formatObject");function P1(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let s=0;s<r;++s)i.push(hu(t[s],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}o(P1,"formatArray");function A1(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}o(A1,"getObjectTag");var rt=globalThis.process&&globalThis.process.env.NODE_ENV==="production"?o(function(e,r){return e instanceof r},"instanceOf"):o(function(e,r){if(e instanceof r)return!0;if(typeof e=="object"&&e!==null){var n;let i=r.prototype[Symbol.toStringTag],s=Symbol.toStringTag in e?e[Symbol.toStringTag]:(n=e.constructor)===null||n===void 0?void 0:n.name;if(i===s){let a=U(e);throw new Error(`Cannot use ${i} "${a}" from another module or realm.
91
91
 
92
92
  Ensure that there is only one instance of "graphql" in the node_modules
93
93
  directory. If different versions of "graphql" are the dependencies of other
@@ -98,36 +98,36 @@ https://yarnpkg.com/en/docs/selective-version-resolutions
98
98
  Duplicate "graphql" modules cannot be used at the same time since different
99
99
  versions may have different capabilities and behavior. The data from one
100
100
  version used in the function from another could produce confusing and
101
- spurious results.`)}}return!1},"instanceOf");var _i=class{static{o(this,"Source")}constructor(e,r="GraphQL request",n={line:1,column:1}){typeof e=="string"||X(!1,`Body must be a string. Received: ${U(e)}.`),this.body=e,this.name=r,this.locationOffset=n,this.locationOffset.line>0||X(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||X(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}};function Dw(t){return rt(t,_i)}o(Dw,"isSource");function gu(t,e){return new yu(t,e).parseDocument()}o(gu,"parse");function bu(t,e){let r=new yu(t,e);r.expectToken(R.SOF);let n=r.parseValueLiteral(!1);return r.expectToken(R.EOF),n}o(bu,"parseValue");var yu=class{static{o(this,"Parser")}constructor(e,r={}){let n=Dw(e)?e:new _i(e);this._lexer=new Eo(n),this._options=r,this._tokenCounter=0}parseName(){let e=this.expectToken(R.NAME);return this.node(e,{kind:S.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:S.DOCUMENT,definitions:this.many(R.SOF,this.parseDefinition,R.EOF)})}parseDefinition(){if(this.peek(R.BRACE_L))return this.parseOperationDefinition();let e=this.peekDescription(),r=e?this._lexer.lookahead():this._lexer.token;if(r.kind===R.NAME){switch(r.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}if(e)throw we(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(r.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(r)}parseOperationDefinition(){let e=this._lexer.token;if(this.peek(R.BRACE_L))return this.node(e,{kind:S.OPERATION_DEFINITION,operation:ft.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});let r=this.parseOperationType(),n;return this.peek(R.NAME)&&(n=this.parseName()),this.node(e,{kind:S.OPERATION_DEFINITION,operation:r,name:n,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){let e=this.expectToken(R.NAME);switch(e.value){case"query":return ft.QUERY;case"mutation":return ft.MUTATION;case"subscription":return ft.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(R.PAREN_L,this.parseVariableDefinition,R.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:S.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(R.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(R.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){let e=this._lexer.token;return this.expectToken(R.DOLLAR),this.node(e,{kind:S.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:S.SELECTION_SET,selections:this.many(R.BRACE_L,this.parseSelection,R.BRACE_R)})}parseSelection(){return this.peek(R.SPREAD)?this.parseFragment():this.parseField()}parseField(){let e=this._lexer.token,r=this.parseName(),n,i;return this.expectOptionalToken(R.COLON)?(n=r,i=this.parseName()):i=r,this.node(e,{kind:S.FIELD,alias:n,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(R.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){let r=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(R.PAREN_L,r,R.PAREN_R)}parseArgument(e=!1){let r=this._lexer.token,n=this.parseName();return this.expectToken(R.COLON),this.node(r,{kind:S.ARGUMENT,name:n,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){let e=this._lexer.token;this.expectToken(R.SPREAD);let r=this.expectOptionalKeyword("on");return!r&&this.peek(R.NAME)?this.node(e,{kind:S.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(e,{kind:S.INLINE_FRAGMENT,typeCondition:r?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){let e=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(e,{kind:S.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(e,{kind:S.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(e){let r=this._lexer.token;switch(r.kind){case R.BRACKET_L:return this.parseList(e);case R.BRACE_L:return this.parseObject(e);case R.INT:return this.advanceLexer(),this.node(r,{kind:S.INT,value:r.value});case R.FLOAT:return this.advanceLexer(),this.node(r,{kind:S.FLOAT,value:r.value});case R.STRING:case R.BLOCK_STRING:return this.parseStringLiteral();case R.NAME:switch(this.advanceLexer(),r.value){case"true":return this.node(r,{kind:S.BOOLEAN,value:!0});case"false":return this.node(r,{kind:S.BOOLEAN,value:!1});case"null":return this.node(r,{kind:S.NULL});default:return this.node(r,{kind:S.ENUM,value:r.value})}case R.DOLLAR:if(e)if(this.expectToken(R.DOLLAR),this._lexer.token.kind===R.NAME){let n=this._lexer.token.value;throw we(this._lexer.source,r.start,`Unexpected variable "$${n}" in constant value.`)}else throw this.unexpected(r);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){let e=this._lexer.token;return this.advanceLexer(),this.node(e,{kind:S.STRING,value:e.value,block:e.kind===R.BLOCK_STRING})}parseList(e){let r=o(()=>this.parseValueLiteral(e),"item");return this.node(this._lexer.token,{kind:S.LIST,values:this.any(R.BRACKET_L,r,R.BRACKET_R)})}parseObject(e){let r=o(()=>this.parseObjectField(e),"item");return this.node(this._lexer.token,{kind:S.OBJECT,fields:this.any(R.BRACE_L,r,R.BRACE_R)})}parseObjectField(e){let r=this._lexer.token,n=this.parseName();return this.expectToken(R.COLON),this.node(r,{kind:S.OBJECT_FIELD,name:n,value:this.parseValueLiteral(e)})}parseDirectives(e){let r=[];for(;this.peek(R.AT);)r.push(this.parseDirective(e));return r}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){let r=this._lexer.token;return this.expectToken(R.AT),this.node(r,{kind:S.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){let e=this._lexer.token,r;if(this.expectOptionalToken(R.BRACKET_L)){let n=this.parseTypeReference();this.expectToken(R.BRACKET_R),r=this.node(e,{kind:S.LIST_TYPE,type:n})}else r=this.parseNamedType();return this.expectOptionalToken(R.BANG)?this.node(e,{kind:S.NON_NULL_TYPE,type:r}):r}parseNamedType(){return this.node(this._lexer.token,{kind:S.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(R.STRING)||this.peek(R.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("schema");let n=this.parseConstDirectives(),i=this.many(R.BRACE_L,this.parseOperationTypeDefinition,R.BRACE_R);return this.node(e,{kind:S.SCHEMA_DEFINITION,description:r,directives:n,operationTypes:i})}parseOperationTypeDefinition(){let e=this._lexer.token,r=this.parseOperationType();this.expectToken(R.COLON);let n=this.parseNamedType();return this.node(e,{kind:S.OPERATION_TYPE_DEFINITION,operation:r,type:n})}parseScalarTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("scalar");let n=this.parseName(),i=this.parseConstDirectives();return this.node(e,{kind:S.SCALAR_TYPE_DEFINITION,description:r,name:n,directives:i})}parseObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("type");let n=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),a=this.parseFieldsDefinition();return this.node(e,{kind:S.OBJECT_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(R.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(R.BRACE_L,this.parseFieldDefinition,R.BRACE_R)}parseFieldDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName(),i=this.parseArgumentDefs();this.expectToken(R.COLON);let s=this.parseTypeReference(),a=this.parseConstDirectives();return this.node(e,{kind:S.FIELD_DEFINITION,description:r,name:n,arguments:i,type:s,directives:a})}parseArgumentDefs(){return this.optionalMany(R.PAREN_L,this.parseInputValueDef,R.PAREN_R)}parseInputValueDef(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName();this.expectToken(R.COLON);let i=this.parseTypeReference(),s;this.expectOptionalToken(R.EQUALS)&&(s=this.parseConstValueLiteral());let a=this.parseConstDirectives();return this.node(e,{kind:S.INPUT_VALUE_DEFINITION,description:r,name:n,type:i,defaultValue:s,directives:a})}parseInterfaceTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("interface");let n=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),a=this.parseFieldsDefinition();return this.node(e,{kind:S.INTERFACE_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseUnionTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("union");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseUnionMemberTypes();return this.node(e,{kind:S.UNION_TYPE_DEFINITION,description:r,name:n,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(R.EQUALS)?this.delimitedMany(R.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("enum");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseEnumValuesDefinition();return this.node(e,{kind:S.ENUM_TYPE_DEFINITION,description:r,name:n,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(R.BRACE_L,this.parseEnumValueDefinition,R.BRACE_R)}parseEnumValueDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(e,{kind:S.ENUM_VALUE_DEFINITION,description:r,name:n,directives:i})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw we(this._lexer.source,this._lexer.token.start,`${mu(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("input");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseInputFieldsDefinition();return this.node(e,{kind:S.INPUT_OBJECT_TYPE_DEFINITION,description:r,name:n,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(R.BRACE_L,this.parseInputValueDef,R.BRACE_R)}parseTypeSystemExtension(){let e=this._lexer.lookahead();if(e.kind===R.NAME)switch(e.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension()}throw this.unexpected(e)}parseSchemaExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");let r=this.parseConstDirectives(),n=this.optionalMany(R.BRACE_L,this.parseOperationTypeDefinition,R.BRACE_R);if(r.length===0&&n.length===0)throw this.unexpected();return this.node(e,{kind:S.SCHEMA_EXTENSION,directives:r,operationTypes:n})}parseScalarTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");let r=this.parseName(),n=this.parseConstDirectives();if(n.length===0)throw this.unexpected();return this.node(e,{kind:S.SCALAR_TYPE_EXTENSION,name:r,directives:n})}parseObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(n.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(e,{kind:S.OBJECT_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:s})}parseInterfaceTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(n.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(e,{kind:S.INTERFACE_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:s})}parseUnionTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseUnionMemberTypes();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.UNION_TYPE_EXTENSION,name:r,directives:n,types:i})}parseEnumTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.ENUM_TYPE_EXTENSION,name:r,directives:n,values:i})}parseInputObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.INPUT_OBJECT_TYPE_EXTENSION,name:r,directives:n,fields:i})}parseDirectiveDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("directive"),this.expectToken(R.AT);let n=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");let a=this.parseDirectiveLocations();return this.node(e,{kind:S.DIRECTIVE_DEFINITION,description:r,name:n,arguments:i,repeatable:s,locations:a})}parseDirectiveLocations(){return this.delimitedMany(R.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){let e=this._lexer.token,r=this.parseName();if(Object.prototype.hasOwnProperty.call(ee,r.value))return r;throw this.unexpected(e)}node(e,r){return this._options.noLocation!==!0&&(r.loc=new yo(e,this._lexer.lastToken,this._lexer.source)),r}peek(e){return this._lexer.token.kind===e}expectToken(e){let r=this._lexer.token;if(r.kind===e)return this.advanceLexer(),r;throw we(this._lexer.source,r.start,`Expected ${Mw(e)}, found ${mu(r)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e?(this.advanceLexer(),!0):!1}expectKeyword(e){let r=this._lexer.token;if(r.kind===R.NAME&&r.value===e)this.advanceLexer();else throw we(this._lexer.source,r.start,`Expected "${e}", found ${mu(r)}.`)}expectOptionalKeyword(e){let r=this._lexer.token;return r.kind===R.NAME&&r.value===e?(this.advanceLexer(),!0):!1}unexpected(e){let r=e??this._lexer.token;return we(this._lexer.source,r.start,`Unexpected ${mu(r)}.`)}any(e,r,n){this.expectToken(e);let i=[];for(;!this.expectOptionalToken(n);)i.push(r.call(this));return i}optionalMany(e,r,n){if(this.expectOptionalToken(e)){let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}return[]}many(e,r,n){this.expectToken(e);let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}delimitedMany(e,r){this.expectOptionalToken(e);let n=[];do n.push(r.call(this));while(this.expectOptionalToken(e));return n}advanceLexer(){let{maxTokens:e}=this._options,r=this._lexer.advance();if(e!==void 0&&r.kind!==R.EOF&&(++this._tokenCounter,this._tokenCounter>e))throw we(this._lexer.source,r.start,`Document contains more that ${e} tokens. Parsing aborted.`)}};function mu(t){let e=t.value;return Mw(t.kind)+(e!=null?` "${e}"`:"")}o(mu,"getTokenDesc");function Mw(t){return Cw(t)?`"${t}"`:t}o(Mw,"getTokenKindDesc");function _u(t,e){let[r,n]=e?[t,e]:[void 0,t],i=" Did you mean ";r&&(i+=r+" ");let s=n.map(u=>`"${u}"`);switch(s.length){case 0:return"";case 1:return i+s[0]+"?";case 2:return i+s[0]+" or "+s[1]+"?"}let a=s.slice(0,5),c=a.pop();return i+a.join(", ")+", or "+c+"?"}o(_u,"didYouMean");function ph(t){return t}o(ph,"identityFunc");function Ei(t,e){let r=Object.create(null);for(let n of t)r[e(n)]=n;return r}o(Ei,"keyMap");function qt(t,e,r){let n=Object.create(null);for(let i of t)n[e(i)]=r(i);return n}o(qt,"keyValMap");function wo(t,e){let r=Object.create(null);for(let n of Object.keys(t))r[n]=e(t[n],n);return r}o(wo,"mapValue");function Uw(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let i=t.charCodeAt(r),s=e.charCodeAt(n);if(Eu(i)&&Eu(s)){let a=0;do++r,a=a*10+i-fh,i=t.charCodeAt(r);while(Eu(i)&&a>0);let c=0;do++n,c=c*10+s-fh,s=e.charCodeAt(n);while(Eu(s)&&c>0);if(a<c)return-1;if(a>c)return 1}else{if(i<s)return-1;if(i>s)return 1;++r,++n}}return t.length-e.length}o(Uw,"naturalCompare");var fh=48,P1=57;function Eu(t){return!isNaN(t)&&fh<=t&&t<=P1}o(Eu,"isDigit");function wu(t,e){let r=Object.create(null),n=new hh(t),i=Math.floor(t.length*.4)+1;for(let s of e){let a=n.measure(s,i);a!==void 0&&(r[s]=a)}return Object.keys(r).sort((s,a)=>{let c=r[s]-r[a];return c!==0?c:Uw(s,a)})}o(wu,"suggestionList");var hh=class{static{o(this,"LexicalDistance")}constructor(e){this._input=e,this._inputLowerCase=e.toLowerCase(),this._inputArray=kw(this._inputLowerCase),this._rows=[new Array(e.length+1).fill(0),new Array(e.length+1).fill(0),new Array(e.length+1).fill(0)]}measure(e,r){if(this._input===e)return 0;let n=e.toLowerCase();if(this._inputLowerCase===n)return 1;let i=kw(n),s=this._inputArray;if(i.length<s.length){let d=i;i=s,s=d}let a=i.length,c=s.length;if(a-c>r)return;let u=this._rows;for(let d=0;d<=c;d++)u[0][d]=d;for(let d=1;d<=a;d++){let p=u[(d-1)%3],f=u[d%3],h=f[0]=d;for(let y=1;y<=c;y++){let b=i[d-1]===s[y-1]?0:1,I=Math.min(p[y]+1,f[y-1]+1,p[y-1]+b);if(d>1&&y>1&&i[d-1]===s[y-2]&&i[d-2]===s[y-1]){let A=u[(d-2)%3][y-2];I=Math.min(I,A+1)}I<h&&(h=I),f[y]=I}if(h>r)return}let l=u[a%3][c];return l<=r?l:void 0}};function kw(t){let e=t.length,r=new Array(e);for(let n=0;n<e;++n)r[n]=t.charCodeAt(n);return r}o(kw,"stringToArray");function Ve(t){if(t==null)return Object.create(null);if(Object.getPrototypeOf(t)===null)return t;let e=Object.create(null);for(let[r,n]of Object.entries(t))e[r]=n;return e}o(Ve,"toObjMap");function Fw(t){return`"${t.replace(A1,R1)}"`}o(Fw,"printString");var A1=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function R1(t){return O1[t.charCodeAt(0)]}o(R1,"escapedReplacer");var O1=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"];var mh=Object.freeze({});function xr(t,e,r=lh){let n=new Map;for(let A of Object.values(S))n.set(A,wi(e,A));let i,s=Array.isArray(t),a=[t],c=-1,u=[],l=t,d,p,f=[],h=[];do{c++;let A=c===a.length,g=A&&u.length!==0;if(A){if(d=h.length===0?void 0:f[f.length-1],l=p,p=h.pop(),g)if(s){l=l.slice();let O=0;for(let[V,E]of u){let T=V-O;E===null?(l.splice(T,1),O++):l[T]=E}}else{l=Object.defineProperties({},Object.getOwnPropertyDescriptors(l));for(let[O,V]of u)l[O]=V}c=i.index,a=i.keys,u=i.edits,s=i.inArray,i=i.prev}else if(p){if(d=s?c:a[c],l=p[d],l==null)continue;f.push(d)}let v;if(!Array.isArray(l)){var y,b;go(l)||X(!1,`Invalid AST Node: ${U(l)}.`);let O=A?(y=n.get(l.kind))===null||y===void 0?void 0:y.leave:(b=n.get(l.kind))===null||b===void 0?void 0:b.enter;if(v=O?.call(e,l,d,p,f,h),v===mh)break;if(v===!1){if(!A){f.pop();continue}}else if(v!==void 0&&(u.push([d,v]),!A))if(go(v))l=v;else{f.pop();continue}}if(v===void 0&&g&&u.push([d,l]),A)f.pop();else{var I;i={inArray:s,index:c,keys:a,edits:u,prev:i},s=Array.isArray(l),a=s?l:(I=r[l.kind])!==null&&I!==void 0?I:[],c=-1,u=[],p&&h.push(p),p=l}}while(i!==void 0);return u.length!==0?u[u.length-1][1]:t}o(xr,"visit");function wi(t,e){let r=t[e];return typeof r=="object"?r:typeof r=="function"?{enter:r,leave:void 0}:{enter:t.enter,leave:t.leave}}o(wi,"getEnterLeaveForKind");function Be(t){return xr(t,C1)}o(Be,"print");var N1=80,C1={Name:{leave:t=>t.value},Variable:{leave:t=>"$"+t.name},Document:{leave:t=>q(t.definitions,`
101
+ spurious results.`)}}return!1},"instanceOf");var _i=class{static{o(this,"Source")}constructor(e,r="GraphQL request",n={line:1,column:1}){typeof e=="string"||X(!1,`Body must be a string. Received: ${U(e)}.`),this.body=e,this.name=r,this.locationOffset=n,this.locationOffset.line>0||X(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||X(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}};function Dw(t){return rt(t,_i)}o(Dw,"isSource");function gu(t,e){return new yu(t,e).parseDocument()}o(gu,"parse");function bu(t,e){let r=new yu(t,e);r.expectToken(R.SOF);let n=r.parseValueLiteral(!1);return r.expectToken(R.EOF),n}o(bu,"parseValue");var yu=class{static{o(this,"Parser")}constructor(e,r={}){let n=Dw(e)?e:new _i(e);this._lexer=new Eo(n),this._options=r,this._tokenCounter=0}parseName(){let e=this.expectToken(R.NAME);return this.node(e,{kind:S.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:S.DOCUMENT,definitions:this.many(R.SOF,this.parseDefinition,R.EOF)})}parseDefinition(){if(this.peek(R.BRACE_L))return this.parseOperationDefinition();let e=this.peekDescription(),r=e?this._lexer.lookahead():this._lexer.token;if(r.kind===R.NAME){switch(r.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}if(e)throw we(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(r.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(r)}parseOperationDefinition(){let e=this._lexer.token;if(this.peek(R.BRACE_L))return this.node(e,{kind:S.OPERATION_DEFINITION,operation:ft.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});let r=this.parseOperationType(),n;return this.peek(R.NAME)&&(n=this.parseName()),this.node(e,{kind:S.OPERATION_DEFINITION,operation:r,name:n,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){let e=this.expectToken(R.NAME);switch(e.value){case"query":return ft.QUERY;case"mutation":return ft.MUTATION;case"subscription":return ft.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(R.PAREN_L,this.parseVariableDefinition,R.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:S.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(R.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(R.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){let e=this._lexer.token;return this.expectToken(R.DOLLAR),this.node(e,{kind:S.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:S.SELECTION_SET,selections:this.many(R.BRACE_L,this.parseSelection,R.BRACE_R)})}parseSelection(){return this.peek(R.SPREAD)?this.parseFragment():this.parseField()}parseField(){let e=this._lexer.token,r=this.parseName(),n,i;return this.expectOptionalToken(R.COLON)?(n=r,i=this.parseName()):i=r,this.node(e,{kind:S.FIELD,alias:n,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(R.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){let r=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(R.PAREN_L,r,R.PAREN_R)}parseArgument(e=!1){let r=this._lexer.token,n=this.parseName();return this.expectToken(R.COLON),this.node(r,{kind:S.ARGUMENT,name:n,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){let e=this._lexer.token;this.expectToken(R.SPREAD);let r=this.expectOptionalKeyword("on");return!r&&this.peek(R.NAME)?this.node(e,{kind:S.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(e,{kind:S.INLINE_FRAGMENT,typeCondition:r?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){let e=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(e,{kind:S.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(e,{kind:S.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(e){let r=this._lexer.token;switch(r.kind){case R.BRACKET_L:return this.parseList(e);case R.BRACE_L:return this.parseObject(e);case R.INT:return this.advanceLexer(),this.node(r,{kind:S.INT,value:r.value});case R.FLOAT:return this.advanceLexer(),this.node(r,{kind:S.FLOAT,value:r.value});case R.STRING:case R.BLOCK_STRING:return this.parseStringLiteral();case R.NAME:switch(this.advanceLexer(),r.value){case"true":return this.node(r,{kind:S.BOOLEAN,value:!0});case"false":return this.node(r,{kind:S.BOOLEAN,value:!1});case"null":return this.node(r,{kind:S.NULL});default:return this.node(r,{kind:S.ENUM,value:r.value})}case R.DOLLAR:if(e)if(this.expectToken(R.DOLLAR),this._lexer.token.kind===R.NAME){let n=this._lexer.token.value;throw we(this._lexer.source,r.start,`Unexpected variable "$${n}" in constant value.`)}else throw this.unexpected(r);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){let e=this._lexer.token;return this.advanceLexer(),this.node(e,{kind:S.STRING,value:e.value,block:e.kind===R.BLOCK_STRING})}parseList(e){let r=o(()=>this.parseValueLiteral(e),"item");return this.node(this._lexer.token,{kind:S.LIST,values:this.any(R.BRACKET_L,r,R.BRACKET_R)})}parseObject(e){let r=o(()=>this.parseObjectField(e),"item");return this.node(this._lexer.token,{kind:S.OBJECT,fields:this.any(R.BRACE_L,r,R.BRACE_R)})}parseObjectField(e){let r=this._lexer.token,n=this.parseName();return this.expectToken(R.COLON),this.node(r,{kind:S.OBJECT_FIELD,name:n,value:this.parseValueLiteral(e)})}parseDirectives(e){let r=[];for(;this.peek(R.AT);)r.push(this.parseDirective(e));return r}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){let r=this._lexer.token;return this.expectToken(R.AT),this.node(r,{kind:S.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){let e=this._lexer.token,r;if(this.expectOptionalToken(R.BRACKET_L)){let n=this.parseTypeReference();this.expectToken(R.BRACKET_R),r=this.node(e,{kind:S.LIST_TYPE,type:n})}else r=this.parseNamedType();return this.expectOptionalToken(R.BANG)?this.node(e,{kind:S.NON_NULL_TYPE,type:r}):r}parseNamedType(){return this.node(this._lexer.token,{kind:S.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(R.STRING)||this.peek(R.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("schema");let n=this.parseConstDirectives(),i=this.many(R.BRACE_L,this.parseOperationTypeDefinition,R.BRACE_R);return this.node(e,{kind:S.SCHEMA_DEFINITION,description:r,directives:n,operationTypes:i})}parseOperationTypeDefinition(){let e=this._lexer.token,r=this.parseOperationType();this.expectToken(R.COLON);let n=this.parseNamedType();return this.node(e,{kind:S.OPERATION_TYPE_DEFINITION,operation:r,type:n})}parseScalarTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("scalar");let n=this.parseName(),i=this.parseConstDirectives();return this.node(e,{kind:S.SCALAR_TYPE_DEFINITION,description:r,name:n,directives:i})}parseObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("type");let n=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),a=this.parseFieldsDefinition();return this.node(e,{kind:S.OBJECT_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(R.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(R.BRACE_L,this.parseFieldDefinition,R.BRACE_R)}parseFieldDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName(),i=this.parseArgumentDefs();this.expectToken(R.COLON);let s=this.parseTypeReference(),a=this.parseConstDirectives();return this.node(e,{kind:S.FIELD_DEFINITION,description:r,name:n,arguments:i,type:s,directives:a})}parseArgumentDefs(){return this.optionalMany(R.PAREN_L,this.parseInputValueDef,R.PAREN_R)}parseInputValueDef(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName();this.expectToken(R.COLON);let i=this.parseTypeReference(),s;this.expectOptionalToken(R.EQUALS)&&(s=this.parseConstValueLiteral());let a=this.parseConstDirectives();return this.node(e,{kind:S.INPUT_VALUE_DEFINITION,description:r,name:n,type:i,defaultValue:s,directives:a})}parseInterfaceTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("interface");let n=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),a=this.parseFieldsDefinition();return this.node(e,{kind:S.INTERFACE_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseUnionTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("union");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseUnionMemberTypes();return this.node(e,{kind:S.UNION_TYPE_DEFINITION,description:r,name:n,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(R.EQUALS)?this.delimitedMany(R.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("enum");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseEnumValuesDefinition();return this.node(e,{kind:S.ENUM_TYPE_DEFINITION,description:r,name:n,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(R.BRACE_L,this.parseEnumValueDefinition,R.BRACE_R)}parseEnumValueDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(e,{kind:S.ENUM_VALUE_DEFINITION,description:r,name:n,directives:i})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw we(this._lexer.source,this._lexer.token.start,`${mu(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("input");let n=this.parseName(),i=this.parseConstDirectives(),s=this.parseInputFieldsDefinition();return this.node(e,{kind:S.INPUT_OBJECT_TYPE_DEFINITION,description:r,name:n,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(R.BRACE_L,this.parseInputValueDef,R.BRACE_R)}parseTypeSystemExtension(){let e=this._lexer.lookahead();if(e.kind===R.NAME)switch(e.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension()}throw this.unexpected(e)}parseSchemaExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");let r=this.parseConstDirectives(),n=this.optionalMany(R.BRACE_L,this.parseOperationTypeDefinition,R.BRACE_R);if(r.length===0&&n.length===0)throw this.unexpected();return this.node(e,{kind:S.SCHEMA_EXTENSION,directives:r,operationTypes:n})}parseScalarTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");let r=this.parseName(),n=this.parseConstDirectives();if(n.length===0)throw this.unexpected();return this.node(e,{kind:S.SCALAR_TYPE_EXTENSION,name:r,directives:n})}parseObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(n.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(e,{kind:S.OBJECT_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:s})}parseInterfaceTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(n.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(e,{kind:S.INTERFACE_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:s})}parseUnionTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseUnionMemberTypes();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.UNION_TYPE_EXTENSION,name:r,directives:n,types:i})}parseEnumTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.ENUM_TYPE_EXTENSION,name:r,directives:n,values:i})}parseInputObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();if(n.length===0&&i.length===0)throw this.unexpected();return this.node(e,{kind:S.INPUT_OBJECT_TYPE_EXTENSION,name:r,directives:n,fields:i})}parseDirectiveDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("directive"),this.expectToken(R.AT);let n=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");let a=this.parseDirectiveLocations();return this.node(e,{kind:S.DIRECTIVE_DEFINITION,description:r,name:n,arguments:i,repeatable:s,locations:a})}parseDirectiveLocations(){return this.delimitedMany(R.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){let e=this._lexer.token,r=this.parseName();if(Object.prototype.hasOwnProperty.call(ee,r.value))return r;throw this.unexpected(e)}node(e,r){return this._options.noLocation!==!0&&(r.loc=new yo(e,this._lexer.lastToken,this._lexer.source)),r}peek(e){return this._lexer.token.kind===e}expectToken(e){let r=this._lexer.token;if(r.kind===e)return this.advanceLexer(),r;throw we(this._lexer.source,r.start,`Expected ${Mw(e)}, found ${mu(r)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e?(this.advanceLexer(),!0):!1}expectKeyword(e){let r=this._lexer.token;if(r.kind===R.NAME&&r.value===e)this.advanceLexer();else throw we(this._lexer.source,r.start,`Expected "${e}", found ${mu(r)}.`)}expectOptionalKeyword(e){let r=this._lexer.token;return r.kind===R.NAME&&r.value===e?(this.advanceLexer(),!0):!1}unexpected(e){let r=e??this._lexer.token;return we(this._lexer.source,r.start,`Unexpected ${mu(r)}.`)}any(e,r,n){this.expectToken(e);let i=[];for(;!this.expectOptionalToken(n);)i.push(r.call(this));return i}optionalMany(e,r,n){if(this.expectOptionalToken(e)){let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}return[]}many(e,r,n){this.expectToken(e);let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}delimitedMany(e,r){this.expectOptionalToken(e);let n=[];do n.push(r.call(this));while(this.expectOptionalToken(e));return n}advanceLexer(){let{maxTokens:e}=this._options,r=this._lexer.advance();if(e!==void 0&&r.kind!==R.EOF&&(++this._tokenCounter,this._tokenCounter>e))throw we(this._lexer.source,r.start,`Document contains more that ${e} tokens. Parsing aborted.`)}};function mu(t){let e=t.value;return Mw(t.kind)+(e!=null?` "${e}"`:"")}o(mu,"getTokenDesc");function Mw(t){return Cw(t)?`"${t}"`:t}o(Mw,"getTokenKindDesc");function _u(t,e){let[r,n]=e?[t,e]:[void 0,t],i=" Did you mean ";r&&(i+=r+" ");let s=n.map(u=>`"${u}"`);switch(s.length){case 0:return"";case 1:return i+s[0]+"?";case 2:return i+s[0]+" or "+s[1]+"?"}let a=s.slice(0,5),c=a.pop();return i+a.join(", ")+", or "+c+"?"}o(_u,"didYouMean");function ph(t){return t}o(ph,"identityFunc");function Ei(t,e){let r=Object.create(null);for(let n of t)r[e(n)]=n;return r}o(Ei,"keyMap");function qt(t,e,r){let n=Object.create(null);for(let i of t)n[e(i)]=r(i);return n}o(qt,"keyValMap");function wo(t,e){let r=Object.create(null);for(let n of Object.keys(t))r[n]=e(t[n],n);return r}o(wo,"mapValue");function Uw(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let i=t.charCodeAt(r),s=e.charCodeAt(n);if(Eu(i)&&Eu(s)){let a=0;do++r,a=a*10+i-fh,i=t.charCodeAt(r);while(Eu(i)&&a>0);let c=0;do++n,c=c*10+s-fh,s=e.charCodeAt(n);while(Eu(s)&&c>0);if(a<c)return-1;if(a>c)return 1}else{if(i<s)return-1;if(i>s)return 1;++r,++n}}return t.length-e.length}o(Uw,"naturalCompare");var fh=48,R1=57;function Eu(t){return!isNaN(t)&&fh<=t&&t<=R1}o(Eu,"isDigit");function wu(t,e){let r=Object.create(null),n=new hh(t),i=Math.floor(t.length*.4)+1;for(let s of e){let a=n.measure(s,i);a!==void 0&&(r[s]=a)}return Object.keys(r).sort((s,a)=>{let c=r[s]-r[a];return c!==0?c:Uw(s,a)})}o(wu,"suggestionList");var hh=class{static{o(this,"LexicalDistance")}constructor(e){this._input=e,this._inputLowerCase=e.toLowerCase(),this._inputArray=kw(this._inputLowerCase),this._rows=[new Array(e.length+1).fill(0),new Array(e.length+1).fill(0),new Array(e.length+1).fill(0)]}measure(e,r){if(this._input===e)return 0;let n=e.toLowerCase();if(this._inputLowerCase===n)return 1;let i=kw(n),s=this._inputArray;if(i.length<s.length){let d=i;i=s,s=d}let a=i.length,c=s.length;if(a-c>r)return;let u=this._rows;for(let d=0;d<=c;d++)u[0][d]=d;for(let d=1;d<=a;d++){let p=u[(d-1)%3],f=u[d%3],h=f[0]=d;for(let y=1;y<=c;y++){let b=i[d-1]===s[y-1]?0:1,I=Math.min(p[y]+1,f[y-1]+1,p[y-1]+b);if(d>1&&y>1&&i[d-1]===s[y-2]&&i[d-2]===s[y-1]){let A=u[(d-2)%3][y-2];I=Math.min(I,A+1)}I<h&&(h=I),f[y]=I}if(h>r)return}let l=u[a%3][c];return l<=r?l:void 0}};function kw(t){let e=t.length,r=new Array(e);for(let n=0;n<e;++n)r[n]=t.charCodeAt(n);return r}o(kw,"stringToArray");function Ve(t){if(t==null)return Object.create(null);if(Object.getPrototypeOf(t)===null)return t;let e=Object.create(null);for(let[r,n]of Object.entries(t))e[r]=n;return e}o(Ve,"toObjMap");function Fw(t){return`"${t.replace(O1,N1)}"`}o(Fw,"printString");var O1=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function N1(t){return C1[t.charCodeAt(0)]}o(N1,"escapedReplacer");var C1=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"];var mh=Object.freeze({});function xr(t,e,r=lh){let n=new Map;for(let A of Object.values(S))n.set(A,wi(e,A));let i,s=Array.isArray(t),a=[t],c=-1,u=[],l=t,d,p,f=[],h=[];do{c++;let A=c===a.length,g=A&&u.length!==0;if(A){if(d=h.length===0?void 0:f[f.length-1],l=p,p=h.pop(),g)if(s){l=l.slice();let O=0;for(let[V,E]of u){let T=V-O;E===null?(l.splice(T,1),O++):l[T]=E}}else{l=Object.defineProperties({},Object.getOwnPropertyDescriptors(l));for(let[O,V]of u)l[O]=V}c=i.index,a=i.keys,u=i.edits,s=i.inArray,i=i.prev}else if(p){if(d=s?c:a[c],l=p[d],l==null)continue;f.push(d)}let v;if(!Array.isArray(l)){var y,b;go(l)||X(!1,`Invalid AST Node: ${U(l)}.`);let O=A?(y=n.get(l.kind))===null||y===void 0?void 0:y.leave:(b=n.get(l.kind))===null||b===void 0?void 0:b.enter;if(v=O?.call(e,l,d,p,f,h),v===mh)break;if(v===!1){if(!A){f.pop();continue}}else if(v!==void 0&&(u.push([d,v]),!A))if(go(v))l=v;else{f.pop();continue}}if(v===void 0&&g&&u.push([d,l]),A)f.pop();else{var I;i={inArray:s,index:c,keys:a,edits:u,prev:i},s=Array.isArray(l),a=s?l:(I=r[l.kind])!==null&&I!==void 0?I:[],c=-1,u=[],p&&h.push(p),p=l}}while(i!==void 0);return u.length!==0?u[u.length-1][1]:t}o(xr,"visit");function wi(t,e){let r=t[e];return typeof r=="object"?r:typeof r=="function"?{enter:r,leave:void 0}:{enter:t.enter,leave:t.leave}}o(wi,"getEnterLeaveForKind");function Be(t){return xr(t,L1)}o(Be,"print");var x1=80,L1={Name:{leave:t=>t.value},Variable:{leave:t=>"$"+t.name},Document:{leave:t=>q(t.definitions,`
102
102
 
103
- `)},OperationDefinition:{leave(t){let e=re("(",q(t.variableDefinitions,", "),")"),r=q([t.operation,q([t.name,e]),q(t.directives," ")]," ");return(r==="query"?"":r+" ")+t.selectionSet}},VariableDefinition:{leave:({variable:t,type:e,defaultValue:r,directives:n})=>t+": "+e+re(" = ",r)+re(" ",q(n," "))},SelectionSet:{leave:({selections:t})=>St(t)},Field:{leave({alias:t,name:e,arguments:r,directives:n,selectionSet:i}){let s=re("",t,": ")+e,a=s+re("(",q(r,", "),")");return a.length>N1&&(a=s+re(`(
103
+ `)},OperationDefinition:{leave(t){let e=ne("(",q(t.variableDefinitions,", "),")"),r=q([t.operation,q([t.name,e]),q(t.directives," ")]," ");return(r==="query"?"":r+" ")+t.selectionSet}},VariableDefinition:{leave:({variable:t,type:e,defaultValue:r,directives:n})=>t+": "+e+ne(" = ",r)+ne(" ",q(n," "))},SelectionSet:{leave:({selections:t})=>St(t)},Field:{leave({alias:t,name:e,arguments:r,directives:n,selectionSet:i}){let s=ne("",t,": ")+e,a=s+ne("(",q(r,", "),")");return a.length>x1&&(a=s+ne(`(
104
104
  `,vu(q(r,`
105
105
  `)),`
106
- )`)),q([a,q(n," "),i]," ")}},Argument:{leave:({name:t,value:e})=>t+": "+e},FragmentSpread:{leave:({name:t,directives:e})=>"..."+t+re(" ",q(e," "))},InlineFragment:{leave:({typeCondition:t,directives:e,selectionSet:r})=>q(["...",re("on ",t),q(e," "),r]," ")},FragmentDefinition:{leave:({name:t,typeCondition:e,variableDefinitions:r,directives:n,selectionSet:i})=>`fragment ${t}${re("(",q(r,", "),")")} on ${e} ${re("",q(n," ")," ")}`+i},IntValue:{leave:({value:t})=>t},FloatValue:{leave:({value:t})=>t},StringValue:{leave:({value:t,block:e})=>e?Ow(t):Fw(t)},BooleanValue:{leave:({value:t})=>t?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:t})=>t},ListValue:{leave:({values:t})=>"["+q(t,", ")+"]"},ObjectValue:{leave:({fields:t})=>"{"+q(t,", ")+"}"},ObjectField:{leave:({name:t,value:e})=>t+": "+e},Directive:{leave:({name:t,arguments:e})=>"@"+t+re("(",q(e,", "),")")},NamedType:{leave:({name:t})=>t},ListType:{leave:({type:t})=>"["+t+"]"},NonNullType:{leave:({type:t})=>t+"!"},SchemaDefinition:{leave:({description:t,directives:e,operationTypes:r})=>re("",t,`
107
- `)+q(["schema",q(e," "),St(r)]," ")},OperationTypeDefinition:{leave:({operation:t,type:e})=>t+": "+e},ScalarTypeDefinition:{leave:({description:t,name:e,directives:r})=>re("",t,`
108
- `)+q(["scalar",e,q(r," ")]," ")},ObjectTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>re("",t,`
109
- `)+q(["type",e,re("implements ",q(r," & ")),q(n," "),St(i)]," ")},FieldDefinition:{leave:({description:t,name:e,arguments:r,type:n,directives:i})=>re("",t,`
110
- `)+e+(Hw(r)?re(`(
106
+ )`)),q([a,q(n," "),i]," ")}},Argument:{leave:({name:t,value:e})=>t+": "+e},FragmentSpread:{leave:({name:t,directives:e})=>"..."+t+ne(" ",q(e," "))},InlineFragment:{leave:({typeCondition:t,directives:e,selectionSet:r})=>q(["...",ne("on ",t),q(e," "),r]," ")},FragmentDefinition:{leave:({name:t,typeCondition:e,variableDefinitions:r,directives:n,selectionSet:i})=>`fragment ${t}${ne("(",q(r,", "),")")} on ${e} ${ne("",q(n," ")," ")}`+i},IntValue:{leave:({value:t})=>t},FloatValue:{leave:({value:t})=>t},StringValue:{leave:({value:t,block:e})=>e?Ow(t):Fw(t)},BooleanValue:{leave:({value:t})=>t?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:t})=>t},ListValue:{leave:({values:t})=>"["+q(t,", ")+"]"},ObjectValue:{leave:({fields:t})=>"{"+q(t,", ")+"}"},ObjectField:{leave:({name:t,value:e})=>t+": "+e},Directive:{leave:({name:t,arguments:e})=>"@"+t+ne("(",q(e,", "),")")},NamedType:{leave:({name:t})=>t},ListType:{leave:({type:t})=>"["+t+"]"},NonNullType:{leave:({type:t})=>t+"!"},SchemaDefinition:{leave:({description:t,directives:e,operationTypes:r})=>ne("",t,`
107
+ `)+q(["schema",q(e," "),St(r)]," ")},OperationTypeDefinition:{leave:({operation:t,type:e})=>t+": "+e},ScalarTypeDefinition:{leave:({description:t,name:e,directives:r})=>ne("",t,`
108
+ `)+q(["scalar",e,q(r," ")]," ")},ObjectTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>ne("",t,`
109
+ `)+q(["type",e,ne("implements ",q(r," & ")),q(n," "),St(i)]," ")},FieldDefinition:{leave:({description:t,name:e,arguments:r,type:n,directives:i})=>ne("",t,`
110
+ `)+e+(Hw(r)?ne(`(
111
111
  `,vu(q(r,`
112
112
  `)),`
113
- )`):re("(",q(r,", "),")"))+": "+n+re(" ",q(i," "))},InputValueDefinition:{leave:({description:t,name:e,type:r,defaultValue:n,directives:i})=>re("",t,`
114
- `)+q([e+": "+r,re("= ",n),q(i," ")]," ")},InterfaceTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>re("",t,`
115
- `)+q(["interface",e,re("implements ",q(r," & ")),q(n," "),St(i)]," ")},UnionTypeDefinition:{leave:({description:t,name:e,directives:r,types:n})=>re("",t,`
116
- `)+q(["union",e,q(r," "),re("= ",q(n," | "))]," ")},EnumTypeDefinition:{leave:({description:t,name:e,directives:r,values:n})=>re("",t,`
117
- `)+q(["enum",e,q(r," "),St(n)]," ")},EnumValueDefinition:{leave:({description:t,name:e,directives:r})=>re("",t,`
118
- `)+q([e,q(r," ")]," ")},InputObjectTypeDefinition:{leave:({description:t,name:e,directives:r,fields:n})=>re("",t,`
119
- `)+q(["input",e,q(r," "),St(n)]," ")},DirectiveDefinition:{leave:({description:t,name:e,arguments:r,repeatable:n,locations:i})=>re("",t,`
120
- `)+"directive @"+e+(Hw(r)?re(`(
113
+ )`):ne("(",q(r,", "),")"))+": "+n+ne(" ",q(i," "))},InputValueDefinition:{leave:({description:t,name:e,type:r,defaultValue:n,directives:i})=>ne("",t,`
114
+ `)+q([e+": "+r,ne("= ",n),q(i," ")]," ")},InterfaceTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>ne("",t,`
115
+ `)+q(["interface",e,ne("implements ",q(r," & ")),q(n," "),St(i)]," ")},UnionTypeDefinition:{leave:({description:t,name:e,directives:r,types:n})=>ne("",t,`
116
+ `)+q(["union",e,q(r," "),ne("= ",q(n," | "))]," ")},EnumTypeDefinition:{leave:({description:t,name:e,directives:r,values:n})=>ne("",t,`
117
+ `)+q(["enum",e,q(r," "),St(n)]," ")},EnumValueDefinition:{leave:({description:t,name:e,directives:r})=>ne("",t,`
118
+ `)+q([e,q(r," ")]," ")},InputObjectTypeDefinition:{leave:({description:t,name:e,directives:r,fields:n})=>ne("",t,`
119
+ `)+q(["input",e,q(r," "),St(n)]," ")},DirectiveDefinition:{leave:({description:t,name:e,arguments:r,repeatable:n,locations:i})=>ne("",t,`
120
+ `)+"directive @"+e+(Hw(r)?ne(`(
121
121
  `,vu(q(r,`
122
122
  `)),`
123
- )`):re("(",q(r,", "),")"))+(n?" repeatable":"")+" on "+q(i," | ")},SchemaExtension:{leave:({directives:t,operationTypes:e})=>q(["extend schema",q(t," "),St(e)]," ")},ScalarTypeExtension:{leave:({name:t,directives:e})=>q(["extend scalar",t,q(e," ")]," ")},ObjectTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>q(["extend type",t,re("implements ",q(e," & ")),q(r," "),St(n)]," ")},InterfaceTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>q(["extend interface",t,re("implements ",q(e," & ")),q(r," "),St(n)]," ")},UnionTypeExtension:{leave:({name:t,directives:e,types:r})=>q(["extend union",t,q(e," "),re("= ",q(r," | "))]," ")},EnumTypeExtension:{leave:({name:t,directives:e,values:r})=>q(["extend enum",t,q(e," "),St(r)]," ")},InputObjectTypeExtension:{leave:({name:t,directives:e,fields:r})=>q(["extend input",t,q(e," "),St(r)]," ")}};function q(t,e=""){var r;return(r=t?.filter(n=>n).join(e))!==null&&r!==void 0?r:""}o(q,"join");function St(t){return re(`{
123
+ )`):ne("(",q(r,", "),")"))+(n?" repeatable":"")+" on "+q(i," | ")},SchemaExtension:{leave:({directives:t,operationTypes:e})=>q(["extend schema",q(t," "),St(e)]," ")},ScalarTypeExtension:{leave:({name:t,directives:e})=>q(["extend scalar",t,q(e," ")]," ")},ObjectTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>q(["extend type",t,ne("implements ",q(e," & ")),q(r," "),St(n)]," ")},InterfaceTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>q(["extend interface",t,ne("implements ",q(e," & ")),q(r," "),St(n)]," ")},UnionTypeExtension:{leave:({name:t,directives:e,types:r})=>q(["extend union",t,q(e," "),ne("= ",q(r," | "))]," ")},EnumTypeExtension:{leave:({name:t,directives:e,values:r})=>q(["extend enum",t,q(e," "),St(r)]," ")},InputObjectTypeExtension:{leave:({name:t,directives:e,fields:r})=>q(["extend input",t,q(e," "),St(r)]," ")}};function q(t,e=""){var r;return(r=t?.filter(n=>n).join(e))!==null&&r!==void 0?r:""}o(q,"join");function St(t){return ne(`{
124
124
  `,vu(q(t,`
125
125
  `)),`
126
- }`)}o(St,"block");function re(t,e,r=""){return e!=null&&e!==""?t+e+r:""}o(re,"wrap");function vu(t){return re(" ",t.replace(/\n/g,`
126
+ }`)}o(St,"block");function ne(t,e,r=""){return e!=null&&e!==""?t+e+r:""}o(ne,"wrap");function vu(t){return ne(" ",t.replace(/\n/g,`
127
127
  `))}o(vu,"indent");function Hw(t){var e;return(e=t?.some(r=>r.includes(`
128
- `)))!==null&&e!==void 0?e:!1}o(Hw,"hasMultilineItems");function vo(t,e){switch(t.kind){case S.NULL:return null;case S.INT:return parseInt(t.value,10);case S.FLOAT:return parseFloat(t.value);case S.STRING:case S.ENUM:case S.BOOLEAN:return t.value;case S.LIST:return t.values.map(r=>vo(r,e));case S.OBJECT:return qt(t.fields,r=>r.name.value,r=>vo(r.value,e));case S.VARIABLE:return e?.[t.name.value]}}o(vo,"valueFromASTUntyped");function Ze(t){if(t!=null||X(!1,"Must provide name."),typeof t=="string"||X(!1,"Expected name to be a string."),t.length===0)throw new $("Expected name to be a non-empty string.");for(let e=1;e<t.length;++e)if(!pu(t.charCodeAt(e)))throw new $(`Names must only contain [_a-zA-Z0-9] but "${t}" does not.`);if(!bo(t.charCodeAt(0)))throw new $(`Names must start with [_a-zA-Z] but "${t}" does not.`);return t}o(Ze,"assertName");function yh(t){if(t==="true"||t==="false"||t==="null")throw new $(`Enum values cannot be named: ${t}`);return Ze(t)}o(yh,"assertEnumValueName");function Su(t){return Lr(t)||qe(t)||Ce(t)||ht(t)||it(t)||Ue(t)||Xe(t)||ye(t)}o(Su,"isType");function Lr(t){return rt(t,nt)}o(Lr,"isScalarType");function qe(t){return rt(t,He)}o(qe,"isObjectType");function Iu(t){if(!qe(t))throw new Error(`Expected ${U(t)} to be a GraphQL Object type.`);return t}o(Iu,"assertObjectType");function Ce(t){return rt(t,er)}o(Ce,"isInterfaceType");function Pu(t){if(!Ce(t))throw new Error(`Expected ${U(t)} to be a GraphQL Interface type.`);return t}o(Pu,"assertInterfaceType");function ht(t){return rt(t,dn)}o(ht,"isUnionType");function it(t){return rt(t,$t)}o(it,"isEnumType");function Ue(t){return rt(t,pn)}o(Ue,"isInputObjectType");function Xe(t){return rt(t,ve)}o(Xe,"isListType");function ye(t){return rt(t,Q)}o(ye,"isNonNullType");function ot(t){return Lr(t)||it(t)||Ue(t)||To(t)&&ot(t.ofType)}o(ot,"isInputType");function tr(t){return Lr(t)||qe(t)||Ce(t)||ht(t)||it(t)||To(t)&&tr(t.ofType)}o(tr,"isOutputType");function Dr(t){return Lr(t)||it(t)}o(Dr,"isLeafType");function jt(t){return qe(t)||Ce(t)||ht(t)}o(jt,"isCompositeType");function Mr(t){return Ce(t)||ht(t)}o(Mr,"isAbstractType");var ve=class{static{o(this,"GraphQLList")}constructor(e){Su(e)||X(!1,`Expected ${U(e)} to be a GraphQL type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLList"}toString(){return"["+String(this.ofType)+"]"}toJSON(){return this.toString()}},Q=class{static{o(this,"GraphQLNonNull")}constructor(e){Au(e)||X(!1,`Expected ${U(e)} to be a GraphQL nullable type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLNonNull"}toString(){return String(this.ofType)+"!"}toJSON(){return this.toString()}};function To(t){return Xe(t)||ye(t)}o(To,"isWrappingType");function Au(t){return Su(t)&&!ye(t)}o(Au,"isNullableType");function Ru(t){if(!Au(t))throw new Error(`Expected ${U(t)} to be a GraphQL nullable type.`);return t}o(Ru,"assertNullableType");function Ou(t){if(t)return ye(t)?t.ofType:t}o(Ou,"getNullableType");function It(t){if(t){let e=t;for(;To(e);)e=e.ofType;return e}}o(It,"getNamedType");function Nu(t){return typeof t=="function"?t():t}o(Nu,"resolveReadonlyArrayThunk");function Cu(t){return typeof t=="function"?t():t}o(Cu,"resolveObjMapThunk");var nt=class{static{o(this,"GraphQLScalarType")}constructor(e){var r,n,i,s;let a=(r=e.parseValue)!==null&&r!==void 0?r:ph;this.name=Ze(e.name),this.description=e.description,this.specifiedByURL=e.specifiedByURL,this.serialize=(n=e.serialize)!==null&&n!==void 0?n:ph,this.parseValue=a,this.parseLiteral=(i=e.parseLiteral)!==null&&i!==void 0?i:(c,u)=>a(vo(c,u)),this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(s=e.extensionASTNodes)!==null&&s!==void 0?s:[],e.specifiedByURL==null||typeof e.specifiedByURL=="string"||X(!1,`${this.name} must provide "specifiedByURL" as a string, but got: ${U(e.specifiedByURL)}.`),e.serialize==null||typeof e.serialize=="function"||X(!1,`${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`),e.parseLiteral&&(typeof e.parseValue=="function"&&typeof e.parseLiteral=="function"||X(!1,`${this.name} must provide both "parseValue" and "parseLiteral" functions.`))}get[Symbol.toStringTag](){return"GraphQLScalarType"}toConfig(){return{name:this.name,description:this.description,specifiedByURL:this.specifiedByURL,serialize:this.serialize,parseValue:this.parseValue,parseLiteral:this.parseLiteral,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},He=class{static{o(this,"GraphQLObjectType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.isTypeOf=e.isTypeOf,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=()=>$w(e),this._interfaces=()=>qw(e),e.isTypeOf==null||typeof e.isTypeOf=="function"||X(!1,`${this.name} must provide "isTypeOf" as a function, but got: ${U(e.isTypeOf)}.`)}get[Symbol.toStringTag](){return"GraphQLObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return{name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:jw(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function qw(t){var e;let r=Nu((e=t.interfaces)!==null&&e!==void 0?e:[]);return Array.isArray(r)||X(!1,`${t.name} interfaces must be an Array or a function which returns an Array.`),r}o(qw,"defineInterfaces");function $w(t){let e=Cu(t.fields);return vi(e)||X(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),wo(e,(r,n)=>{var i;vi(r)||X(!1,`${t.name}.${n} field config must be an object.`),r.resolve==null||typeof r.resolve=="function"||X(!1,`${t.name}.${n} field resolver must be a function if provided, but got: ${U(r.resolve)}.`);let s=(i=r.args)!==null&&i!==void 0?i:{};return vi(s)||X(!1,`${t.name}.${n} args must be an object with argument names as keys.`),{name:Ze(n),description:r.description,type:r.type,args:gh(s),resolve:r.resolve,subscribe:r.subscribe,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}})}o($w,"defineFieldMap");function gh(t){return Object.entries(t).map(([e,r])=>({name:Ze(e),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}))}o(gh,"defineArguments");function vi(t){return Ne(t)&&!Array.isArray(t)}o(vi,"isPlainObj");function jw(t){return wo(t,e=>({description:e.description,type:e.type,args:bh(e.args),resolve:e.resolve,subscribe:e.subscribe,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(jw,"fieldsToFieldsConfig");function bh(t){return qt(t,e=>e.name,e=>({description:e.description,type:e.type,defaultValue:e.defaultValue,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(bh,"argsToArgsConfig");var er=class{static{o(this,"GraphQLInterfaceType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=$w.bind(void 0,e),this._interfaces=qw.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||X(!1,`${this.name} must provide "resolveType" as a function, but got: ${U(e.resolveType)}.`)}get[Symbol.toStringTag](){return"GraphQLInterfaceType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return{name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:jw(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},dn=class{static{o(this,"GraphQLUnionType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._types=x1.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||X(!1,`${this.name} must provide "resolveType" as a function, but got: ${U(e.resolveType)}.`)}get[Symbol.toStringTag](){return"GraphQLUnionType"}getTypes(){return typeof this._types=="function"&&(this._types=this._types()),this._types}toConfig(){return{name:this.name,description:this.description,types:this.getTypes(),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function x1(t){let e=Nu(t.types);return Array.isArray(e)||X(!1,`Must provide Array of types or a function which returns such an array for Union ${t.name}.`),e}o(x1,"defineTypes");var $t=class{static{o(this,"GraphQLEnumType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._values=L1(this.name,e.values),this._valueLookup=new Map(this._values.map(n=>[n.value,n])),this._nameLookup=Ei(this._values,n=>n.name)}get[Symbol.toStringTag](){return"GraphQLEnumType"}getValues(){return this._values}getValue(e){return this._nameLookup[e]}serialize(e){let r=this._valueLookup.get(e);if(r===void 0)throw new $(`Enum "${this.name}" cannot represent value: ${U(e)}`);return r.name}parseValue(e){if(typeof e!="string"){let n=U(e);throw new $(`Enum "${this.name}" cannot represent non-string value: ${n}.`+Tu(this,n))}let r=this.getValue(e);if(r==null)throw new $(`Value "${e}" does not exist in "${this.name}" enum.`+Tu(this,e));return r.value}parseLiteral(e,r){if(e.kind!==S.ENUM){let i=Be(e);throw new $(`Enum "${this.name}" cannot represent non-enum value: ${i}.`+Tu(this,i),{nodes:e})}let n=this.getValue(e.value);if(n==null){let i=Be(e);throw new $(`Value "${i}" does not exist in "${this.name}" enum.`+Tu(this,i),{nodes:e})}return n.value}toConfig(){let e=qt(this.getValues(),r=>r.name,r=>({description:r.description,value:r.value,deprecationReason:r.deprecationReason,extensions:r.extensions,astNode:r.astNode}));return{name:this.name,description:this.description,values:e,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function Tu(t,e){let r=t.getValues().map(i=>i.name),n=wu(e,r);return _u("the enum value",n)}o(Tu,"didYouMeanEnumValue");function L1(t,e){return vi(e)||X(!1,`${t} values must be an object with value names as keys.`),Object.entries(e).map(([r,n])=>(vi(n)||X(!1,`${t}.${r} must refer to an object with a "value" key representing an internal value but got: ${U(n)}.`),{name:yh(r),description:n.description,value:n.value!==void 0?n.value:r,deprecationReason:n.deprecationReason,extensions:Ve(n.extensions),astNode:n.astNode}))}o(L1,"defineEnumValues");var pn=class{static{o(this,"GraphQLInputObjectType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=D1.bind(void 0,e)}get[Symbol.toStringTag](){return"GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let e=wo(this.getFields(),r=>({description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:r.extensions,astNode:r.astNode}));return{name:this.name,description:this.description,fields:e,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function D1(t){let e=Cu(t.fields);return vi(e)||X(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),wo(e,(r,n)=>(!("resolve"in r)||X(!1,`${t.name}.${n} field has a resolve property, but Input Types cannot define resolvers.`),{name:Ze(n),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}))}o(D1,"defineInputFieldMap");var xu=2147483647,Lu=-2147483648,_h=new nt({name:"Int",description:"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.",serialize(t){let e=So(t);if(typeof e=="boolean")return e?1:0;let r=e;if(typeof e=="string"&&e!==""&&(r=Number(e)),typeof r!="number"||!Number.isInteger(r))throw new $(`Int cannot represent non-integer value: ${U(e)}`);if(r>xu||r<Lu)throw new $("Int cannot represent non 32-bit signed integer value: "+U(e));return r},parseValue(t){if(typeof t!="number"||!Number.isInteger(t))throw new $(`Int cannot represent non-integer value: ${U(t)}`);if(t>xu||t<Lu)throw new $(`Int cannot represent non 32-bit signed integer value: ${t}`);return t},parseLiteral(t){if(t.kind!==S.INT)throw new $(`Int cannot represent non-integer value: ${Be(t)}`,{nodes:t});let e=parseInt(t.value,10);if(e>xu||e<Lu)throw new $(`Int cannot represent non 32-bit signed integer value: ${t.value}`,{nodes:t});return e}}),Vw=new nt({name:"Float",description:"The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).",serialize(t){let e=So(t);if(typeof e=="boolean")return e?1:0;let r=e;if(typeof e=="string"&&e!==""&&(r=Number(e)),typeof r!="number"||!Number.isFinite(r))throw new $(`Float cannot represent non numeric value: ${U(e)}`);return r},parseValue(t){if(typeof t!="number"||!Number.isFinite(t))throw new $(`Float cannot represent non numeric value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.FLOAT&&t.kind!==S.INT)throw new $(`Float cannot represent non numeric value: ${Be(t)}`,t);return parseFloat(t.value)}}),he=new nt({name:"String",description:"The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.",serialize(t){let e=So(t);if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"&&Number.isFinite(e))return e.toString();throw new $(`String cannot represent value: ${U(t)}`)},parseValue(t){if(typeof t!="string")throw new $(`String cannot represent a non string value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.STRING)throw new $(`String cannot represent a non string value: ${Be(t)}`,{nodes:t});return t.value}}),Ge=new nt({name:"Boolean",description:"The `Boolean` scalar type represents `true` or `false`.",serialize(t){let e=So(t);if(typeof e=="boolean")return e;if(Number.isFinite(e))return e!==0;throw new $(`Boolean cannot represent a non boolean value: ${U(e)}`)},parseValue(t){if(typeof t!="boolean")throw new $(`Boolean cannot represent a non boolean value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.BOOLEAN)throw new $(`Boolean cannot represent a non boolean value: ${Be(t)}`,{nodes:t});return t.value}}),Du=new nt({name:"ID",description:'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',serialize(t){let e=So(t);if(typeof e=="string")return e;if(Number.isInteger(e))return String(e);throw new $(`ID cannot represent value: ${U(t)}`)},parseValue(t){if(typeof t=="string")return t;if(typeof t=="number"&&Number.isInteger(t))return t.toString();throw new $(`ID cannot represent value: ${U(t)}`)},parseLiteral(t){if(t.kind!==S.STRING&&t.kind!==S.INT)throw new $("ID cannot represent a non-string and non-integer value: "+Be(t),{nodes:t});return t.value}}),Eh=Object.freeze([he,_h,Vw,Ge,Du]);function So(t){if(Ne(t)){if(typeof t.valueOf=="function"){let e=t.valueOf();if(!Ne(e))return e}if(typeof t.toJSON=="function")return t.toJSON()}return t}o(So,"serializeObject");function wh(t){return rt(t,Pt)}o(wh,"isDirective");var Pt=class{static{o(this,"GraphQLDirective")}constructor(e){var r,n;this.name=Ze(e.name),this.description=e.description,this.locations=e.locations,this.isRepeatable=(r=e.isRepeatable)!==null&&r!==void 0?r:!1,this.extensions=Ve(e.extensions),this.astNode=e.astNode,Array.isArray(e.locations)||X(!1,`@${e.name} locations must be an Array.`);let i=(n=e.args)!==null&&n!==void 0?n:{};Ne(i)&&!Array.isArray(i)||X(!1,`@${e.name} args must be an object with argument names as keys.`),this.args=gh(i)}get[Symbol.toStringTag](){return"GraphQLDirective"}toConfig(){return{name:this.name,description:this.description,locations:this.locations,args:bh(this.args),isRepeatable:this.isRepeatable,extensions:this.extensions,astNode:this.astNode}}toString(){return"@"+this.name}toJSON(){return this.toString()}},Bw=new Pt({name:"include",description:"Directs the executor to include this field or fragment only when the `if` argument is true.",locations:[ee.FIELD,ee.FRAGMENT_SPREAD,ee.INLINE_FRAGMENT],args:{if:{type:new Q(Ge),description:"Included when true."}}}),Gw=new Pt({name:"skip",description:"Directs the executor to skip this field or fragment when the `if` argument is true.",locations:[ee.FIELD,ee.FRAGMENT_SPREAD,ee.INLINE_FRAGMENT],args:{if:{type:new Q(Ge),description:"Skipped when true."}}}),Kw="No longer supported",Jw=new Pt({name:"deprecated",description:"Marks an element of a GraphQL schema as no longer supported.",locations:[ee.FIELD_DEFINITION,ee.ARGUMENT_DEFINITION,ee.INPUT_FIELD_DEFINITION,ee.ENUM_VALUE],args:{reason:{type:he,description:"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).",defaultValue:Kw}}}),zw=new Pt({name:"specifiedBy",description:"Exposes a URL that specifies the behavior of this scalar.",locations:[ee.SCALAR],args:{url:{type:new Q(he),description:"The URL that specifies the behavior of this scalar."}}}),vh=Object.freeze([Bw,Gw,Jw,zw]);function Mu(t){return typeof t=="object"&&typeof t?.[Symbol.iterator]=="function"}o(Mu,"isIterableObject");function fn(t,e){if(ye(e)){let r=fn(t,e.ofType);return r?.kind===S.NULL?null:r}if(t===null)return{kind:S.NULL};if(t===void 0)return null;if(Xe(e)){let r=e.ofType;if(Mu(t)){let n=[];for(let i of t){let s=fn(i,r);s!=null&&n.push(s)}return{kind:S.LIST,values:n}}return fn(t,r)}if(Ue(e)){if(!Ne(t))return null;let r=[];for(let n of Object.values(e.getFields())){let i=fn(t[n.name],n.type);i&&r.push({kind:S.OBJECT_FIELD,name:{kind:S.NAME,value:n.name},value:i})}return{kind:S.OBJECT,fields:r}}if(Dr(e)){let r=e.serialize(t);if(r==null)return null;if(typeof r=="boolean")return{kind:S.BOOLEAN,value:r};if(typeof r=="number"&&Number.isFinite(r)){let n=String(r);return Ww.test(n)?{kind:S.INT,value:n}:{kind:S.FLOAT,value:n}}if(typeof r=="string")return it(e)?{kind:S.ENUM,value:r}:e===Du&&Ww.test(r)?{kind:S.INT,value:r}:{kind:S.STRING,value:r};throw new TypeError(`Cannot convert value to AST: ${U(r)}.`)}Ht(!1,"Unexpected input type: "+U(e))}o(fn,"astFromValue");var Ww=/^-?(?:0|[1-9][0-9]*)$/;var Io=new He({name:"__Schema",description:"A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.",fields:()=>({description:{type:he,resolve:t=>t.description},types:{description:"A list of all types supported by this server.",type:new Q(new ve(new Q(mt))),resolve(t){return Object.values(t.getTypeMap())}},queryType:{description:"The type that query operations will be rooted at.",type:new Q(mt),resolve:t=>t.getQueryType()},mutationType:{description:"If this server supports mutation, the type that mutation operations will be rooted at.",type:mt,resolve:t=>t.getMutationType()},subscriptionType:{description:"If this server support subscription, the type that subscription operations will be rooted at.",type:mt,resolve:t=>t.getSubscriptionType()},directives:{description:"A list of all directives supported by this server.",type:new Q(new ve(new Q(Th))),resolve:t=>t.getDirectives()}})}),Th=new He({name:"__Directive",description:`A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
128
+ `)))!==null&&e!==void 0?e:!1}o(Hw,"hasMultilineItems");function vo(t,e){switch(t.kind){case S.NULL:return null;case S.INT:return parseInt(t.value,10);case S.FLOAT:return parseFloat(t.value);case S.STRING:case S.ENUM:case S.BOOLEAN:return t.value;case S.LIST:return t.values.map(r=>vo(r,e));case S.OBJECT:return qt(t.fields,r=>r.name.value,r=>vo(r.value,e));case S.VARIABLE:return e?.[t.name.value]}}o(vo,"valueFromASTUntyped");function Ze(t){if(t!=null||X(!1,"Must provide name."),typeof t=="string"||X(!1,"Expected name to be a string."),t.length===0)throw new $("Expected name to be a non-empty string.");for(let e=1;e<t.length;++e)if(!pu(t.charCodeAt(e)))throw new $(`Names must only contain [_a-zA-Z0-9] but "${t}" does not.`);if(!bo(t.charCodeAt(0)))throw new $(`Names must start with [_a-zA-Z] but "${t}" does not.`);return t}o(Ze,"assertName");function yh(t){if(t==="true"||t==="false"||t==="null")throw new $(`Enum values cannot be named: ${t}`);return Ze(t)}o(yh,"assertEnumValueName");function Su(t){return Lr(t)||qe(t)||Ce(t)||ht(t)||it(t)||Ue(t)||Xe(t)||ye(t)}o(Su,"isType");function Lr(t){return rt(t,nt)}o(Lr,"isScalarType");function qe(t){return rt(t,He)}o(qe,"isObjectType");function Iu(t){if(!qe(t))throw new Error(`Expected ${U(t)} to be a GraphQL Object type.`);return t}o(Iu,"assertObjectType");function Ce(t){return rt(t,er)}o(Ce,"isInterfaceType");function Pu(t){if(!Ce(t))throw new Error(`Expected ${U(t)} to be a GraphQL Interface type.`);return t}o(Pu,"assertInterfaceType");function ht(t){return rt(t,dn)}o(ht,"isUnionType");function it(t){return rt(t,$t)}o(it,"isEnumType");function Ue(t){return rt(t,pn)}o(Ue,"isInputObjectType");function Xe(t){return rt(t,ve)}o(Xe,"isListType");function ye(t){return rt(t,Q)}o(ye,"isNonNullType");function ot(t){return Lr(t)||it(t)||Ue(t)||To(t)&&ot(t.ofType)}o(ot,"isInputType");function tr(t){return Lr(t)||qe(t)||Ce(t)||ht(t)||it(t)||To(t)&&tr(t.ofType)}o(tr,"isOutputType");function Dr(t){return Lr(t)||it(t)}o(Dr,"isLeafType");function jt(t){return qe(t)||Ce(t)||ht(t)}o(jt,"isCompositeType");function Mr(t){return Ce(t)||ht(t)}o(Mr,"isAbstractType");var ve=class{static{o(this,"GraphQLList")}constructor(e){Su(e)||X(!1,`Expected ${U(e)} to be a GraphQL type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLList"}toString(){return"["+String(this.ofType)+"]"}toJSON(){return this.toString()}},Q=class{static{o(this,"GraphQLNonNull")}constructor(e){Au(e)||X(!1,`Expected ${U(e)} to be a GraphQL nullable type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLNonNull"}toString(){return String(this.ofType)+"!"}toJSON(){return this.toString()}};function To(t){return Xe(t)||ye(t)}o(To,"isWrappingType");function Au(t){return Su(t)&&!ye(t)}o(Au,"isNullableType");function Ru(t){if(!Au(t))throw new Error(`Expected ${U(t)} to be a GraphQL nullable type.`);return t}o(Ru,"assertNullableType");function Ou(t){if(t)return ye(t)?t.ofType:t}o(Ou,"getNullableType");function It(t){if(t){let e=t;for(;To(e);)e=e.ofType;return e}}o(It,"getNamedType");function Nu(t){return typeof t=="function"?t():t}o(Nu,"resolveReadonlyArrayThunk");function Cu(t){return typeof t=="function"?t():t}o(Cu,"resolveObjMapThunk");var nt=class{static{o(this,"GraphQLScalarType")}constructor(e){var r,n,i,s;let a=(r=e.parseValue)!==null&&r!==void 0?r:ph;this.name=Ze(e.name),this.description=e.description,this.specifiedByURL=e.specifiedByURL,this.serialize=(n=e.serialize)!==null&&n!==void 0?n:ph,this.parseValue=a,this.parseLiteral=(i=e.parseLiteral)!==null&&i!==void 0?i:(c,u)=>a(vo(c,u)),this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(s=e.extensionASTNodes)!==null&&s!==void 0?s:[],e.specifiedByURL==null||typeof e.specifiedByURL=="string"||X(!1,`${this.name} must provide "specifiedByURL" as a string, but got: ${U(e.specifiedByURL)}.`),e.serialize==null||typeof e.serialize=="function"||X(!1,`${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`),e.parseLiteral&&(typeof e.parseValue=="function"&&typeof e.parseLiteral=="function"||X(!1,`${this.name} must provide both "parseValue" and "parseLiteral" functions.`))}get[Symbol.toStringTag](){return"GraphQLScalarType"}toConfig(){return{name:this.name,description:this.description,specifiedByURL:this.specifiedByURL,serialize:this.serialize,parseValue:this.parseValue,parseLiteral:this.parseLiteral,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},He=class{static{o(this,"GraphQLObjectType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.isTypeOf=e.isTypeOf,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=()=>$w(e),this._interfaces=()=>qw(e),e.isTypeOf==null||typeof e.isTypeOf=="function"||X(!1,`${this.name} must provide "isTypeOf" as a function, but got: ${U(e.isTypeOf)}.`)}get[Symbol.toStringTag](){return"GraphQLObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return{name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:jw(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function qw(t){var e;let r=Nu((e=t.interfaces)!==null&&e!==void 0?e:[]);return Array.isArray(r)||X(!1,`${t.name} interfaces must be an Array or a function which returns an Array.`),r}o(qw,"defineInterfaces");function $w(t){let e=Cu(t.fields);return vi(e)||X(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),wo(e,(r,n)=>{var i;vi(r)||X(!1,`${t.name}.${n} field config must be an object.`),r.resolve==null||typeof r.resolve=="function"||X(!1,`${t.name}.${n} field resolver must be a function if provided, but got: ${U(r.resolve)}.`);let s=(i=r.args)!==null&&i!==void 0?i:{};return vi(s)||X(!1,`${t.name}.${n} args must be an object with argument names as keys.`),{name:Ze(n),description:r.description,type:r.type,args:gh(s),resolve:r.resolve,subscribe:r.subscribe,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}})}o($w,"defineFieldMap");function gh(t){return Object.entries(t).map(([e,r])=>({name:Ze(e),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}))}o(gh,"defineArguments");function vi(t){return Ne(t)&&!Array.isArray(t)}o(vi,"isPlainObj");function jw(t){return wo(t,e=>({description:e.description,type:e.type,args:bh(e.args),resolve:e.resolve,subscribe:e.subscribe,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(jw,"fieldsToFieldsConfig");function bh(t){return qt(t,e=>e.name,e=>({description:e.description,type:e.type,defaultValue:e.defaultValue,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(bh,"argsToArgsConfig");var er=class{static{o(this,"GraphQLInterfaceType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=$w.bind(void 0,e),this._interfaces=qw.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||X(!1,`${this.name} must provide "resolveType" as a function, but got: ${U(e.resolveType)}.`)}get[Symbol.toStringTag](){return"GraphQLInterfaceType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}getInterfaces(){return typeof this._interfaces=="function"&&(this._interfaces=this._interfaces()),this._interfaces}toConfig(){return{name:this.name,description:this.description,interfaces:this.getInterfaces(),fields:jw(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},dn=class{static{o(this,"GraphQLUnionType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._types=D1.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||X(!1,`${this.name} must provide "resolveType" as a function, but got: ${U(e.resolveType)}.`)}get[Symbol.toStringTag](){return"GraphQLUnionType"}getTypes(){return typeof this._types=="function"&&(this._types=this._types()),this._types}toConfig(){return{name:this.name,description:this.description,types:this.getTypes(),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function D1(t){let e=Nu(t.types);return Array.isArray(e)||X(!1,`Must provide Array of types or a function which returns such an array for Union ${t.name}.`),e}o(D1,"defineTypes");var $t=class{static{o(this,"GraphQLEnumType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._values=M1(this.name,e.values),this._valueLookup=new Map(this._values.map(n=>[n.value,n])),this._nameLookup=Ei(this._values,n=>n.name)}get[Symbol.toStringTag](){return"GraphQLEnumType"}getValues(){return this._values}getValue(e){return this._nameLookup[e]}serialize(e){let r=this._valueLookup.get(e);if(r===void 0)throw new $(`Enum "${this.name}" cannot represent value: ${U(e)}`);return r.name}parseValue(e){if(typeof e!="string"){let n=U(e);throw new $(`Enum "${this.name}" cannot represent non-string value: ${n}.`+Tu(this,n))}let r=this.getValue(e);if(r==null)throw new $(`Value "${e}" does not exist in "${this.name}" enum.`+Tu(this,e));return r.value}parseLiteral(e,r){if(e.kind!==S.ENUM){let i=Be(e);throw new $(`Enum "${this.name}" cannot represent non-enum value: ${i}.`+Tu(this,i),{nodes:e})}let n=this.getValue(e.value);if(n==null){let i=Be(e);throw new $(`Value "${i}" does not exist in "${this.name}" enum.`+Tu(this,i),{nodes:e})}return n.value}toConfig(){let e=qt(this.getValues(),r=>r.name,r=>({description:r.description,value:r.value,deprecationReason:r.deprecationReason,extensions:r.extensions,astNode:r.astNode}));return{name:this.name,description:this.description,values:e,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function Tu(t,e){let r=t.getValues().map(i=>i.name),n=wu(e,r);return _u("the enum value",n)}o(Tu,"didYouMeanEnumValue");function M1(t,e){return vi(e)||X(!1,`${t} values must be an object with value names as keys.`),Object.entries(e).map(([r,n])=>(vi(n)||X(!1,`${t}.${r} must refer to an object with a "value" key representing an internal value but got: ${U(n)}.`),{name:yh(r),description:n.description,value:n.value!==void 0?n.value:r,deprecationReason:n.deprecationReason,extensions:Ve(n.extensions),astNode:n.astNode}))}o(M1,"defineEnumValues");var pn=class{static{o(this,"GraphQLInputObjectType")}constructor(e){var r;this.name=Ze(e.name),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=U1.bind(void 0,e)}get[Symbol.toStringTag](){return"GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let e=wo(this.getFields(),r=>({description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:r.extensions,astNode:r.astNode}));return{name:this.name,description:this.description,fields:e,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function U1(t){let e=Cu(t.fields);return vi(e)||X(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),wo(e,(r,n)=>(!("resolve"in r)||X(!1,`${t.name}.${n} field has a resolve property, but Input Types cannot define resolvers.`),{name:Ze(n),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Ve(r.extensions),astNode:r.astNode}))}o(U1,"defineInputFieldMap");var xu=2147483647,Lu=-2147483648,_h=new nt({name:"Int",description:"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.",serialize(t){let e=So(t);if(typeof e=="boolean")return e?1:0;let r=e;if(typeof e=="string"&&e!==""&&(r=Number(e)),typeof r!="number"||!Number.isInteger(r))throw new $(`Int cannot represent non-integer value: ${U(e)}`);if(r>xu||r<Lu)throw new $("Int cannot represent non 32-bit signed integer value: "+U(e));return r},parseValue(t){if(typeof t!="number"||!Number.isInteger(t))throw new $(`Int cannot represent non-integer value: ${U(t)}`);if(t>xu||t<Lu)throw new $(`Int cannot represent non 32-bit signed integer value: ${t}`);return t},parseLiteral(t){if(t.kind!==S.INT)throw new $(`Int cannot represent non-integer value: ${Be(t)}`,{nodes:t});let e=parseInt(t.value,10);if(e>xu||e<Lu)throw new $(`Int cannot represent non 32-bit signed integer value: ${t.value}`,{nodes:t});return e}}),Vw=new nt({name:"Float",description:"The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).",serialize(t){let e=So(t);if(typeof e=="boolean")return e?1:0;let r=e;if(typeof e=="string"&&e!==""&&(r=Number(e)),typeof r!="number"||!Number.isFinite(r))throw new $(`Float cannot represent non numeric value: ${U(e)}`);return r},parseValue(t){if(typeof t!="number"||!Number.isFinite(t))throw new $(`Float cannot represent non numeric value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.FLOAT&&t.kind!==S.INT)throw new $(`Float cannot represent non numeric value: ${Be(t)}`,t);return parseFloat(t.value)}}),he=new nt({name:"String",description:"The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.",serialize(t){let e=So(t);if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"&&Number.isFinite(e))return e.toString();throw new $(`String cannot represent value: ${U(t)}`)},parseValue(t){if(typeof t!="string")throw new $(`String cannot represent a non string value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.STRING)throw new $(`String cannot represent a non string value: ${Be(t)}`,{nodes:t});return t.value}}),Ge=new nt({name:"Boolean",description:"The `Boolean` scalar type represents `true` or `false`.",serialize(t){let e=So(t);if(typeof e=="boolean")return e;if(Number.isFinite(e))return e!==0;throw new $(`Boolean cannot represent a non boolean value: ${U(e)}`)},parseValue(t){if(typeof t!="boolean")throw new $(`Boolean cannot represent a non boolean value: ${U(t)}`);return t},parseLiteral(t){if(t.kind!==S.BOOLEAN)throw new $(`Boolean cannot represent a non boolean value: ${Be(t)}`,{nodes:t});return t.value}}),Du=new nt({name:"ID",description:'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',serialize(t){let e=So(t);if(typeof e=="string")return e;if(Number.isInteger(e))return String(e);throw new $(`ID cannot represent value: ${U(t)}`)},parseValue(t){if(typeof t=="string")return t;if(typeof t=="number"&&Number.isInteger(t))return t.toString();throw new $(`ID cannot represent value: ${U(t)}`)},parseLiteral(t){if(t.kind!==S.STRING&&t.kind!==S.INT)throw new $("ID cannot represent a non-string and non-integer value: "+Be(t),{nodes:t});return t.value}}),Eh=Object.freeze([he,_h,Vw,Ge,Du]);function So(t){if(Ne(t)){if(typeof t.valueOf=="function"){let e=t.valueOf();if(!Ne(e))return e}if(typeof t.toJSON=="function")return t.toJSON()}return t}o(So,"serializeObject");function wh(t){return rt(t,Pt)}o(wh,"isDirective");var Pt=class{static{o(this,"GraphQLDirective")}constructor(e){var r,n;this.name=Ze(e.name),this.description=e.description,this.locations=e.locations,this.isRepeatable=(r=e.isRepeatable)!==null&&r!==void 0?r:!1,this.extensions=Ve(e.extensions),this.astNode=e.astNode,Array.isArray(e.locations)||X(!1,`@${e.name} locations must be an Array.`);let i=(n=e.args)!==null&&n!==void 0?n:{};Ne(i)&&!Array.isArray(i)||X(!1,`@${e.name} args must be an object with argument names as keys.`),this.args=gh(i)}get[Symbol.toStringTag](){return"GraphQLDirective"}toConfig(){return{name:this.name,description:this.description,locations:this.locations,args:bh(this.args),isRepeatable:this.isRepeatable,extensions:this.extensions,astNode:this.astNode}}toString(){return"@"+this.name}toJSON(){return this.toString()}},Bw=new Pt({name:"include",description:"Directs the executor to include this field or fragment only when the `if` argument is true.",locations:[ee.FIELD,ee.FRAGMENT_SPREAD,ee.INLINE_FRAGMENT],args:{if:{type:new Q(Ge),description:"Included when true."}}}),Gw=new Pt({name:"skip",description:"Directs the executor to skip this field or fragment when the `if` argument is true.",locations:[ee.FIELD,ee.FRAGMENT_SPREAD,ee.INLINE_FRAGMENT],args:{if:{type:new Q(Ge),description:"Skipped when true."}}}),Kw="No longer supported",Jw=new Pt({name:"deprecated",description:"Marks an element of a GraphQL schema as no longer supported.",locations:[ee.FIELD_DEFINITION,ee.ARGUMENT_DEFINITION,ee.INPUT_FIELD_DEFINITION,ee.ENUM_VALUE],args:{reason:{type:he,description:"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).",defaultValue:Kw}}}),zw=new Pt({name:"specifiedBy",description:"Exposes a URL that specifies the behavior of this scalar.",locations:[ee.SCALAR],args:{url:{type:new Q(he),description:"The URL that specifies the behavior of this scalar."}}}),vh=Object.freeze([Bw,Gw,Jw,zw]);function Mu(t){return typeof t=="object"&&typeof t?.[Symbol.iterator]=="function"}o(Mu,"isIterableObject");function fn(t,e){if(ye(e)){let r=fn(t,e.ofType);return r?.kind===S.NULL?null:r}if(t===null)return{kind:S.NULL};if(t===void 0)return null;if(Xe(e)){let r=e.ofType;if(Mu(t)){let n=[];for(let i of t){let s=fn(i,r);s!=null&&n.push(s)}return{kind:S.LIST,values:n}}return fn(t,r)}if(Ue(e)){if(!Ne(t))return null;let r=[];for(let n of Object.values(e.getFields())){let i=fn(t[n.name],n.type);i&&r.push({kind:S.OBJECT_FIELD,name:{kind:S.NAME,value:n.name},value:i})}return{kind:S.OBJECT,fields:r}}if(Dr(e)){let r=e.serialize(t);if(r==null)return null;if(typeof r=="boolean")return{kind:S.BOOLEAN,value:r};if(typeof r=="number"&&Number.isFinite(r)){let n=String(r);return Ww.test(n)?{kind:S.INT,value:n}:{kind:S.FLOAT,value:n}}if(typeof r=="string")return it(e)?{kind:S.ENUM,value:r}:e===Du&&Ww.test(r)?{kind:S.INT,value:r}:{kind:S.STRING,value:r};throw new TypeError(`Cannot convert value to AST: ${U(r)}.`)}Ht(!1,"Unexpected input type: "+U(e))}o(fn,"astFromValue");var Ww=/^-?(?:0|[1-9][0-9]*)$/;var Io=new He({name:"__Schema",description:"A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.",fields:()=>({description:{type:he,resolve:t=>t.description},types:{description:"A list of all types supported by this server.",type:new Q(new ve(new Q(mt))),resolve(t){return Object.values(t.getTypeMap())}},queryType:{description:"The type that query operations will be rooted at.",type:new Q(mt),resolve:t=>t.getQueryType()},mutationType:{description:"If this server supports mutation, the type that mutation operations will be rooted at.",type:mt,resolve:t=>t.getMutationType()},subscriptionType:{description:"If this server support subscription, the type that subscription operations will be rooted at.",type:mt,resolve:t=>t.getSubscriptionType()},directives:{description:"A list of all directives supported by this server.",type:new Q(new ve(new Q(Th))),resolve:t=>t.getDirectives()}})}),Th=new He({name:"__Directive",description:`A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
129
129
 
130
- In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.`,fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},isRepeatable:{type:new Q(Ge),resolve:t=>t.isRepeatable},locations:{type:new Q(new ve(new Q(Sh))),resolve:t=>t.locations},args:{type:new Q(new ve(new Q(Po))),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}}})}),Sh=new $t({name:"__DirectiveLocation",description:"A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.",values:{QUERY:{value:ee.QUERY,description:"Location adjacent to a query operation."},MUTATION:{value:ee.MUTATION,description:"Location adjacent to a mutation operation."},SUBSCRIPTION:{value:ee.SUBSCRIPTION,description:"Location adjacent to a subscription operation."},FIELD:{value:ee.FIELD,description:"Location adjacent to a field."},FRAGMENT_DEFINITION:{value:ee.FRAGMENT_DEFINITION,description:"Location adjacent to a fragment definition."},FRAGMENT_SPREAD:{value:ee.FRAGMENT_SPREAD,description:"Location adjacent to a fragment spread."},INLINE_FRAGMENT:{value:ee.INLINE_FRAGMENT,description:"Location adjacent to an inline fragment."},VARIABLE_DEFINITION:{value:ee.VARIABLE_DEFINITION,description:"Location adjacent to a variable definition."},SCHEMA:{value:ee.SCHEMA,description:"Location adjacent to a schema definition."},SCALAR:{value:ee.SCALAR,description:"Location adjacent to a scalar definition."},OBJECT:{value:ee.OBJECT,description:"Location adjacent to an object type definition."},FIELD_DEFINITION:{value:ee.FIELD_DEFINITION,description:"Location adjacent to a field definition."},ARGUMENT_DEFINITION:{value:ee.ARGUMENT_DEFINITION,description:"Location adjacent to an argument definition."},INTERFACE:{value:ee.INTERFACE,description:"Location adjacent to an interface definition."},UNION:{value:ee.UNION,description:"Location adjacent to a union definition."},ENUM:{value:ee.ENUM,description:"Location adjacent to an enum definition."},ENUM_VALUE:{value:ee.ENUM_VALUE,description:"Location adjacent to an enum value definition."},INPUT_OBJECT:{value:ee.INPUT_OBJECT,description:"Location adjacent to an input object type definition."},INPUT_FIELD_DEFINITION:{value:ee.INPUT_FIELD_DEFINITION,description:"Location adjacent to an input object field definition."}}}),mt=new He({name:"__Type",description:"The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.",fields:()=>({kind:{type:new Q(Ah),resolve(t){if(Lr(t))return ue.SCALAR;if(qe(t))return ue.OBJECT;if(Ce(t))return ue.INTERFACE;if(ht(t))return ue.UNION;if(it(t))return ue.ENUM;if(Ue(t))return ue.INPUT_OBJECT;if(Xe(t))return ue.LIST;if(ye(t))return ue.NON_NULL;Ht(!1,`Unexpected type: "${U(t)}".`)}},name:{type:he,resolve:t=>"name"in t?t.name:void 0},description:{type:he,resolve:t=>"description"in t?t.description:void 0},specifiedByURL:{type:he,resolve:t=>"specifiedByURL"in t?t.specifiedByURL:void 0},fields:{type:new ve(new Q(Ih)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(qe(t)||Ce(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},interfaces:{type:new ve(new Q(mt)),resolve(t){if(qe(t)||Ce(t))return t.getInterfaces()}},possibleTypes:{type:new ve(new Q(mt)),resolve(t,e,r,{schema:n}){if(Mr(t))return n.getPossibleTypes(t)}},enumValues:{type:new ve(new Q(Ph)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(it(t)){let r=t.getValues();return e?r:r.filter(n=>n.deprecationReason==null)}}},inputFields:{type:new ve(new Q(Po)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Ue(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},ofType:{type:mt,resolve:t=>"ofType"in t?t.ofType:void 0}})}),Ih=new He({name:"__Field",description:"Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},args:{type:new Q(new ve(new Q(Po))),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}},type:{type:new Q(mt),resolve:t=>t.type},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),Po=new He({name:"__InputValue",description:"Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},type:{type:new Q(mt),resolve:t=>t.type},defaultValue:{type:he,description:"A GraphQL-formatted string representing the default value for this input value.",resolve(t){let{type:e,defaultValue:r}=t,n=fn(r,e);return n?Be(n):null}},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),Ph=new He({name:"__EnumValue",description:"One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),ue;(function(t){t.SCALAR="SCALAR",t.OBJECT="OBJECT",t.INTERFACE="INTERFACE",t.UNION="UNION",t.ENUM="ENUM",t.INPUT_OBJECT="INPUT_OBJECT",t.LIST="LIST",t.NON_NULL="NON_NULL"})(ue||(ue={}));var Ah=new $t({name:"__TypeKind",description:"An enum describing what kind of type a given `__Type` is.",values:{SCALAR:{value:ue.SCALAR,description:"Indicates this type is a scalar."},OBJECT:{value:ue.OBJECT,description:"Indicates this type is an object. `fields` and `interfaces` are valid fields."},INTERFACE:{value:ue.INTERFACE,description:"Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields."},UNION:{value:ue.UNION,description:"Indicates this type is a union. `possibleTypes` is a valid field."},ENUM:{value:ue.ENUM,description:"Indicates this type is an enum. `enumValues` is a valid field."},INPUT_OBJECT:{value:ue.INPUT_OBJECT,description:"Indicates this type is an input object. `inputFields` is a valid field."},LIST:{value:ue.LIST,description:"Indicates this type is a list. `ofType` is a valid field."},NON_NULL:{value:ue.NON_NULL,description:"Indicates this type is a non-null. `ofType` is a valid field."}}}),Uu={name:"__schema",type:new Q(Io),description:"Access the current type schema of this server.",args:[],resolve:(t,e,r,{schema:n})=>n,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},ku={name:"__type",type:mt,description:"Request the type information of a single type.",args:[{name:"name",description:void 0,type:new Q(he),defaultValue:void 0,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0}],resolve:(t,{name:e},r,{schema:n})=>n.getType(e),deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},Fu={name:"__typename",type:new Q(he),description:"The name of the current Object type at runtime.",args:[],resolve:(t,e,r,{parentType:n})=>n.name,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},Rh=Object.freeze([Io,Th,Sh,mt,Ih,Po,Ph,Ah]);var Ao=class{static{o(this,"GraphQLSchema")}constructor(e){var r,n;this.__validationErrors=e.assumeValid===!0?[]:void 0,Ne(e)||X(!1,"Must provide configuration object."),!e.types||Array.isArray(e.types)||X(!1,`"types" must be Array if provided but got: ${U(e.types)}.`),!e.directives||Array.isArray(e.directives)||X(!1,`"directives" must be Array if provided but got: ${U(e.directives)}.`),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._queryType=e.query,this._mutationType=e.mutation,this._subscriptionType=e.subscription,this._directives=(n=e.directives)!==null&&n!==void 0?n:vh;let i=new Set(e.types);if(e.types!=null)for(let s of e.types)i.delete(s),At(s,i);this._queryType!=null&&At(this._queryType,i),this._mutationType!=null&&At(this._mutationType,i),this._subscriptionType!=null&&At(this._subscriptionType,i);for(let s of this._directives)if(wh(s))for(let a of s.args)At(a.type,i);At(Io,i),this._typeMap=Object.create(null),this._subTypeMap=Object.create(null),this._implementationsMap=Object.create(null);for(let s of i){if(s==null)continue;let a=s.name;if(a||X(!1,"One of the provided types for building the Schema is missing a name."),this._typeMap[a]!==void 0)throw new Error(`Schema must contain uniquely named types but contains multiple types named "${a}".`);if(this._typeMap[a]=s,Ce(s)){for(let c of s.getInterfaces())if(Ce(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.interfaces.push(s)}}else if(qe(s)){for(let c of s.getInterfaces())if(Ce(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.objects.push(s)}}}}get[Symbol.toStringTag](){return"GraphQLSchema"}getQueryType(){return this._queryType}getMutationType(){return this._mutationType}getSubscriptionType(){return this._subscriptionType}getRootType(e){switch(e){case ft.QUERY:return this.getQueryType();case ft.MUTATION:return this.getMutationType();case ft.SUBSCRIPTION:return this.getSubscriptionType()}}getTypeMap(){return this._typeMap}getType(e){return this.getTypeMap()[e]}getPossibleTypes(e){return ht(e)?e.getTypes():this.getImplementations(e).objects}getImplementations(e){let r=this._implementationsMap[e.name];return r??{objects:[],interfaces:[]}}isSubType(e,r){let n=this._subTypeMap[e.name];if(n===void 0){if(n=Object.create(null),ht(e))for(let i of e.getTypes())n[i.name]=!0;else{let i=this.getImplementations(e);for(let s of i.objects)n[s.name]=!0;for(let s of i.interfaces)n[s.name]=!0}this._subTypeMap[e.name]=n}return n[r.name]!==void 0}getDirectives(){return this._directives}getDirective(e){return this.getDirectives().find(r=>r.name===e)}toConfig(){return{description:this.description,query:this.getQueryType(),mutation:this.getMutationType(),subscription:this.getSubscriptionType(),types:Object.values(this.getTypeMap()),directives:this.getDirectives(),extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes,assumeValid:this.__validationErrors!==void 0}}};function At(t,e){let r=It(t);if(!e.has(r)){if(e.add(r),ht(r))for(let n of r.getTypes())At(n,e);else if(qe(r)||Ce(r)){for(let n of r.getInterfaces())At(n,e);for(let n of Object.values(r.getFields())){At(n.type,e);for(let i of n.args)At(i.type,e)}}else if(Ue(r))for(let n of Object.values(r.getFields()))At(n.type,e)}return e}o(At,"collectReferencedTypes");function Ur(t,e){switch(e.kind){case S.LIST_TYPE:{let r=Ur(t,e.type);return r&&new ve(r)}case S.NON_NULL_TYPE:{let r=Ur(t,e.type);return r&&new Q(r)}case S.NAMED_TYPE:return t.getType(e.name.value)}}o(Ur,"typeFromAST");var kr=class{static{o(this,"TypeInfo")}constructor(e,r,n){this._schema=e,this._typeStack=[],this._parentTypeStack=[],this._inputTypeStack=[],this._fieldDefStack=[],this._defaultValueStack=[],this._directive=null,this._argument=null,this._enumValue=null,this._getFieldDef=n??M1,r&&(ot(r)&&this._inputTypeStack.push(r),jt(r)&&this._parentTypeStack.push(r),tr(r)&&this._typeStack.push(r))}get[Symbol.toStringTag](){return"TypeInfo"}getType(){if(this._typeStack.length>0)return this._typeStack[this._typeStack.length-1]}getParentType(){if(this._parentTypeStack.length>0)return this._parentTypeStack[this._parentTypeStack.length-1]}getInputType(){if(this._inputTypeStack.length>0)return this._inputTypeStack[this._inputTypeStack.length-1]}getParentInputType(){if(this._inputTypeStack.length>1)return this._inputTypeStack[this._inputTypeStack.length-2]}getFieldDef(){if(this._fieldDefStack.length>0)return this._fieldDefStack[this._fieldDefStack.length-1]}getDefaultValue(){if(this._defaultValueStack.length>0)return this._defaultValueStack[this._defaultValueStack.length-1]}getDirective(){return this._directive}getArgument(){return this._argument}getEnumValue(){return this._enumValue}enter(e){let r=this._schema;switch(e.kind){case S.SELECTION_SET:{let i=It(this.getType());this._parentTypeStack.push(jt(i)?i:void 0);break}case S.FIELD:{let i=this.getParentType(),s,a;i&&(s=this._getFieldDef(r,i,e),s&&(a=s.type)),this._fieldDefStack.push(s),this._typeStack.push(tr(a)?a:void 0);break}case S.DIRECTIVE:this._directive=r.getDirective(e.name.value);break;case S.OPERATION_DEFINITION:{let i=r.getRootType(e.operation);this._typeStack.push(qe(i)?i:void 0);break}case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:{let i=e.typeCondition,s=i?Ur(r,i):It(this.getType());this._typeStack.push(tr(s)?s:void 0);break}case S.VARIABLE_DEFINITION:{let i=Ur(r,e.type);this._inputTypeStack.push(ot(i)?i:void 0);break}case S.ARGUMENT:{var n;let i,s,a=(n=this.getDirective())!==null&&n!==void 0?n:this.getFieldDef();a&&(i=a.args.find(c=>c.name===e.name.value),i&&(s=i.type)),this._argument=i,this._defaultValueStack.push(i?i.defaultValue:void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.LIST:{let i=Ou(this.getInputType()),s=Xe(i)?i.ofType:i;this._defaultValueStack.push(void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.OBJECT_FIELD:{let i=It(this.getInputType()),s,a;Ue(i)&&(a=i.getFields()[e.name.value],a&&(s=a.type)),this._defaultValueStack.push(a?a.defaultValue:void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.ENUM:{let i=It(this.getInputType()),s;it(i)&&(s=i.getValue(e.value)),this._enumValue=s;break}default:}}leave(e){switch(e.kind){case S.SELECTION_SET:this._parentTypeStack.pop();break;case S.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case S.DIRECTIVE:this._directive=null;break;case S.OPERATION_DEFINITION:case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:this._typeStack.pop();break;case S.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case S.ARGUMENT:this._argument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case S.LIST:case S.OBJECT_FIELD:this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case S.ENUM:this._enumValue=null;break;default:}}};function M1(t,e,r){let n=r.name.value;if(n===Uu.name&&t.getQueryType()===e)return Uu;if(n===ku.name&&t.getQueryType()===e)return ku;if(n===Fu.name&&jt(e))return Fu;if(qe(e)||Ce(e))return e.getFields()[n]}o(M1,"getFieldDef");function Ti(t,e){return{enter(...r){let n=r[0];t.enter(n);let i=wi(e,n.kind).enter;if(i){let s=i.apply(e,r);return s!==void 0&&(t.leave(n),go(s)&&t.enter(s)),s}},leave(...r){let n=r[0],i=wi(e,n.kind).leave,s;return i&&(s=i.apply(e,r)),t.leave(n),s}}}o(Ti,"visitWithTypeInfo");function Hu(t){return t.map(e=>typeof e=="number"?"["+e.toString()+"]":"."+e).join("")}o(Hu,"printPathArray");function Oh(t,e,r){return{prev:t,key:e,typename:r}}o(Oh,"addPath");function rr(t){let e=[],r=t;for(;r;)e.push(r.key),r=r.prev;return e.reverse()}o(rr,"pathToArray");function Nh(t,e,r=U1){return Ro(t,e,r,void 0)}o(Nh,"coerceInputValue");function U1(t,e,r){let n="Invalid value "+U(e);throw t.length>0&&(n+=` at "value${Hu(t)}"`),r.message=n+": "+r.message,r}o(U1,"defaultOnError");function Ro(t,e,r,n){if(ye(e)){if(t!=null)return Ro(t,e.ofType,r,n);r(rr(n),t,new $(`Expected non-nullable type "${U(e)}" not to be null.`));return}if(t==null)return null;if(Xe(e)){let i=e.ofType;return Mu(t)?Array.from(t,(s,a)=>{let c=Oh(n,a,void 0);return Ro(s,i,r,c)}):[Ro(t,i,r,n)]}if(Ue(e)){if(!Ne(t)){r(rr(n),t,new $(`Expected type "${e.name}" to be an object.`));return}let i={},s=e.getFields();for(let a of Object.values(s)){let c=t[a.name];if(c===void 0){if(a.defaultValue!==void 0)i[a.name]=a.defaultValue;else if(ye(a.type)){let u=U(a.type);r(rr(n),t,new $(`Field "${a.name}" of required type "${u}" was not provided.`))}continue}i[a.name]=Ro(c,a.type,r,Oh(n,a.name,e.name))}for(let a of Object.keys(t))if(!s[a]){let c=wu(a,Object.keys(e.getFields()));r(rr(n),t,new $(`Field "${a}" is not defined by type "${e.name}".`+_u(c)))}return i}if(Dr(e)){let i;try{i=e.parseValue(t)}catch(s){s instanceof $?r(rr(n),t,s):r(rr(n),t,new $(`Expected type "${e.name}". `+s.message,{originalError:s}));return}return i===void 0&&r(rr(n),t,new $(`Expected type "${e.name}".`)),i}Ht(!1,"Unexpected input type: "+U(e))}o(Ro,"coerceInputValueImpl");function Vt(t,e,r){if(t){if(t.kind===S.VARIABLE){let n=t.name.value;if(r==null||r[n]===void 0)return;let i=r[n];return i===null&&ye(e)?void 0:i}if(ye(e))return t.kind===S.NULL?void 0:Vt(t,e.ofType,r);if(t.kind===S.NULL)return null;if(Xe(e)){let n=e.ofType;if(t.kind===S.LIST){let s=[];for(let a of t.values)if(Qw(a,r)){if(ye(n))return;s.push(null)}else{let c=Vt(a,n,r);if(c===void 0)return;s.push(c)}return s}let i=Vt(t,n,r);return i===void 0?void 0:[i]}if(Ue(e)){if(t.kind!==S.OBJECT)return;let n=Object.create(null),i=Ei(t.fields,s=>s.name.value);for(let s of Object.values(e.getFields())){let a=i[s.name];if(!a||Qw(a.value,r)){if(s.defaultValue!==void 0)n[s.name]=s.defaultValue;else if(ye(s.type))return;continue}let c=Vt(a.value,s.type,r);if(c===void 0)return;n[s.name]=c}return n}if(Dr(e)){let n;try{n=e.parseLiteral(t,r)}catch{return}return n===void 0?void 0:n}Ht(!1,"Unexpected input type: "+U(e))}}o(Vt,"valueFromAST");function Qw(t,e){return t.kind===S.VARIABLE&&(e==null||e[t.name.value]===void 0)}o(Qw,"isMissingVariable");function qu(t,e,r,n){let i=[],s=n?.maxErrors;try{let a=k1(t,e,r,c=>{if(s!=null&&i.length>=s)throw new $("Too many errors processing variables, error limit reached. Execution aborted.");i.push(c)});if(i.length===0)return{coerced:a}}catch(a){i.push(a)}return{errors:i}}o(qu,"getVariableValues");function k1(t,e,r,n){let i={};for(let s of e){let a=s.variable.name.value,c=Ur(t,s.type);if(!ot(c)){let l=Be(s.type);n(new $(`Variable "$${a}" expected value of type "${l}" which cannot be used as an input type.`,{nodes:s.type}));continue}if(!Yw(r,a)){if(s.defaultValue)i[a]=Vt(s.defaultValue,c);else if(ye(c)){let l=U(c);n(new $(`Variable "$${a}" of required type "${l}" was not provided.`,{nodes:s}))}continue}let u=r[a];if(u===null&&ye(c)){let l=U(c);n(new $(`Variable "$${a}" of non-null type "${l}" must not be null.`,{nodes:s}));continue}i[a]=Nh(u,c,(l,d,p)=>{let f=`Variable "$${a}" got invalid value `+U(d);l.length>0&&(f+=` at "${a}${Hu(l)}"`),n(new $(f+"; "+p.message,{nodes:s,originalError:p}))})}return i}o(k1,"coerceVariableValues");function Oo(t,e,r){var n;let i={},s=(n=e.arguments)!==null&&n!==void 0?n:[],a=Ei(s,c=>c.name.value);for(let c of t.args){let u=c.name,l=c.type,d=a[u];if(!d){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ye(l))throw new $(`Argument "${u}" of required type "${U(l)}" was not provided.`,{nodes:e});continue}let p=d.value,f=p.kind===S.NULL;if(p.kind===S.VARIABLE){let y=p.name.value;if(r==null||!Yw(r,y)){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ye(l))throw new $(`Argument "${u}" of required type "${U(l)}" was provided the variable "$${y}" which was not provided a runtime value.`,{nodes:p});continue}f=r[y]==null}if(f&&ye(l))throw new $(`Argument "${u}" of non-null type "${U(l)}" must not be null.`,{nodes:p});let h=Vt(p,l,r);if(h===void 0)throw new $(`Argument "${u}" has invalid value ${Be(p)}.`,{nodes:p});i[u]=h}return i}o(Oo,"getArgumentValues");function No(t,e,r){var n;let i=(n=e.directives)===null||n===void 0?void 0:n.find(s=>s.name.value===t.name);if(i)return Oo(t,i,r)}o(No,"getDirectiveValues");function Yw(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(Yw,"hasOwnProperty");var $u=class{static{o(this,"ASTValidationContext")}constructor(e,r){this._ast=e,this._fragments=void 0,this._fragmentSpreads=new Map,this._recursivelyReferencedFragments=new Map,this._onError=r}get[Symbol.toStringTag](){return"ASTValidationContext"}reportError(e){this._onError(e)}getDocument(){return this._ast}getFragment(e){let r;if(this._fragments)r=this._fragments;else{r=Object.create(null);for(let n of this.getDocument().definitions)n.kind===S.FRAGMENT_DEFINITION&&(r[n.name.value]=n);this._fragments=r}return r[e]}getFragmentSpreads(e){let r=this._fragmentSpreads.get(e);if(!r){r=[];let n=[e],i;for(;i=n.pop();)for(let s of i.selections)s.kind===S.FRAGMENT_SPREAD?r.push(s):s.selectionSet&&n.push(s.selectionSet);this._fragmentSpreads.set(e,r)}return r}getRecursivelyReferencedFragments(e){let r=this._recursivelyReferencedFragments.get(e);if(!r){r=[];let n=Object.create(null),i=[e.selectionSet],s;for(;s=i.pop();)for(let a of this.getFragmentSpreads(s)){let c=a.name.value;if(n[c]!==!0){n[c]=!0;let u=this.getFragment(c);u&&(r.push(u),i.push(u.selectionSet))}}this._recursivelyReferencedFragments.set(e,r)}return r}},Zw=class extends $u{static{o(this,"SDLValidationContext")}constructor(e,r,n){super(e,n),this._schema=r}get[Symbol.toStringTag](){return"SDLValidationContext"}getSchema(){return this._schema}},Si=class extends $u{static{o(this,"ValidationContext")}constructor(e,r,n,i){super(r,i),this._schema=e,this._typeInfo=n,this._variableUsages=new Map,this._recursiveVariableUsages=new Map}get[Symbol.toStringTag](){return"ValidationContext"}getSchema(){return this._schema}getVariableUsages(e){let r=this._variableUsages.get(e);if(!r){let n=[],i=new kr(this._schema);xr(e,Ti(i,{VariableDefinition:()=>!1,Variable(s){n.push({node:s,type:i.getInputType(),defaultValue:i.getDefaultValue()})}})),r=n,this._variableUsages.set(e,r)}return r}getRecursiveVariableUsages(e){let r=this._recursiveVariableUsages.get(e);if(!r){r=this.getVariableUsages(e);for(let n of this.getRecursivelyReferencedFragments(e))r=r.concat(this.getVariableUsages(n));this._recursiveVariableUsages.set(e,r)}return r}getType(){return this._typeInfo.getType()}getParentType(){return this._typeInfo.getParentType()}getInputType(){return this._typeInfo.getInputType()}getParentInputType(){return this._typeInfo.getParentInputType()}getFieldDef(){return this._typeInfo.getFieldDef()}getDirective(){return this._typeInfo.getDirective()}getArgument(){return this._typeInfo.getArgument()}getEnumValue(){return this._typeInfo.getEnumValue()}};function ju(t){let e={descriptions:!0,specifiedByUrl:!1,directiveIsRepeatable:!1,schemaDescription:!1,inputValueDeprecation:!1,...t},r=e.descriptions?"description":"",n=e.specifiedByUrl?"specifiedByURL":"",i=e.directiveIsRepeatable?"isRepeatable":"",s=e.schemaDescription?r:"";function a(c){return e.inputValueDeprecation?c:""}return o(a,"inputDeprecation"),`
130
+ In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.`,fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},isRepeatable:{type:new Q(Ge),resolve:t=>t.isRepeatable},locations:{type:new Q(new ve(new Q(Sh))),resolve:t=>t.locations},args:{type:new Q(new ve(new Q(Po))),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}}})}),Sh=new $t({name:"__DirectiveLocation",description:"A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.",values:{QUERY:{value:ee.QUERY,description:"Location adjacent to a query operation."},MUTATION:{value:ee.MUTATION,description:"Location adjacent to a mutation operation."},SUBSCRIPTION:{value:ee.SUBSCRIPTION,description:"Location adjacent to a subscription operation."},FIELD:{value:ee.FIELD,description:"Location adjacent to a field."},FRAGMENT_DEFINITION:{value:ee.FRAGMENT_DEFINITION,description:"Location adjacent to a fragment definition."},FRAGMENT_SPREAD:{value:ee.FRAGMENT_SPREAD,description:"Location adjacent to a fragment spread."},INLINE_FRAGMENT:{value:ee.INLINE_FRAGMENT,description:"Location adjacent to an inline fragment."},VARIABLE_DEFINITION:{value:ee.VARIABLE_DEFINITION,description:"Location adjacent to a variable definition."},SCHEMA:{value:ee.SCHEMA,description:"Location adjacent to a schema definition."},SCALAR:{value:ee.SCALAR,description:"Location adjacent to a scalar definition."},OBJECT:{value:ee.OBJECT,description:"Location adjacent to an object type definition."},FIELD_DEFINITION:{value:ee.FIELD_DEFINITION,description:"Location adjacent to a field definition."},ARGUMENT_DEFINITION:{value:ee.ARGUMENT_DEFINITION,description:"Location adjacent to an argument definition."},INTERFACE:{value:ee.INTERFACE,description:"Location adjacent to an interface definition."},UNION:{value:ee.UNION,description:"Location adjacent to a union definition."},ENUM:{value:ee.ENUM,description:"Location adjacent to an enum definition."},ENUM_VALUE:{value:ee.ENUM_VALUE,description:"Location adjacent to an enum value definition."},INPUT_OBJECT:{value:ee.INPUT_OBJECT,description:"Location adjacent to an input object type definition."},INPUT_FIELD_DEFINITION:{value:ee.INPUT_FIELD_DEFINITION,description:"Location adjacent to an input object field definition."}}}),mt=new He({name:"__Type",description:"The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.",fields:()=>({kind:{type:new Q(Ah),resolve(t){if(Lr(t))return ue.SCALAR;if(qe(t))return ue.OBJECT;if(Ce(t))return ue.INTERFACE;if(ht(t))return ue.UNION;if(it(t))return ue.ENUM;if(Ue(t))return ue.INPUT_OBJECT;if(Xe(t))return ue.LIST;if(ye(t))return ue.NON_NULL;Ht(!1,`Unexpected type: "${U(t)}".`)}},name:{type:he,resolve:t=>"name"in t?t.name:void 0},description:{type:he,resolve:t=>"description"in t?t.description:void 0},specifiedByURL:{type:he,resolve:t=>"specifiedByURL"in t?t.specifiedByURL:void 0},fields:{type:new ve(new Q(Ih)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(qe(t)||Ce(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},interfaces:{type:new ve(new Q(mt)),resolve(t){if(qe(t)||Ce(t))return t.getInterfaces()}},possibleTypes:{type:new ve(new Q(mt)),resolve(t,e,r,{schema:n}){if(Mr(t))return n.getPossibleTypes(t)}},enumValues:{type:new ve(new Q(Ph)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(it(t)){let r=t.getValues();return e?r:r.filter(n=>n.deprecationReason==null)}}},inputFields:{type:new ve(new Q(Po)),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Ue(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},ofType:{type:mt,resolve:t=>"ofType"in t?t.ofType:void 0}})}),Ih=new He({name:"__Field",description:"Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},args:{type:new Q(new ve(new Q(Po))),args:{includeDeprecated:{type:Ge,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}},type:{type:new Q(mt),resolve:t=>t.type},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),Po=new He({name:"__InputValue",description:"Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},type:{type:new Q(mt),resolve:t=>t.type},defaultValue:{type:he,description:"A GraphQL-formatted string representing the default value for this input value.",resolve(t){let{type:e,defaultValue:r}=t,n=fn(r,e);return n?Be(n):null}},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),Ph=new He({name:"__EnumValue",description:"One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.",fields:()=>({name:{type:new Q(he),resolve:t=>t.name},description:{type:he,resolve:t=>t.description},isDeprecated:{type:new Q(Ge),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:he,resolve:t=>t.deprecationReason}})}),ue;(function(t){t.SCALAR="SCALAR",t.OBJECT="OBJECT",t.INTERFACE="INTERFACE",t.UNION="UNION",t.ENUM="ENUM",t.INPUT_OBJECT="INPUT_OBJECT",t.LIST="LIST",t.NON_NULL="NON_NULL"})(ue||(ue={}));var Ah=new $t({name:"__TypeKind",description:"An enum describing what kind of type a given `__Type` is.",values:{SCALAR:{value:ue.SCALAR,description:"Indicates this type is a scalar."},OBJECT:{value:ue.OBJECT,description:"Indicates this type is an object. `fields` and `interfaces` are valid fields."},INTERFACE:{value:ue.INTERFACE,description:"Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields."},UNION:{value:ue.UNION,description:"Indicates this type is a union. `possibleTypes` is a valid field."},ENUM:{value:ue.ENUM,description:"Indicates this type is an enum. `enumValues` is a valid field."},INPUT_OBJECT:{value:ue.INPUT_OBJECT,description:"Indicates this type is an input object. `inputFields` is a valid field."},LIST:{value:ue.LIST,description:"Indicates this type is a list. `ofType` is a valid field."},NON_NULL:{value:ue.NON_NULL,description:"Indicates this type is a non-null. `ofType` is a valid field."}}}),Uu={name:"__schema",type:new Q(Io),description:"Access the current type schema of this server.",args:[],resolve:(t,e,r,{schema:n})=>n,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},ku={name:"__type",type:mt,description:"Request the type information of a single type.",args:[{name:"name",description:void 0,type:new Q(he),defaultValue:void 0,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0}],resolve:(t,{name:e},r,{schema:n})=>n.getType(e),deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},Fu={name:"__typename",type:new Q(he),description:"The name of the current Object type at runtime.",args:[],resolve:(t,e,r,{parentType:n})=>n.name,deprecationReason:void 0,extensions:Object.create(null),astNode:void 0},Rh=Object.freeze([Io,Th,Sh,mt,Ih,Po,Ph,Ah]);var Ao=class{static{o(this,"GraphQLSchema")}constructor(e){var r,n;this.__validationErrors=e.assumeValid===!0?[]:void 0,Ne(e)||X(!1,"Must provide configuration object."),!e.types||Array.isArray(e.types)||X(!1,`"types" must be Array if provided but got: ${U(e.types)}.`),!e.directives||Array.isArray(e.directives)||X(!1,`"directives" must be Array if provided but got: ${U(e.directives)}.`),this.description=e.description,this.extensions=Ve(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._queryType=e.query,this._mutationType=e.mutation,this._subscriptionType=e.subscription,this._directives=(n=e.directives)!==null&&n!==void 0?n:vh;let i=new Set(e.types);if(e.types!=null)for(let s of e.types)i.delete(s),At(s,i);this._queryType!=null&&At(this._queryType,i),this._mutationType!=null&&At(this._mutationType,i),this._subscriptionType!=null&&At(this._subscriptionType,i);for(let s of this._directives)if(wh(s))for(let a of s.args)At(a.type,i);At(Io,i),this._typeMap=Object.create(null),this._subTypeMap=Object.create(null),this._implementationsMap=Object.create(null);for(let s of i){if(s==null)continue;let a=s.name;if(a||X(!1,"One of the provided types for building the Schema is missing a name."),this._typeMap[a]!==void 0)throw new Error(`Schema must contain uniquely named types but contains multiple types named "${a}".`);if(this._typeMap[a]=s,Ce(s)){for(let c of s.getInterfaces())if(Ce(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.interfaces.push(s)}}else if(qe(s)){for(let c of s.getInterfaces())if(Ce(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.objects.push(s)}}}}get[Symbol.toStringTag](){return"GraphQLSchema"}getQueryType(){return this._queryType}getMutationType(){return this._mutationType}getSubscriptionType(){return this._subscriptionType}getRootType(e){switch(e){case ft.QUERY:return this.getQueryType();case ft.MUTATION:return this.getMutationType();case ft.SUBSCRIPTION:return this.getSubscriptionType()}}getTypeMap(){return this._typeMap}getType(e){return this.getTypeMap()[e]}getPossibleTypes(e){return ht(e)?e.getTypes():this.getImplementations(e).objects}getImplementations(e){let r=this._implementationsMap[e.name];return r??{objects:[],interfaces:[]}}isSubType(e,r){let n=this._subTypeMap[e.name];if(n===void 0){if(n=Object.create(null),ht(e))for(let i of e.getTypes())n[i.name]=!0;else{let i=this.getImplementations(e);for(let s of i.objects)n[s.name]=!0;for(let s of i.interfaces)n[s.name]=!0}this._subTypeMap[e.name]=n}return n[r.name]!==void 0}getDirectives(){return this._directives}getDirective(e){return this.getDirectives().find(r=>r.name===e)}toConfig(){return{description:this.description,query:this.getQueryType(),mutation:this.getMutationType(),subscription:this.getSubscriptionType(),types:Object.values(this.getTypeMap()),directives:this.getDirectives(),extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes,assumeValid:this.__validationErrors!==void 0}}};function At(t,e){let r=It(t);if(!e.has(r)){if(e.add(r),ht(r))for(let n of r.getTypes())At(n,e);else if(qe(r)||Ce(r)){for(let n of r.getInterfaces())At(n,e);for(let n of Object.values(r.getFields())){At(n.type,e);for(let i of n.args)At(i.type,e)}}else if(Ue(r))for(let n of Object.values(r.getFields()))At(n.type,e)}return e}o(At,"collectReferencedTypes");function Ur(t,e){switch(e.kind){case S.LIST_TYPE:{let r=Ur(t,e.type);return r&&new ve(r)}case S.NON_NULL_TYPE:{let r=Ur(t,e.type);return r&&new Q(r)}case S.NAMED_TYPE:return t.getType(e.name.value)}}o(Ur,"typeFromAST");var kr=class{static{o(this,"TypeInfo")}constructor(e,r,n){this._schema=e,this._typeStack=[],this._parentTypeStack=[],this._inputTypeStack=[],this._fieldDefStack=[],this._defaultValueStack=[],this._directive=null,this._argument=null,this._enumValue=null,this._getFieldDef=n??k1,r&&(ot(r)&&this._inputTypeStack.push(r),jt(r)&&this._parentTypeStack.push(r),tr(r)&&this._typeStack.push(r))}get[Symbol.toStringTag](){return"TypeInfo"}getType(){if(this._typeStack.length>0)return this._typeStack[this._typeStack.length-1]}getParentType(){if(this._parentTypeStack.length>0)return this._parentTypeStack[this._parentTypeStack.length-1]}getInputType(){if(this._inputTypeStack.length>0)return this._inputTypeStack[this._inputTypeStack.length-1]}getParentInputType(){if(this._inputTypeStack.length>1)return this._inputTypeStack[this._inputTypeStack.length-2]}getFieldDef(){if(this._fieldDefStack.length>0)return this._fieldDefStack[this._fieldDefStack.length-1]}getDefaultValue(){if(this._defaultValueStack.length>0)return this._defaultValueStack[this._defaultValueStack.length-1]}getDirective(){return this._directive}getArgument(){return this._argument}getEnumValue(){return this._enumValue}enter(e){let r=this._schema;switch(e.kind){case S.SELECTION_SET:{let i=It(this.getType());this._parentTypeStack.push(jt(i)?i:void 0);break}case S.FIELD:{let i=this.getParentType(),s,a;i&&(s=this._getFieldDef(r,i,e),s&&(a=s.type)),this._fieldDefStack.push(s),this._typeStack.push(tr(a)?a:void 0);break}case S.DIRECTIVE:this._directive=r.getDirective(e.name.value);break;case S.OPERATION_DEFINITION:{let i=r.getRootType(e.operation);this._typeStack.push(qe(i)?i:void 0);break}case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:{let i=e.typeCondition,s=i?Ur(r,i):It(this.getType());this._typeStack.push(tr(s)?s:void 0);break}case S.VARIABLE_DEFINITION:{let i=Ur(r,e.type);this._inputTypeStack.push(ot(i)?i:void 0);break}case S.ARGUMENT:{var n;let i,s,a=(n=this.getDirective())!==null&&n!==void 0?n:this.getFieldDef();a&&(i=a.args.find(c=>c.name===e.name.value),i&&(s=i.type)),this._argument=i,this._defaultValueStack.push(i?i.defaultValue:void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.LIST:{let i=Ou(this.getInputType()),s=Xe(i)?i.ofType:i;this._defaultValueStack.push(void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.OBJECT_FIELD:{let i=It(this.getInputType()),s,a;Ue(i)&&(a=i.getFields()[e.name.value],a&&(s=a.type)),this._defaultValueStack.push(a?a.defaultValue:void 0),this._inputTypeStack.push(ot(s)?s:void 0);break}case S.ENUM:{let i=It(this.getInputType()),s;it(i)&&(s=i.getValue(e.value)),this._enumValue=s;break}default:}}leave(e){switch(e.kind){case S.SELECTION_SET:this._parentTypeStack.pop();break;case S.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case S.DIRECTIVE:this._directive=null;break;case S.OPERATION_DEFINITION:case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:this._typeStack.pop();break;case S.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case S.ARGUMENT:this._argument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case S.LIST:case S.OBJECT_FIELD:this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case S.ENUM:this._enumValue=null;break;default:}}};function k1(t,e,r){let n=r.name.value;if(n===Uu.name&&t.getQueryType()===e)return Uu;if(n===ku.name&&t.getQueryType()===e)return ku;if(n===Fu.name&&jt(e))return Fu;if(qe(e)||Ce(e))return e.getFields()[n]}o(k1,"getFieldDef");function Ti(t,e){return{enter(...r){let n=r[0];t.enter(n);let i=wi(e,n.kind).enter;if(i){let s=i.apply(e,r);return s!==void 0&&(t.leave(n),go(s)&&t.enter(s)),s}},leave(...r){let n=r[0],i=wi(e,n.kind).leave,s;return i&&(s=i.apply(e,r)),t.leave(n),s}}}o(Ti,"visitWithTypeInfo");function Hu(t){return t.map(e=>typeof e=="number"?"["+e.toString()+"]":"."+e).join("")}o(Hu,"printPathArray");function Oh(t,e,r){return{prev:t,key:e,typename:r}}o(Oh,"addPath");function rr(t){let e=[],r=t;for(;r;)e.push(r.key),r=r.prev;return e.reverse()}o(rr,"pathToArray");function Nh(t,e,r=F1){return Ro(t,e,r,void 0)}o(Nh,"coerceInputValue");function F1(t,e,r){let n="Invalid value "+U(e);throw t.length>0&&(n+=` at "value${Hu(t)}"`),r.message=n+": "+r.message,r}o(F1,"defaultOnError");function Ro(t,e,r,n){if(ye(e)){if(t!=null)return Ro(t,e.ofType,r,n);r(rr(n),t,new $(`Expected non-nullable type "${U(e)}" not to be null.`));return}if(t==null)return null;if(Xe(e)){let i=e.ofType;return Mu(t)?Array.from(t,(s,a)=>{let c=Oh(n,a,void 0);return Ro(s,i,r,c)}):[Ro(t,i,r,n)]}if(Ue(e)){if(!Ne(t)){r(rr(n),t,new $(`Expected type "${e.name}" to be an object.`));return}let i={},s=e.getFields();for(let a of Object.values(s)){let c=t[a.name];if(c===void 0){if(a.defaultValue!==void 0)i[a.name]=a.defaultValue;else if(ye(a.type)){let u=U(a.type);r(rr(n),t,new $(`Field "${a.name}" of required type "${u}" was not provided.`))}continue}i[a.name]=Ro(c,a.type,r,Oh(n,a.name,e.name))}for(let a of Object.keys(t))if(!s[a]){let c=wu(a,Object.keys(e.getFields()));r(rr(n),t,new $(`Field "${a}" is not defined by type "${e.name}".`+_u(c)))}return i}if(Dr(e)){let i;try{i=e.parseValue(t)}catch(s){s instanceof $?r(rr(n),t,s):r(rr(n),t,new $(`Expected type "${e.name}". `+s.message,{originalError:s}));return}return i===void 0&&r(rr(n),t,new $(`Expected type "${e.name}".`)),i}Ht(!1,"Unexpected input type: "+U(e))}o(Ro,"coerceInputValueImpl");function Vt(t,e,r){if(t){if(t.kind===S.VARIABLE){let n=t.name.value;if(r==null||r[n]===void 0)return;let i=r[n];return i===null&&ye(e)?void 0:i}if(ye(e))return t.kind===S.NULL?void 0:Vt(t,e.ofType,r);if(t.kind===S.NULL)return null;if(Xe(e)){let n=e.ofType;if(t.kind===S.LIST){let s=[];for(let a of t.values)if(Qw(a,r)){if(ye(n))return;s.push(null)}else{let c=Vt(a,n,r);if(c===void 0)return;s.push(c)}return s}let i=Vt(t,n,r);return i===void 0?void 0:[i]}if(Ue(e)){if(t.kind!==S.OBJECT)return;let n=Object.create(null),i=Ei(t.fields,s=>s.name.value);for(let s of Object.values(e.getFields())){let a=i[s.name];if(!a||Qw(a.value,r)){if(s.defaultValue!==void 0)n[s.name]=s.defaultValue;else if(ye(s.type))return;continue}let c=Vt(a.value,s.type,r);if(c===void 0)return;n[s.name]=c}return n}if(Dr(e)){let n;try{n=e.parseLiteral(t,r)}catch{return}return n===void 0?void 0:n}Ht(!1,"Unexpected input type: "+U(e))}}o(Vt,"valueFromAST");function Qw(t,e){return t.kind===S.VARIABLE&&(e==null||e[t.name.value]===void 0)}o(Qw,"isMissingVariable");function qu(t,e,r,n){let i=[],s=n?.maxErrors;try{let a=H1(t,e,r,c=>{if(s!=null&&i.length>=s)throw new $("Too many errors processing variables, error limit reached. Execution aborted.");i.push(c)});if(i.length===0)return{coerced:a}}catch(a){i.push(a)}return{errors:i}}o(qu,"getVariableValues");function H1(t,e,r,n){let i={};for(let s of e){let a=s.variable.name.value,c=Ur(t,s.type);if(!ot(c)){let l=Be(s.type);n(new $(`Variable "$${a}" expected value of type "${l}" which cannot be used as an input type.`,{nodes:s.type}));continue}if(!Yw(r,a)){if(s.defaultValue)i[a]=Vt(s.defaultValue,c);else if(ye(c)){let l=U(c);n(new $(`Variable "$${a}" of required type "${l}" was not provided.`,{nodes:s}))}continue}let u=r[a];if(u===null&&ye(c)){let l=U(c);n(new $(`Variable "$${a}" of non-null type "${l}" must not be null.`,{nodes:s}));continue}i[a]=Nh(u,c,(l,d,p)=>{let f=`Variable "$${a}" got invalid value `+U(d);l.length>0&&(f+=` at "${a}${Hu(l)}"`),n(new $(f+"; "+p.message,{nodes:s,originalError:p}))})}return i}o(H1,"coerceVariableValues");function Oo(t,e,r){var n;let i={},s=(n=e.arguments)!==null&&n!==void 0?n:[],a=Ei(s,c=>c.name.value);for(let c of t.args){let u=c.name,l=c.type,d=a[u];if(!d){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ye(l))throw new $(`Argument "${u}" of required type "${U(l)}" was not provided.`,{nodes:e});continue}let p=d.value,f=p.kind===S.NULL;if(p.kind===S.VARIABLE){let y=p.name.value;if(r==null||!Yw(r,y)){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ye(l))throw new $(`Argument "${u}" of required type "${U(l)}" was provided the variable "$${y}" which was not provided a runtime value.`,{nodes:p});continue}f=r[y]==null}if(f&&ye(l))throw new $(`Argument "${u}" of non-null type "${U(l)}" must not be null.`,{nodes:p});let h=Vt(p,l,r);if(h===void 0)throw new $(`Argument "${u}" has invalid value ${Be(p)}.`,{nodes:p});i[u]=h}return i}o(Oo,"getArgumentValues");function No(t,e,r){var n;let i=(n=e.directives)===null||n===void 0?void 0:n.find(s=>s.name.value===t.name);if(i)return Oo(t,i,r)}o(No,"getDirectiveValues");function Yw(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(Yw,"hasOwnProperty");var $u=class{static{o(this,"ASTValidationContext")}constructor(e,r){this._ast=e,this._fragments=void 0,this._fragmentSpreads=new Map,this._recursivelyReferencedFragments=new Map,this._onError=r}get[Symbol.toStringTag](){return"ASTValidationContext"}reportError(e){this._onError(e)}getDocument(){return this._ast}getFragment(e){let r;if(this._fragments)r=this._fragments;else{r=Object.create(null);for(let n of this.getDocument().definitions)n.kind===S.FRAGMENT_DEFINITION&&(r[n.name.value]=n);this._fragments=r}return r[e]}getFragmentSpreads(e){let r=this._fragmentSpreads.get(e);if(!r){r=[];let n=[e],i;for(;i=n.pop();)for(let s of i.selections)s.kind===S.FRAGMENT_SPREAD?r.push(s):s.selectionSet&&n.push(s.selectionSet);this._fragmentSpreads.set(e,r)}return r}getRecursivelyReferencedFragments(e){let r=this._recursivelyReferencedFragments.get(e);if(!r){r=[];let n=Object.create(null),i=[e.selectionSet],s;for(;s=i.pop();)for(let a of this.getFragmentSpreads(s)){let c=a.name.value;if(n[c]!==!0){n[c]=!0;let u=this.getFragment(c);u&&(r.push(u),i.push(u.selectionSet))}}this._recursivelyReferencedFragments.set(e,r)}return r}},Zw=class extends $u{static{o(this,"SDLValidationContext")}constructor(e,r,n){super(e,n),this._schema=r}get[Symbol.toStringTag](){return"SDLValidationContext"}getSchema(){return this._schema}},Si=class extends $u{static{o(this,"ValidationContext")}constructor(e,r,n,i){super(r,i),this._schema=e,this._typeInfo=n,this._variableUsages=new Map,this._recursiveVariableUsages=new Map}get[Symbol.toStringTag](){return"ValidationContext"}getSchema(){return this._schema}getVariableUsages(e){let r=this._variableUsages.get(e);if(!r){let n=[],i=new kr(this._schema);xr(e,Ti(i,{VariableDefinition:()=>!1,Variable(s){n.push({node:s,type:i.getInputType(),defaultValue:i.getDefaultValue()})}})),r=n,this._variableUsages.set(e,r)}return r}getRecursiveVariableUsages(e){let r=this._recursiveVariableUsages.get(e);if(!r){r=this.getVariableUsages(e);for(let n of this.getRecursivelyReferencedFragments(e))r=r.concat(this.getVariableUsages(n));this._recursiveVariableUsages.set(e,r)}return r}getType(){return this._typeInfo.getType()}getParentType(){return this._typeInfo.getParentType()}getInputType(){return this._typeInfo.getInputType()}getParentInputType(){return this._typeInfo.getParentInputType()}getFieldDef(){return this._typeInfo.getFieldDef()}getDirective(){return this._typeInfo.getDirective()}getArgument(){return this._typeInfo.getArgument()}getEnumValue(){return this._typeInfo.getEnumValue()}};function ju(t){let e={descriptions:!0,specifiedByUrl:!1,directiveIsRepeatable:!1,schemaDescription:!1,inputValueDeprecation:!1,...t},r=e.descriptions?"description":"",n=e.specifiedByUrl?"specifiedByURL":"",i=e.directiveIsRepeatable?"isRepeatable":"",s=e.schemaDescription?r:"";function a(c){return e.inputValueDeprecation?c:""}return o(a,"inputDeprecation"),`
131
131
  query IntrospectionQuery {
132
132
  __schema {
133
133
  ${s}
@@ -232,5 +232,5 @@ In some cases, you need to provide options to alter GraphQL's execution behavior
232
232
  }
233
233
  }
234
234
  }
235
- `}o(ju,"getIntrospectionQuery");function Vu(t,e){Ne(t)&&Ne(t.__schema)||X(!1,`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${U(t)}.`);let r=t.__schema,n=qt(r.types,w=>w.name,w=>f(w));for(let w of[...Eh,...Rh])n[w.name]&&(n[w.name]=w);let i=r.queryType?d(r.queryType):null,s=r.mutationType?d(r.mutationType):null,a=r.subscriptionType?d(r.subscriptionType):null,c=r.directives?r.directives.map(C):[];return new Ao({description:r.description,query:i,mutation:s,subscription:a,types:Object.values(n),directives:c,assumeValid:e?.assumeValid});function u(w){if(w.kind===ue.LIST){let P=w.ofType;if(!P)throw new Error("Decorated type deeper than introspection query.");return new ve(u(P))}if(w.kind===ue.NON_NULL){let P=w.ofType;if(!P)throw new Error("Decorated type deeper than introspection query.");let L=u(P);return new Q(Ru(L))}return l(w)}function l(w){let P=w.name;if(!P)throw new Error(`Unknown type reference: ${U(w)}.`);let L=n[P];if(!L)throw new Error(`Invalid or incomplete schema, unknown type: ${P}. Ensure that a full introspection query is used in order to build a client schema.`);return L}function d(w){return Iu(l(w))}function p(w){return Pu(l(w))}function f(w){if(w!=null&&w.name!=null&&w.kind!=null)switch(w.kind){case ue.SCALAR:return h(w);case ue.OBJECT:return b(w);case ue.INTERFACE:return I(w);case ue.UNION:return A(w);case ue.ENUM:return g(w);case ue.INPUT_OBJECT:return v(w)}let P=U(w);throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${P}.`)}function h(w){return new nt({name:w.name,description:w.description,specifiedByURL:w.specifiedByURL})}function y(w){if(w.interfaces===null&&w.kind===ue.INTERFACE)return[];if(!w.interfaces){let P=U(w);throw new Error(`Introspection result missing interfaces: ${P}.`)}return w.interfaces.map(p)}function b(w){return new He({name:w.name,description:w.description,interfaces:()=>y(w),fields:()=>O(w)})}function I(w){return new er({name:w.name,description:w.description,interfaces:()=>y(w),fields:()=>O(w)})}function A(w){if(!w.possibleTypes){let P=U(w);throw new Error(`Introspection result missing possibleTypes: ${P}.`)}return new dn({name:w.name,description:w.description,types:()=>w.possibleTypes.map(d)})}function g(w){if(!w.enumValues){let P=U(w);throw new Error(`Introspection result missing enumValues: ${P}.`)}return new $t({name:w.name,description:w.description,values:qt(w.enumValues,P=>P.name,P=>({description:P.description,deprecationReason:P.deprecationReason}))})}function v(w){if(!w.inputFields){let P=U(w);throw new Error(`Introspection result missing inputFields: ${P}.`)}return new pn({name:w.name,description:w.description,fields:()=>E(w.inputFields)})}function O(w){if(!w.fields)throw new Error(`Introspection result missing fields: ${U(w)}.`);return qt(w.fields,P=>P.name,V)}function V(w){let P=u(w.type);if(!tr(P)){let L=U(P);throw new Error(`Introspection must provide output type for fields, but received: ${L}.`)}if(!w.args){let L=U(w);throw new Error(`Introspection result missing field args: ${L}.`)}return{description:w.description,deprecationReason:w.deprecationReason,type:P,args:E(w.args)}}function E(w){return qt(w,P=>P.name,T)}function T(w){let P=u(w.type);if(!ot(P)){let te=U(P);throw new Error(`Introspection must provide input type for arguments, but received: ${te}.`)}let L=w.defaultValue!=null?Vt(bu(w.defaultValue),P):void 0;return{description:w.description,type:P,defaultValue:L,deprecationReason:w.deprecationReason}}function C(w){if(!w.args){let P=U(w);throw new Error(`Introspection result missing directive args: ${P}.`)}if(!w.locations){let P=U(w);throw new Error(`Introspection result missing directive locations: ${P}.`)}return new Pt({name:w.name,description:w.description,isRepeatable:w.isRepeatable,locations:w.locations.slice(),args:E(w.args)})}}o(Vu,"buildClientSchema");function aM(t,e){return`The query exceeds the maximum complexity of ${t}. Actual complexity is ${e}`}o(aM,"queryComplexityMessage");function Xw(t){let e=new kr(t.schema),r=[],n=new Si(t.schema,t.query,e,s=>r.push(s)),i=new Ch(n,{maximumComplexity:t.maximumComplexity??1/0,estimators:t.estimators,variables:t.variables,operationName:t.operationName,context:t.context});if(xr(t.query,Ti(e,i)),r.length)throw r.pop();return i.complexity}o(Xw,"getComplexity");var Ch=class{static{o(this,"QueryComplexity")}context;complexity;options;OperationDefinition;estimators;includeDirectiveDef;skipDirectiveDef;variableValues;requestContext;constructor(e,r){if(Number(r.maximumComplexity)<=0)throw new Error("Maximum query complexity must be a positive number");this.context=e,this.complexity=0,this.options=r,this.includeDirectiveDef=this.context.getSchema().getDirective("include")||void 0,this.skipDirectiveDef=this.context.getSchema().getDirective("skip")||void 0,this.estimators=r.estimators,this.variableValues={},this.requestContext=r.context,this.OperationDefinition={enter:this.onOperationDefinitionEnter,leave:this.onOperationDefinitionLeave}}onOperationDefinitionEnter(e){if(typeof this.options.operationName=="string"&&this.options.operationName!==e.name?.value)return;let{coerced:r,errors:n}=qu(this.context.getSchema(),e.variableDefinitions?[...e.variableDefinitions]:[],this.options.variables??{});if(n&&n.length){n.forEach(s=>this.context.reportError(s));return}this.variableValues=r||{};let i=this.context.getSchema();switch(e.operation){case"query":{let s=i.getQueryType();if(!s)throw new Error("Schema does not define the required query root type");this.complexity+=this.nodeComplexity(e,s);break}case"mutation":{let s=i.getMutationType();if(!s)throw new Error("Schema does not define the required mutation root type");this.complexity+=this.nodeComplexity(e,s);break}case"subscription":{let s=i.getSubscriptionType();if(!s)throw new Error("Schema does not define the required mutation subscription type");this.complexity+=this.nodeComplexity(e,s);break}default:throw new Error(`Query complexity could not be calculated for operation of type ${e.operation}`)}}onOperationDefinitionLeave(e){if(!(typeof this.options.operationName=="string"&&this.options.operationName!==e.name?.value)&&(this.options.onComplete&&this.options.onComplete(this.complexity),this.complexity>this.options.maximumComplexity))return this.context.reportError(this.createError())}nodeComplexity(e,r){if(e.selectionSet){let n={};(r instanceof He||r instanceof er)&&(n=r.getFields());let i;Mr(r)?i=this.context.getSchema().getPossibleTypes(r).map(a=>a.name):i=[r.name];let s=e.selectionSet.selections.reduce((a,c)=>{let u=a,l=!0,d=!1;for(let p of c.directives??[])switch(p.name.value){case"include":{let h=this.includeDirectiveDef&&No(this.includeDirectiveDef,c,this.variableValues||{});typeof h?.if=="boolean"&&(l=h.if);break}case"skip":{let h=this.skipDirectiveDef&&No(this.skipDirectiveDef,c,this.variableValues||{});typeof h?.if=="boolean"&&(d=h.if);break}}if(!l||d)return a;switch(c.kind){case S.FIELD:{let p=n[c.name.value];if(!p)break;let f=It(p.type),h;try{h=Oo(p,c,this.variableValues||{})}catch(A){return this.context.reportError(A),a}let y=0;jt(f)&&(y=this.nodeComplexity(c,f));let b={childComplexity:y,args:h,field:p,node:c,type:r,context:this.requestContext};if(!this.estimators.find(A=>{let g=A(b);return typeof g=="number"&&!isNaN(g)?(u=Ii(g,a,i),!0):!1}))return this.context.reportError(new $(`No complexity could be calculated for field ${r.name}.${p.name}. At least one complexity estimator has to return a complexity score.`)),a;break}case S.FRAGMENT_SPREAD:{let p=this.context.getFragment(c.name.value);if(!p)break;let f=this.context.getSchema().getType(p.typeCondition.name.value);if(!jt(f))break;let h=this.nodeComplexity(p,f);Mr(f)?u=Ii(h,a,this.context.getSchema().getPossibleTypes(f).map(y=>y.name)):u=Ii(h,a,[f.name]);break}case S.INLINE_FRAGMENT:{let p=r;if(c.typeCondition&&c.typeCondition.name&&(p=this.context.getSchema().getType(c.typeCondition.name.value)||p,!jt(p)))break;let f=this.nodeComplexity(c,p);Mr(p)?u=Ii(f,a,this.context.getSchema().getPossibleTypes(p).map(h=>h.name)):u=Ii(f,a,[p.name]);break}default:{u=Ii(this.nodeComplexity(c,r),a,i);break}}return u},{});return s?Math.max(...Object.values(s),0):NaN}return 0}createError(){return typeof this.options.createError=="function"?this.options.createError(this.options.maximumComplexity,this.complexity):new $(aM(this.options.maximumComplexity,this.complexity))}};function Ii(t,e,r){for(let n of r)Object.prototype.hasOwnProperty.call(e,n)?e[n]+=t:e[n]=t;return e}o(Ii,"addComplexities");function ev(t){let e=t?.defaultComplexity??1;return r=>e+r.childComplexity}o(ev,"simpleEstimator");var tv=o((t,e,r={})=>{let{definitions:n}=t,i=cM(n),s=uM(n);return Object.entries(s).map(([a,c])=>Bu(c,i,0,e,a,r))},"depthLimit");function cM(t){return t.reduce((e,r)=>(r.kind===S.FRAGMENT_DEFINITION&&(e[r?.name?.value??""]=r),e),{})}o(cM,"getFragments");function uM(t){return t.reduce((e,r)=>{if(r.kind===S.OPERATION_DEFINITION){let n=r?.name?.value??"";e[n]=r}return e},{})}o(uM,"getQueriesAndMutations");function Bu(t,e,r,n,i,s){if(r>n)throw s?.onLimitReached?.(r,i),new $(`${i||"Your query"} exceeds maximum operation depth of ${n}`,{nodes:[t]});let a=s?.ignore??[/^__/];switch(t.kind){case S.FIELD:return lM(t,a)||!t.selectionSet?0:1+Math.max(...t.selectionSet.selections.map(c=>Bu(c,e,r+1,n,i,s)));case S.FRAGMENT_SPREAD:return Bu(e[t.name.value],e,r,n,i,s);case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:case S.OPERATION_DEFINITION:return Math.max(...t.selectionSet.selections.map(c=>Bu(c,e,r,n,i,s)));default:throw new Error("uh oh! depth crawler cannot handle: "+t.kind)}}o(Bu,"determineDepth");var lM=o((t,e)=>e.find(r=>t.name.value.match(r)!==null)||!1,"isIgnored");var dM=o(async(t,e)=>{if(!e.complexityLimit)throw new Pi.ConfigurationError("No complexity maximum defined, you need to pass a maxComplexity to the policy");let n=e.endpointUrl;if(!n)throw new Pi.ConfigurationError("No GraphQL endpoint, you need to pass a endpointUrl to the policy");let i=ju(),c=(await(await fetch(n,{method:"POST",body:JSON.stringify({query:i}),headers:{"Content-Type":"application/json"}})).json()).data;if(!c||!c?.__schema)throw new $("GraphQL introspection query failed, enable introspection or pass a schema url in configuration.");let u=Vu(c,{assumeValid:!0}),l=Xw({estimators:[ev({defaultComplexity:1})],schema:u,query:t,variables:{count:10}});if(e.complexityLimit&&l>e.complexityLimit)throw new $(`Query is too complex (${l}/${e.complexityLimit}), remove some fields and try again`)},"applyComplexityLimitPolicy"),pM=o(async(t,e)=>{let r=e.depthLimit;if(!r)throw new Pi.ConfigurationError("No maximum depth defined, you need to pass a maxDepth to the policy");return Math.max(...tv(t,r))},"applyDepthLimitPolicy"),rv=o(async(t,e,r)=>{let n=Pi.SystemLogMap.getLogger(e);try{let s=await t.clone().json(),a=gu(s.query);r.useDepthLimit&&await pM(a,r.useDepthLimit),r.useComplexityLimit&&await dM(a,r.useComplexityLimit)}catch(i){if(i instanceof $)return n.info(i),new Response(JSON.stringify(i.toJSON()),{status:400,headers:{"Content-Type":"application/json"}});throw i}return t},"GraphQLComplexityLimitInboundPolicy");var nv=Mh(Kt());function fM(t){if(!t)return!1;let e=t.replace(/\s/g,"");return e.includes("__schema")||e.includes("__type")}o(fM,"isIntrospectionQuery");var iv=o(async(t,e)=>{let n=await t.clone().json();return fM(n.query)?nv.HttpProblems.forbidden(t,e,{detail:"Introspection queries are not allowed"}):t},"GraphQLDisableIntrospectionInboundPolicy");
235
+ `}o(ju,"getIntrospectionQuery");function Vu(t,e){Ne(t)&&Ne(t.__schema)||X(!1,`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${U(t)}.`);let r=t.__schema,n=qt(r.types,w=>w.name,w=>f(w));for(let w of[...Eh,...Rh])n[w.name]&&(n[w.name]=w);let i=r.queryType?d(r.queryType):null,s=r.mutationType?d(r.mutationType):null,a=r.subscriptionType?d(r.subscriptionType):null,c=r.directives?r.directives.map(C):[];return new Ao({description:r.description,query:i,mutation:s,subscription:a,types:Object.values(n),directives:c,assumeValid:e?.assumeValid});function u(w){if(w.kind===ue.LIST){let P=w.ofType;if(!P)throw new Error("Decorated type deeper than introspection query.");return new ve(u(P))}if(w.kind===ue.NON_NULL){let P=w.ofType;if(!P)throw new Error("Decorated type deeper than introspection query.");let L=u(P);return new Q(Ru(L))}return l(w)}function l(w){let P=w.name;if(!P)throw new Error(`Unknown type reference: ${U(w)}.`);let L=n[P];if(!L)throw new Error(`Invalid or incomplete schema, unknown type: ${P}. Ensure that a full introspection query is used in order to build a client schema.`);return L}function d(w){return Iu(l(w))}function p(w){return Pu(l(w))}function f(w){if(w!=null&&w.name!=null&&w.kind!=null)switch(w.kind){case ue.SCALAR:return h(w);case ue.OBJECT:return b(w);case ue.INTERFACE:return I(w);case ue.UNION:return A(w);case ue.ENUM:return g(w);case ue.INPUT_OBJECT:return v(w)}let P=U(w);throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${P}.`)}function h(w){return new nt({name:w.name,description:w.description,specifiedByURL:w.specifiedByURL})}function y(w){if(w.interfaces===null&&w.kind===ue.INTERFACE)return[];if(!w.interfaces){let P=U(w);throw new Error(`Introspection result missing interfaces: ${P}.`)}return w.interfaces.map(p)}function b(w){return new He({name:w.name,description:w.description,interfaces:()=>y(w),fields:()=>O(w)})}function I(w){return new er({name:w.name,description:w.description,interfaces:()=>y(w),fields:()=>O(w)})}function A(w){if(!w.possibleTypes){let P=U(w);throw new Error(`Introspection result missing possibleTypes: ${P}.`)}return new dn({name:w.name,description:w.description,types:()=>w.possibleTypes.map(d)})}function g(w){if(!w.enumValues){let P=U(w);throw new Error(`Introspection result missing enumValues: ${P}.`)}return new $t({name:w.name,description:w.description,values:qt(w.enumValues,P=>P.name,P=>({description:P.description,deprecationReason:P.deprecationReason}))})}function v(w){if(!w.inputFields){let P=U(w);throw new Error(`Introspection result missing inputFields: ${P}.`)}return new pn({name:w.name,description:w.description,fields:()=>E(w.inputFields)})}function O(w){if(!w.fields)throw new Error(`Introspection result missing fields: ${U(w)}.`);return qt(w.fields,P=>P.name,V)}function V(w){let P=u(w.type);if(!tr(P)){let L=U(P);throw new Error(`Introspection must provide output type for fields, but received: ${L}.`)}if(!w.args){let L=U(w);throw new Error(`Introspection result missing field args: ${L}.`)}return{description:w.description,deprecationReason:w.deprecationReason,type:P,args:E(w.args)}}function E(w){return qt(w,P=>P.name,T)}function T(w){let P=u(w.type);if(!ot(P)){let te=U(P);throw new Error(`Introspection must provide input type for arguments, but received: ${te}.`)}let L=w.defaultValue!=null?Vt(bu(w.defaultValue),P):void 0;return{description:w.description,type:P,defaultValue:L,deprecationReason:w.deprecationReason}}function C(w){if(!w.args){let P=U(w);throw new Error(`Introspection result missing directive args: ${P}.`)}if(!w.locations){let P=U(w);throw new Error(`Introspection result missing directive locations: ${P}.`)}return new Pt({name:w.name,description:w.description,isRepeatable:w.isRepeatable,locations:w.locations.slice(),args:E(w.args)})}}o(Vu,"buildClientSchema");function uM(t,e){return`The query exceeds the maximum complexity of ${t}. Actual complexity is ${e}`}o(uM,"queryComplexityMessage");function Xw(t){let e=new kr(t.schema),r=[],n=new Si(t.schema,t.query,e,s=>r.push(s)),i=new Ch(n,{maximumComplexity:t.maximumComplexity??1/0,estimators:t.estimators,variables:t.variables,operationName:t.operationName,context:t.context});if(xr(t.query,Ti(e,i)),r.length)throw r.pop();return i.complexity}o(Xw,"getComplexity");var Ch=class{static{o(this,"QueryComplexity")}context;complexity;options;OperationDefinition;estimators;includeDirectiveDef;skipDirectiveDef;variableValues;requestContext;constructor(e,r){if(Number(r.maximumComplexity)<=0)throw new Error("Maximum query complexity must be a positive number");this.context=e,this.complexity=0,this.options=r,this.includeDirectiveDef=this.context.getSchema().getDirective("include")||void 0,this.skipDirectiveDef=this.context.getSchema().getDirective("skip")||void 0,this.estimators=r.estimators,this.variableValues={},this.requestContext=r.context,this.OperationDefinition={enter:this.onOperationDefinitionEnter,leave:this.onOperationDefinitionLeave}}onOperationDefinitionEnter(e){if(typeof this.options.operationName=="string"&&this.options.operationName!==e.name?.value)return;let{coerced:r,errors:n}=qu(this.context.getSchema(),e.variableDefinitions?[...e.variableDefinitions]:[],this.options.variables??{});if(n&&n.length){n.forEach(s=>this.context.reportError(s));return}this.variableValues=r||{};let i=this.context.getSchema();switch(e.operation){case"query":{let s=i.getQueryType();if(!s)throw new Error("Schema does not define the required query root type");this.complexity+=this.nodeComplexity(e,s);break}case"mutation":{let s=i.getMutationType();if(!s)throw new Error("Schema does not define the required mutation root type");this.complexity+=this.nodeComplexity(e,s);break}case"subscription":{let s=i.getSubscriptionType();if(!s)throw new Error("Schema does not define the required mutation subscription type");this.complexity+=this.nodeComplexity(e,s);break}default:throw new Error(`Query complexity could not be calculated for operation of type ${e.operation}`)}}onOperationDefinitionLeave(e){if(!(typeof this.options.operationName=="string"&&this.options.operationName!==e.name?.value)&&(this.options.onComplete&&this.options.onComplete(this.complexity),this.complexity>this.options.maximumComplexity))return this.context.reportError(this.createError())}nodeComplexity(e,r){if(e.selectionSet){let n={};(r instanceof He||r instanceof er)&&(n=r.getFields());let i;Mr(r)?i=this.context.getSchema().getPossibleTypes(r).map(a=>a.name):i=[r.name];let s=e.selectionSet.selections.reduce((a,c)=>{let u=a,l=!0,d=!1;for(let p of c.directives??[])switch(p.name.value){case"include":{let h=this.includeDirectiveDef&&No(this.includeDirectiveDef,c,this.variableValues||{});typeof h?.if=="boolean"&&(l=h.if);break}case"skip":{let h=this.skipDirectiveDef&&No(this.skipDirectiveDef,c,this.variableValues||{});typeof h?.if=="boolean"&&(d=h.if);break}}if(!l||d)return a;switch(c.kind){case S.FIELD:{let p=n[c.name.value];if(!p)break;let f=It(p.type),h;try{h=Oo(p,c,this.variableValues||{})}catch(A){return this.context.reportError(A),a}let y=0;jt(f)&&(y=this.nodeComplexity(c,f));let b={childComplexity:y,args:h,field:p,node:c,type:r,context:this.requestContext};if(!this.estimators.find(A=>{let g=A(b);return typeof g=="number"&&!isNaN(g)?(u=Ii(g,a,i),!0):!1}))return this.context.reportError(new $(`No complexity could be calculated for field ${r.name}.${p.name}. At least one complexity estimator has to return a complexity score.`)),a;break}case S.FRAGMENT_SPREAD:{let p=this.context.getFragment(c.name.value);if(!p)break;let f=this.context.getSchema().getType(p.typeCondition.name.value);if(!jt(f))break;let h=this.nodeComplexity(p,f);Mr(f)?u=Ii(h,a,this.context.getSchema().getPossibleTypes(f).map(y=>y.name)):u=Ii(h,a,[f.name]);break}case S.INLINE_FRAGMENT:{let p=r;if(c.typeCondition&&c.typeCondition.name&&(p=this.context.getSchema().getType(c.typeCondition.name.value)||p,!jt(p)))break;let f=this.nodeComplexity(c,p);Mr(p)?u=Ii(f,a,this.context.getSchema().getPossibleTypes(p).map(h=>h.name)):u=Ii(f,a,[p.name]);break}default:{u=Ii(this.nodeComplexity(c,r),a,i);break}}return u},{});return s?Math.max(...Object.values(s),0):NaN}return 0}createError(){return typeof this.options.createError=="function"?this.options.createError(this.options.maximumComplexity,this.complexity):new $(uM(this.options.maximumComplexity,this.complexity))}};function Ii(t,e,r){for(let n of r)Object.prototype.hasOwnProperty.call(e,n)?e[n]+=t:e[n]=t;return e}o(Ii,"addComplexities");function ev(t){let e=t?.defaultComplexity??1;return r=>e+r.childComplexity}o(ev,"simpleEstimator");var tv=o((t,e,r={})=>{let{definitions:n}=t,i=lM(n),s=dM(n);return Object.entries(s).map(([a,c])=>Bu(c,i,0,e,a,r))},"depthLimit");function lM(t){return t.reduce((e,r)=>(r.kind===S.FRAGMENT_DEFINITION&&(e[r?.name?.value??""]=r),e),{})}o(lM,"getFragments");function dM(t){return t.reduce((e,r)=>{if(r.kind===S.OPERATION_DEFINITION){let n=r?.name?.value??"";e[n]=r}return e},{})}o(dM,"getQueriesAndMutations");function Bu(t,e,r,n,i,s){if(r>n)throw s?.onLimitReached?.(r,i),new $(`${i||"Your query"} exceeds maximum operation depth of ${n}`,{nodes:[t]});let a=s?.ignore??[/^__/];switch(t.kind){case S.FIELD:return pM(t,a)||!t.selectionSet?0:1+Math.max(...t.selectionSet.selections.map(c=>Bu(c,e,r+1,n,i,s)));case S.FRAGMENT_SPREAD:return Bu(e[t.name.value],e,r,n,i,s);case S.INLINE_FRAGMENT:case S.FRAGMENT_DEFINITION:case S.OPERATION_DEFINITION:return Math.max(...t.selectionSet.selections.map(c=>Bu(c,e,r,n,i,s)));default:throw new Error("uh oh! depth crawler cannot handle: "+t.kind)}}o(Bu,"determineDepth");var pM=o((t,e)=>e.find(r=>t.name.value.match(r)!==null)||!1,"isIgnored");var fM=o(async(t,e)=>{if(!e.complexityLimit)throw new Pi.ConfigurationError("No complexity maximum defined, you need to pass a maxComplexity to the policy");let n=e.endpointUrl;if(!n)throw new Pi.ConfigurationError("No GraphQL endpoint, you need to pass a endpointUrl to the policy");let i=ju(),c=(await(await fetch(n,{method:"POST",body:JSON.stringify({query:i}),headers:{"Content-Type":"application/json"}})).json()).data;if(!c||!c?.__schema)throw new $("GraphQL introspection query failed, enable introspection or pass a schema url in configuration.");let u=Vu(c,{assumeValid:!0}),l=Xw({estimators:[ev({defaultComplexity:1})],schema:u,query:t,variables:{count:10}});if(e.complexityLimit&&l>e.complexityLimit)throw new $(`Query is too complex (${l}/${e.complexityLimit}), remove some fields and try again`)},"applyComplexityLimitPolicy"),hM=o(async(t,e)=>{let r=e.depthLimit;if(!r)throw new Pi.ConfigurationError("No maximum depth defined, you need to pass a maxDepth to the policy");return Math.max(...tv(t,r))},"applyDepthLimitPolicy"),rv=o(async(t,e,r)=>{let n=Pi.SystemLogMap.getLogger(e);try{let s=await t.clone().json(),a=gu(s.query);r.useDepthLimit&&await hM(a,r.useDepthLimit),r.useComplexityLimit&&await fM(a,r.useComplexityLimit)}catch(i){if(i instanceof $)return n.info(i),new Response(JSON.stringify(i.toJSON()),{status:400,headers:{"Content-Type":"application/json"}});throw i}return t},"GraphQLComplexityLimitInboundPolicy");var nv=Mh(Kt());function mM(t){if(!t)return!1;let e=t.replace(/\s/g,"");return e.includes("__schema")||e.includes("__type")}o(mM,"isIntrospectionQuery");var iv=o(async(t,e)=>{let n=await t.clone().json();return mM(n.query)?nv.HttpProblems.forbidden(t,e,{detail:"Introspection queries are not allowed"}):t},"GraphQLDisableIntrospectionInboundPolicy");
236
236
  /*! For license information please see index.minified.js.LEGAL.txt */