@zuplo/graphql 5.1482.0 → 5.1483.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 +36 -36
  2. package/package.json +1 -1
package/index.minified.js CHANGED
@@ -22,17 +22,17 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- "use strict";var Cb=Object.create;var Jn=Object.defineProperty;var Lb=Object.getOwnPropertyDescriptor;var Db=Object.getOwnPropertyNames;var Ub=Object.getPrototypeOf,Mb=Object.prototype.hasOwnProperty;var o=(t,e)=>Jn(t,"name",{value:e,configurable:!0});var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var g=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ki=(t,e)=>{for(var r in e)Jn(t,r,{get:e[r],enumerable:!0})},Mp=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Db(e))!Mb.call(t,i)&&i!==r&&Jn(t,i,{get:()=>e[i],enumerable:!(n=Lb(e,i))||n.enumerable});return t};var kp=(t,e,r)=>(r=t!=null?Cb(Ub(t)):{},Mp(e||!t||!t.__esModule?Jn(r,"default",{value:t,enumerable:!0}):r,t)),Ji=t=>Mp(Jn({},"__esModule",{value:!0}),t);var D=g(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.FeatureNotEnabledError=ht.ConfigurationError=ht.RuntimeError=ht.SystemError=void 0;var jc=class extends Error{static{o(this,"SystemError")}constructor(e,r){super(e,r),this.name="InternalError"}};ht.SystemError=jc;var zn=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"}};ht.RuntimeError=zn;var Vc=class extends zn{static{o(this,"ConfigurationError")}constructor(e,r){super(e,r),this.name="ConfigurationError"}};ht.ConfigurationError=Vc;var Gc=class extends zn{static{o(this,"FeatureNotEnabledError")}constructor(e,r){super(e,r),this.name="FeatureNotEnabledError"}};ht.FeatureNotEnabledError=Gc});var te=g(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.Environment=void 0;var kb=D(),Bc=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 kb.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 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"}};zi.Environment=Bc});var $p=g(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Fp=te();Function.prototype.toString=function(){return"[native code]"};var Wi=globalThis,Hp=Wi.caches;if(Hp){let t=Hp.open;Wi.caches.open=function(e){let r=Fp.Environment.instance.deploymentName??Fp.Environment.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete Wi.caches.default,Object.freeze(Wi.caches)}});var zc=g(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.MemoryCache=void 0;var Fb=1e4,Hb=1e3,jp=new Map,Kc=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+Fb*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#r.forEach((r,n)=>{r.expiresAt>=e&&this.#r.delete(n)})}},Jc=class{static{o(this,"MemoryCache")}constructor(e,r={maxSize:Hb}){this.name=e;let n=jp.get(e);n||(n=new Kc(r),jp.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()}};Qi.MemoryCache=Jc});var Yc=g(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.ZoneCache=void 0;var Wc="__zuplo-expiry-header",Qc=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(Wc);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(Wc,`${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(Wc,`${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)}};Yi.ZoneCache=Qc});var br=g(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.MemoryZoneReadThroughCache=void 0;var qb=zc(),$b=Yc(),Zc=class{static{o(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new qb.MemoryCache(n),this.#r=new $b.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};this.#r.put(e,i,n).catch(s=>{"logger"in this.#n?this.#n.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,s):"log"in this.#n&&this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,s)})}};Zi.MemoryZoneReadThroughCache=Zc});var Vp=g(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.VALID_COMPATIBILITY_DATES=void 0;Xi.VALID_COMPATIBILITY_DATES=Object.freeze(["2023-03-14"])});var Wn=g(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.INTERNAL_HEADERS_TO_REMOVE=N.ZP_TIMEZONE_HEADER=N.ZP_REGION_CODE_HEADER=N.ZP_REGION_HEADER=N.ZP_METRO_CODE_HEADER=N.ZP_POSTAL_CODE_HEADER=N.ZP_COLO_HEADER=N.ZP_AS_ORG_HEADER=N.ZP_ASN_HEADER=N.TRUE_CLIENT_IP=N.ZP_IP_LATITUDE_HEADER=N.ZP_IP_LONGITUDE_HEADER=N.ZP_IP_COUNTRY_HEADER=N.ZP_IP_CONTINENT_HEADER=N.ZP_IP_CITY_HEADER=N.CF_IP_LATITUDE_HEADER=N.CF_IP_LONGITUDE_HEADER=N.CF_IP_COUNTRY_HEADER=N.CF_IP_CONTINENT_HEADER=N.CF_IP_CITY_HEADER=N.RAY_ID_HEADER=N.BODY_REMOVED_HEADER=N.REQUEST_ID_HEADER=N.LEGACY_REQUEST_ID_HEADER=void 0;N.LEGACY_REQUEST_ID_HEADER="zuplo-request-id";N.REQUEST_ID_HEADER="zp-rid";N.BODY_REMOVED_HEADER="zp-body-removed";N.RAY_ID_HEADER="cf-ray";N.CF_IP_CITY_HEADER="cf-ipcity";N.CF_IP_CONTINENT_HEADER="cf-ipcontinent";N.CF_IP_COUNTRY_HEADER="cf-ipcountry";N.CF_IP_LONGITUDE_HEADER="cf-iplongitude";N.CF_IP_LATITUDE_HEADER="cf-iplatitude";N.ZP_IP_CITY_HEADER="zp-ipcity";N.ZP_IP_CONTINENT_HEADER="zp-ipcontinent";N.ZP_IP_COUNTRY_HEADER="zp-ipcountry";N.ZP_IP_LONGITUDE_HEADER="zp-iplongitude";N.ZP_IP_LATITUDE_HEADER="zp-iplatitude";N.TRUE_CLIENT_IP="true-client-ip";N.ZP_ASN_HEADER="zp-asn";N.ZP_AS_ORG_HEADER="zp-asorg";N.ZP_COLO_HEADER="zp-colo";N.ZP_POSTAL_CODE_HEADER="zp-postalcode";N.ZP_METRO_CODE_HEADER="zp-metrocode";N.ZP_REGION_HEADER="zp-region";N.ZP_REGION_CODE_HEADER="zp-regioncode";N.ZP_TIMEZONE_HEADER="zp-timezone";N.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",N.CF_IP_CITY_HEADER,N.CF_IP_CONTINENT_HEADER,N.CF_IP_COUNTRY_HEADER,N.CF_IP_LONGITUDE_HEADER,N.ZP_ASN_HEADER,N.ZP_AS_ORG_HEADER,N.ZP_COLO_HEADER,N.ZP_POSTAL_CODE_HEADER,N.ZP_METRO_CODE_HEADER,N.ZP_REGION_HEADER,N.ZP_REGION_CODE_HEADER,N.ZP_TIMEZONE_HEADER]});var Zp=g(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.generateColor=w.colorFunctions=w.stripColor=w.bgRgb24=w.rgb24=w.bgRgb8=w.rgb8=w.bgBrightWhite=w.bgBrightCyan=w.bgBrightMagenta=w.bgBrightBlue=w.bgBrightYellow=w.bgBrightGreen=w.bgBrightRed=w.bgBrightBlack=w.bgWhite=w.bgCyan=w.bgMagenta=w.bgBlue=w.bgYellow=w.bgGreen=w.bgRed=w.bgBlack=w.brightWhite=w.brightCyan=w.brightMagenta=w.brightBlue=w.brightYellow=w.brightGreen=w.brightRed=w.brightBlack=w.gray=w.white=w.cyan=w.magenta=w.blue=w.yellow=w.green=w.red=w.black=w.strikethrough=w.hidden=w.inverse=w.underline=w.italic=w.dim=w.bold=w.reset=w.getColorEnabled=w.setColorEnabled=void 0;var Gp=!0,Xc=!Gp;function jb(t){Gp||(Xc=t)}o(jb,"setColorEnabled");w.setColorEnabled=jb;function Vb(){return Xc}o(Vb,"getColorEnabled");w.getColorEnabled=Vb;function q(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}o(q,"code");function $(t,e){return Xc?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}o($,"run");function Gb(t){return $(t,q([0],0))}o(Gb,"reset");w.reset=Gb;function Bb(t){return $(t,q([1],22))}o(Bb,"bold");w.bold=Bb;function Kb(t){return $(t,q([2],22))}o(Kb,"dim");w.dim=Kb;function Jb(t){return $(t,q([3],23))}o(Jb,"italic");w.italic=Jb;function zb(t){return $(t,q([4],24))}o(zb,"underline");w.underline=zb;function Wb(t){return $(t,q([7],27))}o(Wb,"inverse");w.inverse=Wb;function Qb(t){return $(t,q([8],28))}o(Qb,"hidden");w.hidden=Qb;function Yb(t){return $(t,q([9],29))}o(Yb,"strikethrough");w.strikethrough=Yb;function Zb(t){return $(t,q([30],39))}o(Zb,"black");w.black=Zb;function Bp(t){return $(t,q([31],39))}o(Bp,"red");w.red=Bp;function Kp(t){return $(t,q([32],39))}o(Kp,"green");w.green=Kp;function Jp(t){return $(t,q([33],39))}o(Jp,"yellow");w.yellow=Jp;function zp(t){return $(t,q([34],39))}o(zp,"blue");w.blue=zp;function Wp(t){return $(t,q([35],39))}o(Wp,"magenta");w.magenta=Wp;function Qp(t){return $(t,q([36],39))}o(Qp,"cyan");w.cyan=Qp;function Xb(t){return $(t,q([37],39))}o(Xb,"white");w.white=Xb;function eE(t){return Yp(t)}o(eE,"gray");w.gray=eE;function Yp(t){return $(t,q([90],39))}o(Yp,"brightBlack");w.brightBlack=Yp;function tE(t){return $(t,q([91],39))}o(tE,"brightRed");w.brightRed=tE;function rE(t){return $(t,q([92],39))}o(rE,"brightGreen");w.brightGreen=rE;function nE(t){return $(t,q([93],39))}o(nE,"brightYellow");w.brightYellow=nE;function iE(t){return $(t,q([94],39))}o(iE,"brightBlue");w.brightBlue=iE;function oE(t){return $(t,q([95],39))}o(oE,"brightMagenta");w.brightMagenta=oE;function sE(t){return $(t,q([96],39))}o(sE,"brightCyan");w.brightCyan=sE;function aE(t){return $(t,q([97],39))}o(aE,"brightWhite");w.brightWhite=aE;function cE(t){return $(t,q([40],49))}o(cE,"bgBlack");w.bgBlack=cE;function uE(t){return $(t,q([41],49))}o(uE,"bgRed");w.bgRed=uE;function lE(t){return $(t,q([42],49))}o(lE,"bgGreen");w.bgGreen=lE;function dE(t){return $(t,q([43],49))}o(dE,"bgYellow");w.bgYellow=dE;function pE(t){return $(t,q([44],49))}o(pE,"bgBlue");w.bgBlue=pE;function hE(t){return $(t,q([45],49))}o(hE,"bgMagenta");w.bgMagenta=hE;function fE(t){return $(t,q([46],49))}o(fE,"bgCyan");w.bgCyan=fE;function mE(t){return $(t,q([47],49))}o(mE,"bgWhite");w.bgWhite=mE;function yE(t){return $(t,q([100],49))}o(yE,"bgBrightBlack");w.bgBrightBlack=yE;function gE(t){return $(t,q([101],49))}o(gE,"bgBrightRed");w.bgBrightRed=gE;function _E(t){return $(t,q([102],49))}o(_E,"bgBrightGreen");w.bgBrightGreen=_E;function bE(t){return $(t,q([103],49))}o(bE,"bgBrightYellow");w.bgBrightYellow=bE;function EE(t){return $(t,q([104],49))}o(EE,"bgBrightBlue");w.bgBrightBlue=EE;function wE(t){return $(t,q([105],49))}o(wE,"bgBrightMagenta");w.bgBrightMagenta=wE;function vE(t){return $(t,q([106],49))}o(vE,"bgBrightCyan");w.bgBrightCyan=vE;function TE(t){return $(t,q([107],49))}o(TE,"bgBrightWhite");w.bgBrightWhite=TE;function $t(t,e=255,r=0){return Math.trunc(Math.max(Math.min(t,e),r))}o($t,"clampAndTruncate");function SE(t,e){return $(t,q([38,5,$t(e)],39))}o(SE,"rgb8");w.rgb8=SE;function IE(t,e){return $(t,q([48,5,$t(e)],49))}o(IE,"bgRgb8");w.bgRgb8=IE;function AE(t,e){return typeof e=="number"?$(t,q([38,2,e>>16&255,e>>8&255,e&255],39)):$(t,q([38,2,$t(e.r),$t(e.g),$t(e.b)],39))}o(AE,"rgb24");w.rgb24=AE;function PE(t,e){return typeof e=="number"?$(t,q([48,2,e>>16&255,e>>8&255,e&255],49)):$(t,q([48,2,$t(e.r),$t(e.g),$t(e.b)],49))}o(PE,"bgRgb24");w.bgRgb24=PE;var RE=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 OE(t){return t.replace(RE,"")}o(OE,"stripColor");w.stripColor=OE;w.colorFunctions=[Bp,Kp,Jp,zp,Wp,Qp];function xE(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(xE,"hashCode");function NE(t){let e=Math.abs(xE(t));return w.colorFunctions[e%w.colorFunctions.length]}o(NE,"generateColor");w.generateColor=NE});var Xp=g(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.format=void 0;function CE(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
- `).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(CE,"format");eo.format=CE});var oh=g(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.inspect=void 0;function Er(t,e,r,n){let i={seen:[],stylize:LE,showHidden:e??!1,depth:r??2,colors:n??!1,customInspect:!0};return i.colors&&(i.stylize=UE),to(i,t,i.depth)}o(Er,"inspect");ro.inspect=Er;Er.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]};Er.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function LE(t,e){return t}o(LE,"stylizeNoColor");function DE(t){return typeof t=="boolean"}o(DE,"isBoolean");function th(t){return t===void 0}o(th,"isUndefined");function UE(t,e){let r=Er.styles[e];return r?"\x1B["+Er.colors[r][0]+"m"+t+"\x1B["+Er.colors[r][1]+"m":t}o(UE,"stylizeWithColor");function eu(t){return typeof t=="function"}o(eu,"isFunction");function rh(t){return typeof t=="string"}o(rh,"isString");function ME(t){return typeof t=="number"}o(ME,"isNumber");function nh(t){return t===null}o(nh,"isNull");function ih(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(ih,"hasOwn");function tu(t){return ou(t)&&su(t)==="[object RegExp]"}o(tu,"isRegExp");function ou(t){return typeof t=="object"&&t!==null}o(ou,"isObject");function ru(t){return ou(t)&&(su(t)==="[object Error]"||t instanceof Error)}o(ru,"isError");function eh(t){return ou(t)&&su(t)==="[object Date]"}o(eh,"isDate");function su(t){return Object.prototype.toString.call(t)}o(su,"objectToString");function kE(t){let e={};return t.forEach(function(r,n){e[r]=!0}),e}o(kE,"arrayToHash");function FE(t,e,r,n,i){let s=[];for(let a=0,c=e.length;a<c;++a)ih(e,String(a))?s.push(iu(t,e,r,n,String(a),!0)):s.push("");return i.forEach(function(a){a.match(/^\d+$/)||s.push(iu(t,e,r,n,a,!0))}),s}o(FE,"formatArray");function nu(t){return"["+Error.prototype.toString.call(t)+"]"}o(nu,"formatError");function to(t,e,r){if(t.customInspect&&e&&eu(e.inspect)&&e.inspect!==Er&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(r,t);return rh(d)||(d=to(t,d,r)),d}let n=HE(t,e);if(n)return n;let i=Object.keys(e),s=kE(i);try{t.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(e))}catch{}if(ru(e)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return nu(e);if(i.length===0){if(eu(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(tu(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(eh(e))return t.stylize(Date.prototype.toString.call(e),"date");if(ru(e))return nu(e)}let a="",c=!1,u=["{","}"];if(Array.isArray(e)&&(c=!0,u=["[","]"]),eu(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),tu(e)&&(a=" "+RegExp.prototype.toString.call(e)),eh(e)&&(a=" "+Date.prototype.toUTCString.call(e)),ru(e)&&(a=" "+nu(e)),i.length===0&&(!c||e.length==0))return u[0]+a+u[1];if(r<0)return tu(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return c?l=FE(t,e,r,s,i):l=i.map(function(d){return iu(t,e,r,s,d,c)}),t.seen.pop(),qE(l,a,u)}o(to,"formatValue");function iu(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")),ih(n,i)||(a="["+i+"]"),c||(t.seen.indexOf(u.value)<0?(nh(r)?c=to(t,u.value,null):c=to(t,u.value,r-1),c.indexOf(`
25
+ "use strict";var Db=Object.create;var Jn=Object.defineProperty;var Ub=Object.getOwnPropertyDescriptor;var Mb=Object.getOwnPropertyNames;var kb=Object.getPrototypeOf,Fb=Object.prototype.hasOwnProperty;var o=(t,e)=>Jn(t,"name",{value:e,configurable:!0});var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var g=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ki=(t,e)=>{for(var r in e)Jn(t,r,{get:e[r],enumerable:!0})},kp=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mb(e))!Fb.call(t,i)&&i!==r&&Jn(t,i,{get:()=>e[i],enumerable:!(n=Ub(e,i))||n.enumerable});return t};var Fp=(t,e,r)=>(r=t!=null?Db(kb(t)):{},kp(e||!t||!t.__esModule?Jn(r,"default",{value:t,enumerable:!0}):r,t)),Ji=t=>kp(Jn({},"__esModule",{value:!0}),t);var D=g(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.FeatureNotEnabledError=ht.ConfigurationError=ht.RuntimeError=ht.SystemError=void 0;var Vc=class extends Error{static{o(this,"SystemError")}constructor(e,r){super(e,r),this.name="InternalError"}};ht.SystemError=Vc;var zn=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"}};ht.RuntimeError=zn;var Gc=class extends zn{static{o(this,"ConfigurationError")}constructor(e,r){super(e,r),this.name="ConfigurationError"}};ht.ConfigurationError=Gc;var Bc=class extends zn{static{o(this,"FeatureNotEnabledError")}constructor(e,r){super(e,r),this.name="FeatureNotEnabledError"}};ht.FeatureNotEnabledError=Bc});var te=g(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.Environment=void 0;var Hb=D(),Kc=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 Hb.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 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"}};zi.Environment=Kc});var jp=g($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var Hp=te();Function.prototype.toString=function(){return"[native code]"};var Wi=globalThis,qp=Wi.caches;if(qp){let t=qp.open;Wi.caches.open=function(e){let r=Hp.Environment.instance.deploymentName??Hp.Environment.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete Wi.caches.default,Object.freeze(Wi.caches)}});var Wc=g(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.MemoryCache=void 0;var qb=1e4,$b=1e3,Vp=new Map,Jc=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+qb*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#r.forEach((r,n)=>{r.expiresAt>=e&&this.#r.delete(n)})}},zc=class{static{o(this,"MemoryCache")}constructor(e,r={maxSize:$b}){this.name=e;let n=Vp.get(e);n||(n=new Jc(r),Vp.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()}};Qi.MemoryCache=zc});var Zc=g(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.ZoneCache=void 0;var Qc="__zuplo-expiry-header",Yc=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(Qc);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(Qc,`${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(Qc,`${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)}};Yi.ZoneCache=Yc});var br=g(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.MemoryZoneReadThroughCache=void 0;var jb=Wc(),Vb=Zc(),Xc=class{static{o(this,"MemoryZoneReadThroughCache")}constructor(e,r){let n=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new jb.MemoryCache(n),this.#r=new Vb.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};this.#r.put(e,i,n).catch(s=>{"logger"in this.#n?this.#n.logger?.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,s):"log"in this.#n&&this.#n.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,s)})}};Zi.MemoryZoneReadThroughCache=Xc});var Gp=g(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.VALID_COMPATIBILITY_DATES=void 0;Xi.VALID_COMPATIBILITY_DATES=Object.freeze(["2023-03-14"])});var Wn=g(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.INTERNAL_HEADERS_TO_REMOVE=N.ZP_TIMEZONE_HEADER=N.ZP_REGION_CODE_HEADER=N.ZP_REGION_HEADER=N.ZP_METRO_CODE_HEADER=N.ZP_POSTAL_CODE_HEADER=N.ZP_COLO_HEADER=N.ZP_AS_ORG_HEADER=N.ZP_ASN_HEADER=N.TRUE_CLIENT_IP=N.ZP_IP_LATITUDE_HEADER=N.ZP_IP_LONGITUDE_HEADER=N.ZP_IP_COUNTRY_HEADER=N.ZP_IP_CONTINENT_HEADER=N.ZP_IP_CITY_HEADER=N.CF_IP_LATITUDE_HEADER=N.CF_IP_LONGITUDE_HEADER=N.CF_IP_COUNTRY_HEADER=N.CF_IP_CONTINENT_HEADER=N.CF_IP_CITY_HEADER=N.RAY_ID_HEADER=N.BODY_REMOVED_HEADER=N.REQUEST_ID_HEADER=N.LEGACY_REQUEST_ID_HEADER=void 0;N.LEGACY_REQUEST_ID_HEADER="zuplo-request-id";N.REQUEST_ID_HEADER="zp-rid";N.BODY_REMOVED_HEADER="zp-body-removed";N.RAY_ID_HEADER="cf-ray";N.CF_IP_CITY_HEADER="cf-ipcity";N.CF_IP_CONTINENT_HEADER="cf-ipcontinent";N.CF_IP_COUNTRY_HEADER="cf-ipcountry";N.CF_IP_LONGITUDE_HEADER="cf-iplongitude";N.CF_IP_LATITUDE_HEADER="cf-iplatitude";N.ZP_IP_CITY_HEADER="zp-ipcity";N.ZP_IP_CONTINENT_HEADER="zp-ipcontinent";N.ZP_IP_COUNTRY_HEADER="zp-ipcountry";N.ZP_IP_LONGITUDE_HEADER="zp-iplongitude";N.ZP_IP_LATITUDE_HEADER="zp-iplatitude";N.TRUE_CLIENT_IP="true-client-ip";N.ZP_ASN_HEADER="zp-asn";N.ZP_AS_ORG_HEADER="zp-asorg";N.ZP_COLO_HEADER="zp-colo";N.ZP_POSTAL_CODE_HEADER="zp-postalcode";N.ZP_METRO_CODE_HEADER="zp-metrocode";N.ZP_REGION_HEADER="zp-region";N.ZP_REGION_CODE_HEADER="zp-regioncode";N.ZP_TIMEZONE_HEADER="zp-timezone";N.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",N.CF_IP_CITY_HEADER,N.CF_IP_CONTINENT_HEADER,N.CF_IP_COUNTRY_HEADER,N.CF_IP_LONGITUDE_HEADER,N.ZP_ASN_HEADER,N.ZP_AS_ORG_HEADER,N.ZP_COLO_HEADER,N.ZP_POSTAL_CODE_HEADER,N.ZP_METRO_CODE_HEADER,N.ZP_REGION_HEADER,N.ZP_REGION_CODE_HEADER,N.ZP_TIMEZONE_HEADER]});var Xp=g(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.generateColor=w.colorFunctions=w.stripColor=w.bgRgb24=w.rgb24=w.bgRgb8=w.rgb8=w.bgBrightWhite=w.bgBrightCyan=w.bgBrightMagenta=w.bgBrightBlue=w.bgBrightYellow=w.bgBrightGreen=w.bgBrightRed=w.bgBrightBlack=w.bgWhite=w.bgCyan=w.bgMagenta=w.bgBlue=w.bgYellow=w.bgGreen=w.bgRed=w.bgBlack=w.brightWhite=w.brightCyan=w.brightMagenta=w.brightBlue=w.brightYellow=w.brightGreen=w.brightRed=w.brightBlack=w.gray=w.white=w.cyan=w.magenta=w.blue=w.yellow=w.green=w.red=w.black=w.strikethrough=w.hidden=w.inverse=w.underline=w.italic=w.dim=w.bold=w.reset=w.getColorEnabled=w.setColorEnabled=void 0;var Bp=!0,eu=!Bp;function Gb(t){Bp||(eu=t)}o(Gb,"setColorEnabled");w.setColorEnabled=Gb;function Bb(){return eu}o(Bb,"getColorEnabled");w.getColorEnabled=Bb;function q(t,e){return{open:`\x1B[${t.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}o(q,"code");function $(t,e){return eu?`${e.open}${t.replace(e.regexp,e.open)}${e.close}`:t}o($,"run");function Kb(t){return $(t,q([0],0))}o(Kb,"reset");w.reset=Kb;function Jb(t){return $(t,q([1],22))}o(Jb,"bold");w.bold=Jb;function zb(t){return $(t,q([2],22))}o(zb,"dim");w.dim=zb;function Wb(t){return $(t,q([3],23))}o(Wb,"italic");w.italic=Wb;function Qb(t){return $(t,q([4],24))}o(Qb,"underline");w.underline=Qb;function Yb(t){return $(t,q([7],27))}o(Yb,"inverse");w.inverse=Yb;function Zb(t){return $(t,q([8],28))}o(Zb,"hidden");w.hidden=Zb;function Xb(t){return $(t,q([9],29))}o(Xb,"strikethrough");w.strikethrough=Xb;function eE(t){return $(t,q([30],39))}o(eE,"black");w.black=eE;function Kp(t){return $(t,q([31],39))}o(Kp,"red");w.red=Kp;function Jp(t){return $(t,q([32],39))}o(Jp,"green");w.green=Jp;function zp(t){return $(t,q([33],39))}o(zp,"yellow");w.yellow=zp;function Wp(t){return $(t,q([34],39))}o(Wp,"blue");w.blue=Wp;function Qp(t){return $(t,q([35],39))}o(Qp,"magenta");w.magenta=Qp;function Yp(t){return $(t,q([36],39))}o(Yp,"cyan");w.cyan=Yp;function tE(t){return $(t,q([37],39))}o(tE,"white");w.white=tE;function rE(t){return Zp(t)}o(rE,"gray");w.gray=rE;function Zp(t){return $(t,q([90],39))}o(Zp,"brightBlack");w.brightBlack=Zp;function nE(t){return $(t,q([91],39))}o(nE,"brightRed");w.brightRed=nE;function iE(t){return $(t,q([92],39))}o(iE,"brightGreen");w.brightGreen=iE;function oE(t){return $(t,q([93],39))}o(oE,"brightYellow");w.brightYellow=oE;function sE(t){return $(t,q([94],39))}o(sE,"brightBlue");w.brightBlue=sE;function aE(t){return $(t,q([95],39))}o(aE,"brightMagenta");w.brightMagenta=aE;function cE(t){return $(t,q([96],39))}o(cE,"brightCyan");w.brightCyan=cE;function uE(t){return $(t,q([97],39))}o(uE,"brightWhite");w.brightWhite=uE;function lE(t){return $(t,q([40],49))}o(lE,"bgBlack");w.bgBlack=lE;function dE(t){return $(t,q([41],49))}o(dE,"bgRed");w.bgRed=dE;function pE(t){return $(t,q([42],49))}o(pE,"bgGreen");w.bgGreen=pE;function hE(t){return $(t,q([43],49))}o(hE,"bgYellow");w.bgYellow=hE;function fE(t){return $(t,q([44],49))}o(fE,"bgBlue");w.bgBlue=fE;function mE(t){return $(t,q([45],49))}o(mE,"bgMagenta");w.bgMagenta=mE;function yE(t){return $(t,q([46],49))}o(yE,"bgCyan");w.bgCyan=yE;function gE(t){return $(t,q([47],49))}o(gE,"bgWhite");w.bgWhite=gE;function _E(t){return $(t,q([100],49))}o(_E,"bgBrightBlack");w.bgBrightBlack=_E;function bE(t){return $(t,q([101],49))}o(bE,"bgBrightRed");w.bgBrightRed=bE;function EE(t){return $(t,q([102],49))}o(EE,"bgBrightGreen");w.bgBrightGreen=EE;function wE(t){return $(t,q([103],49))}o(wE,"bgBrightYellow");w.bgBrightYellow=wE;function vE(t){return $(t,q([104],49))}o(vE,"bgBrightBlue");w.bgBrightBlue=vE;function TE(t){return $(t,q([105],49))}o(TE,"bgBrightMagenta");w.bgBrightMagenta=TE;function SE(t){return $(t,q([106],49))}o(SE,"bgBrightCyan");w.bgBrightCyan=SE;function IE(t){return $(t,q([107],49))}o(IE,"bgBrightWhite");w.bgBrightWhite=IE;function jt(t,e=255,r=0){return Math.trunc(Math.max(Math.min(t,e),r))}o(jt,"clampAndTruncate");function AE(t,e){return $(t,q([38,5,jt(e)],39))}o(AE,"rgb8");w.rgb8=AE;function PE(t,e){return $(t,q([48,5,jt(e)],49))}o(PE,"bgRgb8");w.bgRgb8=PE;function RE(t,e){return typeof e=="number"?$(t,q([38,2,e>>16&255,e>>8&255,e&255],39)):$(t,q([38,2,jt(e.r),jt(e.g),jt(e.b)],39))}o(RE,"rgb24");w.rgb24=RE;function OE(t,e){return typeof e=="number"?$(t,q([48,2,e>>16&255,e>>8&255,e&255],49)):$(t,q([48,2,jt(e.r),jt(e.g),jt(e.b)],49))}o(OE,"bgRgb24");w.bgRgb24=OE;var xE=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 NE(t){return t.replace(xE,"")}o(NE,"stripColor");w.stripColor=NE;w.colorFunctions=[Kp,Jp,zp,Wp,Qp,Yp];function CE(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(CE,"hashCode");function LE(t){let e=Math.abs(CE(t));return w.colorFunctions[e%w.colorFunctions.length]}o(LE,"generateColor");w.generateColor=LE});var eh=g(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.format=void 0;function DE(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
+ `).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(DE,"format");eo.format=DE});var sh=g(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.inspect=void 0;function Er(t,e,r,n){let i={seen:[],stylize:UE,showHidden:e??!1,depth:r??2,colors:n??!1,customInspect:!0};return i.colors&&(i.stylize=kE),to(i,t,i.depth)}o(Er,"inspect");ro.inspect=Er;Er.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]};Er.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function UE(t,e){return t}o(UE,"stylizeNoColor");function ME(t){return typeof t=="boolean"}o(ME,"isBoolean");function rh(t){return t===void 0}o(rh,"isUndefined");function kE(t,e){let r=Er.styles[e];return r?"\x1B["+Er.colors[r][0]+"m"+t+"\x1B["+Er.colors[r][1]+"m":t}o(kE,"stylizeWithColor");function tu(t){return typeof t=="function"}o(tu,"isFunction");function nh(t){return typeof t=="string"}o(nh,"isString");function FE(t){return typeof t=="number"}o(FE,"isNumber");function ih(t){return t===null}o(ih,"isNull");function oh(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(oh,"hasOwn");function ru(t){return su(t)&&au(t)==="[object RegExp]"}o(ru,"isRegExp");function su(t){return typeof t=="object"&&t!==null}o(su,"isObject");function nu(t){return su(t)&&(au(t)==="[object Error]"||t instanceof Error)}o(nu,"isError");function th(t){return su(t)&&au(t)==="[object Date]"}o(th,"isDate");function au(t){return Object.prototype.toString.call(t)}o(au,"objectToString");function HE(t){let e={};return t.forEach(function(r,n){e[r]=!0}),e}o(HE,"arrayToHash");function qE(t,e,r,n,i){let s=[];for(let a=0,c=e.length;a<c;++a)oh(e,String(a))?s.push(ou(t,e,r,n,String(a),!0)):s.push("");return i.forEach(function(a){a.match(/^\d+$/)||s.push(ou(t,e,r,n,a,!0))}),s}o(qE,"formatArray");function iu(t){return"["+Error.prototype.toString.call(t)+"]"}o(iu,"formatError");function to(t,e,r){if(t.customInspect&&e&&tu(e.inspect)&&e.inspect!==Er&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(r,t);return nh(d)||(d=to(t,d,r)),d}let n=$E(t,e);if(n)return n;let i=Object.keys(e),s=HE(i);try{t.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(e))}catch{}if(nu(e)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return iu(e);if(i.length===0){if(tu(e)){let d=e.name?": "+e.name:"";return t.stylize("[Function"+d+"]","special")}if(ru(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(th(e))return t.stylize(Date.prototype.toString.call(e),"date");if(nu(e))return iu(e)}let a="",c=!1,u=["{","}"];if(Array.isArray(e)&&(c=!0,u=["[","]"]),tu(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),ru(e)&&(a=" "+RegExp.prototype.toString.call(e)),th(e)&&(a=" "+Date.prototype.toUTCString.call(e)),nu(e)&&(a=" "+iu(e)),i.length===0&&(!c||e.length==0))return u[0]+a+u[1];if(r<0)return ru(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);let l;return c?l=qE(t,e,r,s,i):l=i.map(function(d){return ou(t,e,r,s,d,c)}),t.seen.pop(),jE(l,a,u)}o(to,"formatValue");function ou(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")),oh(n,i)||(a="["+i+"]"),c||(t.seen.indexOf(u.value)<0?(ih(r)?c=to(t,u.value,null):c=to(t,u.value,r-1),c.indexOf(`
27
27
  `)>-1&&(s?c=c.split(`
28
28
  `).map(function(l){return" "+l}).join(`
29
29
  `).substr(2):c=`
30
30
  `+c.split(`
31
31
  `).map(function(l){return" "+l}).join(`
32
- `))):c=t.stylize("[Circular]","special")),th(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(iu,"formatProperty");function HE(t,e){if(th(e))return t.stylize("undefined","undefined");if(rh(e)){let r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(ME(e))return t.stylize(""+e,"number");if(DE(e))return t.stylize(""+e,"boolean");if(nh(e))return t.stylize("null","null")}o(HE,"formatPrimitive");function qE(t,e,r){let n=0;return t.reduce(function(s,a){return n++,a.indexOf(`
32
+ `))):c=t.stylize("[Circular]","special")),rh(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(ou,"formatProperty");function $E(t,e){if(rh(e))return t.stylize("undefined","undefined");if(nh(e)){let r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(FE(e))return t.stylize(""+e,"number");if(ME(e))return t.stylize(""+e,"boolean");if(ih(e))return t.stylize("null","null")}o($E,"formatPrimitive");function jE(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(qE,"reduceToSingleString")});var sh=g(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.format=void 0;var $E=Xp(),jE=oh(),VE=o((t,...e)=>(0,$E.format)(jE.inspect,t,e),"format");no.format=VE});var wr=g(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.debug=jt.withoutEnv=jt.Debugger=void 0;var GE=Zp(),BE=sh(),io=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,GE.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,BE.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};jt.Debugger=io;var oo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ah(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(ah,"extract");var Qn;function KE(t){t||(t=[]),typeof t=="string"&&(t=ah(t)),Qn=new oo(t)}o(KE,"withoutEnv");jt.withoutEnv=KE;function JE(t){let e=globalThis.DEBUG;Qn||(Qn=new oo(ah(e)));let r=new io(Qn,t);return Qn.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(JE,"debug");jt.debug=JE});var ao=g(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.ProblemResponseFormatter=Hr.InternalProblemResponseFormatter=void 0;var zE=D(),so=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 zE.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};Hr.InternalProblemResponseFormatter=so;var au=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await so.problemResponseFormat(e,r,n)}};Hr.ProblemResponseFormatter=au});var Ot=g(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.initializeRuntime=me.invokeOnResponseSendingFinalExtensions=me.invokeOnResponseSendingExtensions=me.invokeOnRequestExtensions=me.plugins=me.runtimeExtensions=me.InitializableRuntimePlugin=me.RuntimePlugin=void 0;var WE=ao(),uo=class{static{o(this,"RuntimePlugin")}};me.RuntimePlugin=uo;var lo=class extends uo{static{o(this,"InitializableRuntimePlugin")}};me.InitializableRuntimePlugin=lo;me.runtimeExtensions={};var cu=[];me.plugins=cu;var ch=[],uh=[],lh=[],co={addPlugin(t){cu.push(t)},addRequestHook(t){ch.push(t)},addResponseSendingHook(t){uh.push(t)},addResponseSendingFinalHook(t){lh.push(t)}},QE=o(async(t,e)=>{let r=t;for(let n of ch)if(r=await n(r,e),r instanceof Response)return r;return r},"invokeOnRequestExtensions");me.invokeOnRequestExtensions=QE;var YE=o(async(t,e,r)=>{let n=t;for(let i of uh)n=await i(t,e,r);return n},"invokeOnResponseSendingExtensions");me.invokeOnResponseSendingExtensions=YE;var ZE=o(async(t,e,r)=>{for(let n of lh)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");me.invokeOnResponseSendingFinalExtensions=ZE;async function XE(t=()=>Promise.resolve()){await t(co),me.runtimeExtensions.value=co;let e=cu.filter(r=>r instanceof lo);for(let r of e)await r.initialize(co);WE.InternalProblemResponseFormatter.setProblemResponseFormat(co.problemResponseFormat)}o(XE,"initializeRuntime");me.initializeRuntime=XE});var Vt=g(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.Pipeline=void 0;var ew=ke(),uu=vr(),dh=Ot(),lu=class{static{o(this,"Pipeline")}constructor(e,r,n){this.execute=this.#t(e,r,n)}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=(e,r,n)=>async(i,s)=>{let a=[...e],c=o(async y=>{let v=a.pop();return v?v(i,s,n,c):await this.#e(async S=>{let M=await r(S,s);return tw(M)},n)(y,s)},"nextPipe"),l=await c(i),d=new uu.ResponseSendingEvent(i,l);s.dispatchEvent(d);let p=uu.ZuploContextExtensions.getContextExtensions(s),m=p.latestRequest,f;try{f=await d.mutableResponse}catch(y){return s.log.error(y),n.errorHandler(i,s,y)}try{f=await p.onResponseSending(f,m,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(i,s,y)}try{f=await(0,dh.invokeOnResponseSendingExtensions)(f,m,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(i,s,y)}s.dispatchEvent(new uu.ResponseSentEvent(i,f));try{await p.onResponseSendingFinal(l,m,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await(0,dh.invokeOnResponseSendingFinalExtensions)(l,m,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return f}};po.Pipeline=lu;function tw(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,ew.serialize)(t),{headers:{"content-type":"application/json"}})}o(tw,"resultToResponse")});var fo=g(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.MetricsPlugin=void 0;var rw=Ot(),du=class extends rw.RuntimePlugin{static{o(this,"MetricsPlugin")}};ho.MetricsPlugin=du});var Ge=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.SystemLogMap=void 0;var nw=D(),pu=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 nw.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};mo.SystemLogMap=pu});var we=g(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.BatchDispatch=void 0;var hu=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i}#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&&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}};yo.BatchDispatch=hu});var hh=g(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.EllieMetricsTransport=void 0;var ph=Ge(),iw=we(),go=te(),fu=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=go.Environment.instance.loggingId,this.#e=e,this.#t=new iw.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,ph.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}=go.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":go.Environment.instance.deploymentName??"unknown","user-agent":go.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();ph.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};_o.EllieMetricsTransport=fu});var ft=g(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.systemNoVersion=Tr.SystemRouteConfiguration=void 0;var mu=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=Tr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};Tr.SystemRouteConfiguration=mu;Tr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var Sr=g(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.metricsProcessor=void 0;var fh=Wn(),ow=vr(),sw=Ot(),aw=fo(),cw=hh(),uw=ft(),lw=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(fh.RAY_ID_HEADER)??void 0,u=t.headers.get(fh.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof uw.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=ow.ZuploContextExtensions.getContextExtensions(e).latestRequest,m={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},f=[];return f.push(new cw.EllieMetricsTransport(e)),sw.plugins.forEach(y=>{if(y instanceof aw.MetricsPlugin){let v=y.getTransport();f.push(v)}}),f.forEach(y=>{y.pushMetrics(m,e)}),a},"metricsProcessor");bo.metricsProcessor=lw});var yh=g(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.SystemRouteName=void 0;var mh;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(mh||(Eo.SystemRouteName=mh={}))});var _h=g(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0})});var Ir=g(Gt=>{"use strict";var dw=Gt&&Gt.__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]}),bh=Gt&&Gt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&dw(e,t,r)};Object.defineProperty(Gt,"__esModule",{value:!0});bh(yh(),Gt);bh(_h(),Gt)});var Eh=g(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.registerBuildRoute=void 0;var pw=xt(),hw=Vt(),fw=Sr(),mw=Ir(),yw=ft(),gw=Ge(),_w=te(),bw=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 pw.HttpProblems.notFound(s,a);let l=_w.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,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"&&gw.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 hw.Pipeline([fw.metricsProcessor],r,e),i=new yw.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:mw.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");wo.registerBuildRoute=bw});var yu=g(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.HTTP_STATUS_TITLES=qr.HttpStatusCode=void 0;var wh;(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"})(wh||(qr.HttpStatusCode=wh={}));qr.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 ve=g(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.HttpProblems=void 0;var Ew=ke(),ww=Wn(),O=yu(),vw=te(),gu=ao();function Tw(t){return`${new URL(t.url).pathname}`}o(Tw,"instance");function Sw(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:vw.Environment.instance.build.BUILD_ID},n=t.headers.get(ww.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(Sw,"trace");var Iw=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Tw(e),trace:Sw(e,r),...n},additionalHeaders:i,statusText:Ew.httpStatuses[t.status]}),"merge"),_u=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?gu.ProblemResponseFormatter.format(e,r,n):gu.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:O.HTTP_STATUS_TITLES[e],...r}}},bu=class extends _u{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=Iw(this.getProblemFromStatus(e),r,n,i,s);return gu.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(O.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(O.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(O.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(O.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(O.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(O.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(O.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(O.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(O.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(O.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(O.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(O.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(O.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(O.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(O.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(O.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(O.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(O.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(O.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(O.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(O.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(O.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(O.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(O.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(O.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(O.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(O.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(O.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(O.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(O.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(O.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(O.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(O.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(O.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(O.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(O.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(O.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(O.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(O.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(O.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(O.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(O.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(O.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(O.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(O.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};vo.HttpProblems=bu});var Eu=g($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.generateCorsHeaders=$r.findMatchingOrigin=void 0;var Aw=o((t,e)=>{if(e!==null)if(t){let r=To(t).split(",");if(r.find(c=>c==="*"))return e;let i=r.map(c=>c.trim().toLowerCase()),s=e.toLowerCase();return i.find(c=>c===s)}else return},"findMatchingOrigin");$r.findMatchingOrigin=Aw;var Pw=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=To(t.allowedHeaders)),t.allowedMethods&&(r["access-control-allow-methods"]=To(t.allowedMethods)),t.exposeHeaders&&(r["access-control-expose-headers"]=To(t.exposeHeaders));let n=t.allowCredentials?.toString()??void 0;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");$r.generateCorsHeaders=Pw;var To=o(t=>Array.isArray(t)?t.map(e=>e.trim()).join(", "):t,"normalizePolicies")});var Th=g(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.registerCorsRoute=void 0;var Rw=D(),Ow=Vt(),wu=ve(),xw=Sr(),Nw=Ir(),Cw=ft(),vh=Eu(),Lw=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 wu.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,u);if(!m)return wu.HttpProblems.notFound(a,c);let f=m.routeConfiguration,y=Dw(l,d,p,f,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):wu.HttpProblems.notFound(a,c)},"optionsHandler"),i=new Ow.Pipeline([xw.metricsProcessor],n,e),s=new Cw.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:Nw.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");So.registerCorsRoute=Lw;var Dw=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;let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new Rw.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section`);let c=(0,vh.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,vh.generateCorsHeaders)(a,c)}:s},"validateAndBuildResponseHeaders")});var Sh=g(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.registerNoRoutes=void 0;var Uw=Vt(),Mw=Sr(),kw=Ir(),Fw=ft(),Hw=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 Uw.Pipeline([Mw.metricsProcessor],r,e),i=new Fw.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:kw.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");Io.registerNoRoutes=Hw});var Ih=g(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.registerNotMatchedHandler=Ar.notFoundRouteConfiguration=void 0;var qw=vr(),$w=Ot(),jw=Vt(),Vw=ve(),Gw=Sr(),Bw=Ir(),Kw=ft();Ar.notFoundRouteConfiguration=new Kw.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:Bw.SystemRouteName.UnmatchedPath});var Jw=o((t,e)=>{let r=o(async(i,s)=>{let a=$w.runtimeExtensions.value?.notFoundHandler;if(a){let c=qw.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return Vw.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new jw.Pipeline([Gw.metricsProcessor],r,e);t.addRoute(Ar.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Ar.registerNotMatchedHandler=Jw});var vu=g(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.corsProcessor=void 0;var Rh=D(),Ah=Eu(),zw=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ph=o(t=>{zw.forEach(e=>t.delete(e))},"stripCorsHeaders"),Ww=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 Ph(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 Rh.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Qw(i,r.routeData.corsPolicies),c=Yw(t,a),u=new Headers(s.headers);return Ph(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");Ao.corsProcessor=Ww;var Qw=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:["*"],allowedOrigins:["*"],allowedMethods:t.methods,exposeHeaders:["*"],allowCredentials:!0,maxAge:600};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Rh.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),Yw=o((t,e)=>{let r=(0,Ah.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,Ah.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var Oh=g(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.registerPingRoute=void 0;var Zw=Vt(),Xw=vu(),ev=Ir(),tv=ft(),rv=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new Zw.Pipeline([Xw.corsProcessor],r,e),i=new tv.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:ev.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");Po.registerPingRoute=rv});var Tu=g(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.getDevPortalRuntimeConfig=mt.DEV_PORTAL_LEGACY_PATHNAME=mt.DEFAULT_DEV_PORTAL_PATHNAME=void 0;mt.DEFAULT_DEV_PORTAL_PATHNAME="/docs";mt.DEV_PORTAL_LEGACY_PATHNAME="/__zuplo/dev-portal";function nv(t){let{developerPortal:e}=t.runtimeSettings,r=e?.sitePathname;return r===mt.DEV_PORTAL_LEGACY_PATHNAME&&(r=void 0),{sitePathname:iv(r??mt.DEFAULT_DEV_PORTAL_PATHNAME)}}o(nv,"getDevPortalRuntimeConfig");mt.getDevPortalRuntimeConfig=nv;function iv(t){let e=t.trim().toLowerCase();return e.endsWith("/")&&(e=e.slice(0,-1)),e}o(iv,"normalizePathname")});var Nh=g(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.deepFreeze=void 0;function xh(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&xh(r)}return Object.freeze(t)}o(xh,"deepFreeze");Ro.deepFreeze=xh});var Yn=g(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ZuploRequest=void 0;var Ch=Nh(),Su=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){this.#e={};let e=new URL(this.url).searchParams;for(let[r,n]of e.entries())this.#e[r]=n}return(0,Ch.deepFreeze)(this.#e)}get params(){return(0,Ch.deepFreeze)(this.#t)}user};Oo.ZuploRequest=Su});var Zn=g(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.policyProcessor=Nt.toStackedInboundHandler=Nt.getInboundPolicyHandlerAndOptions=void 0;var ov=vr(),jr=D(),Lh=Yn();function Dh(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.map(s=>{let a=e?.find(u=>u.name===s);if(!a)throw new jr.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${s}' ${n&&`on route '${n}'`}. Expected a function, received '${typeof c}'`);return{exportName:a.handler.export,handler:c,options:a.handler.options,policyName:a.name}})}o(Dh,"getInboundPolicyHandlerAndOptions");Nt.getInboundPolicyHandlerAndOptions=Dh;function sv(t,e){return(t.policies?.outbound??[]).map(i=>{let s=e?.find(c=>c.name===i);if(!s)throw new jr.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);return{exportName:s.handler.export,handler:a,options:s.handler.options,policyName:s.name}})}o(sv,"getOutboundPolicyHandlerAndOptions");var av=o(t=>async(e,r)=>{let n=ov.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,a.options,a.policyName);if(n.latestRequest=s,c instanceof Lh.ZuploRequest)s=c;else if(c instanceof Request)s=new Lh.ZuploRequest(e);else{if(c instanceof Response)return c;throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}}return s},"toStackedInboundHandler");Nt.toStackedInboundHandler=av;var cv=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,a.options,a.policyName);if(!(c instanceof Response))throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),uv=o(async(t,e,r,n)=>{let i=Dh(e.route,r.routeData.policies),s=sv(e.route,r.routeData.policies),a=(0,Nt.toStackedInboundHandler)(i);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await n(c),l=cv(s);return u.ok?l(u,t,e):u}catch(c){return e.log.error(c),r.errorHandler(t,e,c)}},"policyProcessor");Nt.policyProcessor=uv});var Uh=g(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.serialize=Vr.parse=void 0;var lv=Object.prototype.toString,xo=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function dv(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||hv,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]=yv(l,i)}s=c+1}return r}o(dv,"parse");Vr.parse=dv;function pv(t,e,r){let n=r||{},i=n.encode||fv;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!xo.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!xo.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(!xo.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!xo.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!mv(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(pv,"serialize");Vr.serialize=pv;function hv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(hv,"decode");function fv(t){return encodeURIComponent(t)}o(fv,"encode");function mv(t){return lv.call(t)==="[object Date]"||t instanceof Date}o(mv,"isDate");function yv(t,e){try{return e(t)}catch{return t}}o(yv,"tryDecode")});var Mh=g(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.devPortalBaseURL=void 0;var gv=Uh();function _v(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,gv.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(_v,"devPortalBaseURL");No.devPortalBaseURL=_v});var qh=g(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.registerDevPortalLegacyRedirectRoute=Br.registerDevPortalV3Route=void 0;var Iu=xt(),kh=Vt(),Fh=Sr(),bv=Zn(),Hh=ft(),Ev=Mh(),Bt=te(),Gr=Tu(),wv="dev-portal-id",vv="dev-portal-host",Tv="zp-account",Sv="zp-project",Iv="dev-portal-build",Av=`
35
+ `)+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}o(jE,"reduceToSingleString")});var ah=g(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.format=void 0;var VE=eh(),GE=sh(),BE=o((t,...e)=>(0,VE.format)(GE.inspect,t,e),"format");no.format=BE});var wr=g(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.debug=Vt.withoutEnv=Vt.Debugger=void 0;var KE=Xp(),JE=ah(),io=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,r){this.manager=e,this.ns=r,this.color=(0,KE.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,JE.format)(r,...e);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};Vt.Debugger=io;var oo=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function ch(t){return!t||t.length===0?[]:(t=t.replace(/\s/g,"").replace(/\*/g,".+"),t.split(",").map(e=>new RegExp(`^${e}$`)))}o(ch,"extract");var Qn;function zE(t){t||(t=[]),typeof t=="string"&&(t=ch(t)),Qn=new oo(t)}o(zE,"withoutEnv");Vt.withoutEnv=zE;function WE(t){let e=globalThis.DEBUG;Qn||(Qn=new oo(ch(e)));let r=new io(Qn,t);return Qn.debuggers.set(t,r),Object.assign(r.log.bind(r),{self:r})}o(WE,"debug");Vt.debug=WE});var ao=g(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.ProblemResponseFormatter=Hr.InternalProblemResponseFormatter=void 0;var QE=D(),so=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 QE.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};Hr.InternalProblemResponseFormatter=so;var cu=class{static{o(this,"ProblemResponseFormatter")}static async format(e,r,n){return await so.problemResponseFormat(e,r,n)}};Hr.ProblemResponseFormatter=cu});var Ot=g(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.initializeRuntime=me.invokeOnResponseSendingFinalExtensions=me.invokeOnResponseSendingExtensions=me.invokeOnRequestExtensions=me.plugins=me.runtimeExtensions=me.InitializableRuntimePlugin=me.RuntimePlugin=void 0;var YE=ao(),uo=class{static{o(this,"RuntimePlugin")}};me.RuntimePlugin=uo;var lo=class extends uo{static{o(this,"InitializableRuntimePlugin")}};me.InitializableRuntimePlugin=lo;me.runtimeExtensions={};var uu=[];me.plugins=uu;var uh=[],lh=[],dh=[],co={addPlugin(t){uu.push(t)},addRequestHook(t){uh.push(t)},addResponseSendingHook(t){lh.push(t)},addResponseSendingFinalHook(t){dh.push(t)}},ZE=o(async(t,e)=>{let r=t;for(let n of uh)if(r=await n(r,e),r instanceof Response)return r;return r},"invokeOnRequestExtensions");me.invokeOnRequestExtensions=ZE;var XE=o(async(t,e,r)=>{let n=t;for(let i of lh)n=await i(t,e,r);return n},"invokeOnResponseSendingExtensions");me.invokeOnResponseSendingExtensions=XE;var ew=o(async(t,e,r)=>{for(let n of dh)await n(t,e,r)},"invokeOnResponseSendingFinalExtensions");me.invokeOnResponseSendingFinalExtensions=ew;async function tw(t=()=>Promise.resolve()){await t(co),me.runtimeExtensions.value=co;let e=uu.filter(r=>r instanceof lo);for(let r of e)await r.initialize(co);YE.InternalProblemResponseFormatter.setProblemResponseFormat(co.problemResponseFormat)}o(tw,"initializeRuntime");me.initializeRuntime=tw});var Gt=g(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.Pipeline=void 0;var rw=ke(),lu=vr(),ph=Ot(),du=class{static{o(this,"Pipeline")}constructor(e,r,n){this.execute=this.#t(e,r,n)}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=(e,r,n)=>async(i,s)=>{let a=[...e],c=o(async y=>{let v=a.pop();return v?v(i,s,n,c):await this.#e(async S=>{let M=await r(S,s);return nw(M)},n)(y,s)},"nextPipe"),l=await c(i),d=new lu.ResponseSendingEvent(i,l);s.dispatchEvent(d);let p=lu.ZuploContextExtensions.getContextExtensions(s),m=p.latestRequest,f;try{f=await d.mutableResponse}catch(y){return s.log.error(y),n.errorHandler(i,s,y)}try{f=await p.onResponseSending(f,m,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(i,s,y)}try{f=await(0,ph.invokeOnResponseSendingExtensions)(f,m,s)}catch(y){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${y.message}'`,y),n.errorHandler(i,s,y)}s.dispatchEvent(new lu.ResponseSentEvent(i,f));try{await p.onResponseSendingFinal(l,m,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}try{await(0,ph.invokeOnResponseSendingFinalExtensions)(l,m,s)}catch(y){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${y.message}'`,y),y}return f}};po.Pipeline=du;function nw(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response((0,rw.serialize)(t),{headers:{"content-type":"application/json"}})}o(nw,"resultToResponse")});var fo=g(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.MetricsPlugin=void 0;var iw=Ot(),pu=class extends iw.RuntimePlugin{static{o(this,"MetricsPlugin")}};ho.MetricsPlugin=pu});var Ge=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.SystemLogMap=void 0;var ow=D(),hu=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 ow.SystemError(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};mo.SystemLogMap=hu});var we=g(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.BatchDispatch=void 0;var fu=class{static{o(this,"BatchDispatch")}constructor(e,r,n,i){this.#t=e,this.#o=r,this.#n=n,this.#r=i}#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&&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}};yo.BatchDispatch=fu});var fh=g(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.EllieMetricsTransport=void 0;var hh=Ge(),sw=we(),go=te(),mu=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(e){this.#r=go.Environment.instance.loggingId,this.#e=e,this.#t=new sw.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,hh.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}=go.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":go.Environment.instance.deploymentName??"unknown","user-agent":go.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();hh.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};_o.EllieMetricsTransport=mu});var ft=g(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.systemNoVersion=Tr.SystemRouteConfiguration=void 0;var yu=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=Tr.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};Tr.SystemRouteConfiguration=yu;Tr.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var Sr=g(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.metricsProcessor=void 0;var mh=Wn(),aw=vr(),cw=Ot(),uw=fo(),lw=fh(),dw=ft(),pw=o(async(t,e,r,n)=>{let i=new Date,s=Date.now(),a=await n(t),c=t.headers.get(mh.RAY_ID_HEADER)??void 0,u=t.headers.get(mh.TRUE_CLIENT_IP)??void 0,l=e.incomingRequestProperties,d;e.route instanceof dw.SystemRouteConfiguration&&(d=e.route.systemRouteName);let p=aw.ZuploContextExtensions.getContextExtensions(e).latestRequest,m={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},f=[];return f.push(new lw.EllieMetricsTransport(e)),cw.plugins.forEach(y=>{if(y instanceof uw.MetricsPlugin){let v=y.getTransport();f.push(v)}}),f.forEach(y=>{y.pushMetrics(m,e)}),a},"metricsProcessor");bo.metricsProcessor=pw});var gh=g(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.SystemRouteName=void 0;var yh;(function(t){t.Build="build-data",t.CorsPreflight="cors-preflight",t.DeveloperPortal="developer-portal",t.DeveloperPortalLegacy="developer-portal-legacy",t.EmptyGatewayCatchall="empty-gateway-catchall",t.Ping="ping",t.UnmatchedPath="unmatched-path"})(yh||(Eo.SystemRouteName=yh={}))});var bh=g(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0})});var Ir=g(Bt=>{"use strict";var hw=Bt&&Bt.__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]}),Eh=Bt&&Bt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&hw(e,t,r)};Object.defineProperty(Bt,"__esModule",{value:!0});Eh(gh(),Bt);Eh(bh(),Bt)});var wh=g(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.registerBuildRoute=void 0;var fw=xt(),mw=Gt(),yw=Sr(),gw=Ir(),_w=ft(),bw=Ge(),Ew=te(),ww=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 fw.HttpProblems.notFound(s,a);let l=Ew.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,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"&&bw.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 mw.Pipeline([yw.metricsProcessor],r,e),i=new _w.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:gw.SystemRouteName.Build});t.addRoute(i,n.execute)},"registerBuildRoute");wo.registerBuildRoute=ww});var gu=g(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.HTTP_STATUS_TITLES=qr.HttpStatusCode=void 0;var vh;(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"})(vh||(qr.HttpStatusCode=vh={}));qr.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 ve=g(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.HttpProblems=void 0;var vw=ke(),Tw=Wn(),O=gu(),Sw=te(),_u=ao();function Iw(t){return`${new URL(t.url).pathname}`}o(Iw,"instance");function Aw(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:Sw.Environment.instance.build.BUILD_ID},n=t.headers.get(Tw.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(Aw,"trace");var Pw=o((t,e,r,n,i)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:Iw(e),trace:Aw(e,r),...n},additionalHeaders:i,statusText:vw.httpStatuses[t.status]}),"merge"),bu=class{static{o(this,"HttpProblemsBase")}static format=(e,r,n)=>"problem"in e?_u.ProblemResponseFormatter.format(e,r,n):_u.ProblemResponseFormatter.format({problem:e},r,n);static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:O.HTTP_STATUS_TITLES[e],...r}}},Eu=class extends bu{static{o(this,"HttpProblems")}static#e(e,r,n,i,s){let a=Pw(this.getProblemFromStatus(e),r,n,i,s);return _u.ProblemResponseFormatter.format(a,r,n)}static continue=(e,r,n,i)=>this.#e(O.HttpStatusCode.OK,e,r,n,i);static switchingProtocols=(e,r,n,i)=>this.#e(O.HttpStatusCode.SWITCHING_PROTOCOLS,e,r,n,i);static processing=(e,r,n,i)=>this.#e(O.HttpStatusCode.PROCESSING,e,r,n,i);static earlyHints=(e,r,n,i)=>this.#e(O.HttpStatusCode.EARLY_HINTS,e,r,n,i);static ok=(e,r,n,i)=>this.#e(O.HttpStatusCode.OK,e,r,n,i);static created=(e,r,n,i)=>this.#e(O.HttpStatusCode.CREATED,e,r,n,i);static accepted=(e,r,n,i)=>this.#e(O.HttpStatusCode.ACCEPTED,e,r,n,i);static nonAuthoritativeInformation=(e,r,n,i)=>this.#e(O.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,e,r,n,i);static noContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.NO_CONTENT,e,r,n,i);static resetContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.RESET_CONTENT,e,r,n,i);static partialContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.PARTIAL_CONTENT,e,r,n,i);static multiStatus=(e,r,n,i)=>this.#e(O.HttpStatusCode.MULTI_STATUS,e,r,n,i);static alreadyReported=(e,r,n,i)=>this.#e(O.HttpStatusCode.ALREADY_REPORTED,e,r,n,i);static imUsed=(e,r,n,i)=>this.#e(O.HttpStatusCode.IM_USED,e,r,n,i);static multipleChoices=(e,r,n,i)=>this.#e(O.HttpStatusCode.MULTIPLE_CHOICES,e,r,n,i);static movedPermanently=(e,r,n,i)=>this.#e(O.HttpStatusCode.MOVED_PERMANENTLY,e,r,n,i);static found=(e,r,n,i)=>this.#e(O.HttpStatusCode.FOUND,e,r,n,i);static seeOther=(e,r,n,i)=>this.#e(O.HttpStatusCode.SEE_OTHER,e,r,n,i);static notModified=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_MODIFIED,e,r,n,i);static useProxy=(e,r,n,i)=>this.#e(O.HttpStatusCode.USE_PROXY,e,r,n,i);static switchProxy=(e,r,n,i)=>this.#e(O.HttpStatusCode.SWITCH_PROXY,e,r,n,i);static temporaryRedirect=(e,r,n,i)=>this.#e(O.HttpStatusCode.TEMPORARY_REDIRECT,e,r,n,i);static permanentRedirect=(e,r,n,i)=>this.#e(O.HttpStatusCode.PERMANENT_REDIRECT,e,r,n,i);static badRequest=(e,r,n,i)=>this.#e(O.HttpStatusCode.BAD_REQUEST,e,r,n,i);static unauthorized=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNAUTHORIZED,e,r,n,i);static paymentRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PAYMENT_REQUIRED,e,r,n,i);static forbidden=(e,r,n,i)=>this.#e(O.HttpStatusCode.FORBIDDEN,e,r,n,i);static notFound=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_FOUND,e,r,n,i);static methodNotAllowed=(e,r,n,i)=>this.#e(O.HttpStatusCode.METHOD_NOT_ALLOWED,e,r,n,i);static notAcceptable=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_ACCEPTABLE,e,r,n,i);static proxyAuthenticationRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,e,r,n,i);static requestTimeout=(e,r,n,i)=>this.#e(O.HttpStatusCode.REQUEST_TIMEOUT,e,r,n,i);static conflict=(e,r,n,i)=>this.#e(O.HttpStatusCode.CONFLICT,e,r,n,i);static gone=(e,r,n,i)=>this.#e(O.HttpStatusCode.GONE,e,r,n,i);static lengthRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.LENGTH_REQUIRED,e,r,n,i);static preconditionFailed=(e,r,n,i)=>this.#e(O.HttpStatusCode.PRECONDITION_FAILED,e,r,n,i);static contentTooLarge=(e,r,n,i)=>this.#e(O.HttpStatusCode.CONTENT_TOO_LARGE,e,r,n,i);static uriTooLong=(e,r,n,i)=>this.#e(O.HttpStatusCode.URI_TOO_LONG,e,r,n,i);static unsupportedMediaType=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,e,r,n,i);static rangeNotSatisfiable=(e,r,n,i)=>this.#e(O.HttpStatusCode.RANGE_NOT_SATISFIABLE,e,r,n,i);static expectationFailed=(e,r,n,i)=>this.#e(O.HttpStatusCode.EXPECTATION_FAILED,e,r,n,i);static imATeapot=(e,r,n,i)=>this.#e(O.HttpStatusCode.I_AM_A_TEAPOT,e,r,n,i);static misdirectedRequest=(e,r,n,i)=>this.#e(O.HttpStatusCode.MISDIRECTED_REQUEST,e,r,n,i);static unprocessableContent=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNPROCESSABLE_CONTENT,e,r,n,i);static locked=(e,r,n,i)=>this.#e(O.HttpStatusCode.LOCKED,e,r,n,i);static failedDependency=(e,r,n,i)=>this.#e(O.HttpStatusCode.FAILED_DEPENDENCY,e,r,n,i);static tooEarly=(e,r,n,i)=>this.#e(O.HttpStatusCode.TOO_EARLY,e,r,n,i);static upgradeRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.UPGRADE_REQUIRED,e,r,n,i);static preconditionRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.PRECONDITION_REQUIRED,e,r,n,i);static tooManyRequests=(e,r,n,i)=>this.#e(O.HttpStatusCode.TOO_MANY_REQUESTS,e,r,n,i);static requestHeaderFieldsTooLarge=(e,r,n,i)=>this.#e(O.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,e,r,n,i);static unavailableForLegalReasons=(e,r,n,i)=>this.#e(O.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,e,r,n,i);static internalServerError=(e,r,n,i)=>this.#e(O.HttpStatusCode.INTERNAL_SERVER_ERROR,e,r,n,i);static notImplemented=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_IMPLEMENTED,e,r,n,i);static badGateway=(e,r,n,i)=>this.#e(O.HttpStatusCode.BAD_GATEWAY,e,r,n,i);static serviceUnavailable=(e,r,n,i)=>this.#e(O.HttpStatusCode.SERVICE_UNAVAILABLE,e,r,n,i);static gatewayTimeout=(e,r,n,i)=>this.#e(O.HttpStatusCode.GATEWAY_TIMEOUT,e,r,n,i);static httpVersionNotSupported=(e,r,n,i)=>this.#e(O.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,e,r,n,i);static variantAlsoNegotiates=(e,r,n,i)=>this.#e(O.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,e,r,n,i);static insufficientStorage=(e,r,n,i)=>this.#e(O.HttpStatusCode.INSUFFICIENT_STORAGE,e,r,n,i);static loopDetected=(e,r,n,i)=>this.#e(O.HttpStatusCode.LOOP_DETECTED,e,r,n,i);static notExtended=(e,r,n,i)=>this.#e(O.HttpStatusCode.NOT_EXTENDED,e,r,n,i);static networkAuthenticationRequired=(e,r,n,i)=>this.#e(O.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,e,r,n,i)};vo.HttpProblems=Eu});var wu=g($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.generateCorsHeaders=$r.findMatchingOrigin=void 0;var Rw=o((t,e)=>{if(e!==null)if(t){let r=To(t).split(",");if(r.find(c=>c==="*"))return e;let i=r.map(c=>c.trim().toLowerCase()),s=e.toLowerCase();return i.find(c=>c===s)}else return},"findMatchingOrigin");$r.findMatchingOrigin=Rw;var Ow=o((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=To(t.allowedHeaders)),t.allowedMethods&&(r["access-control-allow-methods"]=To(t.allowedMethods)),t.exposeHeaders&&(r["access-control-expose-headers"]=To(t.exposeHeaders));let n=t.allowCredentials?.toString()??void 0;n&&(r["access-control-allow-credentials"]=n);let i=t.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");$r.generateCorsHeaders=Ow;var To=o(t=>Array.isArray(t)?t.map(e=>e.trim()).join(", "):t,"normalizePolicies")});var Sh=g(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.registerCorsRoute=void 0;var xw=D(),Nw=Gt(),vu=ve(),Cw=Sr(),Lw=Ir(),Dw=ft(),Th=wu(),Uw=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 vu.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let m=t.lookup(l,u);if(!m)return vu.HttpProblems.notFound(a,c);let f=m.routeConfiguration,y=Mw(l,d,p,f,r);return y.isValid?new Response(void 0,{status:200,statusText:"OK",headers:y.headers}):vu.HttpProblems.notFound(a,c)},"optionsHandler"),i=new Nw.Pipeline([Cw.metricsProcessor],n,e),s=new Dw.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:Lw.SystemRouteName.CorsPreflight});t.addRoute(s,i.execute)},"registerCorsRoute");So.registerCorsRoute=Uw;var Mw=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;let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new xw.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section`);let c=(0,Th.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,Th.generateCorsHeaders)(a,c)}:s},"validateAndBuildResponseHeaders")});var Ih=g(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.registerNoRoutes=void 0;var kw=Gt(),Fw=Sr(),Hw=Ir(),qw=ft(),$w=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 kw.Pipeline([Fw.metricsProcessor],r,e),i=new qw.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:Hw.SystemRouteName.EmptyGatewayCatchall});t.addRoute(i,n.execute)},"registerNoRoutes");Io.registerNoRoutes=$w});var Ah=g(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.registerNotMatchedHandler=Ar.notFoundRouteConfiguration=void 0;var jw=vr(),Vw=Ot(),Gw=Gt(),Bw=ve(),Kw=Sr(),Jw=Ir(),zw=ft();Ar.notFoundRouteConfiguration=new zw.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:Jw.SystemRouteName.UnmatchedPath});var Ww=o((t,e)=>{let r=o(async(i,s)=>{let a=Vw.runtimeExtensions.value?.notFoundHandler;if(a){let c=jw.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return Bw.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new Gw.Pipeline([Kw.metricsProcessor],r,e);t.addRoute(Ar.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Ar.registerNotMatchedHandler=Ww});var Tu=g(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.corsProcessor=void 0;var Oh=D(),Ph=wu(),Qw=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Rh=o(t=>{Qw.forEach(e=>t.delete(e))},"stripCorsHeaders"),Yw=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 Rh(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 Oh.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Zw(i,r.routeData.corsPolicies),c=Xw(t,a),u=new Headers(s.headers);return Rh(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");Ao.corsProcessor=Yw;var Zw=o((t,e)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:["*"],allowedOrigins:["*"],allowedMethods:t.methods,exposeHeaders:["*"],allowCredentials:!0,maxAge:600};let r=e?.find(n=>n.name===t.corsPolicy);if(r===void 0)throw new Oh.ConfigurationError(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),Xw=o((t,e)=>{let r=(0,Ph.findMatchingOrigin)(e.allowedOrigins,t.headers.get("origin"));return r?(0,Ph.generateCorsHeaders)(e,r):{}},"getCorsHeaders")});var xh=g(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.registerPingRoute=void 0;var ev=Gt(),tv=Tu(),rv=Ir(),nv=ft(),iv=o((t,e)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new ev.Pipeline([tv.corsProcessor],r,e),i=new nv.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:rv.SystemRouteName.Ping});t.addRoute(i,n.execute)},"registerPingRoute");Po.registerPingRoute=iv});var Su=g(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.getDevPortalRuntimeConfig=mt.DEV_PORTAL_LEGACY_PATHNAME=mt.DEFAULT_DEV_PORTAL_PATHNAME=void 0;mt.DEFAULT_DEV_PORTAL_PATHNAME="/docs";mt.DEV_PORTAL_LEGACY_PATHNAME="/__zuplo/dev-portal";function ov(t){let{developerPortal:e}=t.runtimeSettings,r=e?.sitePathname;return r===mt.DEV_PORTAL_LEGACY_PATHNAME&&(r=void 0),{sitePathname:sv(r??mt.DEFAULT_DEV_PORTAL_PATHNAME)}}o(ov,"getDevPortalRuntimeConfig");mt.getDevPortalRuntimeConfig=ov;function sv(t){let e=t.trim().toLowerCase();return e.endsWith("/")&&(e=e.slice(0,-1)),e}o(sv,"normalizePathname")});var Ch=g(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.deepFreeze=void 0;function Nh(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&Nh(r)}return Object.freeze(t)}o(Nh,"deepFreeze");Ro.deepFreeze=Nh});var Yn=g(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ZuploRequest=void 0;var Lh=Ch(),Iu=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){this.#e={};let e=new URL(this.url).searchParams;for(let[r,n]of e.entries())this.#e[r]=n}return(0,Lh.deepFreeze)(this.#e)}get params(){return(0,Lh.deepFreeze)(this.#t)}user};Oo.ZuploRequest=Iu});var Zn=g(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.policyProcessor=Nt.toStackedInboundHandler=Nt.getInboundPolicyHandlerAndOptions=void 0;var av=vr(),jr=D(),Dh=Yn();function Uh(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.map(s=>{let a=e?.find(u=>u.name===s);if(!a)throw new jr.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${s}' ${n&&`on route '${n}'`}. Expected a function, received '${typeof c}'`);return{exportName:a.handler.export,handler:c,options:a.handler.options,policyName:a.name}})}o(Uh,"getInboundPolicyHandlerAndOptions");Nt.getInboundPolicyHandlerAndOptions=Uh;function cv(t,e){return(t.policies?.outbound??[]).map(i=>{let s=e?.find(c=>c.name===i);if(!s)throw new jr.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${t.path}' was found in the policies configuration (check case).`);let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${t.path}'`);return{exportName:s.handler.export,handler:a,options:s.handler.options,policyName:s.name}})}o(cv,"getOutboundPolicyHandlerAndOptions");var uv=o(t=>async(e,r)=>{let n=av.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,a.options,a.policyName);if(n.latestRequest=s,c instanceof Dh.ZuploRequest)s=c;else if(c instanceof Request)s=new Dh.ZuploRequest(e);else{if(c instanceof Response)return c;throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}}return s},"toStackedInboundHandler");Nt.toStackedInboundHandler=uv;var lv=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,a.options,a.policyName);if(!(c instanceof Response))throw new jr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),dv=o(async(t,e,r,n)=>{let i=Uh(e.route,r.routeData.policies),s=cv(e.route,r.routeData.policies),a=(0,Nt.toStackedInboundHandler)(i);try{let c=await a(t,e);if(c instanceof Response)return c;let u=await n(c),l=lv(s);return u.ok?l(u,t,e):u}catch(c){return e.log.error(c),r.errorHandler(t,e,c)}},"policyProcessor");Nt.policyProcessor=dv});var Mh=g(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.serialize=Vr.parse=void 0;var pv=Object.prototype.toString,xo=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function hv(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");let r={},i=(e||{}).decode||mv,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]=_v(l,i)}s=c+1}return r}o(hv,"parse");Vr.parse=hv;function fv(t,e,r){let n=r||{},i=n.encode||yv;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!xo.test(t))throw new TypeError("argument name is invalid");let s=i(e);if(s&&!xo.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(!xo.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!xo.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!gv(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(fv,"serialize");Vr.serialize=fv;function mv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}o(mv,"decode");function yv(t){return encodeURIComponent(t)}o(yv,"encode");function gv(t){return pv.call(t)==="[object Date]"||t instanceof Date}o(gv,"isDate");function _v(t,e){try{return e(t)}catch{return t}}o(_v,"tryDecode")});var kh=g(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.devPortalBaseURL=void 0;var bv=Mh();function Ev(t,e){try{let r=/v\d+(-\d+)?/g,i=(0,bv.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(Ev,"devPortalBaseURL");No.devPortalBaseURL=Ev});var $h=g(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.registerDevPortalLegacyRedirectRoute=Br.registerDevPortalV3Route=void 0;var Au=xt(),Fh=Gt(),Hh=Sr(),wv=Zn(),qh=ft(),vv=kh(),Kt=te(),Gr=Su(),Tv="dev-portal-id",Sv="dev-portal-host",Iv="zp-account",Av="zp-project",Pv="dev-portal-build",Rv=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,33 +46,33 @@
46
46
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
47
47
  </body>
48
48
  </html>
49
- `,Pv=o((t,e)=>{let r=(0,Gr.getDevPortalRuntimeConfig)(e),n=Bt.Environment.instance.deploymentName,i=Bt.Environment.instance.devPortalBaseUrl,s=o(async(u,l)=>{if(Bt.Environment.instance.isLocalDevelopment)return new Response(Av,{headers:{"content-type":"text/html"}});if(!n)return Iu.HttpProblems.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=(0,Ev.devPortalBaseURL)(i,u.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:y,body:v}=u;return Bt.Environment.instance.build.ACCOUNT_NAME&&f.set(Tv,Bt.Environment.instance.build.ACCOUNT_NAME),Bt.Environment.instance.build.PROJECT_NAME&&f.set(Sv,Bt.Environment.instance.build.PROJECT_NAME),f.set(wv,n),f.set(vv,d.host),f.set(Iv,Bt.Environment.instance.build.BUILD_ID),await fetch(m.toString(),{headers:f,method:y,body:v,redirect:"manual"})},"devPortalRoute"),a=new kh.Pipeline([Fh.metricsProcessor,bv.policyProcessor],s,e),c=new Hh.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${r.sitePathname}|/_next)(.*)`,systemRouteName:Iu.SystemRouteName.DeveloperPortal});t.addRoute(c,a.execute)},"registerDevPortalV3Route");Br.registerDevPortalV3Route=Pv;var Rv=o((t,e)=>{let{sitePathname:r}=(0,Gr.getDevPortalRuntimeConfig)(e),n=o(async a=>{let c=new URL(a.url);return r===Gr.DEV_PORTAL_LEGACY_PATHNAME?c.pathname=`/docs${c.pathname.substring(Gr.DEV_PORTAL_LEGACY_PATHNAME.length)}`:c.pathname=`${r}${c.pathname.substring(Gr.DEV_PORTAL_LEGACY_PATHNAME.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),i=new kh.Pipeline([Fh.metricsProcessor],n,e),s=new Hh.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Gr.DEV_PORTAL_LEGACY_PATHNAME}(.*)`,systemRouteName:Iu.SystemRouteName.DeveloperPortalLegacy});t.addRoute(s,i.execute)},"registerDevPortalLegacyRedirectRoute");Br.registerDevPortalLegacyRedirectRoute=Rv});var Au=g(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.API_KEY=Kr.SYSTEM_LOGGER=void 0;Kr.SYSTEM_LOGGER="system-logger";Kr.API_KEY="api-key"});var $h=g(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.CoreLogger=void 0;var Pu=0,Ru=class{static{o(this,"CoreLogger")}constructor(e,r,n,i,s){this.#r=r,this.#n=n??"local",this.#i=i,this.#o=s,this.#e(e)}#e=e=>{let r=["error","warn","info","debug"],n=!1,i=o(()=>{},"emptyFunction"),s=o((a,c)=>{this.#o.forEach(u=>{u.log(a,c)})},"pushFunction");r.forEach(a=>{this.#t[a]=n?i:s,a==e&&(n=!0)})};#t={};#r;#n;#i;#o;log(e,r,n,i,s,a){Pu>=Number.MAX_SAFE_INTEGER&&(Pu=0);let c={requestId:n,rayId:i,level:e,logSource:r,messages:s,timestamp:new Date,logOwner:this.#r,loggingId:this.#n,buildId:this.#i,vectorClock:Pu++};this.#t[e](c,a)}};Co.CoreLogger=Ru});var Ct=g(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.LogPlugin=void 0;var Ov=Ot(),Ou=class extends Ov.RuntimePlugin{static{o(this,"LogPlugin")}};Lo.LogPlugin=Ou});var jh=g(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.LoggingContext=void 0;var xu=class{static{o(this,"LoggingContext")}constructor(e,r,n){this.#e=e,this.custom=r,this.originalRequest=n}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};Do.LoggingContext=xu});var Vh=g(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.RequestLogger=void 0;var Nu=class{static{o(this,"RequestLogger")}constructor(e,r,n,i){this.#t=e,this.#r=r,this.#n=n,this.#i=i}#e="request";#t;#r;#n;#i;debug=(...e)=>{this.#n.log("debug",this.#e,this.#t,this.#r,e,this.#i)};info=(...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#i)};log=(...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#i)};warn=(...e)=>{this.#n.log("warn",this.#e,this.#t,this.#r,e,this.#i)};error=(...e)=>{this.#n.log("error",this.#e,this.#t,this.#r,e,this.#i)}};Uo.RequestLogger=Nu});var Jr=g(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.isObject=k.getOwnEnumerableKeys=k.isRegexp=k.isStringArray=k.isNonEmptyString=k.isString=k.toString=void 0;var{toString:xv}=Object.prototype,{propertyIsEnumerable:Nv}=Object.prototype;function Gh(t){return xv.call(t)}o(Gh,"toString");k.toString=Gh;function Mo(t){return typeof t=="string"}o(Mo,"isString");k.isString=Mo;function Cv(t){return Mo(t)&&t!==""}o(Cv,"isNonEmptyString");k.isNonEmptyString=Cv;function Lv(t){return Array.isArray(t)&&t.every(e=>Mo(e))}o(Lv,"isStringArray");k.isStringArray=Lv;function Dv(t){return Gh(t)==="[object RegExp]"}o(Dv,"isRegexp");k.isRegexp=Dv;function Uv(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Nv.call(t,e))]}o(Uv,"getOwnEnumerableKeys");k.getOwnEnumerableKeys=Uv;function Bh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Bh,"isObject");k.isObject=Bh;function Mv(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(Mv,"isTypedArray");k.isTypedArray=Mv;function kv(t){return typeof t=="number"&&!isNaN(t)}o(kv,"isNumber");k.isNumber=kv;function Fv(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(Fv,"isIterable");k.isIterable=Fv;function Hv(t){return t===!0||t===!1}o(Hv,"isBoolean");k.isBoolean=Hv;function Kh(t){return typeof t>"u"}o(Kh,"isUndefined");k.isUndefined=Kh;function qv(t){return!Xn(t)}o(qv,"isDefined");k.isDefined=qv;function Xn(t){return Kh(t)||t===null}o(Xn,"isUndefinedOrNull");k.isUndefinedOrNull=Xn;function $v(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o($v,"assertType");k.assertType=$v;function jv(t){if(Xn(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(jv,"assertIsDefined");k.assertIsDefined=jv;function Vv(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Xn(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(Vv,"assertAllDefined");k.assertAllDefined=Vv;var Gv=Object.prototype.hasOwnProperty;function Bv(t){if(!Bh(t))return!1;for(let e in t)if(Gv.call(t,e))return!1;return!0}o(Bv,"isEmptyObject");k.isEmptyObject=Bv;function Cu(t){return typeof t=="function"}o(Cu,"isFunction");k.isFunction=Cu;function Kv(...t){return t.length>0&&t.every(Cu)}o(Kv,"areFunctions");k.areFunctions=Kv;function Jv(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)Jh(t[n],e[n])}o(Jv,"validateConstraints");k.validateConstraints=Jv;function Jh(t,e){if(Mo(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(Cu(e)){try{if(t instanceof e)return}catch{}if(!Xn(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(Jh,"validateConstraint");k.validateConstraint=Jh;function zv(t){return t===null?void 0:t}o(zv,"withNullAsUndefined");k.withNullAsUndefined=zv;function Wv(t){return typeof t>"u"?null:t}o(Wv,"withUndefinedAsNull");k.withUndefinedAsNull=Wv;function Qv(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(Qv,"isErrorLike");k.isErrorLike=Qv});var Pr=g(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.cleanStack=Kt.serializeError=Kt.NonError=void 0;var zh=Jr(),Yv=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Zv=new Map(Yv),Lu=class t extends Error{static{o(this,"NonError")}name="NonError";constructor(e){super(t._prepareSuperMessage(e))}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}};Kt.NonError=Lu;var Xv=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Du=Symbol(".toJSON was called"),eT=o(t=>{t[Du]=!0;let e=t.toJSON();return delete t[Du],e},"toJSON"),tT=o(t=>Zv.get(t)??Error,"getErrorConstructor"),Wh=o(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c})=>{if(!r)if(Array.isArray(t))r=[];else if(!c&&(0,zh.isErrorLike)(t)){let l=tT(t.name);r=new l}else r={};if(e.push(t),s>=i)return r;if(a&&typeof t.toJSON=="function"&&t[Du]!==!0)return eT(t);let u=o(l=>Wh({from:l,seen:[...e],forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=u(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of Xv)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:(0,zh.isErrorLike)(t[l])?u(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function rT(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Wh({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}o(rT,"serializeError");Kt.serializeError=rT;var nT=/file:\/\/\/(.*?)\/dist\//g,iT=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,oT="at async Event.respondWith";function sT(t){return typeof t!="string"?t:t.split(`
50
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(nT,"").replaceAll(iT,"").replaceAll(oT,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
51
- `)}o(sT,"cleanStack");Kt.cleanStack=sT});var Qh=g(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var Uu=Jr();function aT(t,e,r=""){let n=[],i=e?.maxDepth??3;return o(function s(a,c={},u,l){let d=c.indent||" ",p;c.inlineCharacterLimit===void 0?p={newline:`
49
+ `,Ov=o((t,e)=>{let r=(0,Gr.getDevPortalRuntimeConfig)(e),n=Kt.Environment.instance.deploymentName,i=Kt.Environment.instance.devPortalBaseUrl,s=o(async(u,l)=>{if(Kt.Environment.instance.isLocalDevelopment)return new Response(Rv,{headers:{"content-type":"text/html"}});if(!n)return Au.HttpProblems.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=(0,vv.devPortalBaseURL)(i,u.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:y,body:v}=u;return Kt.Environment.instance.build.ACCOUNT_NAME&&f.set(Iv,Kt.Environment.instance.build.ACCOUNT_NAME),Kt.Environment.instance.build.PROJECT_NAME&&f.set(Av,Kt.Environment.instance.build.PROJECT_NAME),f.set(Tv,n),f.set(Sv,d.host),f.set(Pv,Kt.Environment.instance.build.BUILD_ID),await fetch(m.toString(),{headers:f,method:y,body:v,redirect:"manual"})},"devPortalRoute"),a=new Fh.Pipeline([Hh.metricsProcessor,wv.policyProcessor],s,e),c=new qh.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${r.sitePathname}|/_next)(.*)`,systemRouteName:Au.SystemRouteName.DeveloperPortal});t.addRoute(c,a.execute)},"registerDevPortalV3Route");Br.registerDevPortalV3Route=Ov;var xv=o((t,e)=>{let{sitePathname:r}=(0,Gr.getDevPortalRuntimeConfig)(e),n=o(async a=>{let c=new URL(a.url);return r===Gr.DEV_PORTAL_LEGACY_PATHNAME?c.pathname=`/docs${c.pathname.substring(Gr.DEV_PORTAL_LEGACY_PATHNAME.length)}`:c.pathname=`${r}${c.pathname.substring(Gr.DEV_PORTAL_LEGACY_PATHNAME.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),i=new Fh.Pipeline([Hh.metricsProcessor],n,e),s=new qh.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Gr.DEV_PORTAL_LEGACY_PATHNAME}(.*)`,systemRouteName:Au.SystemRouteName.DeveloperPortalLegacy});t.addRoute(s,i.execute)},"registerDevPortalLegacyRedirectRoute");Br.registerDevPortalLegacyRedirectRoute=xv});var Pu=g(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.API_KEY=Kr.SYSTEM_LOGGER=void 0;Kr.SYSTEM_LOGGER="system-logger";Kr.API_KEY="api-key"});var jh=g(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.CoreLogger=void 0;var Ru=0,Ou=class{static{o(this,"CoreLogger")}constructor(e,r,n,i,s){this.#r=r,this.#n=n??"local",this.#i=i,this.#o=s,this.#e(e)}#e=e=>{let r=["error","warn","info","debug"],n=!1,i=o(()=>{},"emptyFunction"),s=o((a,c)=>{this.#o.forEach(u=>{u.log(a,c)})},"pushFunction");r.forEach(a=>{this.#t[a]=n?i:s,a==e&&(n=!0)})};#t={};#r;#n;#i;#o;log(e,r,n,i,s,a){Ru>=Number.MAX_SAFE_INTEGER&&(Ru=0);let c={requestId:n,rayId:i,level:e,logSource:r,messages:s,timestamp:new Date,logOwner:this.#r,loggingId:this.#n,buildId:this.#i,vectorClock:Ru++};this.#t[e](c,a)}};Co.CoreLogger=Ou});var Ct=g(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.LogPlugin=void 0;var Nv=Ot(),xu=class extends Nv.RuntimePlugin{static{o(this,"LogPlugin")}};Lo.LogPlugin=xu});var Vh=g(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.LoggingContext=void 0;var Nu=class{static{o(this,"LoggingContext")}constructor(e,r,n){this.#e=e,this.custom=r,this.originalRequest=n}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};Do.LoggingContext=Nu});var Gh=g(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.RequestLogger=void 0;var Cu=class{static{o(this,"RequestLogger")}constructor(e,r,n,i){this.#t=e,this.#r=r,this.#n=n,this.#i=i}#e="request";#t;#r;#n;#i;debug=(...e)=>{this.#n.log("debug",this.#e,this.#t,this.#r,e,this.#i)};info=(...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#i)};log=(...e)=>{this.#n.log("info",this.#e,this.#t,this.#r,e,this.#i)};warn=(...e)=>{this.#n.log("warn",this.#e,this.#t,this.#r,e,this.#i)};error=(...e)=>{this.#n.log("error",this.#e,this.#t,this.#r,e,this.#i)}};Uo.RequestLogger=Cu});var Jr=g(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.isObject=k.getOwnEnumerableKeys=k.isRegexp=k.isStringArray=k.isNonEmptyString=k.isString=k.toString=void 0;var{toString:Cv}=Object.prototype,{propertyIsEnumerable:Lv}=Object.prototype;function Bh(t){return Cv.call(t)}o(Bh,"toString");k.toString=Bh;function Mo(t){return typeof t=="string"}o(Mo,"isString");k.isString=Mo;function Dv(t){return Mo(t)&&t!==""}o(Dv,"isNonEmptyString");k.isNonEmptyString=Dv;function Uv(t){return Array.isArray(t)&&t.every(e=>Mo(e))}o(Uv,"isStringArray");k.isStringArray=Uv;function Mv(t){return Bh(t)==="[object RegExp]"}o(Mv,"isRegexp");k.isRegexp=Mv;function kv(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Lv.call(t,e))]}o(kv,"getOwnEnumerableKeys");k.getOwnEnumerableKeys=kv;function Kh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}o(Kh,"isObject");k.isObject=Kh;function Fv(t){let e=Object.getPrototypeOf(Uint8Array);return typeof t=="object"&&t instanceof e}o(Fv,"isTypedArray");k.isTypedArray=Fv;function Hv(t){return typeof t=="number"&&!isNaN(t)}o(Hv,"isNumber");k.isNumber=Hv;function qv(t){return!!t&&typeof t[Symbol.iterator]=="function"}o(qv,"isIterable");k.isIterable=qv;function $v(t){return t===!0||t===!1}o($v,"isBoolean");k.isBoolean=$v;function Jh(t){return typeof t>"u"}o(Jh,"isUndefined");k.isUndefined=Jh;function jv(t){return!Xn(t)}o(jv,"isDefined");k.isDefined=jv;function Xn(t){return Jh(t)||t===null}o(Xn,"isUndefinedOrNull");k.isUndefinedOrNull=Xn;function Vv(t,e){if(!t)throw new Error(e?`Unexpected type, expected '${e}'`:"Unexpected type")}o(Vv,"assertType");k.assertType=Vv;function Gv(t){if(Xn(t))throw new Error("Assertion Failed: argument is undefined or null");return t}o(Gv,"assertIsDefined");k.assertIsDefined=Gv;function Bv(...t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(Xn(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);e.push(n)}return e}o(Bv,"assertAllDefined");k.assertAllDefined=Bv;var Kv=Object.prototype.hasOwnProperty;function Jv(t){if(!Kh(t))return!1;for(let e in t)if(Kv.call(t,e))return!1;return!0}o(Jv,"isEmptyObject");k.isEmptyObject=Jv;function Lu(t){return typeof t=="function"}o(Lu,"isFunction");k.isFunction=Lu;function zv(...t){return t.length>0&&t.every(Lu)}o(zv,"areFunctions");k.areFunctions=zv;function Wv(t,e){let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)zh(t[n],e[n])}o(Wv,"validateConstraints");k.validateConstraints=Wv;function zh(t,e){if(Mo(e)){if(typeof t!==e)throw new Error(`argument does not match constraint: typeof ${e}`)}else if(Lu(e)){try{if(t instanceof e)return}catch{}if(!Xn(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(zh,"validateConstraint");k.validateConstraint=zh;function Qv(t){return t===null?void 0:t}o(Qv,"withNullAsUndefined");k.withNullAsUndefined=Qv;function Yv(t){return typeof t>"u"?null:t}o(Yv,"withUndefinedAsNull");k.withUndefinedAsNull=Yv;function Zv(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}o(Zv,"isErrorLike");k.isErrorLike=Zv});var Pr=g(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.cleanStack=Jt.serializeError=Jt.NonError=void 0;var Wh=Jr(),Xv=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),eT=new Map(Xv),Du=class t extends Error{static{o(this,"NonError")}name="NonError";constructor(e){super(t._prepareSuperMessage(e))}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}};Jt.NonError=Du;var tT=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Uu=Symbol(".toJSON was called"),rT=o(t=>{t[Uu]=!0;let e=t.toJSON();return delete t[Uu],e},"toJSON"),nT=o(t=>eT.get(t)??Error,"getErrorConstructor"),Qh=o(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c})=>{if(!r)if(Array.isArray(t))r=[];else if(!c&&(0,Wh.isErrorLike)(t)){let l=nT(t.name);r=new l}else r={};if(e.push(t),s>=i)return r;if(a&&typeof t.toJSON=="function"&&t[Uu]!==!0)return rT(t);let u=o(l=>Qh({from:l,seen:[...e],forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=u(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of tT)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:(0,Wh.isErrorLike)(t[l])?u(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function iT(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Qh({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}o(iT,"serializeError");Jt.serializeError=iT;var oT=/file:\/\/\/(.*?)\/dist\//g,sT=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,aT="at async Event.respondWith";function cT(t){return typeof t!="string"?t:t.split(`
50
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(oT,"").replaceAll(sT,"").replaceAll(aT,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
51
+ `)}o(cT,"cleanStack");Jt.cleanStack=cT});var Yh=g(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var Mu=Jr();function uT(t,e,r=""){let n=[],i=e?.maxDepth??3;return o(function s(a,c={},u,l){let d=c.indent||" ",p;c.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
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 m=o(f=>{if(c.inlineCharacterLimit===void 0)return f;let y=f.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:f.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
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,Uu.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 f="["+p.newline+a.map((y,v)=>{let T=a.length-1===v?p.newline:","+p.newlineOrSpace,S=s(y,c,u+d,l+1);return c.transform&&(S=c.transform(a,v,S)),p.indent+S+T}).join("")+p.pad+"]";return n.pop(),m(f)}if((0,Uu.isObject)(a)){let f=(0,Uu.getOwnEnumerableKeys)(a);if(c.filter&&(f=f.filter(v=>c.filter?.(a,v))),f.length===0)return"{}";n.push(a);let y="{"+p.newline+f.map((v,T)=>{let S=f.length-1===T?p.newline:","+p.newlineOrSpace,M=typeof v=="symbol",H=!M&&/^[a-z$_][$\w]*$/i.test(v),R=M||H?v:s(v,c,"",l+1),ne=s(a[v],c,u+d,l+1);return c.transform&&(ne=c.transform(a,v,ne)),p.indent+String(R)+": "+ne+S}).join("")+p.pad+"}";return n.pop(),m(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,f=>f===`
55
- `?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,r,0)}o(aT,"stringifyObject");Mu.default=aT});var yt=g(Fe=>{"use strict";var cT=Fe&&Fe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.stringifyNonStringToText=Fe.stringifyNonString=Fe.messagesToMultilineText=Fe.extractBestMessage=Fe.makeErrorsSerializable=void 0;var ku=Pr(),Yh=cT(Qh()),Zh=Jr();function uT(t){return t.map(e=>(0,ku.serializeError)(e))}o(uT,"makeErrorsSerializable");Fe.makeErrorsSerializable=uT;function lT(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:Xh((0,ku.serializeError)(e))}o(lT,"extractBestMessage");Fe.extractBestMessage=lT;function dT(t){let e=[];return t.forEach(r=>{if(typeof r=="string")e.push(r);else if((0,Zh.isErrorLike)(r))if(r.stack)e.push(r.stack);else{let n=(0,Yh.default)((0,ku.serializeError)(r));e.push(n)}else if(typeof r=="object"){let n=(0,Yh.default)(r);e.push(n)}else{let n=ef(r);e.push(n)}}),e.join(`
56
- `)}o(dT,"messagesToMultilineText");Fe.messagesToMultilineText=dT;function Xh(t){return typeof t=="string"?t:JSON.stringify(t)}o(Xh,"stringifyNonString");Fe.stringifyNonString=Xh;function ef(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,Zh.toString)(t):"unknown"}o(ef,"stringifyNonStringToText");Fe.stringifyNonStringToText=ef});var L,se,Te=I(()=>{L=crypto,se=o(t=>t instanceof CryptoKey,"isCryptoKey")});var pT,ko,Fu=I(()=>{Te();pT=o(async(t,e)=>{let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await L.subtle.digest(r,e))},"digest"),ko=pT});function Se(...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 tf(t,e){return Se(Z.encode(t),new Uint8Array([0]),e)}function Hu(t,e,r){if(e<0||e>=Fo)throw new RangeError(`value must be >= 0 and <= ${Fo-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function Ho(t){let e=Math.floor(t/Fo),r=t%Fo,n=new Uint8Array(8);return Hu(n,e,0),Hu(n,r,4),n}function qo(t){let e=new Uint8Array(4);return Hu(e,t),e}function $o(t){return Se(qo(t.length),t)}async function rf(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(qo(s+1)),a.set(t,4),a.set(r,4+t.length),i.set(await ko("sha256",a),s*32)}return i.slice(0,e>>3)}var Z,ce,Fo,ye=I(()=>{Fu();Z=new TextEncoder,ce=new TextDecoder,Fo=2**32;o(Se,"concat");o(tf,"p2s");o(Hu,"writeUInt32BE");o(Ho,"uint64be");o(qo,"uint32be");o($o,"lengthAndInput");o(rf,"concatKdf")});var jo,X,qu,re,Ie=I(()=>{ye();jo=o(t=>{let e=t;typeof e=="string"&&(e=Z.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"),X=o(t=>jo(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),qu=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"),re=o(t=>{let e=t;e instanceof Uint8Array&&(e=ce.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return qu(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var $u={};Ki($u,{JOSEAlgNotAllowed:()=>Jt,JOSEError:()=>pe,JOSENotSupported:()=>U,JWEDecryptionFailed:()=>Lt,JWEInvalid:()=>P,JWKInvalid:()=>ei,JWKSInvalid:()=>zt,JWKSMultipleMatchingKeys:()=>ti,JWKSNoMatchingKey:()=>Rr,JWKSTimeout:()=>ri,JWSInvalid:()=>z,JWSSignatureVerificationFailed:()=>Or,JWTClaimValidationFailed:()=>ge,JWTExpired:()=>zr,JWTInvalid:()=>ue});var pe,ge,zr,Jt,U,Lt,P,z,ue,ei,zt,Rr,ti,ri,Or,V=I(()=>{pe=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)}},ge=class extends pe{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}},zr=class extends pe{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}},Jt=class extends pe{static{o(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},U=class extends pe{static{o(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Lt=class extends pe{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"}},P=class extends pe{static{o(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},z=class extends pe{static{o(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},ue=class extends pe{static{o(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ei=class extends pe{static{o(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},zt=class extends pe{static{o(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Rr=class extends pe{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"}},ti=class extends pe{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"}},ri=class extends pe{static{o(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Or=class extends pe{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 Wt,ni=I(()=>{Te();Wt=L.getRandomValues.bind(L)});function ju(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 U(`Unsupported JWE Algorithm: ${t}`)}}var Vo,Go=I(()=>{V();ni();o(ju,"bitLength");Vo=o(t=>Wt(new Uint8Array(ju(t)>>3)),"default")});var hT,Bo,Vu=I(()=>{V();Go();hT=o((t,e)=>{if(e.length<<3!==ju(t))throw new P("Invalid Initialization Vector length")},"checkIvLength"),Bo=hT});var fT,Wr,Gu=I(()=>{V();fT=o((t,e)=>{let r=t.byteLength<<3;if(r!==e)throw new P(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)},"checkCekLength"),Wr=fT});var mT,of,sf=I(()=>{mT=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"),of=mT});function Ae(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function Qt(t,e){return t.name===e}function Ko(t){return parseInt(t.name.slice(4),10)}function yT(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function af(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 cf(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Qt(t.algorithm,"HMAC"))throw Ae("HMAC");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Qt(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Ae("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Qt(t.algorithm,"RSA-PSS"))throw Ae("RSA-PSS");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Ae("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Qt(t.algorithm,"ECDSA"))throw Ae("ECDSA");let n=yT(e);if(t.algorithm.namedCurve!==n)throw Ae(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}af(t,r)}function He(t,e,...r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Qt(t.algorithm,"AES-GCM"))throw Ae("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Ae(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Qt(t.algorithm,"AES-KW"))throw Ae("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Ae(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Ae("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Qt(t.algorithm,"PBKDF2"))throw Ae("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Qt(t.algorithm,"RSA-OAEP"))throw Ae("RSA-OAEP");let n=parseInt(e.slice(9),10)||1;if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}af(t,r)}var Yt=I(()=>{o(Ae,"unusable");o(Qt,"isAlgorithm");o(Ko,"getHashLength");o(yT,"getNamedCurve");o(af,"checkUsage");o(cf,"checkSigCryptoKey");o(He,"checkEncCryptoKey")});function uf(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 Bu(t,e,...r){return uf(`Key for the ${t} algorithm must be `,e,...r)}var ie,ot=I(()=>{o(uf,"message");ie=o((t,...e)=>uf("Key must be ",t,...e),"default");o(Bu,"withAlg")});var Ku,W,st=I(()=>{Te();Ku=o(t=>se(t),"default"),W=["CryptoKey"]});async function gT(t,e,r,n,i,s){if(!(e instanceof Uint8Array))throw new TypeError(ie(e,"Uint8Array"));let a=parseInt(t.slice(1,4),10),c=await L.subtle.importKey("raw",e.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await L.subtle.importKey("raw",e.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Se(s,n,r,Ho(s.length<<3)),d=new Uint8Array((await L.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=of(i,d)}catch{}if(!p)throw new Lt;let m;try{m=new Uint8Array(await L.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!m)throw new Lt;return m}async function _T(t,e,r,n,i,s){let a;e instanceof Uint8Array?a=await L.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(He(e,t,"decrypt"),a=e);try{return new Uint8Array(await L.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},a,Se(r,i)))}catch{throw new Lt}}var bT,Jo,Ju=I(()=>{ye();Vu();Gu();sf();V();Te();Yt();ot();st();o(gT,"cbcDecrypt");o(_T,"gcmDecrypt");bT=o(async(t,e,r,n,i,s)=>{if(!se(e)&&!(e instanceof Uint8Array))throw new TypeError(ie(e,...W,"Uint8Array"));switch(Bo(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&Wr(e,parseInt(t.slice(-3),10)),gT(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&Wr(e,parseInt(t.slice(1,4),10)),_T(t,e,r,n,i,s);default:throw new U("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),Jo=bT});var lf,df,zu=I(()=>{V();lf=o(async()=>{throw new U('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"),df=o(async()=>{throw new U('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 ET,gt,Qr=I(()=>{ET=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"),gt=ET});function wT(t){return typeof t=="object"&&t!==null}function Q(t){if(!wT(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=I(()=>{o(wT,"isObjectLike");o(Q,"isObject")});var vT,Yr,Wu=I(()=>{vT=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],Yr=vT});function pf(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function hf(t,e,r){if(se(t))return He(t,e,r),t;if(t instanceof Uint8Array)return L.subtle.importKey("raw",t,"AES-KW",!0,[r]);throw new TypeError(ie(t,...W,"Uint8Array"))}var ii,oi,zo=I(()=>{Wu();Te();Yt();ot();st();o(pf,"checkKeySize");o(hf,"getCryptoKey");ii=o(async(t,e,r)=>{let n=await hf(e,t,"wrapKey");pf(n,t);let i=await L.subtle.importKey("raw",r,...Yr);return new Uint8Array(await L.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),oi=o(async(t,e,r)=>{let n=await hf(e,t,"unwrapKey");pf(n,t);let i=await L.subtle.unwrapKey("raw",r,n,"AES-KW",...Yr);return new Uint8Array(await L.subtle.exportKey("raw",i))},"unwrap")});async function Wo(t,e,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!se(t))throw new TypeError(ie(t,...W));if(He(t,"ECDH"),!se(e))throw new TypeError(ie(e,...W));He(e,"ECDH","deriveBits");let a=Se($o(Z.encode(r)),$o(i),$o(s),qo(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 L.subtle.deriveBits({name:t.algorithm.name,public:t},e,c));return rf(u,n,a)}async function ff(t){if(!se(t))throw new TypeError(ie(t,...W));return L.subtle.generateKey(t.algorithm,!0,["deriveBits"])}function Qo(t){if(!se(t))throw new TypeError(ie(t,...W));return["P-256","P-384","P-521"].includes(t.algorithm.namedCurve)||t.algorithm.name==="X25519"||t.algorithm.name==="X448"}var Qu=I(()=>{ye();Te();Yt();ot();st();o(Wo,"deriveKey");o(ff,"generateEpk");o(Qo,"ecdhAllowed")});function Yu(t){if(!(t instanceof Uint8Array)||t.length<8)throw new P("PBES2 Salt Input must be 8 or more octets")}var yf=I(()=>{V();o(Yu,"checkP2s")});function TT(t,e){if(t instanceof Uint8Array)return L.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]);if(se(t))return He(t,e,"deriveBits","deriveKey"),t;throw new TypeError(ie(t,...W,"Uint8Array"))}async function gf(t,e,r,n){Yu(t);let i=tf(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 TT(n,e);if(u.usages.includes("deriveBits"))return new Uint8Array(await L.subtle.deriveBits(a,u,s));if(u.usages.includes("deriveKey"))return L.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var _f,bf,Zu=I(()=>{ni();ye();Ie();zo();yf();Te();Yt();ot();st();o(TT,"getCryptoKey");o(gf,"deriveKey");_f=o(async(t,e,r,n=2048,i=Wt(new Uint8Array(16)))=>{let s=await gf(i,t,n,e);return{encryptedKey:await ii(t.slice(-6),s,r),p2c:n,p2s:X(i)}},"encrypt"),bf=o(async(t,e,r,n,i)=>{let s=await gf(i,t,n,e);return oi(t.slice(-6),s,r)},"decrypt")});function Zr(t){switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new U(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var Ef=I(()=>{V();o(Zr,"subtleRsaEs")});var xr,Yo=I(()=>{xr=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 wf,vf,Xu=I(()=>{Ef();Wu();Te();Yt();Yo();ot();st();wf=o(async(t,e,r)=>{if(!se(e))throw new TypeError(ie(e,...W));if(He(e,t,"encrypt","wrapKey"),xr(t,e),e.usages.includes("encrypt"))return new Uint8Array(await L.subtle.encrypt(Zr(t),e,r));if(e.usages.includes("wrapKey")){let n=await L.subtle.importKey("raw",r,...Yr);return new Uint8Array(await L.subtle.wrapKey("raw",n,e,Zr(t)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),vf=o(async(t,e,r)=>{if(!se(e))throw new TypeError(ie(e,...W));if(He(e,t,"decrypt","unwrapKey"),xr(t,e),e.usages.includes("decrypt"))return new Uint8Array(await L.subtle.decrypt(Zr(t),e,r));if(e.usages.includes("unwrapKey")){let n=await L.subtle.unwrapKey("raw",r,e,Zr(t),...Yr);return new Uint8Array(await L.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function si(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 U(`Unsupported JWE Algorithm: ${t}`)}}var _t,ai=I(()=>{V();ni();o(si,"bitLength");_t=o(t=>Wt(new Uint8Array(si(t)>>3)),"default")});var el,Tf=I(()=>{el=o((t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
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,Mu.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 f="["+p.newline+a.map((y,v)=>{let T=a.length-1===v?p.newline:","+p.newlineOrSpace,S=s(y,c,u+d,l+1);return c.transform&&(S=c.transform(a,v,S)),p.indent+S+T}).join("")+p.pad+"]";return n.pop(),m(f)}if((0,Mu.isObject)(a)){let f=(0,Mu.getOwnEnumerableKeys)(a);if(c.filter&&(f=f.filter(v=>c.filter?.(a,v))),f.length===0)return"{}";n.push(a);let y="{"+p.newline+f.map((v,T)=>{let S=f.length-1===T?p.newline:","+p.newlineOrSpace,M=typeof v=="symbol",H=!M&&/^[a-z$_][$\w]*$/i.test(v),R=M||H?v:s(v,c,"",l+1),ne=s(a[v],c,u+d,l+1);return c.transform&&(ne=c.transform(a,v,ne)),p.indent+String(R)+": "+ne+S}).join("")+p.pad+"}";return n.pop(),m(y)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,f=>f===`
55
+ `?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(t,e,r,0)}o(uT,"stringifyObject");ku.default=uT});var yt=g(Fe=>{"use strict";var lT=Fe&&Fe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.stringifyNonStringToText=Fe.stringifyNonString=Fe.messagesToMultilineText=Fe.extractBestMessage=Fe.makeErrorsSerializable=void 0;var Fu=Pr(),Zh=lT(Yh()),Xh=Jr();function dT(t){return t.map(e=>(0,Fu.serializeError)(e))}o(dT,"makeErrorsSerializable");Fe.makeErrorsSerializable=dT;function pT(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:ef((0,Fu.serializeError)(e))}o(pT,"extractBestMessage");Fe.extractBestMessage=pT;function hT(t){let e=[];return t.forEach(r=>{if(typeof r=="string")e.push(r);else if((0,Xh.isErrorLike)(r))if(r.stack)e.push(r.stack);else{let n=(0,Zh.default)((0,Fu.serializeError)(r));e.push(n)}else if(typeof r=="object"){let n=(0,Zh.default)(r);e.push(n)}else{let n=tf(r);e.push(n)}}),e.join(`
56
+ `)}o(hT,"messagesToMultilineText");Fe.messagesToMultilineText=hT;function ef(t){return typeof t=="string"?t:JSON.stringify(t)}o(ef,"stringifyNonString");Fe.stringifyNonString=ef;function tf(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,Xh.toString)(t):"unknown"}o(tf,"stringifyNonStringToText");Fe.stringifyNonStringToText=tf});var L,se,Te=I(()=>{L=crypto,se=o(t=>t instanceof CryptoKey,"isCryptoKey")});var fT,ko,Hu=I(()=>{Te();fT=o(async(t,e)=>{let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await L.subtle.digest(r,e))},"digest"),ko=fT});function Se(...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 rf(t,e){return Se(Z.encode(t),new Uint8Array([0]),e)}function qu(t,e,r){if(e<0||e>=Fo)throw new RangeError(`value must be >= 0 and <= ${Fo-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function Ho(t){let e=Math.floor(t/Fo),r=t%Fo,n=new Uint8Array(8);return qu(n,e,0),qu(n,r,4),n}function qo(t){let e=new Uint8Array(4);return qu(e,t),e}function $o(t){return Se(qo(t.length),t)}async function nf(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(qo(s+1)),a.set(t,4),a.set(r,4+t.length),i.set(await ko("sha256",a),s*32)}return i.slice(0,e>>3)}var Z,ce,Fo,ye=I(()=>{Hu();Z=new TextEncoder,ce=new TextDecoder,Fo=2**32;o(Se,"concat");o(rf,"p2s");o(qu,"writeUInt32BE");o(Ho,"uint64be");o(qo,"uint32be");o($o,"lengthAndInput");o(nf,"concatKdf")});var jo,X,$u,re,Ie=I(()=>{ye();jo=o(t=>{let e=t;typeof e=="string"&&(e=Z.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"),X=o(t=>jo(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),$u=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"),re=o(t=>{let e=t;e instanceof Uint8Array&&(e=ce.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return $u(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var ju={};Ki(ju,{JOSEAlgNotAllowed:()=>zt,JOSEError:()=>pe,JOSENotSupported:()=>U,JWEDecryptionFailed:()=>Lt,JWEInvalid:()=>P,JWKInvalid:()=>ei,JWKSInvalid:()=>Wt,JWKSMultipleMatchingKeys:()=>ti,JWKSNoMatchingKey:()=>Rr,JWKSTimeout:()=>ri,JWSInvalid:()=>z,JWSSignatureVerificationFailed:()=>Or,JWTClaimValidationFailed:()=>ge,JWTExpired:()=>zr,JWTInvalid:()=>ue});var pe,ge,zr,zt,U,Lt,P,z,ue,ei,Wt,Rr,ti,ri,Or,V=I(()=>{pe=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)}},ge=class extends pe{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}},zr=class extends pe{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}},zt=class extends pe{static{o(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},U=class extends pe{static{o(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Lt=class extends pe{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"}},P=class extends pe{static{o(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},z=class extends pe{static{o(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},ue=class extends pe{static{o(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ei=class extends pe{static{o(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},Wt=class extends pe{static{o(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Rr=class extends pe{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"}},ti=class extends pe{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"}},ri=class extends pe{static{o(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Or=class extends pe{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 Qt,ni=I(()=>{Te();Qt=L.getRandomValues.bind(L)});function Vu(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 U(`Unsupported JWE Algorithm: ${t}`)}}var Vo,Go=I(()=>{V();ni();o(Vu,"bitLength");Vo=o(t=>Qt(new Uint8Array(Vu(t)>>3)),"default")});var mT,Bo,Gu=I(()=>{V();Go();mT=o((t,e)=>{if(e.length<<3!==Vu(t))throw new P("Invalid Initialization Vector length")},"checkIvLength"),Bo=mT});var yT,Wr,Bu=I(()=>{V();yT=o((t,e)=>{let r=t.byteLength<<3;if(r!==e)throw new P(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)},"checkCekLength"),Wr=yT});var gT,sf,af=I(()=>{gT=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"),sf=gT});function Ae(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function Yt(t,e){return t.name===e}function Ko(t){return parseInt(t.name.slice(4),10)}function _T(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function cf(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 uf(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Yt(t.algorithm,"HMAC"))throw Ae("HMAC");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Yt(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Ae("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Yt(t.algorithm,"RSA-PSS"))throw Ae("RSA-PSS");let n=parseInt(e.slice(2),10);if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Ae("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Yt(t.algorithm,"ECDSA"))throw Ae("ECDSA");let n=_T(e);if(t.algorithm.namedCurve!==n)throw Ae(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}cf(t,r)}function He(t,e,...r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Yt(t.algorithm,"AES-GCM"))throw Ae("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Ae(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Yt(t.algorithm,"AES-KW"))throw Ae("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Ae(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Ae("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Yt(t.algorithm,"PBKDF2"))throw Ae("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Yt(t.algorithm,"RSA-OAEP"))throw Ae("RSA-OAEP");let n=parseInt(e.slice(9),10)||1;if(Ko(t.algorithm.hash)!==n)throw Ae(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}cf(t,r)}var Zt=I(()=>{o(Ae,"unusable");o(Yt,"isAlgorithm");o(Ko,"getHashLength");o(_T,"getNamedCurve");o(cf,"checkUsage");o(uf,"checkSigCryptoKey");o(He,"checkEncCryptoKey")});function lf(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 Ku(t,e,...r){return lf(`Key for the ${t} algorithm must be `,e,...r)}var ie,ot=I(()=>{o(lf,"message");ie=o((t,...e)=>lf("Key must be ",t,...e),"default");o(Ku,"withAlg")});var Ju,W,st=I(()=>{Te();Ju=o(t=>se(t),"default"),W=["CryptoKey"]});async function bT(t,e,r,n,i,s){if(!(e instanceof Uint8Array))throw new TypeError(ie(e,"Uint8Array"));let a=parseInt(t.slice(1,4),10),c=await L.subtle.importKey("raw",e.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await L.subtle.importKey("raw",e.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Se(s,n,r,Ho(s.length<<3)),d=new Uint8Array((await L.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=sf(i,d)}catch{}if(!p)throw new Lt;let m;try{m=new Uint8Array(await L.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!m)throw new Lt;return m}async function ET(t,e,r,n,i,s){let a;e instanceof Uint8Array?a=await L.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):(He(e,t,"decrypt"),a=e);try{return new Uint8Array(await L.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},a,Se(r,i)))}catch{throw new Lt}}var wT,Jo,zu=I(()=>{ye();Gu();Bu();af();V();Te();Zt();ot();st();o(bT,"cbcDecrypt");o(ET,"gcmDecrypt");wT=o(async(t,e,r,n,i,s)=>{if(!se(e)&&!(e instanceof Uint8Array))throw new TypeError(ie(e,...W,"Uint8Array"));switch(Bo(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&Wr(e,parseInt(t.slice(-3),10)),bT(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&Wr(e,parseInt(t.slice(1,4),10)),ET(t,e,r,n,i,s);default:throw new U("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),Jo=wT});var df,pf,Wu=I(()=>{V();df=o(async()=>{throw new U('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"),pf=o(async()=>{throw new U('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 vT,gt,Qr=I(()=>{vT=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"),gt=vT});function TT(t){return typeof t=="object"&&t!==null}function Q(t){if(!TT(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=I(()=>{o(TT,"isObjectLike");o(Q,"isObject")});var ST,Yr,Qu=I(()=>{ST=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],Yr=ST});function hf(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ff(t,e,r){if(se(t))return He(t,e,r),t;if(t instanceof Uint8Array)return L.subtle.importKey("raw",t,"AES-KW",!0,[r]);throw new TypeError(ie(t,...W,"Uint8Array"))}var ii,oi,zo=I(()=>{Qu();Te();Zt();ot();st();o(hf,"checkKeySize");o(ff,"getCryptoKey");ii=o(async(t,e,r)=>{let n=await ff(e,t,"wrapKey");hf(n,t);let i=await L.subtle.importKey("raw",r,...Yr);return new Uint8Array(await L.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),oi=o(async(t,e,r)=>{let n=await ff(e,t,"unwrapKey");hf(n,t);let i=await L.subtle.unwrapKey("raw",r,n,"AES-KW",...Yr);return new Uint8Array(await L.subtle.exportKey("raw",i))},"unwrap")});async function Wo(t,e,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!se(t))throw new TypeError(ie(t,...W));if(He(t,"ECDH"),!se(e))throw new TypeError(ie(e,...W));He(e,"ECDH","deriveBits");let a=Se($o(Z.encode(r)),$o(i),$o(s),qo(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 L.subtle.deriveBits({name:t.algorithm.name,public:t},e,c));return nf(u,n,a)}async function mf(t){if(!se(t))throw new TypeError(ie(t,...W));return L.subtle.generateKey(t.algorithm,!0,["deriveBits"])}function Qo(t){if(!se(t))throw new TypeError(ie(t,...W));return["P-256","P-384","P-521"].includes(t.algorithm.namedCurve)||t.algorithm.name==="X25519"||t.algorithm.name==="X448"}var Yu=I(()=>{ye();Te();Zt();ot();st();o(Wo,"deriveKey");o(mf,"generateEpk");o(Qo,"ecdhAllowed")});function Zu(t){if(!(t instanceof Uint8Array)||t.length<8)throw new P("PBES2 Salt Input must be 8 or more octets")}var gf=I(()=>{V();o(Zu,"checkP2s")});function IT(t,e){if(t instanceof Uint8Array)return L.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]);if(se(t))return He(t,e,"deriveBits","deriveKey"),t;throw new TypeError(ie(t,...W,"Uint8Array"))}async function _f(t,e,r,n){Zu(t);let i=rf(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 IT(n,e);if(u.usages.includes("deriveBits"))return new Uint8Array(await L.subtle.deriveBits(a,u,s));if(u.usages.includes("deriveKey"))return L.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var bf,Ef,Xu=I(()=>{ni();ye();Ie();zo();gf();Te();Zt();ot();st();o(IT,"getCryptoKey");o(_f,"deriveKey");bf=o(async(t,e,r,n=2048,i=Qt(new Uint8Array(16)))=>{let s=await _f(i,t,n,e);return{encryptedKey:await ii(t.slice(-6),s,r),p2c:n,p2s:X(i)}},"encrypt"),Ef=o(async(t,e,r,n,i)=>{let s=await _f(i,t,n,e);return oi(t.slice(-6),s,r)},"decrypt")});function Zr(t){switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new U(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var wf=I(()=>{V();o(Zr,"subtleRsaEs")});var xr,Yo=I(()=>{xr=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 vf,Tf,el=I(()=>{wf();Qu();Te();Zt();Yo();ot();st();vf=o(async(t,e,r)=>{if(!se(e))throw new TypeError(ie(e,...W));if(He(e,t,"encrypt","wrapKey"),xr(t,e),e.usages.includes("encrypt"))return new Uint8Array(await L.subtle.encrypt(Zr(t),e,r));if(e.usages.includes("wrapKey")){let n=await L.subtle.importKey("raw",r,...Yr);return new Uint8Array(await L.subtle.wrapKey("raw",n,e,Zr(t)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),Tf=o(async(t,e,r)=>{if(!se(e))throw new TypeError(ie(e,...W));if(He(e,t,"decrypt","unwrapKey"),xr(t,e),e.usages.includes("decrypt"))return new Uint8Array(await L.subtle.decrypt(Zr(t),e,r));if(e.usages.includes("unwrapKey")){let n=await L.subtle.unwrapKey("raw",r,e,Zr(t),...Yr);return new Uint8Array(await L.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function si(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 U(`Unsupported JWE Algorithm: ${t}`)}}var _t,ai=I(()=>{V();ni();o(si,"bitLength");_t=o(t=>Qt(new Uint8Array(si(t)>>3)),"default")});var tl,Sf=I(()=>{tl=o((t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
57
57
  `);return`-----BEGIN ${e}-----
58
58
  ${r}
59
- -----END ${e}-----`},"default")});function If(t){let e=[],r=0;for(;r<t.length;){let n=Nf(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Nf(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 ST(t){let e=If(If(Nf(t).contents)[0].contents);return jo(e[e[0].raw[0]===160?6:5].raw)}function IT(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=qu(e);return el(ST(r),"PUBLIC KEY")}var Af,Pf,Rf,Zt,Sf,Of,xf,tl,Cf,Zo=I(()=>{Te();ot();Ie();Tf();V();st();Af=o(async(t,e,r)=>{if(!se(r))throw new TypeError(ie(r,...W));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return el(jo(new Uint8Array(await L.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Pf=o(t=>Af("public","spki",t),"toSPKI"),Rf=o(t=>Af("private","pkcs8",t),"toPKCS8"),Zt=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])||Zt(t,e,n+1)},"findOid"),Sf=o(t=>{switch(!0){case Zt(t,[42,134,72,206,61,3,1,7]):return"P-256";case Zt(t,[43,129,4,0,34]):return"P-384";case Zt(t,[43,129,4,0,35]):return"P-521";case Zt(t,[43,101,110]):return"X25519";case Zt(t,[43,101,111]):return"X448";case Zt(t,[43,101,112]):return"Ed25519";case Zt(t,[43,101,113]):return"Ed448";default:throw new U("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Of=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=Sf(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:Sf(u)},c=l?["verify"]:["sign"];break;default:throw new U('Invalid or unsupported "alg" (Algorithm) value')}return L.subtle.importKey(e,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),xf=o((t,e,r)=>Of(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),tl=o((t,e,r)=>Of(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");o(If,"getElement");o(Nf,"parseElement");o(ST,"spkiFromX509");o(IT,"getSPKI");Cf=o((t,e,r)=>{let n;try{n=IT(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return tl(n,e,r)},"fromX509")});function AT(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 U(`${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 U('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 U('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 U('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 U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new U('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var PT,rl,Lf=I(()=>{Te();V();Ie();o(AT,"subtleMapping");PT=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}=AT(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 L.subtle.importKey("raw",re(t.k),...s);let a={...t};return delete a.alg,delete a.use,L.subtle.importKey("jwk",a,...s)},"parse"),rl=PT});async function Df(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return tl(t,e,r)}async function Uf(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Cf(t,e,r)}async function Mf(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return xf(t,e,r)}async function Xt(t,e,r){var n;if(!Q(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?rl({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):re(t.k);case"RSA":if(t.oth!==void 0)throw new U('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return rl({...t,alg:e});default:throw new U('Unsupported "kty" (Key Type) Parameter value')}}var ci=I(()=>{Ie();Zo();Lf();V();qe();o(Df,"importSPKI");o(Uf,"importX509");o(Mf,"importPKCS8");o(Xt,"importJWK")});var RT,OT,xT,er,ui=I(()=>{ot();st();RT=o((t,e)=>{if(!(e instanceof Uint8Array)){if(!Ku(e))throw new TypeError(Bu(t,e,...W,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${W.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),OT=o((t,e,r)=>{if(!Ku(e))throw new TypeError(Bu(t,e,...W));if(e.type==="secret")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),xT=o((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?RT(t,e):OT(t,e,r)},"checkKeyType"),er=xT});async function NT(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(ie(r,"Uint8Array"));let s=parseInt(t.slice(1,4),10),a=await L.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await L.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await L.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Se(i,n,u,Ho(i.length<<3)),d=new Uint8Array((await L.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function CT(t,e,r,n,i){let s;r instanceof Uint8Array?s=await L.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(He(r,t,"encrypt"),s=r);let a=new Uint8Array(await L.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 LT,li,nl=I(()=>{ye();Vu();Gu();Te();Yt();ot();V();st();o(NT,"cbcEncrypt");o(CT,"gcmEncrypt");LT=o(async(t,e,r,n,i)=>{if(!se(r)&&!(r instanceof Uint8Array))throw new TypeError(ie(r,...W,"Uint8Array"));switch(Bo(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&Wr(r,parseInt(t.slice(-3),10)),NT(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&Wr(r,parseInt(t.slice(1,4),10)),CT(t,e,r,n,i);default:throw new U("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),li=LT});async function kf(t,e,r,n){let i=t.slice(0,7);n||(n=Vo(i));let{ciphertext:s,tag:a}=await li(i,r,e,n,new Uint8Array(0));return{encryptedKey:s,iv:X(n),tag:X(a)}}async function Ff(t,e,r,n,i){let s=t.slice(0,7);return Jo(s,e,r,n,i,new Uint8Array(0))}var il=I(()=>{nl();Ju();Go();Ie();o(kf,"wrap");o(Ff,"unwrap")});async function DT(t,e,r,n,i){switch(er(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new P("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new P("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Q(n.epk))throw new P('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Qo(e))throw new U("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Xt(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new P('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new P('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await Wo(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?si(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new P("JWE Encrypted Key missing");return oi(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 P("JWE Encrypted Key missing");return vf(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new P("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new P('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new P('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new P('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return bf(t,e,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new P("JWE Encrypted Key missing");return oi(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new P("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new P('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new P('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=re(n.iv),a=re(n.tag);return Ff(t,e,r,s,a)}default:throw new U('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Hf,qf=I(()=>{zo();Qu();Zu();Xu();Ie();V();ai();ci();ui();qe();il();o(DT,"decryptKeyManagement");Hf=DT});function UT(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 U(`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 bt,Xr=I(()=>{V();o(UT,"validateCrit");bt=UT});var MT,di,ol=I(()=>{MT=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"),di=MT});async function en(t,e,r){var n;if(!Q(t))throw new P("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new P("JOSE Header missing");if(typeof t.iv!="string")throw new P("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new P("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new P("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new P("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new P("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new P("JWE AAD incorrect type");if(t.header!==void 0&&!Q(t.header))throw new P("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!Q(t.unprotected))throw new P("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let H=re(t.protected);i=JSON.parse(ce.decode(H))}catch{throw new P("JWE Protected Header is invalid")}if(!gt(i,t.header,t.unprotected))throw new P("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...t.header,...t.unprotected};if(bt(P,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new U('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new P("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new P("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&di("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&di("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new Jt('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new Jt('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=re(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let m;try{m=await Hf(a,e,d,s,r)}catch(H){if(H instanceof TypeError||H instanceof P||H instanceof U)throw H;m=_t(c)}let f=re(t.iv),y=re(t.tag),v=Z.encode((n=t.protected)!==null&&n!==void 0?n:""),T;t.aad!==void 0?T=Se(v,Z.encode("."),Z.encode(t.aad)):T=v;let S=await Jo(c,m,re(t.ciphertext),f,y,T);s.zip==="DEF"&&(S=await(r?.inflateRaw||lf)(S));let M={plaintext:S};return t.protected!==void 0&&(M.protectedHeader=i),t.aad!==void 0&&(M.additionalAuthenticatedData=re(t.aad)),t.unprotected!==void 0&&(M.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(M.unprotectedHeader=t.header),p?{...M,key:e}:M}var Xo=I(()=>{Ie();Ju();zu();V();Qr();qe();qf();ye();ai();Xr();ol();o(en,"flattenedDecrypt")});async function es(t,e,r){if(t instanceof Uint8Array&&(t=ce.decode(t)),typeof t!="string")throw new P("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 P("Invalid Compact JWE");let l=await en({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 sl=I(()=>{Xo();V();ye();o(es,"compactDecrypt")});async function $f(t,e,r){if(!Q(t))throw new P("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(Q))throw new P("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new P("JWE Recipients has no members");for(let n of t.recipients)try{return await en({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 Lt}var jf=I(()=>{Xo();V();qe();o($f,"generalDecrypt")});var kT,Vf,Gf=I(()=>{Te();ot();Ie();st();kT=o(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:X(t)};if(!se(t))throw new TypeError(ie(t,...W,"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 L.subtle.exportKey("jwk",t);return s},"keyToJWK"),Vf=kT});async function Bf(t){return Pf(t)}async function Kf(t){return Rf(t)}async function ts(t){return Vf(t)}var al=I(()=>{Zo();Zo();Gf();o(Bf,"exportSPKI");o(Kf,"exportPKCS8");o(ts,"exportJWK")});async function FT(t,e,r,n,i={}){let s,a,c;switch(er(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(!Qo(r))throw new U("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 ff(r)).privateKey);let{x:p,y:m,crv:f,kty:y}=await ts(d),v=await Wo(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?si(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:f,kty:y}},y==="EC"&&(a.epk.y=m),u&&(a.apu=X(u)),l&&(a.apv=X(l)),t==="ECDH-ES"){c=v;break}c=n||_t(e);let T=t.slice(-6);s=await ii(T,v,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||_t(e),s=await wf(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||_t(e);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await _f(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||_t(e),s=await ii(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||_t(e);let{iv:u}=i;({encryptedKey:s,...a}=await kf(t,r,c,u));break}default:throw new U('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var rs,cl=I(()=>{zo();Qu();Zu();Xu();Ie();ai();V();al();ui();il();o(FT,"encryptKeyManagement");rs=FT});var ul,Dt,ns=I(()=>{Ie();nl();zu();Go();cl();V();Qr();ye();Xr();ul=Symbol(),Dt=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 P("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!gt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new P("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(bt(P,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new U('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new P('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new P('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 rs(i,s,e,this._cek,this._keyManagementParameters)),y&&(r&&ul 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=Vo(s));let u,l,d;this._protectedHeader?l=Z.encode(X(JSON.stringify(this._protectedHeader))):l=Z.encode(""),this._aad?(d=X(this._aad),u=Se(l,Z.encode("."),Z.encode(d))):u=l;let p,m;if(n.zip==="DEF"){let y=await(r?.deflateRaw||df)(this._plaintext);({ciphertext:p,tag:m}=await li(s,y,c,this._iv,u))}else({ciphertext:p,tag:m}=await li(s,this._plaintext,c,this._iv,u));let f={ciphertext:X(p),iv:X(this._iv),tag:X(m)};return a&&(f.encrypted_key=X(a)),d&&(f.aad=d),this._protectedHeader&&(f.protected=ce.decode(l)),this._sharedUnprotectedHeader&&(f.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(f.header=this._unprotectedHeader),f}}});var ll,is,Jf=I(()=>{ns();V();ai();Qr();cl();Ie();Xr();ll=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}},is=class{static{o(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new ll(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 P("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Dt(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(!gt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new P("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 P('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new P('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new P('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new P('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(bt(P,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=_t(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 m={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let v=await new Dt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:m}).encrypt(l.key,{...l.options,...e,[ul]:!0});c.ciphertext=v.ciphertext,c.iv=v.iv,c.tag=v.tag,v.aad&&(c.aad=v.aad),v.protected&&(c.protected=v.protected),v.unprotected&&(c.unprotected=v.unprotected),d.encrypted_key=v.encrypted_key,v.header&&(d.header=v.header);continue}let{encryptedKey:f,parameters:y}=await rs(((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:m});d.encrypted_key=X(f),(l.unprotectedHeader||y)&&(d.header={...l.unprotectedHeader,...y})}return c}}});function pi(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 U(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var dl=I(()=>{V();o(pi,"subtleDsa")});function hi(t,e,r){if(se(e))return cf(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ie(e,...W));return L.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ie(e,...W,"Uint8Array"))}var pl=I(()=>{Te();Yt();ot();st();o(hi,"getCryptoKey")});var HT,zf,Wf=I(()=>{dl();Te();Yo();pl();HT=o(async(t,e,r,n)=>{let i=await hi(t,e,"verify");xr(t,i);let s=pi(t,i.algorithm);try{return await L.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),zf=HT});async function tn(t,e,r){var n;if(!Q(t))throw new z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new z("JWS Payload missing");if(typeof t.signature!="string")throw new z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Q(t.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let T=re(t.protected);i=JSON.parse(ce.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!gt(i,t.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...t.header},a=bt(z,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&di("algorithms",r.algorithms);if(l&&!l.has(u))throw new Jt('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),er(u,e,"verify");let p=Se(Z.encode((n=t.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof t.payload=="string"?Z.encode(t.payload):t.payload),m=re(t.signature);if(!await zf(u,e,m,p))throw new Or;let y;c?y=re(t.payload):typeof t.payload=="string"?y=Z.encode(t.payload):y=t.payload;let v={payload:y};return t.protected!==void 0&&(v.protectedHeader=i),t.header!==void 0&&(v.unprotectedHeader=t.header),d?{...v,key:e}:v}var os=I(()=>{Ie();Wf();V();ye();Qr();qe();ui();Xr();ol();o(tn,"flattenedVerify")});async function ss(t,e,r){if(t instanceof Uint8Array&&(t=ce.decode(t)),typeof t!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await tn({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 hl=I(()=>{os();V();ye();o(ss,"compactVerify")});async function Qf(t,e,r){if(!Q(t))throw new z("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(Q))throw new z("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await tn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new Or}var Yf=I(()=>{os();V();qe();o(Qf,"generalVerify")});var rn,fl=I(()=>{rn=o(t=>Math.floor(t.getTime()/1e3),"default")});var qT,nn,ml=I(()=>{qT=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,nn=o(t=>{let e=qT.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 Zf,$T,on,as=I(()=>{V();ye();fl();ml();qe();Zf=o(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),$T=o((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),on=o((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||Zf(t.typ)!==Zf(n)))throw new ge('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ce.decode(e))}catch{}if(!Q(i))throw new ue("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 f of new Set(s.reverse()))if(!(f in i))throw new ge(`missing required "${f}" claim`,f,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new ge('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new ge('unexpected "sub" claim value',"sub","check_failed");if(u&&!$T(i.aud,typeof u=="string"?[u]:u))throw new ge('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=nn(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,m=rn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new ge('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new ge('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>m+d)throw new ge('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new ge('"exp" claim must be a number',"exp","invalid");if(i.exp<=m-d)throw new zr('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let f=m-i.iat,y=typeof l=="number"?l:nn(l);if(f-d>y)throw new zr('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(f<0-d)throw new ge('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function Xf(t,e,r){var n;let i=await ss(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new ue("JWTs MUST NOT use unencoded payload");let a={payload:on(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var em=I(()=>{hl();as();V();o(Xf,"jwtVerify")});async function tm(t,e,r){let n=await es(t,e,r),i=on(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new ge('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new ge('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new ge('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof e=="function"?{...a,key:n.key}:a}var rm=I(()=>{sl();as();V();o(tm,"jwtDecrypt")});var sn,yl=I(()=>{ns();sn=class{static{o(this,"CompactEncrypt")}constructor(e){this._flattened=new Dt(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 jT,nm,im=I(()=>{dl();Te();Yo();pl();jT=o(async(t,e,r)=>{let n=await hi(t,e,"sign");xr(t,n);let i=await L.subtle.sign(pi(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),nm=jT});var tr,cs=I(()=>{Ie();im();Qr();V();ye();ui();Xr();tr=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 z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!gt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=bt(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');er(a,e,"sign");let c=this._payload;s&&(c=Z.encode(X(c)));let u;this._protectedHeader?u=Z.encode(X(JSON.stringify(this._protectedHeader))):u=Z.encode("");let l=Se(u,Z.encode("."),c),d=await nm(a,e,l),p={signature:X(d),payload:""};return s&&(p.payload=ce.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ce.decode(u)),p}}});var an,gl=I(()=>{cs();an=class{static{o(this,"CompactSign")}constructor(e){this._flattened=new tr(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 _l,us,om=I(()=>{cs();V();_l=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}},us=class{static{o(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new _l(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("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 tr(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 z("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var rr,ls=I(()=>{fl();qe();ml();rr=class{static{o(this,"ProduceJWT")}constructor(e){if(!Q(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:rn(new Date)+nn(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:rn(new Date)+nn(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:rn(new Date)}:this._payload={...this._payload,iat:e},this}}});var ds,sm=I(()=>{gl();V();ye();ls();ds=class extends rr{static{o(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new an(Z.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 ue("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var ps,am=I(()=>{yl();ye();ls();ps=class extends rr{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 sn(Z.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 bl(t,e){if(!Q(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":nr(t.crv,'"crv" (Curve) Parameter'),nr(t.x,'"x" (X Coordinate) Parameter'),nr(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":nr(t.crv,'"crv" (Subtype of Key Pair) Parameter'),nr(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":nr(t.e,'"e" (Exponent) Parameter'),nr(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":nr(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new U('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await ko(e,n))}async function cm(t,e){e??(e="sha256");let r=await bl(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var nr,um=I(()=>{Fu();Ie();V();ye();qe();nr=o((t,e)=>{if(typeof t!="string"||!t)throw new ei(`${e} missing or invalid`)},"check");o(bl,"calculateJwkThumbprint");o(cm,"calculateJwkThumbprintUri")});async function lm(t,e){let r={...t,...e?.header};if(!Q(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await Xt({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var dm=I(()=>{ci();qe();V();o(lm,"EmbeddedJWK")});function VT(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 U('Unsupported "alg" value for a JSON Web Key Set')}}function El(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(GT)}function GT(t){return Q(t)}function BT(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function pm(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Xt({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new zt("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function hm(t){let e=new fi(t);return async function(r,n){return e.getKey(r,n)}}var fi,wl=I(()=>{ci();V();qe();o(VT,"getKtyFromAlg");o(El,"isJWKSLike");o(GT,"isJWKLike");o(BT,"clone");fi=class{static{o(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!El(e))throw new zt("JSON Web Key Set malformed");this._jwks=BT(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=VT(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 Rr;if(u!==1){let l=new ti,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await pm(d,p,n)}catch{continue}},l}return pm(this._cached,c,n)}};o(pm,"importWithAlgCache");o(hm,"createLocalJWKSet")});var KT,fm,mm=I(()=>{V();KT=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 ri:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new pe("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new pe("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),fm=KT});function JT(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function ym(t,e){let r=new vl(t,e);return async function(n,i){return r.getKey(n,i)}}var vl,gm=I(()=>{mm();V();wl();o(JT,"isCloudflareWorkers");vl=class extends fi{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 Rr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&JT()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=fm(this._url,this._timeoutDuration,this._options).then(e=>{if(!El(e))throw new zt("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(ym,"createRemoteJWKSet")});var hs,_m=I(()=>{Ie();ye();V();as();ls();hs=class extends rr{static{o(this,"UnsecuredJWT")}encode(){let e=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new ue("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3||s!=="")throw new ue("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ce.decode(re(n))),c.alg!=="none")throw new Error}catch{throw new ue("Invalid Unsecured JWT")}return{payload:on(c,re(i),r),header:c}}}});var Tl={};Ki(Tl,{decode:()=>mi,encode:()=>zT});var zT,mi,fs=I(()=>{Ie();zT=X,mi=re});function bm(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(ce.decode(mi(e)));if(!Q(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var Em=I(()=>{fs();ye();qe();o(bm,"decodeProtectedHeader")});function wm(t){if(typeof t!="string")throw new ue("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new ue("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ue("Invalid JWT");if(!e)throw new ue("JWTs must contain a payload");let n;try{n=mi(e)}catch{throw new ue("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ce.decode(n))}catch{throw new ue("Failed to parse the decoded payload as JSON")}if(!Q(i))throw new ue("Invalid JWT Claims Set");return i}var vm=I(()=>{fs();ye();qe();V();o(wm,"decodeJwt")});async function Tm(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),Wt(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 U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return L.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,s)}function Sl(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new U("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Sm(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:Sl(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:Sl(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:Sl(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 U("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 U("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return L.subtle.generateKey(s,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var Il=I(()=>{Te();V();ni();o(Tm,"generateSecret");o(Sl,"getModulusLengthOption");o(Sm,"generateKeyPair")});async function Im(t,e){return Sm(t,e)}var Am=I(()=>{Il();o(Im,"generateKeyPair")});async function Pm(t,e){return Tm(t,e)}var Rm=I(()=>{Il();o(Pm,"generateSecret")});var ms={};Ki(ms,{CompactEncrypt:()=>sn,CompactSign:()=>an,EmbeddedJWK:()=>lm,EncryptJWT:()=>ps,FlattenedEncrypt:()=>Dt,FlattenedSign:()=>tr,GeneralEncrypt:()=>is,GeneralSign:()=>us,SignJWT:()=>ds,UnsecuredJWT:()=>hs,base64url:()=>Tl,calculateJwkThumbprint:()=>bl,calculateJwkThumbprintUri:()=>cm,compactDecrypt:()=>es,compactVerify:()=>ss,createLocalJWKSet:()=>hm,createRemoteJWKSet:()=>ym,decodeJwt:()=>wm,decodeProtectedHeader:()=>bm,errors:()=>$u,exportJWK:()=>ts,exportPKCS8:()=>Kf,exportSPKI:()=>Bf,flattenedDecrypt:()=>en,flattenedVerify:()=>tn,generalDecrypt:()=>$f,generalVerify:()=>Qf,generateKeyPair:()=>Im,generateSecret:()=>Pm,importJWK:()=>Xt,importPKCS8:()=>Mf,importSPKI:()=>Df,importX509:()=>Uf,jwtDecrypt:()=>tm,jwtVerify:()=>Xf});var ys=I(()=>{sl();Xo();jf();Jf();hl();os();Yf();em();rm();yl();ns();gl();cs();om();sm();am();um();dm();wl();gm();_m();al();ci();Em();vm();V();Am();Rm();fs()});var _s=g(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.fetchRetry=void 0;var WT=D();async function QT(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 WT.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(QT,"fetchRetry");gs.fetchRetry=QT});var cn=g(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GcpServiceAccount=Ze.fetchToken=Ze.exchangeGgpJwtForIdToken=Ze.exchangeFirebaseJwtForIdToken=Ze.getTokenFromGcpServiceAccount=void 0;var Om=(ys(),Ji(ms)),YT=D(),ZT=_s();async function XT({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=t;return await new Om.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}o(XT,"getTokenFromGcpServiceAccount");Ze.getTokenFromGcpServiceAccount=XT;async function eS(t,e,r){return Pl(t,{token:e,returnSecureToken:!0},r)}o(eS,"exchangeFirebaseJwtForIdToken");Ze.exchangeFirebaseJwtForIdToken=eS;async function tS(t,e,r){return Pl(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}o(tS,"exchangeGgpJwtForIdToken");Ze.exchangeGgpJwtForIdToken=tS;async function Pl(t,e,r){let n=await(0,ZT.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 YT.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Pl,"fetchToken");Ze.fetchToken=Pl;var Al=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,Om.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}};Ze.GcpServiceAccount=Al});var Es=g(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.GoogleLogTransport=Ut.ZuploToGCPMap=Ut.GoogleCloudLoggingPlugin=void 0;var rS=we(),Rl=te(),Ol=cn(),nS=Ct(),xm=yt(),xl=class extends nS.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new bs(this.options)}};Ut.GoogleCloudLoggingPlugin=xl;var iS="https://logging.googleapis.com/v2/entries:write?alt=json";Ut.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var bs=class{static{o(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=Rl.Environment.instance.loggingEnvironmentType,this.#o=Rl.Environment.instance.loggingEnvironmentStage,this.#n=Rl.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(e,r){if(e.messages.length===0)return;let n={allMessages:(0,xm.makeErrorsSerializable)(e.messages)};this.#t||(this.#t=await Ol.GcpServiceAccount.init(this.#e));let i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:Ut.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,xm.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 Ol.GcpServiceAccount.init(this.#e));let r=await(0,Ol.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(iS,{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 rS.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Ut.GoogleLogTransport=bs});var Nl=g(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.gcpLogFormat=un.GCP_LOG_FORMAT=void 0;var Nm=yt(),oS=Es();un.GCP_LOG_FORMAT="gcp";function sS(t){let e={allMessages:(0,Nm.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Nm.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:oS.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(sS,"gcpLogFormat");un.gcpLogFormat=sS});var Lm=g(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.ConsoleTransport=void 0;var Cm=Nl(),Cl=class{static{o(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;async log(e){if(this.#t===Cm.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Cm.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}])}};ws.ConsoleTransport=Cl});var Fl=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.DataDogTransport=ln.DataDogLoggingPlugin=void 0;var aS=we(),Ll=te(),cS=Ct(),Dm=yt(),kl=class extends cS.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new vs(this.options)}};ln.DataDogLoggingPlugin=kl;var Dl="__ddtags",Ul="__ddattr",Ml=o(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),uS=o(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(Ml(n)):r.push(`${Ml(n)}:${Ml(i.toString())}`)}),r.join(",")},"formatTags"),vs=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=Ll.Environment.instance.loggingEnvironmentType,this.#i=Ll.Environment.instance.loggingEnvironmentStage,this.#r=Ll.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){let n={},i=r.custom[Dl];i&&typeof i=="object"&&Object.assign(n,i);let s=[...e.messages],a=e.messages.findIndex(f=>f[Dl]!==void 0);a>-1&&(Object.assign(n,s[a][Dl]),s.splice(a,1));let c={},u=r.custom[Ul];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(f=>f[Ul]!==void 0);l>-1&&(Object.assign(c,s[l][Ul]),s.splice(l,1));let d=(0,Dm.makeErrorsSerializable)(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Dm.extractBestMessage)(d),service:e.loggingId,ddtags:uS(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(m,c),this.batcher.enqueue(m),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 aS.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};ln.DataDogTransport=vs});var Mm=g(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ProcessTransport=void 0;var Um=Nl(),Hl=class{static{o(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;async log(e){if(this.#t===Um.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Um.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}])}};Ts.ProcessTransport=Hl});var Fm=g(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.RemoteLogTransport=void 0;var lS=we(),km=te(),dS=yt(),pS=o(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0&&fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,dS.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":km.Environment.instance.systemUserAgent,"zp-dn":km.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Ss,ql=class{static{o(this,"RemoteLogTransport")}constructor(e){Ss||(Ss=new lS.BatchDispatch("remote-log-transport",1,pS(e)))}async log(e,r){Ss.enqueue(e),r.waitUntil(Ss.waitUntilFlushed())}};Is.RemoteLogTransport=ql});var Hm=g(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.unifiedFormatter=Nr.SeverityNumberOpenTelemetryMap=void 0;Nr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var hS=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:Nr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Nr.unifiedFormatter=hS});var $m=g(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.UnifiedLogTransport=void 0;var fS=we(),qm=te(),mS=Hm(),yS=o(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,mS.unifiedFormatter)(r,n);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":qm.Environment.instance.systemUserAgent,"zp-dn":qm.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),As,$l=class{static{o(this,"UnifiedLogTransport")}constructor(e){As||(As=new fS.BatchDispatch("unified-log-transport",1,yS(e)))}async log(e,r){As.enqueue(e),r.waitUntil(As.waitUntilFlushed())}};Ps.UnifiedLogTransport=$l});var zm=g(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.LogInitializer=void 0;var gS=wr(),_S=Ot(),jm=Au(),Vm=te(),Gm=$h(),bS=Ct(),ES=jh(),Bm=Vh(),Km=Lm(),wS=Fl(),vS=Es(),Jm=Mm(),TS=Fm(),SS=$m(),jl=(0,gS.debug)("zuplo:logging"),Vl=class{static{o(this,"LogInitializer")}serviceProvider;systemCoreLogger;userCoreLogger;constructor(e){this.serviceProvider=e,this.systemCoreLogger=this.setupSystemCoreLogger(Vm.Environment.instance),this.userCoreLogger=this.setupUserCoreLogger(Vm.Environment.instance)}setupSystemCoreLogger(e){let{runtime:r,build:n}=e;jl("Gateway.setupSystemCoreLogger");let i=[],s=this.serviceProvider.getService(jm.SYSTEM_LOGGER);return s?i.push(new Jm.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&i.push(new Km.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new SS.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Gm.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}setupUserCoreLogger(e){jl("Gateway.setupUserCoreLogger");let r=[],{runtime:n,build:i}=e,s=this.serviceProvider.getService(jm.SYSTEM_LOGGER);if(s&&s.captureUserLogs===!0?r.push(new Jm.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&r.push(new Km.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new TS.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),n.GCP_USER_LOG_NAME&&n.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new vS.GoogleLogTransport({serviceAccountJson:n.GCP_USER_LOG_SVC_ACCT_JSON,logName:n.GCP_USER_LOG_NAME})),n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=n.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new wS.DataDogTransport({apiKey:n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return _S.plugins.forEach(a=>{a instanceof bS.LogPlugin&&r.push(a.getTransport())}),new Gm.CoreLogger(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,r,n,i,s){jl("Gateway.createRequestLoggers");let a=new ES.LoggingContext(n,i,s),c=new Bm.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new Bm.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};Rs.LogInitializer=Vl});var Bl=g(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.UserRouteConfiguration=void 0;var Gl=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};Os.UserRouteConfiguration=Gl});var Jl=g(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.Router=Et.RouterError=Et.LookupResult=Et.RouterEntry=void 0;var Wm=D(),IS=ft(),AS=Bl(),xs=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};Et.RouterEntry=xs;var yi=class{static{o(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Et.LookupResult=yi;var Ns=class extends Error{static{o(this,"RouterError")}constructor(e,r){super(e,r)}};Et.RouterError=Ns;var Kl=class{static{o(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof AS.UserRouteConfiguration||e instanceof IS.SystemRouteConfiguration))throw new Wm.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 xs(i,s,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ns(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(e,r){if(typeof e>"u")throw new Wm.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 yi(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 yi(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Et.Router=Kl});var dn=g(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.Gateway=void 0;var PS=wr(),Qm=Eh(),Ym=Th(),RS=Sh(),Zm=Ih(),Xm=Oh(),ir=Wn(),Cs=vr(),OS=Tu(),ey=qh(),vt=D(),zl=Ot(),xS=zm(),NS=Vt(),CS=ve(),LS=vu(),DS=Sr(),US=Zn(),MS=Yn(),kS=Jl(),Wl=ft(),ty=Bl(),FS=Ge(),ry=te(),ny=Pr(),HS=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],wt=(0,PS.debug)("zuplo:runtime"),qS=o(t=>{let e=t.findIndex(r=>r.name===Wl.systemNoVersion.name);return e>-1?[...t.splice(e),Wl.systemNoVersion]:[...t,Wl.systemNoVersion]},"setupSystemNoVersion"),Ql=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,wt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=new xS.LogInitializer(n)}static async initialize(e,r,n,i,s){if(wt("Gateway.initialize"),!t.#e){await(0,zl.initializeRuntime)(s);let a=new t(e,r,n,i);t.#e=a}return t.#e}static purgeGatewayCache(){wt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new vt.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[US.policyProcessor,LS.corsProcessor,DS.metricsProcessor];#i;setupRoutes=()=>{wt("Gateway.setupRoutes");let e=this.routeData,r=qS(e.versions),n=new kS.Router(r);return e.routes.length===0?((0,Qm.registerBuildRoute)(n,this),(0,Xm.registerPingRoute)(n,this),(0,Ym.registerCorsRoute)(n,this),(0,RS.registerNoRoutes)(n,this),n):((0,ey.registerDevPortalLegacyRedirectRoute)(n,this),(0,ey.registerDevPortalV3Route)(n,this),(0,Qm.registerBuildRoute)(n,this),(0,Xm.registerPingRoute)(n,this),(0,Ym.registerCorsRoute)(n,this),e.routes.forEach(i=>{let s;if(typeof i.handler?.module=="object"&&(s=i.handler?.module[i.handler.export]),typeof s!="function")throw new vt.ConfigurationError(`Invalid state - No handler on route for path '${i.path}'`);let a=s,c=new NS.Pipeline(this.#n,a,this),u=new ty.UserRouteConfiguration(i);n.addRoute(u,c.execute)}),(0,Zm.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 vt.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 wt("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){wt("Gateway.internalErrorResponse");let i={};if(ry.Environment.instance.isDeno){if(n instanceof vt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,ny.serializeError)(n.cause);"stack"in s&&(s.stack=(0,ny.cleanStack)(s.stack)),i={cause:s}}}return CS.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}#s(e){if(ry.Environment.instance.isCloudflare)return e;{let r=new Headers;for(let[n,i]of e.headers)ir.INTERNAL_HEADERS_TO_REMOVE.includes(n.toLowerCase())||r.set(n,i);return new Request(e,{headers:r})}}async handleRequest(e,r){let n=e.headers.get(ir.REQUEST_ID_HEADER)??e.headers.get(ir.LEGACY_REQUEST_ID_HEADER),i=e.headers.get(ir.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(e.headers);T.set(ir.REQUEST_ID_HEADER,n),e=new Request(e,{headers:T})}if(["GET","HEAD"].includes(e.method)&&e.body){let T=new Headers(e.headers);T.set(ir.BODY_REMOVED_HEADER,"true"),e=new Request(e,{headers:T,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,s,e),u=new URL(e.url),l=u.pathname,d=this.#r.lookup(e.method,l);if(!d)throw new vt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Cs.HeaderIncomingRequestProperties(e.headers),m=this.#s(e),f=new MS.ZuploRequest(m,{params:d.params}),y=new Cs.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:s,incomingRequestProperties:p}),v=Cs.ZuploContextExtensions.initialize(y,f);if(d.routeConfiguration===Zm.notFoundRouteConfiguration&&zl.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);v.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof ty.UserRouteConfiguration)}try{if(FS.SystemLogMap.addLogger(y,c),!u.pathname.startsWith("/__zuplo")){let H=await(0,zl.invokeOnRequestExtensions)(f,y);if(H instanceof Response)return H;{let R=Cs.ZuploContextExtensions.getContextExtensions(y);f=H,R.latestRequest=f}}[...HS,(0,OS.getDevPortalRuntimeConfig)(this).sitePathname].filter(H=>new RegExp(H).test(u.pathname)).length===0&&a.debug(`Request received '${u.pathname}'`,{method:e.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;$S(S,d,e),wt("Gateway.handleRequest - call user handler");let M=await S(f,y);if(wt("Gateway.handleRequest - user handler"),!(M instanceof Response))throw new vt.RuntimeError(`Invalid Response type from the request handler: ${typeof M}`);if(M.bodyUsed)throw new vt.RuntimeError("The response object has already been used. Return a new response instead.");if(M.headers.get(ir.REQUEST_ID_HEADER)===null&&!M.webSocket){let H=new Headers(M.headers);return H.set(ir.REQUEST_ID_HEADER,n),new Response(M.body,{status:M.status,statusText:M.statusText,headers:H,cf:M.cf})}else return M}catch(T){return wt("Gateway - error executing handler",T),T instanceof vt.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(f,y,T)}}};Ls.Gateway=Ql;function $S(t,e,r){if(wt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new vt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new vt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}o($S,"checkHandler")});var iy=g(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.invokeInboundPolicy=void 0;var jS=D(),VS=dn(),GS=Zn(),BS=o(async(t,e,r)=>{let n=VS.Gateway.instance.routeData.policies,i=(0,GS.getInboundPolicyHandlerAndOptions)([t],n);if(i.length===0)throw new jS.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=i[0];return s.handler(e,r,s.options,t)},"invokeInboundPolicy");Ds.invokeInboundPolicy=BS});var vr=g(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.SystemZuploContext=Xe.ZuploContextExtensions=Xe.ResponseSentEvent=Xe.ResponseSendingEvent=Xe.HeaderIncomingRequestProperties=void 0;var _e=Wn(),KS=D(),JS=iy(),Yl=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(_e.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(_e.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(_e.CF_IP_CITY_HEADER)??this.#e.get(_e.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(_e.CF_IP_CONTINENT_HEADER)??this.#e.get(_e.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(_e.CF_IP_COUNTRY_HEADER)??this.#e.get(_e.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(_e.CF_IP_LATITUDE_HEADER)??this.#e.get(_e.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(_e.CF_IP_LONGITUDE_HEADER)??this.#e.get(_e.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(_e.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(_e.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(_e.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(_e.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(_e.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(_e.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}}};Xe.HeaderIncomingRequestProperties=Yl;var Zl=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};Xe.ResponseSendingEvent=Zl;var Xl=class extends Event{static{o(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};Xe.ResponseSentEvent=Xl;var Us=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 KS.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}};Xe.ZuploContextExtensions=Us;var ed=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,fetchEvent: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,JS.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingFinalHook=c=>{Us.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;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)}};Xe.SystemZuploContext=ed});var oy=g(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.ContextLocalStorage=void 0;var td=class t{static{o(this,"ContextLocalStorage")}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)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};Ms.ContextLocalStorage=td});var rd=g(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.environment=or.isZuploReadableEnvVariableName=or.isRestrictedEnvVariableName=void 0;var zS=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function sy(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!zS.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}o(sy,"isRestrictedEnvVariableName");or.isRestrictedEnvVariableName=sy;function ay(t){return!!t.startsWith("ZUPLO_")}o(ay,"isZuploReadableEnvVariableName");or.isZuploReadableEnvVariableName=ay;var WS=new Proxy({},{get(t,e,r){if(sy(String(e))&&!ay(String(e)))return;let n=globalThis,i;return n.process?i=n.process.env[e]:i=n[e],i}});or.environment=WS});var ks=g(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.externalServiceHandler=pn.externalServiceTunnelConfig=void 0;var QS=wr(),Cr=D(),YS=nd(),gi=te(),at=(0,QS.debug)("zuplo:runtime:external-service");function uy(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=gi.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}o(uy,"getServiceAuth");async function ZS(t){let e=uy();if(!e)throw at("There is no external service auth configured for this zup."),new Cr.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw at("Cannot call external service with Request object"),new Cr.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(gi.Environment.instance.useSha256ServiceRouting){at("Using sha256 service routing");let a=gi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await ly(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new Cr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(ZS,"externalServiceTunnelConfig");pn.externalServiceTunnelConfig=ZS;async function XS(t,e){let r=uy();if(r)if(at(`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(gi.Environment.instance.useSha256ServiceRouting){at("Using sha256 service routing");let d=gi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await ly(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new Cr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);at(`Calling external service: ${u.toString()}`);let l=await(0,YS.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 Cr.RuntimeError("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new Cr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new Cr.RuntimeError("There are no external services configured for this zup.")}o(XS,"externalServiceHandler");pn.externalServiceHandler=XS;async function ly(t,e,r,n){let i=t.toLowerCase(),s=e.toLowerCase(),a=r.toLowerCase(),c=eI(n);at(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await cy(`${s}-${i}`),l=await cy(`${s}-${a}-${c}`);return`${u}.${l}`}o(ly,"hashServiceName");async function cy(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(cy,"hashSegment");function eI(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}o(eI,"sanitizeEnvironmentType")});var nd=g(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.originalFetch=void 0;var tI=ks(),dy=new Map;dy.set("service:",tI.externalServiceHandler);hn.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=rI(e);if(typeof t=="string"){let n=new URL(t),i=dy.get(n.protocol);return i?i(t,r):(0,hn.originalFetch)(t,r)}else return(0,hn.originalFetch)(t,r)};var rI=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 fy=g(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.Handler=fn.purgeGatewayCache=void 0;var hy=dn(),py=te(),nI=o(()=>{hy.Gateway.purgeGatewayCache()},"purgeGatewayCache");fn.purgeGatewayCache=nI;var id=class{static{o(this,"Handler")}routeData;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,s,a,c){this.routeData=e,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=s,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(e,r)=>{py.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await hy.Gateway.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let s={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:"Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:py.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(s,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(e,r)}};fn.Handler=id});var _y=g(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.pathToRegexp=Re.tokensToRegexp=Re.regexpToFunction=Re.match=Re.tokensToFunction=Re.compile=Re.parse=void 0;function iI(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(iI,"lexer");function od(t,e){e===void 0&&(e={});for(var r=iI(t),n=e.prefixes,i=n===void 0?"./":n,s="[^".concat(mn(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(Y){if(u<r.length&&r[u].type===Y)return r[u++].value},"tryConsume"),p=o(function(Y){var fe=d(Y);if(fe!==void 0)return fe;var Me=r[u],E=Me.type,F=Me.index;throw new TypeError("Unexpected ".concat(E," at ").concat(F,", expected ").concat(Y))},"mustConsume"),m=o(function(){for(var Y="",fe;fe=d("CHAR")||d("ESCAPED_CHAR");)Y+=fe;return Y},"consumeText");u<r.length;){var f=d("CHAR"),y=d("NAME"),v=d("PATTERN");if(y||v){var T=f||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:y||c++,prefix:T,suffix:"",pattern:v||s,modifier:d("MODIFIER")||""});continue}var S=f||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var M=d("OPEN");if(M){var T=m(),H=d("NAME")||"",R=d("PATTERN")||"",ne=m();p("CLOSE"),a.push({name:H||(R?c++:""),pattern:H&&!R?s:R,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(od,"parse");Re.parse=od;function oI(t,e){return my(od(t,e),e)}o(oI,"compile");Re.compile=oI;function my(t,e){e===void 0&&(e={});var r=sd(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 m=u?u[p.name]:void 0,f=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var v=0;v<m.length;v++){var T=i(m[v],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=i(String(m),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!f){var S=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}o(my,"tokensToFunction");Re.tokensToFunction=my;function sI(t,e){var r=[],n=ad(t,r,e);return yy(n,r,e)}o(sI,"match");Re.match=sI;function yy(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(m){if(a[m]===void 0)return"continue";var f=e[m-1];f.modifier==="*"||f.modifier==="+"?l[f.name]=a[m].split(f.prefix+f.suffix).map(function(y){return i(y,f)}):l[f.name]=i(a[m],f)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(yy,"regexpToFunction");Re.regexpToFunction=yy;function mn(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(mn,"escapeString");function sd(t){return t&&t.sensitive?"":"i"}o(sd,"flags");function aI(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(aI,"regexpToRegexp");function cI(t,e,r){var n=t.map(function(i){return ad(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),sd(r))}o(cI,"arrayToRegexp");function uI(t,e,r){return gy(od(t,r),e,r)}o(uI,"stringToRegexp");function gy(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(F){return F}:l,p=r.delimiter,m=p===void 0?"/#?":p,f=r.endsWith,y=f===void 0?"":f,v="[".concat(mn(y),"]|$"),T="[".concat(mn(m),"]"),S=a?"^":"",M=0,H=t;M<H.length;M++){var R=H[M];if(typeof R=="string")S+=mn(d(R));else{var ne=mn(d(R.prefix)),Y=mn(d(R.suffix));if(R.pattern)if(e&&e.push(R),ne||Y)if(R.modifier==="+"||R.modifier==="*"){var fe=R.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(R.pattern,")(?:").concat(Y).concat(ne,"(?:").concat(R.pattern,"))*)").concat(Y,")").concat(fe)}else S+="(?:".concat(ne,"(").concat(R.pattern,")").concat(Y,")").concat(R.modifier);else R.modifier==="+"||R.modifier==="*"?S+="((?:".concat(R.pattern,")").concat(R.modifier,")"):S+="(".concat(R.pattern,")").concat(R.modifier);else S+="(?:".concat(ne).concat(Y,")").concat(R.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(v,")"):"$";else{var Me=t[t.length-1],E=typeof Me=="string"?T.indexOf(Me[Me.length-1])>-1:Me===void 0;i||(S+="(?:".concat(T,"(?=").concat(v,"))?")),E||(S+="(?=".concat(T,"|").concat(v,")"))}return new RegExp(S,sd(r))}o(gy,"tokensToRegexp");Re.tokensToRegexp=gy;function ad(t,e,r){return t instanceof RegExp?aI(t,e):Array.isArray(t)?cI(t,e,r):uI(t,e,r)}o(ad,"pathToRegexp");Re.pathToRegexp=ad});var dd=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.AwsV4Signer=yn.AwsClient=void 0;var lI=wr(),vy=D(),dI=(0,lI.debug)("zuplo:runtime"),ud=new TextEncoder,by={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"},pI=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],ld=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 Fs(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){dI("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 vy.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};yn.AwsClient=ld;var Fs=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:m,appendSessionToken:f,allHeaders:y,singleEncode:v}){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 T,S;(!u||!l)&&([T,S]=hI(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let M=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"),M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&M.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(R=>y||!pI.includes(R)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(R=>R+":"+(R==="host"?this.url.host:(this.headers.get(R)||"").replace(/\s+/g," "))).join(`
60
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!M.has("X-Amz-Expires")&&M.set("X-Amz-Expires","86400"),M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.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,"/");v||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=wy(this.encodedPath);let H=new Set;this.encodedSearch=[...this.url.searchParams].filter(([R])=>{if(!R)return!1;if(this.service==="s3"){if(H.has(R))return!1;H.add(R)}return!0}).map(R=>R.map(ne=>wy(encodeURIComponent(ne)))).sort(([R,ne],[Y,fe])=>R<Y?-1:R>Y?1:ne<fe?-1:ne>fe?1:0).map(R=>R.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 _i("AWS4"+this.secretAccessKey,e),s=await _i(i,this.region),a=await _i(s,this.service);n=await _i(a,"aws4_request"),this.cache.set(r,n)}return cd(await _i(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,cd(await Ey(await this.canonicalString()))].join(`
59
+ -----END ${e}-----`},"default")});function Af(t){let e=[],r=0;for(;r<t.length;){let n=Cf(t.subarray(r));e.push(n),r+=n.byteLength}return e}function Cf(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 AT(t){let e=Af(Af(Cf(t).contents)[0].contents);return jo(e[e[0].raw[0]===160?6:5].raw)}function PT(t){let e=t.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=$u(e);return tl(AT(r),"PUBLIC KEY")}var Pf,Rf,Of,Xt,If,xf,Nf,rl,Lf,Zo=I(()=>{Te();ot();Ie();Sf();V();st();Pf=o(async(t,e,r)=>{if(!se(r))throw new TypeError(ie(r,...W));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return tl(jo(new Uint8Array(await L.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},"genericExport"),Rf=o(t=>Pf("public","spki",t),"toSPKI"),Of=o(t=>Pf("private","pkcs8",t),"toPKCS8"),Xt=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])||Xt(t,e,n+1)},"findOid"),If=o(t=>{switch(!0){case Xt(t,[42,134,72,206,61,3,1,7]):return"P-256";case Xt(t,[43,129,4,0,34]):return"P-384";case Xt(t,[43,129,4,0,35]):return"P-521";case Xt(t,[43,101,110]):return"X25519";case Xt(t,[43,101,111]):return"X448";case Xt(t,[43,101,112]):return"Ed25519";case Xt(t,[43,101,113]):return"Ed448";default:throw new U("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),xf=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=If(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:If(u)},c=l?["verify"]:["sign"];break;default:throw new U('Invalid or unsupported "alg" (Algorithm) value')}return L.subtle.importKey(e,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),Nf=o((t,e,r)=>xf(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",t,e,r),"fromPKCS8"),rl=o((t,e,r)=>xf(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",t,e,r),"fromSPKI");o(Af,"getElement");o(Cf,"parseElement");o(AT,"spkiFromX509");o(PT,"getSPKI");Lf=o((t,e,r)=>{let n;try{n=PT(t)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return rl(n,e,r)},"fromX509")});function RT(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 U(`${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 U('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 U('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 U('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 U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new U('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var OT,nl,Df=I(()=>{Te();V();Ie();o(RT,"subtleMapping");OT=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}=RT(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 L.subtle.importKey("raw",re(t.k),...s);let a={...t};return delete a.alg,delete a.use,L.subtle.importKey("jwk",a,...s)},"parse"),nl=OT});async function Uf(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return rl(t,e,r)}async function Mf(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Lf(t,e,r)}async function kf(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Nf(t,e,r)}async function er(t,e,r){var n;if(!Q(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?nl({...t,alg:e,ext:(n=t.ext)!==null&&n!==void 0?n:!1}):re(t.k);case"RSA":if(t.oth!==void 0)throw new U('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return nl({...t,alg:e});default:throw new U('Unsupported "kty" (Key Type) Parameter value')}}var ci=I(()=>{Ie();Zo();Df();V();qe();o(Uf,"importSPKI");o(Mf,"importX509");o(kf,"importPKCS8");o(er,"importJWK")});var xT,NT,CT,tr,ui=I(()=>{ot();st();xT=o((t,e)=>{if(!(e instanceof Uint8Array)){if(!Ju(e))throw new TypeError(Ku(t,e,...W,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${W.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),NT=o((t,e,r)=>{if(!Ju(e))throw new TypeError(Ku(t,e,...W));if(e.type==="secret")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),CT=o((t,e,r)=>{t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?xT(t,e):NT(t,e,r)},"checkKeyType"),tr=CT});async function LT(t,e,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(ie(r,"Uint8Array"));let s=parseInt(t.slice(1,4),10),a=await L.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await L.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await L.subtle.encrypt({iv:n,name:"AES-CBC"},a,e)),l=Se(i,n,u,Ho(i.length<<3)),d=new Uint8Array((await L.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function DT(t,e,r,n,i){let s;r instanceof Uint8Array?s=await L.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(He(r,t,"encrypt"),s=r);let a=new Uint8Array(await L.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 UT,li,il=I(()=>{ye();Gu();Bu();Te();Zt();ot();V();st();o(LT,"cbcEncrypt");o(DT,"gcmEncrypt");UT=o(async(t,e,r,n,i)=>{if(!se(r)&&!(r instanceof Uint8Array))throw new TypeError(ie(r,...W,"Uint8Array"));switch(Bo(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&Wr(r,parseInt(t.slice(-3),10)),LT(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&Wr(r,parseInt(t.slice(1,4),10)),DT(t,e,r,n,i);default:throw new U("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),li=UT});async function Ff(t,e,r,n){let i=t.slice(0,7);n||(n=Vo(i));let{ciphertext:s,tag:a}=await li(i,r,e,n,new Uint8Array(0));return{encryptedKey:s,iv:X(n),tag:X(a)}}async function Hf(t,e,r,n,i){let s=t.slice(0,7);return Jo(s,e,r,n,i,new Uint8Array(0))}var ol=I(()=>{il();zu();Go();Ie();o(Ff,"wrap");o(Hf,"unwrap")});async function MT(t,e,r,n,i){switch(tr(t,e,"decrypt"),t){case"dir":{if(r!==void 0)throw new P("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new P("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Q(n.epk))throw new P('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Qo(e))throw new U("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await er(n.epk,t),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new P('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=re(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new P('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=re(n.apv)}let u=await Wo(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?si(n.enc):parseInt(t.slice(-5,-2),10),a,c);if(t==="ECDH-ES")return u;if(r===void 0)throw new P("JWE Encrypted Key missing");return oi(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 P("JWE Encrypted Key missing");return Tf(t,e,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new P("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new P('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new P('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new P('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Ef(t,e,r,n.p2c,re(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new P("JWE Encrypted Key missing");return oi(t,e,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new P("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new P('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new P('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=re(n.iv),a=re(n.tag);return Hf(t,e,r,s,a)}default:throw new U('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var qf,$f=I(()=>{zo();Yu();Xu();el();Ie();V();ai();ci();ui();qe();ol();o(MT,"decryptKeyManagement");qf=MT});function kT(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 U(`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 bt,Xr=I(()=>{V();o(kT,"validateCrit");bt=kT});var FT,di,sl=I(()=>{FT=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"),di=FT});async function en(t,e,r){var n;if(!Q(t))throw new P("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new P("JOSE Header missing");if(typeof t.iv!="string")throw new P("JWE Initialization Vector missing or incorrect type");if(typeof t.ciphertext!="string")throw new P("JWE Ciphertext missing or incorrect type");if(typeof t.tag!="string")throw new P("JWE Authentication Tag missing or incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new P("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new P("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new P("JWE AAD incorrect type");if(t.header!==void 0&&!Q(t.header))throw new P("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!Q(t.unprotected))throw new P("JWE Per-Recipient Unprotected Header incorrect type");let i;if(t.protected)try{let H=re(t.protected);i=JSON.parse(ce.decode(H))}catch{throw new P("JWE Protected Header is invalid")}if(!gt(i,t.header,t.unprotected))throw new P("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...t.header,...t.unprotected};if(bt(P,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new U('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new P("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new P("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&di("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&di("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new zt('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new zt('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;t.encrypted_key!==void 0&&(d=re(t.encrypted_key));let p=!1;typeof e=="function"&&(e=await e(i,t),p=!0);let m;try{m=await qf(a,e,d,s,r)}catch(H){if(H instanceof TypeError||H instanceof P||H instanceof U)throw H;m=_t(c)}let f=re(t.iv),y=re(t.tag),v=Z.encode((n=t.protected)!==null&&n!==void 0?n:""),T;t.aad!==void 0?T=Se(v,Z.encode("."),Z.encode(t.aad)):T=v;let S=await Jo(c,m,re(t.ciphertext),f,y,T);s.zip==="DEF"&&(S=await(r?.inflateRaw||df)(S));let M={plaintext:S};return t.protected!==void 0&&(M.protectedHeader=i),t.aad!==void 0&&(M.additionalAuthenticatedData=re(t.aad)),t.unprotected!==void 0&&(M.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(M.unprotectedHeader=t.header),p?{...M,key:e}:M}var Xo=I(()=>{Ie();zu();Wu();V();Qr();qe();$f();ye();ai();Xr();sl();o(en,"flattenedDecrypt")});async function es(t,e,r){if(t instanceof Uint8Array&&(t=ce.decode(t)),typeof t!="string")throw new P("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 P("Invalid Compact JWE");let l=await en({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 al=I(()=>{Xo();V();ye();o(es,"compactDecrypt")});async function jf(t,e,r){if(!Q(t))throw new P("General JWE must be an object");if(!Array.isArray(t.recipients)||!t.recipients.every(Q))throw new P("JWE Recipients missing or incorrect type");if(!t.recipients.length)throw new P("JWE Recipients has no members");for(let n of t.recipients)try{return await en({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 Lt}var Vf=I(()=>{Xo();V();qe();o(jf,"generalDecrypt")});var HT,Gf,Bf=I(()=>{Te();ot();Ie();st();HT=o(async t=>{if(t instanceof Uint8Array)return{kty:"oct",k:X(t)};if(!se(t))throw new TypeError(ie(t,...W,"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 L.subtle.exportKey("jwk",t);return s},"keyToJWK"),Gf=HT});async function Kf(t){return Rf(t)}async function Jf(t){return Of(t)}async function ts(t){return Gf(t)}var cl=I(()=>{Zo();Zo();Bf();o(Kf,"exportSPKI");o(Jf,"exportPKCS8");o(ts,"exportJWK")});async function qT(t,e,r,n,i={}){let s,a,c;switch(tr(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(!Qo(r))throw new U("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 mf(r)).privateKey);let{x:p,y:m,crv:f,kty:y}=await ts(d),v=await Wo(r,d,t==="ECDH-ES"?e:t,t==="ECDH-ES"?si(e):parseInt(t.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:f,kty:y}},y==="EC"&&(a.epk.y=m),u&&(a.apu=X(u)),l&&(a.apv=X(l)),t==="ECDH-ES"){c=v;break}c=n||_t(e);let T=t.slice(-6);s=await ii(T,v,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||_t(e),s=await vf(t,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||_t(e);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await bf(t,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||_t(e),s=await ii(t,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||_t(e);let{iv:u}=i;({encryptedKey:s,...a}=await Ff(t,r,c,u));break}default:throw new U('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var rs,ul=I(()=>{zo();Yu();Xu();el();Ie();ai();V();cl();ui();ol();o(qT,"encryptKeyManagement");rs=qT});var ll,Dt,ns=I(()=>{Ie();il();Wu();Go();ul();V();Qr();ye();Xr();ll=Symbol(),Dt=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 P("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!gt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new P("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(bt(P,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new U('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new P('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new P('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 rs(i,s,e,this._cek,this._keyManagementParameters)),y&&(r&&ll 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=Vo(s));let u,l,d;this._protectedHeader?l=Z.encode(X(JSON.stringify(this._protectedHeader))):l=Z.encode(""),this._aad?(d=X(this._aad),u=Se(l,Z.encode("."),Z.encode(d))):u=l;let p,m;if(n.zip==="DEF"){let y=await(r?.deflateRaw||pf)(this._plaintext);({ciphertext:p,tag:m}=await li(s,y,c,this._iv,u))}else({ciphertext:p,tag:m}=await li(s,this._plaintext,c,this._iv,u));let f={ciphertext:X(p),iv:X(this._iv),tag:X(m)};return a&&(f.encrypted_key=X(a)),d&&(f.aad=d),this._protectedHeader&&(f.protected=ce.decode(l)),this._sharedUnprotectedHeader&&(f.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(f.header=this._unprotectedHeader),f}}});var dl,is,zf=I(()=>{ns();V();ai();Qr();ul();Ie();Xr();dl=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}},is=class{static{o(this,"GeneralEncrypt")}constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,r){let n=new dl(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 P("at least one recipient must be added");if(e={deflateRaw:e?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Dt(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(!gt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new P("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 P('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new P('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new P('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new P('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(bt(P,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new P('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=_t(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 m={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let v=await new Dt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:m}).encrypt(l.key,{...l.options,...e,[ll]:!0});c.ciphertext=v.ciphertext,c.iv=v.iv,c.tag=v.tag,v.aad&&(c.aad=v.aad),v.protected&&(c.protected=v.protected),v.unprotected&&(c.unprotected=v.unprotected),d.encrypted_key=v.encrypted_key,v.header&&(d.header=v.header);continue}let{encryptedKey:f,parameters:y}=await rs(((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:m});d.encrypted_key=X(f),(l.unprotectedHeader||y)&&(d.header={...l.unprotectedHeader,...y})}return c}}});function pi(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 U(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}var pl=I(()=>{V();o(pi,"subtleDsa")});function hi(t,e,r){if(se(e))return uf(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ie(e,...W));return L.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ie(e,...W,"Uint8Array"))}var hl=I(()=>{Te();Zt();ot();st();o(hi,"getCryptoKey")});var $T,Wf,Qf=I(()=>{pl();Te();Yo();hl();$T=o(async(t,e,r,n)=>{let i=await hi(t,e,"verify");xr(t,i);let s=pi(t,i.algorithm);try{return await L.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),Wf=$T});async function tn(t,e,r){var n;if(!Q(t))throw new z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new z("JWS Payload missing");if(typeof t.signature!="string")throw new z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Q(t.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(t.protected)try{let T=re(t.protected);i=JSON.parse(ce.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!gt(i,t.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...t.header},a=bt(z,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&di("algorithms",r.algorithms);if(l&&!l.has(u))throw new zt('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof t.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof e=="function"&&(e=await e(i,t),d=!0),tr(u,e,"verify");let p=Se(Z.encode((n=t.protected)!==null&&n!==void 0?n:""),Z.encode("."),typeof t.payload=="string"?Z.encode(t.payload):t.payload),m=re(t.signature);if(!await Wf(u,e,m,p))throw new Or;let y;c?y=re(t.payload):typeof t.payload=="string"?y=Z.encode(t.payload):y=t.payload;let v={payload:y};return t.protected!==void 0&&(v.protectedHeader=i),t.header!==void 0&&(v.unprotectedHeader=t.header),d?{...v,key:e}:v}var os=I(()=>{Ie();Qf();V();ye();Qr();qe();ui();Xr();sl();o(tn,"flattenedVerify")});async function ss(t,e,r){if(t instanceof Uint8Array&&(t=ce.decode(t)),typeof t!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await tn({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 fl=I(()=>{os();V();ye();o(ss,"compactVerify")});async function Yf(t,e,r){if(!Q(t))throw new z("General JWS must be an object");if(!Array.isArray(t.signatures)||!t.signatures.every(Q))throw new z("JWS Signatures missing or incorrect type");for(let n of t.signatures)try{return await tn({header:n.header,payload:t.payload,protected:n.protected,signature:n.signature},e,r)}catch{}throw new Or}var Zf=I(()=>{os();V();qe();o(Yf,"generalVerify")});var rn,ml=I(()=>{rn=o(t=>Math.floor(t.getTime()/1e3),"default")});var jT,nn,yl=I(()=>{jT=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,nn=o(t=>{let e=jT.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 Xf,VT,on,as=I(()=>{V();ye();ml();yl();qe();Xf=o(t=>t.toLowerCase().replace(/^application\//,""),"normalizeTyp"),VT=o((t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1,"checkAudiencePresence"),on=o((t,e,r={})=>{let{typ:n}=r;if(n&&(typeof t.typ!="string"||Xf(t.typ)!==Xf(n)))throw new ge('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ce.decode(e))}catch{}if(!Q(i))throw new ue("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 f of new Set(s.reverse()))if(!(f in i))throw new ge(`missing required "${f}" claim`,f,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new ge('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new ge('unexpected "sub" claim value',"sub","check_failed");if(u&&!VT(i.aud,typeof u=="string"?[u]:u))throw new ge('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=nn(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,m=rn(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new ge('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new ge('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>m+d)throw new ge('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new ge('"exp" claim must be a number',"exp","invalid");if(i.exp<=m-d)throw new zr('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let f=m-i.iat,y=typeof l=="number"?l:nn(l);if(f-d>y)throw new zr('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(f<0-d)throw new ge('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function em(t,e,r){var n;let i=await ss(t,e,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new ue("JWTs MUST NOT use unencoded payload");let a={payload:on(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof e=="function"?{...a,key:i.key}:a}var tm=I(()=>{fl();as();V();o(em,"jwtVerify")});async function rm(t,e,r){let n=await es(t,e,r),i=on(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new ge('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new ge('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new ge('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof e=="function"?{...a,key:n.key}:a}var nm=I(()=>{al();as();V();o(rm,"jwtDecrypt")});var sn,gl=I(()=>{ns();sn=class{static{o(this,"CompactEncrypt")}constructor(e){this._flattened=new Dt(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 GT,im,om=I(()=>{pl();Te();Yo();hl();GT=o(async(t,e,r)=>{let n=await hi(t,e,"sign");xr(t,n);let i=await L.subtle.sign(pi(t,n.algorithm),n,r);return new Uint8Array(i)},"sign"),im=GT});var rr,cs=I(()=>{Ie();om();Qr();V();ye();ui();Xr();rr=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 z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!gt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=bt(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');tr(a,e,"sign");let c=this._payload;s&&(c=Z.encode(X(c)));let u;this._protectedHeader?u=Z.encode(X(JSON.stringify(this._protectedHeader))):u=Z.encode("");let l=Se(u,Z.encode("."),c),d=await im(a,e,l),p={signature:X(d),payload:""};return s&&(p.payload=ce.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ce.decode(u)),p}}});var an,_l=I(()=>{cs();an=class{static{o(this,"CompactSign")}constructor(e){this._flattened=new rr(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 bl,us,sm=I(()=>{cs();V();bl=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}},us=class{static{o(this,"GeneralSign")}constructor(e){this._signatures=[],this._payload=e}addSignature(e,r){let n=new bl(this,e,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("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 rr(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 z("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}});var nr,ls=I(()=>{ml();qe();yl();nr=class{static{o(this,"ProduceJWT")}constructor(e){if(!Q(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:rn(new Date)+nn(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:rn(new Date)+nn(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:rn(new Date)}:this._payload={...this._payload,iat:e},this}}});var ds,am=I(()=>{_l();V();ye();ls();ds=class extends nr{static{o(this,"SignJWT")}setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var n;let i=new an(Z.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 ue("JWTs MUST NOT use unencoded payload");return i.sign(e,r)}}});var ps,cm=I(()=>{gl();ye();ls();ps=class extends nr{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 sn(Z.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 El(t,e){if(!Q(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":ir(t.crv,'"crv" (Curve) Parameter'),ir(t.x,'"x" (X Coordinate) Parameter'),ir(t.y,'"y" (Y Coordinate) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":ir(t.crv,'"crv" (Subtype of Key Pair) Parameter'),ir(t.x,'"x" (Public Key) Parameter'),r={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":ir(t.e,'"e" (Exponent) Parameter'),ir(t.n,'"n" (Modulus) Parameter'),r={e:t.e,kty:t.kty,n:t.n};break;case"oct":ir(t.k,'"k" (Key Value) Parameter'),r={k:t.k,kty:t.kty};break;default:throw new U('"kty" (Key Type) Parameter missing or unsupported')}let n=Z.encode(JSON.stringify(r));return X(await ko(e,n))}async function um(t,e){e??(e="sha256");let r=await El(t,e);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${e.slice(-3)}:${r}`}var ir,lm=I(()=>{Hu();Ie();V();ye();qe();ir=o((t,e)=>{if(typeof t!="string"||!t)throw new ei(`${e} missing or invalid`)},"check");o(El,"calculateJwkThumbprint");o(um,"calculateJwkThumbprintUri")});async function dm(t,e){let r={...t,...e?.header};if(!Q(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await er({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var pm=I(()=>{ci();qe();V();o(dm,"EmbeddedJWK")});function BT(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 U('Unsupported "alg" value for a JSON Web Key Set')}}function wl(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(KT)}function KT(t){return Q(t)}function JT(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}async function hm(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await er({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new Wt("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function fm(t){let e=new fi(t);return async function(r,n){return e.getKey(r,n)}}var fi,vl=I(()=>{ci();V();qe();o(BT,"getKtyFromAlg");o(wl,"isJWKSLike");o(KT,"isJWKLike");o(JT,"clone");fi=class{static{o(this,"LocalJWKSet")}constructor(e){if(this._cached=new WeakMap,!wl(e))throw new Wt("JSON Web Key Set malformed");this._jwks=JT(e)}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=BT(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 Rr;if(u!==1){let l=new ti,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await hm(d,p,n)}catch{continue}},l}return hm(this._cached,c,n)}};o(hm,"importWithAlgCache");o(fm,"createLocalJWKSet")});var zT,mm,ym=I(()=>{V();zT=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 ri:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new pe("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new pe("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),mm=zT});function WT(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function gm(t,e){let r=new Tl(t,e);return async function(n,i){return r.getKey(n,i)}}var Tl,_m=I(()=>{ym();V();vl();o(WT,"isCloudflareWorkers");Tl=class extends fi{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 Rr&&this.coolingDown()===!1)return await this.reload(),super.getKey(e,r);throw n}}async reload(){this._pendingFetch&&WT()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=mm(this._url,this._timeoutDuration,this._options).then(e=>{if(!wl(e))throw new Wt("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(gm,"createRemoteJWKSet")});var hs,bm=I(()=>{Ie();ye();V();as();ls();hs=class extends nr{static{o(this,"UnsecuredJWT")}encode(){let e=X(JSON.stringify({alg:"none"})),r=X(JSON.stringify(this._payload));return`${e}.${r}.`}static decode(e,r){if(typeof e!="string")throw new ue("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3||s!=="")throw new ue("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ce.decode(re(n))),c.alg!=="none")throw new Error}catch{throw new ue("Invalid Unsecured JWT")}return{payload:on(c,re(i),r),header:c}}}});var Sl={};Ki(Sl,{decode:()=>mi,encode:()=>QT});var QT,mi,fs=I(()=>{Ie();QT=X,mi=re});function Em(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(ce.decode(mi(e)));if(!Q(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var wm=I(()=>{fs();ye();qe();o(Em,"decodeProtectedHeader")});function vm(t){if(typeof t!="string")throw new ue("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new ue("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ue("Invalid JWT");if(!e)throw new ue("JWTs must contain a payload");let n;try{n=mi(e)}catch{throw new ue("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ce.decode(n))}catch{throw new ue("Failed to parse the decoded payload as JSON")}if(!Q(i))throw new ue("Invalid JWT Claims Set");return i}var Tm=I(()=>{fs();ye();qe();V();o(vm,"decodeJwt")});async function Sm(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),Qt(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 U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return L.subtle.generateKey(i,(r=e?.extractable)!==null&&r!==void 0?r:!1,s)}function Il(t){var e;let r=(e=t?.modulusLength)!==null&&e!==void 0?e:2048;if(typeof r!="number"||r<2048)throw new U("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function Im(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:Il(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:Il(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:Il(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 U("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 U("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new U('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return L.subtle.generateKey(s,(i=e?.extractable)!==null&&i!==void 0?i:!1,a)}var Al=I(()=>{Te();V();ni();o(Sm,"generateSecret");o(Il,"getModulusLengthOption");o(Im,"generateKeyPair")});async function Am(t,e){return Im(t,e)}var Pm=I(()=>{Al();o(Am,"generateKeyPair")});async function Rm(t,e){return Sm(t,e)}var Om=I(()=>{Al();o(Rm,"generateSecret")});var ms={};Ki(ms,{CompactEncrypt:()=>sn,CompactSign:()=>an,EmbeddedJWK:()=>dm,EncryptJWT:()=>ps,FlattenedEncrypt:()=>Dt,FlattenedSign:()=>rr,GeneralEncrypt:()=>is,GeneralSign:()=>us,SignJWT:()=>ds,UnsecuredJWT:()=>hs,base64url:()=>Sl,calculateJwkThumbprint:()=>El,calculateJwkThumbprintUri:()=>um,compactDecrypt:()=>es,compactVerify:()=>ss,createLocalJWKSet:()=>fm,createRemoteJWKSet:()=>gm,decodeJwt:()=>vm,decodeProtectedHeader:()=>Em,errors:()=>ju,exportJWK:()=>ts,exportPKCS8:()=>Jf,exportSPKI:()=>Kf,flattenedDecrypt:()=>en,flattenedVerify:()=>tn,generalDecrypt:()=>jf,generalVerify:()=>Yf,generateKeyPair:()=>Am,generateSecret:()=>Rm,importJWK:()=>er,importPKCS8:()=>kf,importSPKI:()=>Uf,importX509:()=>Mf,jwtDecrypt:()=>rm,jwtVerify:()=>em});var ys=I(()=>{al();Xo();Vf();zf();fl();os();Zf();tm();nm();gl();ns();_l();cs();sm();am();cm();lm();pm();vl();_m();bm();cl();ci();wm();Tm();V();Pm();Om();fs()});var _s=g(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.fetchRetry=void 0;var YT=D();async function ZT(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 YT.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(ZT,"fetchRetry");gs.fetchRetry=ZT});var cn=g(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GcpServiceAccount=Ze.fetchToken=Ze.exchangeGgpJwtForIdToken=Ze.exchangeFirebaseJwtForIdToken=Ze.getTokenFromGcpServiceAccount=void 0;var xm=(ys(),Ji(ms)),XT=D(),eS=_s();async function tS({serviceAccount:t,audience:e,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=t;return await new xm.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(e).setIssuedAt().setExpirationTime(r).sign(a)}o(tS,"getTokenFromGcpServiceAccount");Ze.getTokenFromGcpServiceAccount=tS;async function rS(t,e,r){return Rl(t,{token:e,returnSecureToken:!0},r)}o(rS,"exchangeFirebaseJwtForIdToken");Ze.exchangeFirebaseJwtForIdToken=rS;async function nS(t,e,r){return Rl(t,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},r)}o(nS,"exchangeGgpJwtForIdToken");Ze.exchangeGgpJwtForIdToken=nS;async function Rl(t,e,r){let n=await(0,eS.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 XT.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Rl,"fetchToken");Ze.fetchToken=Rl;var Pl=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,xm.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}};Ze.GcpServiceAccount=Pl});var Es=g(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.GoogleLogTransport=Ut.ZuploToGCPMap=Ut.GoogleCloudLoggingPlugin=void 0;var iS=we(),Ol=te(),xl=cn(),oS=Ct(),Nm=yt(),Nl=class extends oS.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new bs(this.options)}};Ut.GoogleCloudLoggingPlugin=Nl;var sS="https://logging.googleapis.com/v2/entries:write?alt=json";Ut.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var bs=class{static{o(this,"GoogleLogTransport")}constructor(e){this.#r=e.logName,this.#e=e.serviceAccountJson,this.#i=Ol.Environment.instance.loggingEnvironmentType,this.#o=Ol.Environment.instance.loggingEnvironmentStage,this.#n=Ol.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(e,r){if(e.messages.length===0)return;let n={allMessages:(0,Nm.makeErrorsSerializable)(e.messages)};this.#t||(this.#t=await xl.GcpServiceAccount.init(this.#e));let i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:Ut.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,Nm.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 xl.GcpServiceAccount.init(this.#e));let r=await(0,xl.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(sS,{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 iS.BatchDispatch("google-log-transport",1,this.dispatchFunction)};Ut.GoogleLogTransport=bs});var Cl=g(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.gcpLogFormat=un.GCP_LOG_FORMAT=void 0;var Cm=yt(),aS=Es();un.GCP_LOG_FORMAT="gcp";function cS(t){let e={allMessages:(0,Cm.makeErrorsSerializable)(t.messages)},r="zuplo-production",n=(0,Cm.extractBestMessage)(e.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:aS.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(cS,"gcpLogFormat");un.gcpLogFormat=cS});var Dm=g(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.ConsoleTransport=void 0;var Lm=Cl(),Ll=class{static{o(this,"ConsoleTransport")}constructor(e,r){this.#e=e??console,this.#t=r}#e;#t;async log(e){if(this.#t===Lm.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Lm.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}])}};ws.ConsoleTransport=Ll});var Hl=g(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.DataDogTransport=ln.DataDogLoggingPlugin=void 0;var uS=we(),Dl=te(),lS=Ct(),Um=yt(),Fl=class extends lS.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new vs(this.options)}};ln.DataDogLoggingPlugin=Fl;var Ul="__ddtags",Ml="__ddattr",kl=o(t=>t.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),dS=o(t=>{let e=Object.keys(t),r=[];return e.forEach(n=>{let i=t[n];i==null?r.push(kl(n)):r.push(`${kl(n)}:${kl(i.toString())}`)}),r.join(",")},"formatTags"),vs=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=Dl.Environment.instance.loggingEnvironmentType,this.#i=Dl.Environment.instance.loggingEnvironmentStage,this.#r=Dl.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){let n={},i=r.custom[Ul];i&&typeof i=="object"&&Object.assign(n,i);let s=[...e.messages],a=e.messages.findIndex(f=>f[Ul]!==void 0);a>-1&&(Object.assign(n,s[a][Ul]),s.splice(a,1));let c={},u=r.custom[Ml];u&&typeof u=="object"&&Object.assign(c,u);let l=e.messages.findIndex(f=>f[Ml]!==void 0);l>-1&&(Object.assign(c,s[l][Ml]),s.splice(l,1));let d=(0,Um.makeErrorsSerializable)(s),m={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Um.extractBestMessage)(d),service:e.loggingId,ddtags:dS(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(m,c),this.batcher.enqueue(m),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 uS.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};ln.DataDogTransport=vs});var km=g(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ProcessTransport=void 0;var Mm=Cl(),ql=class{static{o(this,"ProcessTransport")}constructor(e,r){this.#e=e,this.#t=r}#e;#t;async log(e){if(this.#t===Mm.GCP_LOG_FORMAT){if(e.messages.length===0)return;this.#e[e.level].apply(null,[(0,Mm.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}])}};Ts.ProcessTransport=ql});var Hm=g(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.RemoteLogTransport=void 0;var pS=we(),Fm=te(),hS=yt(),fS=o(({url:t,remoteLogToken:e,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0&&fetch(`${t}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,hS.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":Fm.Environment.instance.systemUserAgent,"zp-dn":Fm.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Ss,$l=class{static{o(this,"RemoteLogTransport")}constructor(e){Ss||(Ss=new pS.BatchDispatch("remote-log-transport",1,fS(e)))}async log(e,r){Ss.enqueue(e),r.waitUntil(Ss.waitUntilFlushed())}};Is.RemoteLogTransport=$l});var qm=g(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.unifiedFormatter=Nr.SeverityNumberOpenTelemetryMap=void 0;Nr.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var mS=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:Nr.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Nr.unifiedFormatter=mS});var jm=g(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.UnifiedLogTransport=void 0;var yS=we(),$m=te(),gS=qm(),_S=o(({url:t,remoteLogToken:e,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,gS.unifiedFormatter)(r,n);fetch(`${t}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":$m.Environment.instance.systemUserAgent,"zp-dn":$m.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),As,jl=class{static{o(this,"UnifiedLogTransport")}constructor(e){As||(As=new yS.BatchDispatch("unified-log-transport",1,_S(e)))}async log(e,r){As.enqueue(e),r.waitUntil(As.waitUntilFlushed())}};Ps.UnifiedLogTransport=jl});var Wm=g(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.LogInitializer=void 0;var bS=wr(),ES=Ot(),Vm=Pu(),Gm=te(),Bm=jh(),wS=Ct(),vS=Vh(),Km=Gh(),Jm=Dm(),TS=Hl(),SS=Es(),zm=km(),IS=Hm(),AS=jm(),Vl=(0,bS.debug)("zuplo:logging"),Gl=class{static{o(this,"LogInitializer")}serviceProvider;systemCoreLogger;userCoreLogger;constructor(e){this.serviceProvider=e,this.systemCoreLogger=this.setupSystemCoreLogger(Gm.Environment.instance),this.userCoreLogger=this.setupUserCoreLogger(Gm.Environment.instance)}setupSystemCoreLogger(e){let{runtime:r,build:n}=e;Vl("Gateway.setupSystemCoreLogger");let i=[],s=this.serviceProvider.getService(Vm.SYSTEM_LOGGER);return s?i.push(new zm.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&i.push(new Jm.ConsoleTransport(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&i.push(new AS.UnifiedLogTransport({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),new Bm.CoreLogger(e.systemLogLevel,"system",e.loggingId,n.BUILD_ID,i)}setupUserCoreLogger(e){Vl("Gateway.setupUserCoreLogger");let r=[],{runtime:n,build:i}=e,s=this.serviceProvider.getService(Vm.SYSTEM_LOGGER);if(s&&s.captureUserLogs===!0?r.push(new zm.ProcessTransport(s.logger,e.logFormat)):e.isDeno&&r.push(new Jm.ConsoleTransport(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new IS.RemoteLogTransport({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:e.isCloudflare})),n.GCP_USER_LOG_NAME&&n.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new SS.GoogleLogTransport({serviceAccountJson:n.GCP_USER_LOG_SVC_ACCT_JSON,logName:n.GCP_USER_LOG_NAME})),n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=n.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new TS.DataDogTransport({apiKey:n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return ES.plugins.forEach(a=>{a instanceof wS.LogPlugin&&r.push(a.getTransport())}),new Bm.CoreLogger(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,r,n,i,s){Vl("Gateway.createRequestLoggers");let a=new vS.LoggingContext(n,i,s),c=new Km.RequestLogger(e,r,this.systemCoreLogger,a);return{userRequestLogger:new Km.RequestLogger(e,r,this.userCoreLogger,a),systemRequestLogger:c}}};Rs.LogInitializer=Gl});var Kl=g(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.UserRouteConfiguration=void 0;var Bl=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};Os.UserRouteConfiguration=Bl});var zl=g(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.Router=Et.RouterError=Et.LookupResult=Et.RouterEntry=void 0;var Qm=D(),PS=ft(),RS=Kl(),xs=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};Et.RouterEntry=xs;var yi=class{static{o(this,"LookupResult")}constructor(e,r,n){this.routeConfiguration=e,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};Et.LookupResult=yi;var Ns=class extends Error{static{o(this,"RouterError")}constructor(e,r){super(e,r)}};Et.RouterError=Ns;var Jl=class{static{o(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,r){if(!(e instanceof RS.UserRouteConfiguration||e instanceof PS.SystemRouteConfiguration))throw new Qm.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 xs(i,s,e,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ns(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(e,r){if(typeof e>"u")throw new Qm.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 yi(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 yi(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};Et.Router=Jl});var dn=g(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.Gateway=void 0;var OS=wr(),Ym=wh(),Zm=Sh(),xS=Ih(),Xm=Ah(),ey=xh(),or=Wn(),Cs=vr(),NS=Su(),ty=$h(),vt=D(),Wl=Ot(),CS=Wm(),LS=Gt(),DS=ve(),US=Tu(),MS=Sr(),kS=Zn(),FS=Yn(),HS=zl(),Ql=ft(),ry=Kl(),qS=Ge(),ny=te(),iy=Pr(),$S=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],wt=(0,OS.debug)("zuplo:runtime"),jS=o(t=>{let e=t.findIndex(r=>r.name===Ql.systemNoVersion.name);return e>-1?[...t.splice(e),Ql.systemNoVersion]:[...t,Ql.systemNoVersion]},"setupSystemNoVersion"),Yl=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,wt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=new CS.LogInitializer(n)}static async initialize(e,r,n,i,s){if(wt("Gateway.initialize"),!t.#e){await(0,Wl.initializeRuntime)(s);let a=new t(e,r,n,i);t.#e=a}return t.#e}static purgeGatewayCache(){wt("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new vt.SystemError("Gateway cannot be used before it is initialized");return t.#e}instanceId=crypto.randomUUID();#t;#r;#n=[kS.policyProcessor,US.corsProcessor,MS.metricsProcessor];#i;setupRoutes=()=>{wt("Gateway.setupRoutes");let e=this.routeData,r=jS(e.versions),n=new HS.Router(r);return e.routes.length===0?((0,Ym.registerBuildRoute)(n,this),(0,ey.registerPingRoute)(n,this),(0,Zm.registerCorsRoute)(n,this),(0,xS.registerNoRoutes)(n,this),n):((0,ty.registerDevPortalLegacyRedirectRoute)(n,this),(0,ty.registerDevPortalV3Route)(n,this),(0,Ym.registerBuildRoute)(n,this),(0,ey.registerPingRoute)(n,this),(0,Zm.registerCorsRoute)(n,this),e.routes.forEach(i=>{let s;if(typeof i.handler?.module=="object"&&(s=i.handler?.module[i.handler.export]),typeof s!="function")throw new vt.ConfigurationError(`Invalid state - No handler on route for path '${i.path}'`);let a=s,c=new LS.Pipeline(this.#n,a,this),u=new ry.UserRouteConfiguration(i);n.addRoute(u,c.execute)}),(0,Xm.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 vt.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 wt("An error occurred in the user's errorHandler",i),this.#o(e,r,i)}}#o(e,r,n){wt("Gateway.internalErrorResponse");let i={};if(ny.Environment.instance.isDeno){if(n instanceof vt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,iy.serializeError)(n.cause);"stack"in s&&(s.stack=(0,iy.cleanStack)(s.stack)),i={cause:s}}}return DS.HttpProblems.internalServerError(e,r,{detail:n.message,...i})}#s(e){if(ny.Environment.instance.isCloudflare)return e;{let r=new Headers;for(let[n,i]of e.headers)or.INTERNAL_HEADERS_TO_REMOVE.includes(n.toLowerCase())||r.set(n,i);return new Request(e,{headers:r})}}async handleRequest(e,r){let n=e.headers.get(or.REQUEST_ID_HEADER)??e.headers.get(or.LEGACY_REQUEST_ID_HEADER),i=e.headers.get(or.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(e.headers);T.set(or.REQUEST_ID_HEADER,n),e=new Request(e,{headers:T})}if(["GET","HEAD"].includes(e.method)&&e.body){let T=new Headers(e.headers);T.set(or.BODY_REMOVED_HEADER,"true"),e=new Request(e,{headers:T,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,s,e),u=new URL(e.url),l=u.pathname,d=this.#r.lookup(e.method,l);if(!d)throw new vt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Cs.HeaderIncomingRequestProperties(e.headers),m=this.#s(e),f=new FS.ZuploRequest(m,{params:d.params}),y=new Cs.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:s,incomingRequestProperties:p}),v=Cs.ZuploContextExtensions.initialize(y,f);if(d.routeConfiguration===Xm.notFoundRouteConfiguration&&Wl.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);v.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof ry.UserRouteConfiguration)}try{if(qS.SystemLogMap.addLogger(y,c),!u.pathname.startsWith("/__zuplo")){let H=await(0,Wl.invokeOnRequestExtensions)(f,y);if(H instanceof Response)return H;{let R=Cs.ZuploContextExtensions.getContextExtensions(y);f=H,R.latestRequest=f}}[...$S,(0,NS.getDevPortalRuntimeConfig)(this).sitePathname].filter(H=>new RegExp(H).test(u.pathname)).length===0&&a.debug(`Request received '${u.pathname}'`,{method:e.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;VS(S,d,e),wt("Gateway.handleRequest - call user handler");let M=await S(f,y);if(wt("Gateway.handleRequest - user handler"),!(M instanceof Response))throw new vt.RuntimeError(`Invalid Response type from the request handler: ${typeof M}`);if(M.bodyUsed)throw new vt.RuntimeError("The response object has already been used. Return a new response instead.");if(M.headers.get(or.REQUEST_ID_HEADER)===null&&!M.webSocket){let H=new Headers(M.headers);return H.set(or.REQUEST_ID_HEADER,n),new Response(M.body,{status:M.status,statusText:M.statusText,headers:H,cf:M.cf})}else return M}catch(T){return wt("Gateway - error executing handler",T),T instanceof vt.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(f,y,T)}}};Ls.Gateway=Yl;function VS(t,e,r){if(wt("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new vt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new vt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${e.routeConfiguration.path}'`)}o(VS,"checkHandler")});var oy=g(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.invokeInboundPolicy=void 0;var GS=D(),BS=dn(),KS=Zn(),JS=o(async(t,e,r)=>{let n=BS.Gateway.instance.routeData.policies,i=(0,KS.getInboundPolicyHandlerAndOptions)([t],n);if(i.length===0)throw new GS.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=i[0];return s.handler(e,r,s.options,t)},"invokeInboundPolicy");Ds.invokeInboundPolicy=JS});var vr=g(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.SystemZuploContext=Xe.ZuploContextExtensions=Xe.ResponseSentEvent=Xe.ResponseSendingEvent=Xe.HeaderIncomingRequestProperties=void 0;var _e=Wn(),zS=D(),WS=oy(),Zl=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(_e.ZP_ASN_HEADER);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(_e.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(_e.CF_IP_CITY_HEADER)??this.#e.get(_e.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(_e.CF_IP_CONTINENT_HEADER)??this.#e.get(_e.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(_e.CF_IP_COUNTRY_HEADER)??this.#e.get(_e.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(_e.CF_IP_LATITUDE_HEADER)??this.#e.get(_e.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(_e.CF_IP_LONGITUDE_HEADER)??this.#e.get(_e.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(_e.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(_e.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(_e.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(_e.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(_e.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(_e.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}}};Xe.HeaderIncomingRequestProperties=Zl;var Xl=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse};Xe.ResponseSendingEvent=Xl;var ed=class extends Event{static{o(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response};Xe.ResponseSentEvent=ed;var Us=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 zS.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}};Xe.ZuploContextExtensions=Us;var td=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:n,fetchEvent: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,WS.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingFinalHook=c=>{Us.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;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)}};Xe.SystemZuploContext=td});var sy=g(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.ContextLocalStorage=void 0;var rd=class t{static{o(this,"ContextLocalStorage")}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)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};Ms.ContextLocalStorage=rd});var nd=g(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.environment=sr.isZuploReadableEnvVariableName=sr.isRestrictedEnvVariableName=void 0;var QS=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function ay(t){return t.startsWith("__ZUPLO")||t.startsWith("ZUPLO_")?!QS.includes(t)&&!t.startsWith("ZUPLO_PUBLIC_"):!1}o(ay,"isRestrictedEnvVariableName");sr.isRestrictedEnvVariableName=ay;function cy(t){return!!t.startsWith("ZUPLO_")}o(cy,"isZuploReadableEnvVariableName");sr.isZuploReadableEnvVariableName=cy;var YS=new Proxy({},{get(t,e,r){if(ay(String(e))&&!cy(String(e)))return;let n=globalThis,i;return n.process?i=n.process.env[e]:i=n[e],i}});sr.environment=YS});var ks=g(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.externalServiceHandler=pn.externalServiceTunnelConfig=void 0;var ZS=wr(),Cr=D(),XS=id(),gi=te(),at=(0,ZS.debug)("zuplo:runtime:external-service");function ly(){let t,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=gi.Environment.instance.runtime;if(e&&e!=="undefined")try{let r=atob(e);t=JSON.parse(r)}catch{}return t}o(ly,"getServiceAuth");async function eI(t){let e=ly();if(!e)throw at("There is no external service auth configured for this zup."),new Cr.RuntimeError("There are no external services configured for this zup.");if(typeof t!="string")throw at("Cannot call external service with Request object"),new Cr.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(gi.Environment.instance.useSha256ServiceRouting){at("Using sha256 service routing");let a=gi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await dy(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new Cr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(eI,"externalServiceTunnelConfig");pn.externalServiceTunnelConfig=eI;async function tI(t,e){let r=ly();if(r)if(at(`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(gi.Environment.instance.useSha256ServiceRouting){at("Using sha256 service routing");let d=gi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await dy(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw at("Cannot use sha256 service routing, missing build variables"),new Cr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);at(`Calling external service: ${u.toString()}`);let l=await(0,XS.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 Cr.RuntimeError("Could not connect to secure tunnel.");return l}else throw at("Cannot call external service with Request object"),new Cr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw at("There is no external service auth configured for this zup."),new Cr.RuntimeError("There are no external services configured for this zup.")}o(tI,"externalServiceHandler");pn.externalServiceHandler=tI;async function dy(t,e,r,n){let i=t.toLowerCase(),s=e.toLowerCase(),a=r.toLowerCase(),c=rI(n);at(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await uy(`${s}-${i}`),l=await uy(`${s}-${a}-${c}`);return`${u}.${l}`}o(dy,"hashServiceName");async function uy(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(uy,"hashSegment");function rI(t){let e=t.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}o(rI,"sanitizeEnvironmentType")});var id=g(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.originalFetch=void 0;var nI=ks(),py=new Map;py.set("service:",nI.externalServiceHandler);hn.originalFetch=globalThis.fetch;globalThis.fetch=function(t,e){let r=iI(e);if(typeof t=="string"){let n=new URL(t),i=py.get(n.protocol);return i?i(t,r):(0,hn.originalFetch)(t,r)}else return(0,hn.originalFetch)(t,r)};var iI=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 my=g(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.Handler=fn.purgeGatewayCache=void 0;var fy=dn(),hy=te(),oI=o(()=>{fy.Gateway.purgeGatewayCache()},"purgeGatewayCache");fn.purgeGatewayCache=oI;var od=class{static{o(this,"Handler")}routeData;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(e,r,n,i,s,a,c){this.routeData=e,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=s,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(e,r)=>{hy.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await fy.Gateway.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let s={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:"Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",instance:e.url,trace:{timestamp:Date.now(),rayId:e.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:hy.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(s,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(e,r)}};fn.Handler=od});var by=g(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.pathToRegexp=Re.tokensToRegexp=Re.regexpToFunction=Re.match=Re.tokensToFunction=Re.compile=Re.parse=void 0;function sI(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(sI,"lexer");function sd(t,e){e===void 0&&(e={});for(var r=sI(t),n=e.prefixes,i=n===void 0?"./":n,s="[^".concat(mn(e.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(Y){if(u<r.length&&r[u].type===Y)return r[u++].value},"tryConsume"),p=o(function(Y){var fe=d(Y);if(fe!==void 0)return fe;var Me=r[u],E=Me.type,F=Me.index;throw new TypeError("Unexpected ".concat(E," at ").concat(F,", expected ").concat(Y))},"mustConsume"),m=o(function(){for(var Y="",fe;fe=d("CHAR")||d("ESCAPED_CHAR");)Y+=fe;return Y},"consumeText");u<r.length;){var f=d("CHAR"),y=d("NAME"),v=d("PATTERN");if(y||v){var T=f||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:y||c++,prefix:T,suffix:"",pattern:v||s,modifier:d("MODIFIER")||""});continue}var S=f||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var M=d("OPEN");if(M){var T=m(),H=d("NAME")||"",R=d("PATTERN")||"",ne=m();p("CLOSE"),a.push({name:H||(R?c++:""),pattern:H&&!R?s:R,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(sd,"parse");Re.parse=sd;function aI(t,e){return yy(sd(t,e),e)}o(aI,"compile");Re.compile=aI;function yy(t,e){e===void 0&&(e={});var r=ad(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 m=u?u[p.name]:void 0,f=p.modifier==="?"||p.modifier==="*",y=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!y)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var v=0;v<m.length;v++){var T=i(m[v],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var T=i(String(m),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!f){var S=y?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}o(yy,"tokensToFunction");Re.tokensToFunction=yy;function cI(t,e){var r=[],n=cd(t,r,e);return gy(n,r,e)}o(cI,"match");Re.match=cI;function gy(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(m){if(a[m]===void 0)return"continue";var f=e[m-1];f.modifier==="*"||f.modifier==="+"?l[f.name]=a[m].split(f.prefix+f.suffix).map(function(y){return i(y,f)}):l[f.name]=i(a[m],f)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(gy,"regexpToFunction");Re.regexpToFunction=gy;function mn(t){return t.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(mn,"escapeString");function ad(t){return t&&t.sensitive?"":"i"}o(ad,"flags");function uI(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(uI,"regexpToRegexp");function lI(t,e,r){var n=t.map(function(i){return cd(i,e,r).source});return new RegExp("(?:".concat(n.join("|"),")"),ad(r))}o(lI,"arrayToRegexp");function dI(t,e,r){return _y(sd(t,r),e,r)}o(dI,"stringToRegexp");function _y(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(F){return F}:l,p=r.delimiter,m=p===void 0?"/#?":p,f=r.endsWith,y=f===void 0?"":f,v="[".concat(mn(y),"]|$"),T="[".concat(mn(m),"]"),S=a?"^":"",M=0,H=t;M<H.length;M++){var R=H[M];if(typeof R=="string")S+=mn(d(R));else{var ne=mn(d(R.prefix)),Y=mn(d(R.suffix));if(R.pattern)if(e&&e.push(R),ne||Y)if(R.modifier==="+"||R.modifier==="*"){var fe=R.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(R.pattern,")(?:").concat(Y).concat(ne,"(?:").concat(R.pattern,"))*)").concat(Y,")").concat(fe)}else S+="(?:".concat(ne,"(").concat(R.pattern,")").concat(Y,")").concat(R.modifier);else R.modifier==="+"||R.modifier==="*"?S+="((?:".concat(R.pattern,")").concat(R.modifier,")"):S+="(".concat(R.pattern,")").concat(R.modifier);else S+="(?:".concat(ne).concat(Y,")").concat(R.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(v,")"):"$";else{var Me=t[t.length-1],E=typeof Me=="string"?T.indexOf(Me[Me.length-1])>-1:Me===void 0;i||(S+="(?:".concat(T,"(?=").concat(v,"))?")),E||(S+="(?=".concat(T,"|").concat(v,")"))}return new RegExp(S,ad(r))}o(_y,"tokensToRegexp");Re.tokensToRegexp=_y;function cd(t,e,r){return t instanceof RegExp?uI(t,e):Array.isArray(t)?lI(t,e,r):dI(t,e,r)}o(cd,"pathToRegexp");Re.pathToRegexp=cd});var pd=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.AwsV4Signer=yn.AwsClient=void 0;var pI=wr(),Ty=D(),hI=(0,pI.debug)("zuplo:runtime"),ld=new TextEncoder,Ey={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"},fI=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],dd=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 Fs(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){hI("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 Ty.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};yn.AwsClient=dd;var Fs=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:m,appendSessionToken:f,allHeaders:y,singleEncode:v}){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 T,S;(!u||!l)&&([T,S]=mI(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let M=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"),M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&M.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(R=>y||!fI.includes(R)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(R=>R+":"+(R==="host"?this.url.host:(this.headers.get(R)||"").replace(/\s+/g," "))).join(`
60
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!M.has("X-Amz-Expires")&&M.set("X-Amz-Expires","86400"),M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.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,"/");v||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=vy(this.encodedPath);let H=new Set;this.encodedSearch=[...this.url.searchParams].filter(([R])=>{if(!R)return!1;if(this.service==="s3"){if(H.has(R))return!1;H.add(R)}return!0}).map(R=>R.map(ne=>vy(encodeURIComponent(ne)))).sort(([R,ne],[Y,fe])=>R<Y?-1:R>Y?1:ne<fe?-1:ne>fe?1:0).map(R=>R.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 _i("AWS4"+this.secretAccessKey,e),s=await _i(i,this.region),a=await _i(s,this.service);n=await _i(a,"aws4_request"),this.cache.set(r,n)}return ud(await _i(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ud(await wy(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 vy.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=cd(await Ey(this.body||""))}return e}};yn.AwsV4Signer=Fs;async function _i(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?ud.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,ud.encode(e))}o(_i,"hmac");async function Ey(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?ud.encode(t):t)}o(Ey,"hash");function cd(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}o(cd,"buf2hex");function wy(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}o(wy,"encodeRfc3986");function hI(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 by?[by[s],a]:[s,a]}o(hI,"guessServiceRegion")});var Ty=g(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.convertStringToUtf8Array=Tt.convertUtf8ArrayToString=Tt.base64Encode=Tt.base64Decode=void 0;function fI(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(fI,"b64ToUint6");function mI(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|=fI(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(mI,"base64Decode");Tt.base64Decode=mI;function Hs(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}o(Hs,"uint6ToB64");function yI(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(Hs(i>>>18&63),Hs(i>>>12&63),Hs(i>>>6&63),Hs(i&63)),i=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}o(yI,"base64Encode");Tt.base64Encode=yI;function gI(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(gI,"convertUtf8ArrayToString");Tt.convertUtf8ArrayToString=gI;function _I(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(_I,"convertStringToUtf8Array");Tt.convertStringToUtf8Array=_I});var Sy=g(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.toCLFDate=void 0;function gn(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}o(gn,"numberToString");function bI(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",i=gn(Math.floor(r/60)),s=gn(r%60);return`${n}${i}${s}`}o(bI,"getCLFOffset");function EI(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=gn(t.getDate()),n=e[t.getMonth()],i=t.getFullYear(),s=gn(t.getHours()),a=gn(t.getMinutes()),c=gn(t.getSeconds()),u=bI(t);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(EI,"toCLFDate");qs.toCLFDate=EI});var Ny=g(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.getResponse=sr.awsLambdaHandler=sr.AwsLambdaHandlerExtensions=void 0;var wI=wr(),Iy=_y(),bi=D(),vI=xt(),TI=dd(),Py=Ty(),Ry=Sy(),Ay=(0,wI.debug)("zuplo:runtime"),SI="X-Amzn-Trace-Id",II="x-amzn-errortype",Oy=[],AI=o(async(t,e,r)=>{let n=r;for await(let i of Oy)n=await i(t,e,r);return n},"onSendingAwsLambdaEvent"),Be=class extends bi.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(SI)??void 0,this.errorType=r.get(II)??void 0}};sr.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:t=>{Oy.push(t)}};async function PI(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 bi.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new bi.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new bi.ConfigurationError("region is not set in the handler options");if(!s)throw new bi.ConfigurationError("functionName is not set in the handler options");let l=new TI.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Ay(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await xI(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,y;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?y=OI(t,e):y=await RI(t,e,{useAwsResourcePathStyle:c}),Ay("Calling onSendingAwsLambdaEvent hook");let v=await AI(t,e,y);v.body=p,v.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(v)});try{return xy(T)}catch(S){if(S instanceof Be){let M=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&S.traceId?{AMZN_TRACE_ID_HEADER:S.traceId}:void 0;return vI.HttpProblems.internalServerError(t,e,void 0,M)}throw S}}o(PI,"awsLambdaHandler");sr.awsLambdaHandler=PI;async function xy(t){let e;try{e=await t.json()}catch{throw new Be("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 Be(e.message,t.headers):new Be(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Be(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 Be(`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 Be(`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 Be(`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 Be("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new Be("Response was set to base64 encoded but body was not a string",t.headers);n=(0,Py.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 Be(`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(xy,"getResponse");sr.getResponse=xy;async function RI(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,Ry.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:CI(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}o(RI,"buildEventVersion1");function OI(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,Ry.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}o(OI,"buildEventVersion2");async function xI(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&&NI(e,i)){let s=await t.arrayBuffer();r=(0,Py.base64Encode)(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}o(xI,"getBodyResult");function NI(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(NI,"matchesContentType");function CI(t,e=!1){if(!e)return t;let r=(0,Iy.parse)(t),n=(0,Iy.compile)(t),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(CI,"getResourcePath")});var bn=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getHandlerUserLogFunction=_n.logBadGatewayResponses=void 0;var LI=Ge(),DI=te(),UI=[502,503,504];async function MI(t,e){if(UI.includes(t.status)){let r=LI.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(MI,"logBadGatewayResponses");_n.logBadGatewayResponses=MI;var pd;function kI(t){if(pd===void 0){let r=DI.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),pd=r}return t.log[pd]}o(kI,"getHandlerUserLogFunction");_n.getHandlerUserLogFunction=kI});var Ly=g($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.openApiSpecHandler=void 0;var Cy=D(),FI=ve(),hd=te(),HI=bn();async function qI(t,e){let r=hd.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=hd.Environment.instance,i=e.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new Cy.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=$I(s);if(!a.isValid)throw new Cy.ConfigurationError(a.error);let c;hd.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 FI.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,HI.logBadGatewayResponses)(l,e),l}o(qI,"openApiSpecHandler");$s.openApiSpecHandler=qI;var $I=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 Dy=g(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.redirectHandler=void 0;var jI=D();async function VI(t,e){let r=e.route.handler.options;if(!r.location)throw new jI.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(VI,"redirectHandler");js.redirectHandler=VI});var My=g(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.urlForwardHandler=void 0;var GI=D(),Uy=bn();function BI(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(BI,"join");async function KI(t,e){let r=(0,Uy.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 GI.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=BI(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}),m=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),(0,Uy.logBadGatewayResponses)(p,e),p}o(KI,"urlForwardHandler");Vs.urlForwardHandler=KI});var Fy=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.urlRewriteHandler=void 0;var JI=D(),ky=bn(),zI=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 WI(t,e){let r=(0,ky.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new JI.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?zI(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,ky.logBadGatewayResponses)(d,e),d}o(WI,"urlRewriteHandler");Gs.urlRewriteHandler=WI});var qy=g(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.webSocketHandler=void 0;var Hy=D(),QI=ks(),YI=xt(),ZI=te(),XI=bn();async function eA(t,e){let r=ZI.Environment.instance,n=e.route.handler.options,i=(0,XI.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new Hy.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return YI.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Hy.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 f=await(0,QI.externalServiceTunnelConfig)(c),y=new URL(c);c=new URL(`${f.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let T in f.tunnelHeaders)p.set(T,f.tunnelHeaders[T])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let f=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${f}`}}catch{}let m=JSON.stringify({url:c});return new Response(m,{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(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}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(eA,"webSocketHandler");Bs.webSocketHandler=eA});var $y=g(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.webSocketPolicyProcessor=En.getWebSocketPolicyFunctions=void 0;var tA=D(),rA=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 tA.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");En.getWebSocketPolicyFunctions=rA;var nA=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");En.webSocketPolicyProcessor=nA});var Gy=g(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.webSocketPipelineHandler=void 0;var jy=D(),iA=ks(),oA=xt(),sA=te(),aA=bn(),fd=$y();function Vy(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{o(async c=>{let u=await(0,fd.webSocketPolicyProcessor)(c,t,e,r,n,i);u!==void 0&&e.send(u)},"innerPipeline")(s).catch(n.log.error)}catch(a){n.log.error(a)}})}o(Vy,"wireUpListeners");async function cA(t,e){let r=sA.Environment.instance,n=e.route.handler.options,i=(0,aA.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new jy.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return oA.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new jy.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 S=new Headers(t.headers);if(c.startsWith("service:")){let H=await(0,iA.externalServiceTunnelConfig)(c),R=new URL(c);c=new URL(`${H.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let Y in H.tunnelHeaders)S.set(Y,H.tunnelHeaders[Y])}c=c.replace(/^(http)/,"ws");try{if(S.get("Authorization")){let H=S.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${H}`}}catch{}let M=JSON.stringify({url:c});return new Response(M,{headers:S})}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 S=await l.text(),M=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${S}'`;throw new Error(M)}let d=new WebSocketPair,[p,m]=Object.values(d),f=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${f}ms`);let y=l.webSocket;y.accept(),m.accept();let v=n.policies&&n.policies.inbound?(0,fd.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],T=n.policies&&n.policies.outbound?(0,fd.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return Vy(m,y,t,e,v),Vy(y,m,t,e,T),new Response(null,{status:101,webSocket:p})}o(cA,"webSocketPipelineHandler");Ks.webSocketPipelineHandler=cA});var By=g(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.DynaTraceLoggingPlugin=void 0;var uA=we(),md=te(),lA=Pr(),dA=Ct(),pA=yt(),yd=class extends dA.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new gd(this.options)}};Js.DynaTraceLoggingPlugin=yd;var gd=class{static{o(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#n=md.Environment.instance.loggingEnvironmentType,this.#i=md.Environment.instance.loggingEnvironmentStage,this.#r=md.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,pA.stringifyNonString)((0,lA.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 uA.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var Ky=g(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.LokiLoggingPlugin=void 0;var hA=we(),_d=te(),fA=Pr(),mA=Ct(),yA=yt(),bd=class extends mA.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new wd(this.options)}};zs.LokiLoggingPlugin=bd;var Ed=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 gA(t,e){return btoa(`${t}:${e}`)}o(gA,"createBasicDigest");var wd=class{static{o(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=gA(e.username,e.password),this.#n=_d.Environment.instance.loggingEnvironmentType,this.#i=_d.Environment.instance.loggingEnvironmentStage,this.#r=_d.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){let n=new Ed(e.level,this.#r,this.#n,this.#i,e.requestId);e.messages.forEach(i=>{let s={stream:n,message:(0,yA.stringifyNonString)((0,fA.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 hA.BatchDispatch("loki-log-transport",10,this.#s)}});var Jy=g(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.SumoLogicLoggingPlugin=void 0;var _A=we(),vd=te(),bA=Pr(),EA=Ct(),wA=yt(),Td=class extends EA.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Sd(this.options)}};Ws.SumoLogicLoggingPlugin=Td;var Sd=class{static{o(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#i=e.category,this.#o=e.name,this.#r=vd.Environment.instance.loggingEnvironmentType,this.#n=vd.Environment.instance.loggingEnvironmentStage,this.#t=vd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,wA.stringifyNonString)((0,bA.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 _A.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var Wy=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.VMWareLogInsightTransport=wn.VMWareLogInsightLoggingPlugin=void 0;var vA=D(),TA=we(),Id=te(),SA=Ct(),zy=yt(),IA="d3a5b78f-8236-48f5-b1df-4fe269d41172",Ad=class extends SA.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Qs(this.options)}};wn.VMWareLogInsightLoggingPlugin=Ad;var Qs=class{static{o(this,"VMWareLogInsightTransport")}constructor(e){let r;try{r=new URL(e.url)}catch{throw new vA.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.origin,this.#r=Id.Environment.instance.loggingEnvironmentType,this.#n=Id.Environment.instance.loggingEnvironmentStage,this.#t=Id.Environment.instance.deploymentName,this.#i=e.onMessageSending,e.fields&&(this.#o=Object.entries(e.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;async log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=(0,zy.messagesToMultilineText)(e.messages),i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#n},{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.#t&&i.fields.push({name:"environment",content:this.#t}),this.#o&&i.fields.push(...this.#o),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,zy.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#i&&(i=this.#i(i)),i}#s=async e=>{if(e.length===0)return;let r=await fetch(`${this.#e}/api/v1/events/ingest/${IA}`,{method:"POST",body:JSON.stringify(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 TA.BatchDispatch("vmware-log-insights-log-transport",10,this.#s)};wn.VMWareLogInsightTransport=Qs});var Yy=g(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.AWSLogTransport=vn.AWSLoggingPlugin=void 0;var AA=we(),Qy=te(),PA=Pr(),RA=Ct(),OA=yt(),xA=dd(),Pd=class extends RA.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ys(this.options)}};vn.AWSLoggingPlugin=Pd;var Ys=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new AA.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 xA.AwsClient({accessKeyId:e,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=Qy.Environment.instance.loggingEnvironmentType,this.environment=Qy.Environment.instance.deploymentName}async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,OA.stringifyNonString)((0,PA.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())}};vn.AWSLogTransport=Ys});var Zy=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.AWSLoggingPlugin=Oe.VMWareLogInsightLoggingPlugin=Oe.SumoLogicLoggingPlugin=Oe.LokiLoggingPlugin=Oe.GoogleCloudLoggingPlugin=Oe.DynaTraceLoggingPlugin=Oe.DataDogLoggingPlugin=void 0;var NA=Fl();Object.defineProperty(Oe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return NA.DataDogLoggingPlugin}});var CA=By();Object.defineProperty(Oe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return CA.DynaTraceLoggingPlugin}});var LA=Es();Object.defineProperty(Oe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return LA.GoogleCloudLoggingPlugin}});var DA=Ky();Object.defineProperty(Oe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return DA.LokiLoggingPlugin}});var UA=Jy();Object.defineProperty(Oe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return UA.SumoLogicLoggingPlugin}});var MA=Wy();Object.defineProperty(Oe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return MA.VMWareLogInsightLoggingPlugin}});var kA=Yy();Object.defineProperty(Oe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return kA.AWSLoggingPlugin}})});var Xy=g(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.DataDogMetricsError=ar.DataDogMetricsTransport=ar.DataDogMetricsPlugin=void 0;var FA=Ge(),HA=we(),qA=fo(),Rd=new WeakMap,$A={tags:[]},Od=class extends qA.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Zs(this.options)}static setContext(e,r){let n=Rd.get(e);n||(n=$A);let i=Object.assign({...n},r);Rd.set(e,i)}};ar.DataDogMetricsPlugin=Od;var Zs=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 HA.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,FA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),i=this.#n.concat(Rd.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 Xs(await n.text())}};ar.DataDogMetricsTransport=Zs;var Xs=class t extends Error{static{o(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};ar.DataDogMetricsError=Xs});var eg=g(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.DynaTraceMetricsError=cr.DynaTraceMetricsTransport=cr.DynatraceMetricsPlugin=void 0;var jA=Ge(),VA=we(),GA=fo(),xd=new WeakMap,BA={dimensions:[]},Nd=class extends GA.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ea(this.options)}static setContext(e,r){let n=xd.get(e);n||(n=BA);let i=Object.assign({...n},r);xd.set(e,i)}};cr.DynatraceMetricsPlugin=Nd;var ea=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 VA.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,jA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),i=this.dimensions.concat(xd.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 ta(await n.text())}};cr.DynaTraceMetricsTransport=ea;var ta=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};cr.DynaTraceMetricsError=ta});var tg=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.DynatraceMetricsPlugin=Tn.DataDogMetricsPlugin=void 0;var KA=Xy();Object.defineProperty(Tn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return KA.DataDogMetricsPlugin}});var JA=eg();Object.defineProperty(Tn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return JA.DynatraceMetricsPlugin}})});var rg=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.AuditLogDataStaxProvider=void 0;var Cd=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)})}))}};ra.AuditLogDataStaxProvider=Cd});var ig=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.AuditLogPlugin=void 0;var zA=Ot(),WA=we(),Ld=class extends zA.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Dd(e,this.#e,this.#t)}};na.AuditLogPlugin=Ld;var ng=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),QA={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Dd=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...QA};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 WA.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?ng(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?ng(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(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var ia=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.getValueFromRequestUser=Sn.statusCodesStringToNumberArray=void 0;var og=D(),sg=new Map;function YA(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=sg.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 sg.set(t,n),n}o(YA,"statusCodesStringToNumberArray");Sn.statusCodesStringToNumberArray=YA;function ZA(t,e,r){if(!e.startsWith("."))throw new og.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 og.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(ZA,"getValueFromRequestUser");Sn.getValueFromRequestUser=ZA});var dg=g(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.AmberfloMeteringInboundPolicy=In.AmberfloMeteringPolicy=void 0;var ag=D(),XA=we(),cg=ia(),lg=new WeakMap,ug={},Ud=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){lg.set(e,r)}};In.AmberfloMeteringPolicy=Ud;async function eP(t,e,r,n){if(!r.statusCodes)throw new ag.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,cg.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=lg.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new ag.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,cg.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)},m=ug[r.apiKey];if(!m){let f=r.apiKey,y=t.headers.get("zm-test-id")??"";m=new XA.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});S.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),ug[f]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}o(eP,"AmberfloMeteringInboundPolicy");In.AmberfloMeteringInboundPolicy=eP});var ur=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.getPolicyCacheName=void 0;function tP(t){return`zuplo-policy-${t}`}o(tP,"getPolicyCacheName");oa.getPolicyCacheName=tP});var mg=g(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.ApiAuthKeyInboundPolicy=An.ApiKeyInboundPolicy=void 0;var rP=ur(),nP=br(),pg=rd(),Md=D(),iP=xt(),kd=Ge(),Fd=te(),oP=_s(),hg="key-metadata-cache-type";function sP(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(sP,"getKeyValue");async function fg(t,e,r,n){if(!r.bucketName)if(pg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=pg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new Md.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 Md.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:iP.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=sP(a,i);if(!c||c==="")return s("No key present");let u=await aP(c),l=new nP.MemoryZoneReadThroughCache((0,rP.getPolicyCacheName)(n),{logger:kd.SystemLogMap.getLogger(e)}),d=await l.get(u);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==hg&&kd.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${d.typeId}'`,d),s("Authorization Failed");let p={key:c},m=await(0,oP.fetchRetry)({retryDelayMs:5,retries:2,logger:kd.SystemLogMap.getLogger(e)},`${Fd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Fd.Environment.instance.deploymentName??"unknown","User-Agent":Fd.Environment.instance.systemUserAgent},body:JSON.stringify(p)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),T=JSON.parse(v);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new Md.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${m.status}`)}let f=await m.json(),y={isValid:!0,typeId:hg,user:{sub:f.name,data:f.metadata}};return t.user=y.user,l.put(u,y,i.cacheTtlSeconds),t}o(fg,"ApiKeyInboundPolicy");An.ApiKeyInboundPolicy=fg;async function aP(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(aP,"hashValue");An.ApiAuthKeyInboundPolicy=fg});var lr=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.OpenIdJwtInboundPolicy=void 0;var qd=(ys(),Ji(ms)),$d=D(),cP=ve(),Hd={},uP=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new $d.ConfigurationError("Invalid State - jwkUrl not set");Hd[e.jwkUrl]||(Hd[e.jwkUrl]=(0,qd.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,qd.jwtVerify)(t,Hd[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),lP=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,qd.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),dP=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(m=>cP.HttpProblems.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new $d.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new $d.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?uP:lP,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 m=i.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(f){let y=new URL(t.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,f):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,f),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");sa.OpenIdJwtInboundPolicy=dP});var yg=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.Auth0JwtInboundPolicy=void 0;var pP=lr(),hP=o(async(t,e,r,n)=>(0,pP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");aa.Auth0JwtInboundPolicy=hP});var gg=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.BasicAuthInboundPolicy=void 0;var fP=ve(),mP=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>fP.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 m=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===f);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");ca.BasicAuthInboundPolicy=mP});var _g=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.CachingInboundPolicy=void 0;var yP=ur(),gP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function _P(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(_P,"digestMessage");var bP=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 _P(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 EP(t,e,r,n){let i=await caches.open(`${(0,yP.getPolicyCacheName)(n)}-${r.cacheId??""}`),s=r?.cacheHttpMethods?.map(u=>u.toUpperCase())??["GET"],a=await bP(t,r),c=await i.match(a);return c||(e.addEventListener("responseSent",u=>{try{let l=r.statusCodes??[200,206,301,302,303,404,410],d=u.response.clone();if(!l.includes(d.status)||!s.includes(t.method.toUpperCase()))return;let p=r?.expirationSecondsTtl??60,m=new Response(d.body,d);gP.forEach(f=>m.headers.delete(f)),m.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(i.put(a,m))}catch(l){e.log.error(`Error in caching-inbound-policy '${n}': "${l.message}"`,l)}}),t)}o(EP,"CachingInboundPolicy");ua.CachingInboundPolicy=EP});var bg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.ChangeMethodInboundPolicy=void 0;var wP=D(),vP=Yn(),TP=o(async(t,e,r,n)=>{if(!r.method)throw new wP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new vP.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");la.ChangeMethodInboundPolicy=TP});var Eg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.ClearHeadersInboundPolicy=void 0;var SP=ke(),IP=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 SP.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");da.ClearHeadersInboundPolicy=IP});var wg=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.ClearHeadersOutboundPolicy=void 0;var AP=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");pa.ClearHeadersOutboundPolicy=AP});var Tg=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.CognitoJwtInboundPolicy=void 0;var vg=D(),PP=lr(),RP=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new vg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new vg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,PP.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");ha.CognitoJwtInboundPolicy=RP});var Ig=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.CompositeInboundPolicy=void 0;var OP=D(),xP=dn(),Sg=Zn(),NP=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new OP.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=xP.Gateway.instance,s=(0,Sg.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Sg.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");fa.CompositeInboundPolicy=NP});var dr=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.optionValidator=void 0;var Ei=D();function CP(t,e){let r=o((s,a,c)=>{let u=t[s];if(!(c&&u===void 0)){if(u===void 0)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(CP,"optionValidator");ma.optionValidator=CP});var Ag=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.FirebaseJwtInboundPolicy=void 0;var LP=dr(),DP=lr(),UP=o(async(t,e,r,n)=>((0,LP.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,DP.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");ya.FirebaseJwtInboundPolicy=UP});var Pg=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.FormDataToJsonInboundPolicy=void 0;var MP=ke(),kP=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 MP.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");ga.FormDataToJsonInboundPolicy=kP});var Rg=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.GeoFilterInboundPolicy=void 0;var FP=D(),HP=ve(),Pn="__unknown__",qP=o(async(t,e,r,n)=>{let i={allow:{countries:On(r.allow?.countries,"allow.countries",n),regionCodes:On(r.allow?.regionCodes,"allow.regionCode",n),asns:On(r.allow?.asns,"allow.asOrganization",n)},block:{countries:On(r.block?.countries,"block.countries",n),regionCodes:On(r.block?.regionCodes,"block.regionCode",n),asns:On(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Pn,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Pn,c=e.incomingRequestProperties.asn?.toString()??Pn,u=i.ignoreUnknown&&s===Pn,l=i.ignoreUnknown&&a===Pn,d=i.ignoreUnknown&&c===Pn,p=i.allow.countries,m=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||m.length>0&&!m.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return Rn(t,e,n,s,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Rn(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");_a.GeoFilterInboundPolicy=qP;function Rn(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),HP.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(Rn,"blockedResponse");function On(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 FP.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(On,"toLowerStringArray")});var Og=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.JWTScopeValidationInboundPolicy=void 0;var $P=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");ba.JWTScopeValidationInboundPolicy=$P});var Ng=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.MockApiInboundPolicy=void 0;var jP=ve(),VP=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return jd(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 jd(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(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 xg(a[c])}else return a.length>0?xg(a[0]):jd(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");Ea.MockApiInboundPolicy=VP;function xg(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.append("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(xg,"generateResponse");var jd=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return jP.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Mg=g(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.MoesifInboundPolicy=xn.setMoesifContext=void 0;var GP=D(),BP=we(),KP="Incoming",JP={logRequestBody:!0,logResponseBody:!0};function Cg(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(Cg,"headersToObject");function Lg(){return new Date().toISOString()}o(Lg,"timestamp");var Vd=new WeakMap,zP={};function WP(t,e){let r=Vd.get(t);r||(r=zP);let n=Object.assign({...r},e);Vd.set(t,n)}o(WP,"setMoesifContext");xn.setMoesifContext=WP;async function Dg(t,e){let r=t.headers.get("content-type"),n=t.clone();if(r&&r.indexOf("json")!==0)try{return await n.json()}catch(s){e.log.error(s)}let i=await n.text();return e.log.debug({textBody:i}),i}o(Dg,"readBody");var QP={},Gd;function Ug(){if(!Gd)throw new GP.RuntimeError("Invalid State - no _lastLogger");return Gd}o(Ug,"getLastLogger");function YP(t){let e=QP[t];return e||(e=new BP.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);Ug().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||Ug().error({status:i.status,body:await i.text()})})),e}o(YP,"getDispatcher");async function ZP(t,e,r,n){Gd=e.log;let i=Lg(),s=Object.assign(JP,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Dg(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=YP(s.applicationId),d=t.headers.get("true-client-ip"),p=Vd.get(e)??{},m={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Cg(t.headers)},f=s.logResponseBody?await Dg(c,e):void 0,y={time:Lg(),status:c.status,headers:Cg(c.headers),body:f},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:KP};l.enqueue(v),e.waitUntil(l.waitUntilFlushed())}),t}o(ZP,"MoesifInboundPolicy");xn.MoesifInboundPolicy=ZP});var kg=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.OktaJwtInboundPolicy=void 0;var XP=lr(),eR=o(async(t,e,r,n)=>(0,XP.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");wa.OktaJwtInboundPolicy=eR});var Fg=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.PropelAuthJwtInboundPolicy=void 0;var tR=(ys(),Ji(ms)),rR=lr(),Bd,nR=o(async(t,e,r,n)=>{if(!Bd)try{Bd=await(0,tR.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,rR.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Bd,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");va.PropelAuthJwtInboundPolicy=nR});var Hg=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var $e=Jr(),et=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};G.ValidationError=et;var wi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};G.ArgumentUndefinedError=wi;var vi=class extends et{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};G.ArgumentTypeError=vi;function iR(t,e){if((0,$e.isUndefined)(t))throw new wi(e)}o(iR,"throwIfUndefined");G.throwIfUndefined=iR;function Kd(t,e){if((0,$e.isUndefinedOrNull)(t))throw new wi(e)}o(Kd,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Kd;function oR(t,e){if(Kd(t,e),!(0,$e.isString)(t))throw new vi(e,"string")}o(oR,"throwIfNotString");G.throwIfNotString=oR;function sR(t,e){if(Kd(t,e),!(0,$e.isNumber)(t))throw new vi(e,"number")}o(sR,"throwIfNotNumber");G.throwIfNotNumber=sR;var Ti=class extends et{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};G.OptionUndefinedError=Ti;var Nn=class extends et{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=Nn;function aR(t,e,r,n){if((0,$e.isUndefined)(n))throw new Ti(t,e,r)}o(aR,"throwIfOptionUndefined");G.throwIfOptionUndefined=aR;function Ta(t,e,r,n){if((0,$e.isUndefinedOrNull)(n))throw new Ti(t,e,r)}o(Ta,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Ta;function cR(t,e,r,n){if(Ta(t,e,r,n),!(0,$e.isString)(n))throw new Nn(t,e,r,"string")}o(cR,"throwIfOptionNotString");G.throwIfOptionNotString=cR;function uR(t,e,r,n){if(Ta(t,e,r,n),!(0,$e.isNumber)(n))throw new Nn(t,e,r,"number")}o(uR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=uR;function lR(t,e,r,n){if(Ta(t,e,r,n),!(0,$e.isObject)(n))throw new Nn(t,e,r,"object")}o(lR,"throwIfOptionNotObject");G.throwIfOptionNotObject=lR;function dR(t,e){if((0,$e.isUndefined)(t))throw new et(e)}o(dR,"throwIfStateUndefined");G.throwIfStateUndefined=dR;function Sa(t,e){if((0,$e.isUndefinedOrNull)(t))throw new et(e)}o(Sa,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=Sa;function pR(t,e){if(Sa(t,e),!(0,$e.isString)(t))throw new et(e);return!0}o(pR,"throwIfStateNotString");G.throwIfStateNotString=pR;function hR(t,e){if(Sa(t,e),!(0,$e.isNumber)(t))throw new et(e);return!0}o(hR,"throwIfStateNotNumber");G.throwIfStateNotNumber=hR;function fR(t,e){if(Sa(t,e),!(0,$e.isObject)(t))throw new et(e);return!0}o(fR,"throwIfStateNotObject");G.throwIfStateNotObject=fR});var qg=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.InMemoryRedisClient=Cn.StandardRedisClient=void 0;var Jd=D(),Ia=Hg(),zd=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,Ia.throwIfNotString)(e,"redisClientUrl"),(0,Ia.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,Ia.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 Jd.SystemError("Redis client failed with 401: Unauthorized"):new Jd.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Cn.StandardRedisClient=zd;var Wd=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Ia.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 Jd.SystemError("The in-memory redis client only supports /rate-limit calls")}};Cn.InMemoryRedisClient=Wd});var Bg=g(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.RateLimitInboundPolicy=void 0;var mR=wr(),yR=ke(),gR=ur(),Mt=D(),_R=ve(),$g=Ge(),Si=te(),jg=qg(),Vg=Jr(),Aa=(0,mR.debug)("zuplo:policies:RateLimitInboundPolicy"),bR="strict",ER=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),wR=o(async t=>({key:`ip-${ER(t)}`}),"getIP"),vR=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),TR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Pa;function SR(t,e){let r;if(Pa)return Pa;if(Si.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new jg.InMemoryRedisClient,Pa=r,r;let{authApiJWT:n,redisURL:i}=Si.Environment.instance;if(!(0,Vg.isString)(i))throw new Mt.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,Vg.isString)(n))throw new Mt.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=jg.StandardRedisClient.initialize(i,n,Si.Environment.instance.deploymentName??"unknown",Si.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new Mt.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Pa=r,r}o(SR,"getRedisClient");async function Gg(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(Gg,"getCountAndUpdateExpiry");function IR(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new Mt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new Mt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new Mt.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 Mt.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 Mt.RuntimeError(u)}return c},"outerFunction")}o(IR,"wrapUserFunction");var AR="Retry-After",PR=o(async(t,e,r,n)=>{let i=Date.now(),s=$g.SystemLogMap.getLogger(e),a=o((u,l)=>{if(r.throwOnFailure)throw new Mt.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[AR]=l.toString()),_R.HttpProblems.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:IR(r,n),user:vR,ip:wR,all:TR}[r.rateLimitBy],d=await l(t,e,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=SR(n,s),S=`bucket/${Si.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??bR)==="async"){let R=new yR.ZoneCache((0,gR.getPolicyCacheName)(n),{logger:$g.SystemLogMap.getLogger(e)}),ne=Gg(S,f,v,s,e.requestId),Y=await R.get(S);if(Y!==void 0&&Y<=Date.now()){Aa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let fe=Math.round((Y-Date.now())/1e3);return c(y,fe)}return e.addEventListener("responseSending",fe=>{try{let Me=fe,E=Me.mutableResponse;Me.mutableResponse=(async()=>{let F=await ne;if(F.count>m){let Ye=Date.now()+F.ttlSeconds*1e3;return R.put(S,Ye,F.ttlSeconds).catch(Bi=>{throw s.error(Bi),Bi}),Aa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(y,F.ttlSeconds)}return E})()}catch(Me){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,Me)}}),t}let H=await Gg(S,f,v,s,e.requestId);return H.count>m?(Aa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(y,H.ttlSeconds)):t}catch(u){return a(u.message,u),t}finally{let u=Date.now()-i;Aa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Ra.RateLimitInboundPolicy=PR});var Wg=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.ReadmeMetricsInboundPolicy=void 0;var RR=we(),Qd=te(),Kg=ia(),Yd;function Jg(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(Jg,"headersToNameValuePairs");function OR(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(OR,"queryToNameValueParis");function xR(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(xR,"parseIntOrUndefined");var zg={};async function NR(t,e,r,n){let i=new Date,s=Date.now();return Yd||(Yd={name:"zuplo",version:Qd.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Qd.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,Kg.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Qd.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Yd,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:Jg(t.headers),queryString:OR(t.query)},response:{status:a.status,statusText:a.statusText,headers:Jg(a.headers),content:{size:xR(t.headers.get("content-length"))}}}]}}},d=zg[r.apiKey];if(!d){let p=r.apiKey;d=new RR.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(m),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(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),zg[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(NR,"ReadmeMetricsInboundPolicy");Oa.ReadmeMetricsInboundPolicy=NR});var Qg=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.RemoveHeadersInboundPolicy=void 0;var CR=ke(),LR=D(),DR=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new LR.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 CR.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");xa.RemoveHeadersInboundPolicy=DR});var Yg=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.RemoveHeadersOutboundPolicy=void 0;var UR=D(),MR=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new UR.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");Na.RemoveHeadersOutboundPolicy=MR});var Zg=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.RemoveQueryParamsInboundPolicy=void 0;var kR=ke(),FR=D(),HR=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new FR.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 kR.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");Ca.RemoveQueryParamsInboundPolicy=HR});var Xg=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.ReplaceStringOutboundPolicy=void 0;var qR=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");La.ReplaceStringOutboundPolicy=qR});var t_=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.RequestSizeLimitInboundPolicy=void 0;var e_=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),$R=o(async(t,e,r)=>{let n=r.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(t.method))return t;let i=t.headers.get("content-length"),s=i!==null?parseInt(i):void 0;return s&&!isNaN(s)&&s>r.maxSizeInBytes?e_():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?e_():t},"RequestSizeLimitInboundPolicy");Da.RequestSizeLimitInboundPolicy=$R});var Ua=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function jR(t,e,r){return`_${Lr(t+"_"+e+"_"+r)}`}o(jR,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=jR;function VR(t,e,r,n){return`_${Lr(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(VR,"getIdForParameterSchema");tt.getIdForParameterSchema=VR;function GR(t,e,r){return`_${Lr(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Lr(r.toLowerCase())}`}o(GR,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=GR;function BR(t,e){return`_${Lr(t)}__${Lr(e)}`}o(BR,"getIdForRefSchema");tt.getIdForRefSchema=BR;function Lr(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(Lr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Lr});var Ii=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getErrorsFromValidator=Ce.shouldReject=Ce.shouldLog=Ce.logErrors=Ce.validateParameters=Ce.getParametersForOperation=void 0;var KR=dn(),Ma=Dr(),JR=Ua(),zR=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");Ce.getParametersForOperation=zR;var WR=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{if(u.required&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,JR.getIdForParameterSchema)(r,n,i,u.name),d=KR.Gateway.instance.schemaValidator[l],p=d(e[u.name]),m=(0,Ce.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Ce.validateParameters=WR;var QR=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");Ce.logErrors=QR;var YR=o(t=>t===Ma.ValidationOptions.logOnly||t===Ma.ValidationOptions.rejectAndLog,"shouldLog");Ce.shouldLog=YR;var ZR=o(t=>t===Ma.ValidationOptions.rejectOnly||t===Ma.ValidationOptions.rejectAndLog,"shouldReject");Ce.shouldReject=ZR;var XR=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");Ce.getErrorsFromValidator=XR});var r_=g(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.handleBodyValidation=void 0;var eO=dn(),tO=Dr(),ka=ve(),rO=Ua(),Ke=Ii();async function nO(t,e,r){if(!r.validateBody||r.validateBody===tO.ValidationOptions.none)return;let n;try{n=await e.clone().json()}catch(f){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=ka.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",y,[n],f),(0,Ke.shouldReject)(r.validateBody))return v}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=ka.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.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,rO.getIdForRequestBodySchema)(t.route.path,e.method,i),c=eO.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=ka.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Ke.getErrorsFromValidator)(l),m=ka.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",d,[n],p),(0,Ke.shouldReject)(r.validateBody))return m}o(nO,"handleBodyValidation");Fa.handleBodyValidation=nO});var n_=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.handleHeadersValidation=void 0;var iO=Dr(),oO=ve(),Ai=Ii();function sO(t,e,r){if(!r.validateHeaders||r.validateHeaders===iO.ValidationOptions.none)return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,Ai.getParametersForOperation)(t),s=(0,Ai.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=oO.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Ai.shouldLog)(r.validateHeaders)&&(0,Ai.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Ai.shouldReject)(r.validateHeaders))return c}}o(sO,"handleHeadersValidation");Ha.handleHeadersValidation=sO});var i_=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.handlePathParameterValidation=void 0;var aO=Dr(),cO=ve(),Pi=Ii();function uO(t,e,r){if(!r.validatePathParameters||r.validatePathParameters===aO.ValidationOptions.none)return;let n=(0,Pi.getParametersForOperation)(t),i=(0,Pi.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=cO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Pi.shouldLog)(r.validatePathParameters)&&(0,Pi.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Pi.shouldReject)(r.validatePathParameters))return a}}o(uO,"handlePathParameterValidation");qa.handlePathParameterValidation=uO});var o_=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.handleQueryParameterValidation=void 0;var lO=Dr(),dO=ve(),Ri=Ii();function pO(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters===lO.ValidationOptions.none)return;let n=(0,Ri.getParametersForOperation)(t),i=(0,Ri.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=dO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ri.shouldLog)(r.validateQueryParameters)&&(0,Ri.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ri.shouldReject)(r.validateQueryParameters))return a}}o(pO,"handleQueryParameterValidation");$a.handleQueryParameterValidation=pO});var Dr=g(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.SchemaBasedRequestValidation=kt.RequestValidationInboundPolicy=kt.ValidationOptions=void 0;var hO=r_(),fO=n_(),mO=i_(),yO=o_(),s_;(function(t){t.none="none",t.logOnly="log-only",t.rejectAndLog="reject-and-log",t.rejectOnly="reject-only"})(s_||(kt.ValidationOptions=s_={}));var gO=o(async(t,e,r)=>{let n=(0,yO.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,mO.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,fO.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,hO.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");kt.RequestValidationInboundPolicy=gO;kt.SchemaBasedRequestValidation=kt.RequestValidationInboundPolicy});var a_=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.RequireOriginInboundPolicy=void 0;var _O=ke(),bO=D(),EO=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new bO.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 _O.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");ja.RequireOriginInboundPolicy=EO});var c_=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.SetBodyInboundPolicy=void 0;var wO=ke(),vO=o(async(t,e,r)=>new wO.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Va.SetBodyInboundPolicy=vO});var l_=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.SetHeadersInboundPolicy=void 0;var TO=ke(),u_=D(),SO=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new u_.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 u_.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 TO.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Ga.SetHeadersInboundPolicy=SO});var p_=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetHeadersOutboundPolicy=void 0;var d_=D(),IO=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new d_.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 d_.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");Ba.SetHeadersOutboundPolicy=IO});var f_=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SetQueryParamsInboundPolicy=void 0;var AO=ke(),h_=D(),PO=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new h_.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 h_.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 AO.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Ka.SetQueryParamsInboundPolicy=PO});var m_=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SetStatusOutboundPolicy=void 0;var RO=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");Ja.SetStatusOutboundPolicy=RO});var y_=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.SleepInboundPolicy=void 0;var OO=D(),xO=o(async t=>new Promise((r,n)=>{setTimeout(r,t)}),"sleep"),NO=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new OO.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await xO(r.sleepInMs),t},"SleepInboundPolicy");za.SleepInboundPolicy=NO});var __=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.SupabaseJwtInboundPolicy=void 0;var CO=ke(),g_=D(),LO=ve(),DO=dr(),UO=lr(),MO=o(async(t,e,r,n)=>{(0,DO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,UO.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof CO.ZuploRequest))throw new g_.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 g_.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?LO.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Wa.SupabaseJwtInboundPolicy=MO});var E_=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var kO=ur(),FO=br(),b_=D(),HO=Ge(),qO=_s(),$O=dr(),jO=o(async(t,e,r,n)=>{(0,$O.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=new FO.MemoryZoneReadThroughCache((0,kO.getPolicyCacheName)(n),{logger:HO.SystemLogMap.getLogger(e)}),s=await i.get(n);if(!s){let a=await VO(r,e);i.put(n,a.access_token,a.expires_in-(r.expirationOffsetSeconds??300)),s=a.access_token}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Qa.UpstreamAzureAdServiceAuthInboundPolicy=jO;async function VO(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,qO.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 b_.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 b_.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(VO,"getAccessToken")});var v_=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var GO=ur(),BO=br(),KO=D(),JO=Ge(),Zd=cn(),zO=dr(),w_="https://accounts.google.com/o/oauth2/token",Xd,WO=o(async(t,e,r,n)=>{(0,zO.optionValidator)(r,n).required("serviceAccountJson","string"),Xd||(Xd=await Zd.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=new BO.MemoryZoneReadThroughCache((0,GO.getPolicyCacheName)(n),{logger:JO.SystemLogMap.getLogger(e)}),a=await s.get(n);if(!a){let c=await(0,Zd.getTokenFromGcpServiceAccount)({serviceAccount:Xd,audience:w_,payload:i}),u=await(0,Zd.exchangeGgpJwtForIdToken)(w_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u.access_token)throw new KO.RuntimeError("Invalid OAuth response from Firebase");a=u.access_token,s.put(n,a,(u.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Ya.UpstreamFirebaseAdminAuthInboundPolicy=WO});var T_=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.sha256=void 0;async function QO(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(QO,"sha256");Za.sha256=QO});var S_=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.UpstreamFirebaseUserAuthInboundPolicy=void 0;var YO=ur(),ZO=br(),Ln=D(),XO=Ge(),e0=T_(),ep=cn(),t0=ia(),r0=dr(),n0="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",i0=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],tp,o0=o(async(t,e,r,n)=>{if((0,r0.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Ln.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let d in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,d)){if(i0.indexOf(d)!==-1)throw new Ln.ConfigurationError(`Developer claim "${d}" is reserved and cannot be specified.`);i[d]=r.developerClaims[d]}}tp||(tp=await ep.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new Ln.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 Ln.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,t0.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Ln.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=new ZO.MemoryZoneReadThroughCache((0,YO.getPolicyCacheName)(n),{logger:XO.SystemLogMap.getLogger(e)}),c={uid:s,claims:i},u=await(0,e0.sha256)(JSON.stringify(c)),l=await a.get(u);if(!l){let d=await(0,ep.getTokenFromGcpServiceAccount)({serviceAccount:tp,audience:n0,payload:c}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,m=await(0,ep.exchangeFirebaseJwtForIdToken)(p,d,{retries:r.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new Ln.RuntimeError("Invalid token response from Firebase");l=m.idToken,a.put(u,l,(m.expiresIn?parseInt(m.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");Xa.UpstreamFirebaseUserAuthInboundPolicy=o0});var A_=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.UpstreamGcpJwtInboundPolicy=void 0;var I_=cn(),s0=dr(),rp,a0=o(async(t,e,r,n)=>{(0,s0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),rp||(rp=await I_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,I_.getTokenFromGcpServiceAccount)({serviceAccount:rp,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");ec.UpstreamGcpJwtInboundPolicy=a0});var O_=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.UpstreamGcpServiceAuthInboundPolicy=void 0;var P_=ur(),c0=zc(),u0=br(),l0=D(),np=cn(),d0=dr(),R_="https://www.googleapis.com/oauth2/v4/token",ip,p0=o(async(t,e,r,n)=>{(0,d0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),ip||(ip=await np.GcpServiceAccount.init(r.serviceAccountJson));let i;r.useMemoryCacheOnly?i=new c0.MemoryCache((0,P_.getPolicyCacheName)(n)):i=new u0.MemoryZoneReadThroughCache((0,P_.getPolicyCacheName)(n),e);let s=await i.get(n);if(!s){let a=await(0,np.getTokenFromGcpServiceAccount)({serviceAccount:ip,audience:R_,payload:{target_audience:`${r.audience}`}}),{id_token:c}=await(0,np.exchangeGgpJwtForIdToken)(R_,a,{retries:r.tokenRetries??3,retryDelayMs:10});if(!c)throw new l0.RuntimeError("Invalid token response from GCP");s=c,i.put(n,s,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamGcpServiceAuthInboundPolicy");tc.UpstreamGcpServiceAuthInboundPolicy=p0});var N_=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.ValidateJsonSchemaInbound=void 0;var h0=D(),x_=ve(),f0=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return x_.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 h0.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 x_.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");rc.ValidateJsonSchemaInbound=f0});var C_=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.serialize=pr.ContentTypes=void 0;pr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function m0(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(pr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(pr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(m0,"serialize");pr.serialize=m0});var L_=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ServiceProviderImpl=void 0;var y0=D(),op=class t{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,r){if(this.services.get(e))throw new y0.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)}};nc.ServiceProviderImpl=op});var D_=g(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var g0={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"};sp.default=g0});var ke=g(h=>{"use strict";var _0=h&&h.__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]}),U_=h&&h.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_0(e,t,r)},b0=h&&h.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(h,"__esModule",{value:!0});h.RemoveHeadersInboundPolicy=h.ReadmeMetricsInboundPolicy=h.RateLimitInboundPolicy=h.BasicRateLimitInboundPolicy=h.PropelAuthJwtInboundPolicy=h.OpenIdJwtInboundPolicy=h.OktaJwtInboundPolicy=h.setMoesifContext=h.MoesifInboundPolicy=h.MockApiInboundPolicy=h.JWTScopeValidationInboundPolicy=h.GeoFilterInboundPolicy=h.FormDataToJsonInboundPolicy=h.FirebaseJwtInboundPolicy=h.CompositeInboundPolicy=h.CognitoJwtInboundPolicy=h.ClearHeadersOutboundPolicy=h.ClearHeadersInboundPolicy=h.ChangeMethodInboundPolicy=h.CachingInboundPolicy=h.BasicAuthInboundPolicy=h.Auth0JwtInboundPolicy=h.ApiKeyInboundPolicy=h.ApiAuthKeyInboundPolicy=h.AmberfloMeteringPolicy=h.AmberfloMeteringInboundPolicy=h.AuditLogPlugin=h.AuditLogDataStaxProvider=h.HttpStatusCode=h.webSocketPipelineHandler=h.webSocketHandler=h.urlRewriteHandler=h.urlForwardHandler=h.redirectHandler=h.openApiSpecHandler=h.awsLambdaHandler=h.AwsLambdaHandlerExtensions=h.purgeGatewayCache=h.Handler=h.originalFetch=h.ConfigurationError=h.isZuploReadableEnvVariableName=h.isRestrictedEnvVariableName=h.environment=h.ContextLocalStorage=h.ResponseSentEvent=h.ResponseSendingEvent=h.VALID_COMPATIBILITY_DATES=h.ZoneCache=h.MemoryZoneReadThroughCache=void 0;h.sanitizedIdentifierName=h.getRawOperationDataIdentifierName=h.getIdForRequestBodySchema=h.getIdForRefSchema=h.getIdForParameterSchema=h.SystemLogMap=h.httpStatuses=h.SYSTEM_LOGGER=h.API_KEY=h.ServiceProviderImpl=h.serialize=h.ContentTypes=h.Router=h.LookupResult=h.SystemRouteName=h.ZuploRequest=h.ProblemResponseFormatter=h.HttpProblems=h.ValidateJsonSchemaInbound=h.UpstreamGcpServiceAuthInboundPolicy=h.UpstreamGcpJwtInboundPolicy=h.UpstreamFirebaseUserAuthInboundPolicy=h.UpstreamFirebaseAdminAuthInboundPolicy=h.UpstreamAzureAdServiceAuthInboundPolicy=h.SupabaseJwtInboundPolicy=h.SleepInboundPolicy=h.SetStatusOutboundPolicy=h.SetQueryParamsInboundPolicy=h.SetHeadersOutboundPolicy=h.SetHeadersInboundPolicy=h.SetBodyInboundPolicy=h.RequireOriginInboundPolicy=h.SchemaBasedRequestValidation=h.RequestValidationInboundPolicy=h.RequestSizeLimitInboundPolicy=h.ReplaceStringOutboundPolicy=h.RemoveQueryParamsInboundPolicy=h.RemoveHeadersOutboundPolicy=void 0;$p();var E0=br();Object.defineProperty(h,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return E0.MemoryZoneReadThroughCache}});var w0=Yc();Object.defineProperty(h,"ZoneCache",{enumerable:!0,get:function(){return w0.ZoneCache}});var v0=Vp();Object.defineProperty(h,"VALID_COMPATIBILITY_DATES",{enumerable:!0,get:function(){return v0.VALID_COMPATIBILITY_DATES}});var M_=vr();Object.defineProperty(h,"ResponseSendingEvent",{enumerable:!0,get:function(){return M_.ResponseSendingEvent}});Object.defineProperty(h,"ResponseSentEvent",{enumerable:!0,get:function(){return M_.ResponseSentEvent}});var T0=oy();Object.defineProperty(h,"ContextLocalStorage",{enumerable:!0,get:function(){return T0.ContextLocalStorage}});var ap=rd();Object.defineProperty(h,"environment",{enumerable:!0,get:function(){return ap.environment}});Object.defineProperty(h,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return ap.isRestrictedEnvVariableName}});Object.defineProperty(h,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return ap.isZuploReadableEnvVariableName}});var S0=D();Object.defineProperty(h,"ConfigurationError",{enumerable:!0,get:function(){return S0.ConfigurationError}});var I0=nd();Object.defineProperty(h,"originalFetch",{enumerable:!0,get:function(){return I0.originalFetch}});var k_=fy();Object.defineProperty(h,"Handler",{enumerable:!0,get:function(){return k_.Handler}});Object.defineProperty(h,"purgeGatewayCache",{enumerable:!0,get:function(){return k_.purgeGatewayCache}});var F_=Ny();Object.defineProperty(h,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return F_.AwsLambdaHandlerExtensions}});Object.defineProperty(h,"awsLambdaHandler",{enumerable:!0,get:function(){return F_.awsLambdaHandler}});var A0=Ly();Object.defineProperty(h,"openApiSpecHandler",{enumerable:!0,get:function(){return A0.openApiSpecHandler}});var P0=Dy();Object.defineProperty(h,"redirectHandler",{enumerable:!0,get:function(){return P0.redirectHandler}});var R0=My();Object.defineProperty(h,"urlForwardHandler",{enumerable:!0,get:function(){return R0.urlForwardHandler}});var O0=Fy();Object.defineProperty(h,"urlRewriteHandler",{enumerable:!0,get:function(){return O0.urlRewriteHandler}});var x0=qy();Object.defineProperty(h,"webSocketHandler",{enumerable:!0,get:function(){return x0.webSocketHandler}});var N0=Gy();Object.defineProperty(h,"webSocketPipelineHandler",{enumerable:!0,get:function(){return N0.webSocketPipelineHandler}});var C0=yu();Object.defineProperty(h,"HttpStatusCode",{enumerable:!0,get:function(){return C0.HttpStatusCode}});U_(Zy(),h);U_(tg(),h);var L0=rg();Object.defineProperty(h,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return L0.AuditLogDataStaxProvider}});var D0=ig();Object.defineProperty(h,"AuditLogPlugin",{enumerable:!0,get:function(){return D0.AuditLogPlugin}});var H_=dg();Object.defineProperty(h,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringInboundPolicy}});Object.defineProperty(h,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return H_.AmberfloMeteringPolicy}});var q_=mg();Object.defineProperty(h,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiAuthKeyInboundPolicy}});Object.defineProperty(h,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return q_.ApiKeyInboundPolicy}});var U0=yg();Object.defineProperty(h,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return U0.Auth0JwtInboundPolicy}});var M0=gg();Object.defineProperty(h,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return M0.BasicAuthInboundPolicy}});var k0=_g();Object.defineProperty(h,"CachingInboundPolicy",{enumerable:!0,get:function(){return k0.CachingInboundPolicy}});var F0=bg();Object.defineProperty(h,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return F0.ChangeMethodInboundPolicy}});var H0=Eg();Object.defineProperty(h,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return H0.ClearHeadersInboundPolicy}});var q0=wg();Object.defineProperty(h,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return q0.ClearHeadersOutboundPolicy}});var $0=Tg();Object.defineProperty(h,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return $0.CognitoJwtInboundPolicy}});var j0=Ig();Object.defineProperty(h,"CompositeInboundPolicy",{enumerable:!0,get:function(){return j0.CompositeInboundPolicy}});var V0=Ag();Object.defineProperty(h,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return V0.FirebaseJwtInboundPolicy}});var G0=Pg();Object.defineProperty(h,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return G0.FormDataToJsonInboundPolicy}});var B0=Rg();Object.defineProperty(h,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return B0.GeoFilterInboundPolicy}});var K0=Og();Object.defineProperty(h,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return K0.JWTScopeValidationInboundPolicy}});var J0=Ng();Object.defineProperty(h,"MockApiInboundPolicy",{enumerable:!0,get:function(){return J0.MockApiInboundPolicy}});var $_=Mg();Object.defineProperty(h,"MoesifInboundPolicy",{enumerable:!0,get:function(){return $_.MoesifInboundPolicy}});Object.defineProperty(h,"setMoesifContext",{enumerable:!0,get:function(){return $_.setMoesifContext}});var z0=kg();Object.defineProperty(h,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return z0.OktaJwtInboundPolicy}});var W0=lr();Object.defineProperty(h,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return W0.OpenIdJwtInboundPolicy}});var Q0=Fg();Object.defineProperty(h,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return Q0.PropelAuthJwtInboundPolicy}});var j_=Bg();Object.defineProperty(h,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});Object.defineProperty(h,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return j_.RateLimitInboundPolicy}});var Y0=Wg();Object.defineProperty(h,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return Y0.ReadmeMetricsInboundPolicy}});var Z0=Qg();Object.defineProperty(h,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return Z0.RemoveHeadersInboundPolicy}});var X0=Yg();Object.defineProperty(h,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return X0.RemoveHeadersOutboundPolicy}});var ex=Zg();Object.defineProperty(h,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return ex.RemoveQueryParamsInboundPolicy}});var tx=Xg();Object.defineProperty(h,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return tx.ReplaceStringOutboundPolicy}});var rx=t_();Object.defineProperty(h,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return rx.RequestSizeLimitInboundPolicy}});var V_=Dr();Object.defineProperty(h,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return V_.RequestValidationInboundPolicy}});Object.defineProperty(h,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return V_.SchemaBasedRequestValidation}});var nx=a_();Object.defineProperty(h,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return nx.RequireOriginInboundPolicy}});var ix=c_();Object.defineProperty(h,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return ix.SetBodyInboundPolicy}});var ox=l_();Object.defineProperty(h,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return ox.SetHeadersInboundPolicy}});var sx=p_();Object.defineProperty(h,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return sx.SetHeadersOutboundPolicy}});var ax=f_();Object.defineProperty(h,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return ax.SetQueryParamsInboundPolicy}});var cx=m_();Object.defineProperty(h,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return cx.SetStatusOutboundPolicy}});var ux=y_();Object.defineProperty(h,"SleepInboundPolicy",{enumerable:!0,get:function(){return ux.SleepInboundPolicy}});var lx=__();Object.defineProperty(h,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return lx.SupabaseJwtInboundPolicy}});var dx=E_();Object.defineProperty(h,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return dx.UpstreamAzureAdServiceAuthInboundPolicy}});var px=v_();Object.defineProperty(h,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return px.UpstreamFirebaseAdminAuthInboundPolicy}});var hx=S_();Object.defineProperty(h,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return hx.UpstreamFirebaseUserAuthInboundPolicy}});var fx=A_();Object.defineProperty(h,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return fx.UpstreamGcpJwtInboundPolicy}});var mx=O_();Object.defineProperty(h,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return mx.UpstreamGcpServiceAuthInboundPolicy}});var yx=N_();Object.defineProperty(h,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return yx.ValidateJsonSchemaInbound}});var gx=ve();Object.defineProperty(h,"HttpProblems",{enumerable:!0,get:function(){return gx.HttpProblems}});var _x=ao();Object.defineProperty(h,"ProblemResponseFormatter",{enumerable:!0,get:function(){return _x.ProblemResponseFormatter}});var bx=Yn();Object.defineProperty(h,"ZuploRequest",{enumerable:!0,get:function(){return bx.ZuploRequest}});var Ex=Ir();Object.defineProperty(h,"SystemRouteName",{enumerable:!0,get:function(){return Ex.SystemRouteName}});var G_=Jl();Object.defineProperty(h,"LookupResult",{enumerable:!0,get:function(){return G_.LookupResult}});Object.defineProperty(h,"Router",{enumerable:!0,get:function(){return G_.Router}});var B_=C_();Object.defineProperty(h,"ContentTypes",{enumerable:!0,get:function(){return B_.ContentTypes}});Object.defineProperty(h,"serialize",{enumerable:!0,get:function(){return B_.serialize}});var wx=L_();Object.defineProperty(h,"ServiceProviderImpl",{enumerable:!0,get:function(){return wx.ServiceProviderImpl}});var K_=Au();Object.defineProperty(h,"API_KEY",{enumerable:!0,get:function(){return K_.API_KEY}});Object.defineProperty(h,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return K_.SYSTEM_LOGGER}});var vx=D_();Object.defineProperty(h,"httpStatuses",{enumerable:!0,get:function(){return b0(vx).default}});var Tx=Ge();Object.defineProperty(h,"SystemLogMap",{enumerable:!0,get:function(){return Tx.SystemLogMap}});var Oi=Ua();Object.defineProperty(h,"getIdForParameterSchema",{enumerable:!0,get:function(){return Oi.getIdForParameterSchema}});Object.defineProperty(h,"getIdForRefSchema",{enumerable:!0,get:function(){return Oi.getIdForRefSchema}});Object.defineProperty(h,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Oi.getIdForRequestBodySchema}});Object.defineProperty(h,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Oi.getRawOperationDataIdentifierName}});Object.defineProperty(h,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Oi.sanitizedIdentifierName}})});var J_=g(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.BaseCryptoBeta=Dn.supportedDigests=void 0;Dn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var cp=class{static{o(this,"BaseCryptoBeta")}};Dn.BaseCryptoBeta=cp});var z_=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.WorkerCryptoBeta=void 0;var up=J_(),Sx=D(),lp=class extends up.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!up.supportedDigests.includes(e.toLowerCase()))throw new Sx.RuntimeError(`Algorithm ${e} is not supported. Try using ${up.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("")}};ic.WorkerCryptoBeta=lp});var W_=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.BaseKeyValueStore=void 0;var dp=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};oc.BaseKeyValueStore=dp});var Y_=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.WorkerKeyValueStore=void 0;var Q_=D(),Ix=W_(),pp=class extends Ix.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=globalThis.ZUPLO_KV;if(!n)throw new Q_.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 Q_.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)}};sc.WorkerKeyValueStore=pp});var xt=g(ct=>{"use strict";var Ax=ct&&ct.__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]}),Px=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ax(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Px(ke(),ct);var Rx=z_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Rx.WorkerCryptoBeta}});var Ox=Y_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return Ox.WorkerKeyValueStore}})});var MN={};Ki(MN,{GraphQLComplexityLimitInboundPolicy:()=>Ob,GraphQLDisableIntrospectionInboundPolicy:()=>Nb});module.exports=Ji(MN);var Kn=kp(xt());function B(t,e){if(!!!t)throw new Error(e)}o(B,"devAssert");function be(t){return typeof t=="object"&&t!==null}o(be,"isObjectLike");function St(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(St,"invariant");var xx=/\r\n|[\n\r]/g;function Un(t,e){let r=0,n=1;for(let i of t.body.matchAll(xx)){if(typeof i.index=="number"||St(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(Un,"getLocation");function hp(t){return ac(t.source,Un(t.source,t.start))}o(hp,"printLocation");function ac(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}
66
- `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let m=Math.floor(u/80),f=u%80,y=[];for(let v=0;v<p.length;v+=80)y.push(p.slice(v,v+80));return l+Z_([[`${a} |`,y[0]],...y.slice(1,m+1).map(v=>["|",v]),["|","^".padStart(f)],["|",y[m+1]]])}return l+Z_([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(ac,"printSourceLocation");function Z_(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(`
67
- `)}o(Z_,"printPrefixedLines");function Nx(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(Nx,"toNormalizedOptions");var C=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}=Nx(r);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=X_(Array.isArray(a)?a:a?[a]:void 0);let m=X_((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(m==null||(i=m[0])===null||i===void 0?void 0:i.source),this.positions=u??m?.map(y=>y.start),this.locations=u&&c?u.map(y=>Un(c,y)):m?.map(y=>Un(y.source,y.start));let f=be(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??f)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,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+=`
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 Ty.RuntimeError("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=ud(await wy(this.body||""))}return e}};yn.AwsV4Signer=Fs;async function _i(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?ld.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,ld.encode(e))}o(_i,"hmac");async function wy(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?ld.encode(t):t)}o(wy,"hash");function ud(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}o(ud,"buf2hex");function vy(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}o(vy,"encodeRfc3986");function mI(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 Ey?[Ey[s],a]:[s,a]}o(mI,"guessServiceRegion")});var Sy=g(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.convertStringToUtf8Array=Tt.convertUtf8ArrayToString=Tt.base64Encode=Tt.base64Decode=void 0;function yI(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(yI,"b64ToUint6");function gI(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|=yI(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(gI,"base64Decode");Tt.base64Decode=gI;function Hs(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}o(Hs,"uint6ToB64");function _I(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(Hs(i>>>18&63),Hs(i>>>12&63),Hs(i>>>6&63),Hs(i&63)),i=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}o(_I,"base64Encode");Tt.base64Encode=_I;function bI(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(bI,"convertUtf8ArrayToString");Tt.convertUtf8ArrayToString=bI;function EI(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(EI,"convertStringToUtf8Array");Tt.convertStringToUtf8Array=EI});var Iy=g(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.toCLFDate=void 0;function gn(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}o(gn,"numberToString");function wI(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",i=gn(Math.floor(r/60)),s=gn(r%60);return`${n}${i}${s}`}o(wI,"getCLFOffset");function vI(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=gn(t.getDate()),n=e[t.getMonth()],i=t.getFullYear(),s=gn(t.getHours()),a=gn(t.getMinutes()),c=gn(t.getSeconds()),u=wI(t);return`${r}/${n}/${i}:${s}:${a}:${c} ${u}`}o(vI,"toCLFDate");qs.toCLFDate=vI});var Cy=g(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.getResponse=ar.awsLambdaHandler=ar.AwsLambdaHandlerExtensions=void 0;var TI=wr(),Ay=by(),bi=D(),SI=xt(),II=pd(),Ry=Sy(),Oy=Iy(),Py=(0,TI.debug)("zuplo:runtime"),AI="X-Amzn-Trace-Id",PI="x-amzn-errortype",xy=[],RI=o(async(t,e,r)=>{let n=r;for await(let i of xy)n=await i(t,e,r);return n},"onSendingAwsLambdaEvent"),Be=class extends bi.RuntimeError{static{o(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(AI)??void 0,this.errorType=r.get(PI)??void 0}};ar.AwsLambdaHandlerExtensions={addSendingAwsLambdaEventHook:t=>{xy.push(t)}};async function OI(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 bi.ConfigurationError("awsAccessKeyId is not set in the handler options");if(!n)throw new bi.ConfigurationError("secretAccessKey is not set in the handler options");if(!i)throw new bi.ConfigurationError("region is not set in the handler options");if(!s)throw new bi.ConfigurationError("functionName is not set in the handler options");let l=new II.AwsClient({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${i}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Py(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await CI(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,y;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?y=NI(t,e):y=await xI(t,e,{useAwsResourcePathStyle:c}),Py("Calling onSendingAwsLambdaEvent hook");let v=await RI(t,e,y);v.body=p,v.isBase64Encoded=m;let T=await l.fetch(d,{body:JSON.stringify(v)});try{return Ny(T)}catch(S){if(S instanceof Be){let M=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&S.traceId?{AMZN_TRACE_ID_HEADER:S.traceId}:void 0;return SI.HttpProblems.internalServerError(t,e,void 0,M)}throw S}}o(OI,"awsLambdaHandler");ar.awsLambdaHandler=OI;async function Ny(t){let e;try{e=await t.json()}catch{throw new Be("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 Be(e.message,t.headers):new Be(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Be(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 Be(`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 Be(`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 Be(`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 Be("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new Be("Response was set to base64 encoded but body was not a string",t.headers);n=(0,Ry.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 Be(`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(Ny,"getResponse");ar.getResponse=Ny;async function xI(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,Oy.toCLFDate)(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:DI(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}o(xI,"buildEventVersion1");function NI(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,Oy.toCLFDate)(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}o(NI,"buildEventVersion2");async function CI(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&&LI(e,i)){let s=await t.arrayBuffer();r=(0,Ry.base64Encode)(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}o(CI,"getBodyResult");function LI(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}o(LI,"matchesContentType");function DI(t,e=!1){if(!e)return t;let r=(0,Ay.parse)(t),n=(0,Ay.compile)(t),i={};return r.forEach(s=>{typeof s=="string"?i[s]=`{${s}}`:i[s.name]=`{${s.name}}`}),n(i)}o(DI,"getResourcePath")});var bn=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getHandlerUserLogFunction=_n.logBadGatewayResponses=void 0;var UI=Ge(),MI=te(),kI=[502,503,504];async function FI(t,e){if(kI.includes(t.status)){let r=UI.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(FI,"logBadGatewayResponses");_n.logBadGatewayResponses=FI;var hd;function HI(t){if(hd===void 0){let r=MI.Environment.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),hd=r}return t.log[hd]}o(HI,"getHandlerUserLogFunction");_n.getHandlerUserLogFunction=HI});var Dy=g($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.openApiSpecHandler=void 0;var Ly=D(),qI=ve(),fd=te(),$I=bn();async function jI(t,e){let r=fd.Environment.instance.build.BUILD_ID,{buildAssetsUrl:n}=fd.Environment.instance,i=e.route.handler.options,{openApiFilePath:s}=i;if(!s)throw new Ly.ConfigurationError("Open API Spec Handler must have 'openApiFilePath' specified");let a=VI(s);if(!a.isValid)throw new Ly.ConfigurationError(a.error);let c;fd.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 qI.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,$I.logBadGatewayResponses)(l,e),l}o(jI,"openApiSpecHandler");$s.openApiSpecHandler=jI;var VI=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 Uy=g(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.redirectHandler=void 0;var GI=D();async function BI(t,e){let r=e.route.handler.options;if(!r.location)throw new GI.ConfigurationError("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}o(BI,"redirectHandler");js.redirectHandler=BI});var ky=g(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.urlForwardHandler=void 0;var KI=D(),My=bn();function JI(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(JI,"join");async function zI(t,e){let r=(0,My.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 KI.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=JI(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}),m=Date.now()-d;return r(`URL Forward received response ${p.status} - ${p.statusText} in ${m}ms`),(0,My.logBadGatewayResponses)(p,e),p}o(zI,"urlForwardHandler");Vs.urlForwardHandler=zI});var Hy=g(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.urlRewriteHandler=void 0;var WI=D(),Fy=bn(),QI=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 YI(t,e){let r=(0,Fy.getHandlerUserLogFunction)(e),n=e.route.handler.options,i=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new WI.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?QI(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,Fy.logBadGatewayResponses)(d,e),d}o(YI,"urlRewriteHandler");Gs.urlRewriteHandler=YI});var $y=g(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.webSocketHandler=void 0;var qy=D(),ZI=ks(),XI=xt(),eA=te(),tA=bn();async function rA(t,e){let r=eA.Environment.instance,n=e.route.handler.options,i=(0,tA.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new qy.ConfigurationError("WebSocket Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return XI.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new qy.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 f=await(0,ZI.externalServiceTunnelConfig)(c),y=new URL(c);c=new URL(`${f.serviceBaseUrl}${y.pathname}${y.search}`).toString();for(let T in f.tunnelHeaders)p.set(T,f.tunnelHeaders[T])}c=c.replace(/^(http)/,"ws");try{if(p.get("Authorization")){let f=p.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${f}`}}catch{}let m=JSON.stringify({url:c});return new Response(m,{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(),m=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${p}'`;throw new Error(m)}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(rA,"webSocketHandler");Bs.webSocketHandler=rA});var jy=g(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.webSocketPolicyProcessor=En.getWebSocketPolicyFunctions=void 0;var nA=D(),iA=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 nA.ConfigurationError(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions");En.getWebSocketPolicyFunctions=iA;var oA=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");En.webSocketPolicyProcessor=oA});var By=g(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.webSocketPipelineHandler=void 0;var Vy=D(),sA=ks(),aA=xt(),cA=te(),uA=bn(),md=jy();function Gy(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{o(async c=>{let u=await(0,md.webSocketPolicyProcessor)(c,t,e,r,n,i);u!==void 0&&e.send(u)},"innerPipeline")(s).catch(n.log.error)}catch(a){n.log.error(a)}})}o(Gy,"wireUpListeners");async function lA(t,e){let r=cA.Environment.instance,n=e.route.handler.options,i=(0,uA.getHandlerUserLogFunction)(e);if(!n||!n.rewritePattern)throw new Vy.ConfigurationError("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let s=t.headers.get("Upgrade");if(!s||s!=="websocket")return aA.HttpProblems.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new Vy.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 S=new Headers(t.headers);if(c.startsWith("service:")){let H=await(0,sA.externalServiceTunnelConfig)(c),R=new URL(c);c=new URL(`${H.serviceBaseUrl}${R.pathname}${R.search}`).toString();for(let Y in H.tunnelHeaders)S.set(Y,H.tunnelHeaders[Y])}c=c.replace(/^(http)/,"ws");try{if(S.get("Authorization")){let H=S.get("Authorization")?.replace("Bearer ","");c+=`?apiKey=${H}`}}catch{}let M=JSON.stringify({url:c});return new Response(M,{headers:S})}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 S=await l.text(),M=`WebSocket connection error - ${l.status}: ${l.statusText}, content: '${S}'`;throw new Error(M)}let d=new WebSocketPair,[p,m]=Object.values(d),f=Date.now()-u;i(`WebSocket connected, received response ${l.status} - ${l.statusText} in ${f}ms`);let y=l.webSocket;y.accept(),m.accept();let v=n.policies&&n.policies.inbound?(0,md.getWebSocketPolicyFunctions)(n.policies.inbound,"inbound"):[],T=n.policies&&n.policies.outbound?(0,md.getWebSocketPolicyFunctions)(n.policies.outbound,"outbound"):[];return Gy(m,y,t,e,v),Gy(y,m,t,e,T),new Response(null,{status:101,webSocket:p})}o(lA,"webSocketPipelineHandler");Ks.webSocketPipelineHandler=lA});var Ky=g(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.DynaTraceLoggingPlugin=void 0;var dA=we(),yd=te(),pA=Pr(),hA=Ct(),fA=yt(),gd=class extends hA.LogPlugin{static{o(this,"DynaTraceLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new _d(this.options)}};Js.DynaTraceLoggingPlugin=gd;var _d=class{static{o(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#n=yd.Environment.instance.loggingEnvironmentType,this.#i=yd.Environment.instance.loggingEnvironmentStage,this.#r=yd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,fA.stringifyNonString)((0,pA.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 dA.BatchDispatch("dyna-trace-log-transport",10,this.#o)}});var Jy=g(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.LokiLoggingPlugin=void 0;var mA=we(),bd=te(),yA=Pr(),gA=Ct(),_A=yt(),Ed=class extends gA.LogPlugin{static{o(this,"LokiLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new vd(this.options)}};zs.LokiLoggingPlugin=Ed;var wd=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 bA(t,e){return btoa(`${t}:${e}`)}o(bA,"createBasicDigest");var vd=class{static{o(this,"LokiTransport")}constructor(e){this.#e=e.url,this.#t=bA(e.username,e.password),this.#n=bd.Environment.instance.loggingEnvironmentType,this.#i=bd.Environment.instance.loggingEnvironmentStage,this.#r=bd.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(e,r){let n=new wd(e.level,this.#r,this.#n,this.#i,e.requestId);e.messages.forEach(i=>{let s={stream:n,message:(0,_A.stringifyNonString)((0,yA.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 mA.BatchDispatch("loki-log-transport",10,this.#s)}});var zy=g(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.SumoLogicLoggingPlugin=void 0;var EA=we(),Td=te(),wA=Pr(),vA=Ct(),TA=yt(),Sd=class extends vA.LogPlugin{static{o(this,"SumoLogicLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Id(this.options)}};Ws.SumoLogicLoggingPlugin=Sd;var Id=class{static{o(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#i=e.category,this.#o=e.name,this.#r=Td.Environment.instance.loggingEnvironmentType,this.#n=Td.Environment.instance.loggingEnvironmentStage,this.#t=Td.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().toISOString(),message:(0,TA.stringifyNonString)((0,wA.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 EA.BatchDispatch("sumo-logic-log-transport",10,this.#s)}});var Qy=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.VMWareLogInsightTransport=wn.VMWareLogInsightLoggingPlugin=void 0;var SA=D(),IA=we(),Ad=te(),AA=Ct(),Wy=yt(),PA="d3a5b78f-8236-48f5-b1df-4fe269d41172",Pd=class extends AA.LogPlugin{static{o(this,"VMWareLogInsightLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Qs(this.options)}};wn.VMWareLogInsightLoggingPlugin=Pd;var Qs=class{static{o(this,"VMWareLogInsightTransport")}constructor(e){let r;try{r=new URL(e.url)}catch{throw new SA.ConfigurationError(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.origin,this.#r=Ad.Environment.instance.loggingEnvironmentType,this.#n=Ad.Environment.instance.loggingEnvironmentStage,this.#t=Ad.Environment.instance.deploymentName,this.#i=e.onMessageSending,e.fields&&(this.#o=Object.entries(e.fields).map(([n,i])=>({name:n,content:i})))}#e;#t;#r;#n;#i;#o;async log(e,r){let n=this.buildEntry(e,r);this.batcher.enqueue(n),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let n=(0,Wy.messagesToMultilineText)(e.messages),i={timestamp:Date.now(),text:n,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#n},{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.#t&&i.fields.push({name:"environment",content:this.#t}),this.#o&&i.fields.push(...this.#o),r.custom&&Object.entries(r.custom).forEach(([s,a])=>{let c=(0,Wy.stringifyNonStringToText)(a);c&&i.fields.push({name:s,content:c})}),this.#i&&(i=this.#i(i)),i}#s=async e=>{if(e.length===0)return;let r=await fetch(`${this.#e}/api/v1/events/ingest/${PA}`,{method:"POST",body:JSON.stringify(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 IA.BatchDispatch("vmware-log-insights-log-transport",10,this.#s)};wn.VMWareLogInsightTransport=Qs});var Zy=g(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.AWSLogTransport=vn.AWSLoggingPlugin=void 0;var RA=we(),Yy=te(),OA=Pr(),xA=Ct(),NA=yt(),CA=pd(),Rd=class extends xA.LogPlugin{static{o(this,"AWSLoggingPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Ys(this.options)}};vn.AWSLoggingPlugin=Rd;var Ys=class{static{o(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new RA.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 CA.AwsClient({accessKeyId:e,secretAccessKey:i,service:"logs",region:s}),this.logGroupName=n,this.logStreamName=r,this.region=s,this.environmentType=Yy.Environment.instance.loggingEnvironmentType,this.environment=Yy.Environment.instance.deploymentName}async log(e,r){e.messages.forEach(n=>{let i={timestamp:new Date().getTime(),message:JSON.stringify({data:(0,NA.stringifyNonString)((0,OA.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())}};vn.AWSLogTransport=Ys});var Xy=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.AWSLoggingPlugin=Oe.VMWareLogInsightLoggingPlugin=Oe.SumoLogicLoggingPlugin=Oe.LokiLoggingPlugin=Oe.GoogleCloudLoggingPlugin=Oe.DynaTraceLoggingPlugin=Oe.DataDogLoggingPlugin=void 0;var LA=Hl();Object.defineProperty(Oe,"DataDogLoggingPlugin",{enumerable:!0,get:function(){return LA.DataDogLoggingPlugin}});var DA=Ky();Object.defineProperty(Oe,"DynaTraceLoggingPlugin",{enumerable:!0,get:function(){return DA.DynaTraceLoggingPlugin}});var UA=Es();Object.defineProperty(Oe,"GoogleCloudLoggingPlugin",{enumerable:!0,get:function(){return UA.GoogleCloudLoggingPlugin}});var MA=Jy();Object.defineProperty(Oe,"LokiLoggingPlugin",{enumerable:!0,get:function(){return MA.LokiLoggingPlugin}});var kA=zy();Object.defineProperty(Oe,"SumoLogicLoggingPlugin",{enumerable:!0,get:function(){return kA.SumoLogicLoggingPlugin}});var FA=Qy();Object.defineProperty(Oe,"VMWareLogInsightLoggingPlugin",{enumerable:!0,get:function(){return FA.VMWareLogInsightLoggingPlugin}});var HA=Zy();Object.defineProperty(Oe,"AWSLoggingPlugin",{enumerable:!0,get:function(){return HA.AWSLoggingPlugin}})});var eg=g(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.DataDogMetricsError=cr.DataDogMetricsTransport=cr.DataDogMetricsPlugin=void 0;var qA=Ge(),$A=we(),jA=fo(),Od=new WeakMap,VA={tags:[]},xd=class extends jA.MetricsPlugin{static{o(this,"DataDogMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new Zs(this.options)}static setContext(e,r){let n=Od.get(e);n||(n=VA);let i=Object.assign({...n},r);Od.set(e,i)}};cr.DataDogMetricsPlugin=xd;var Zs=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 $A.BatchDispatch("data-dog-metrics-transport",10,this.dispatchFunction,qA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()/1e3),i=this.#n.concat(Od.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 Xs(await n.text())}};cr.DataDogMetricsTransport=Zs;var Xs=class t extends Error{static{o(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};cr.DataDogMetricsError=Xs});var tg=g(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DynaTraceMetricsError=ur.DynaTraceMetricsTransport=ur.DynatraceMetricsPlugin=void 0;var GA=Ge(),BA=we(),KA=fo(),Nd=new WeakMap,JA={dimensions:[]},Cd=class extends KA.MetricsPlugin{static{o(this,"DynatraceMetricsPlugin")}options;constructor(e){super(),this.options=e}getTransport(){return new ea(this.options)}static setContext(e,r){let n=Nd.get(e);n||(n=JA);let i=Object.assign({...n},r);Nd.set(e,i)}};ur.DynatraceMetricsPlugin=Cd;var ea=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 BA.BatchDispatch("dynatrace-metrics-transport",10,this.dispatchFunction,GA.SystemLogMap.getLogger(r)));let n=Math.floor(e.timestamp.getTime()),i=this.dimensions.concat(Nd.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 ta(await n.text())}};ur.DynaTraceMetricsTransport=ea;var ta=class t extends Error{static{o(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};ur.DynaTraceMetricsError=ta});var rg=g(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.DynatraceMetricsPlugin=Tn.DataDogMetricsPlugin=void 0;var zA=eg();Object.defineProperty(Tn,"DataDogMetricsPlugin",{enumerable:!0,get:function(){return zA.DataDogMetricsPlugin}});var WA=tg();Object.defineProperty(Tn,"DynatraceMetricsPlugin",{enumerable:!0,get:function(){return WA.DynatraceMetricsPlugin}})});var ng=g(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.AuditLogDataStaxProvider=void 0;var Ld=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)})}))}};ra.AuditLogDataStaxProvider=Ld});var og=g(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.AuditLogPlugin=void 0;var QA=Ot(),YA=we(),Dd=class extends QA.InitializableRuntimePlugin{static{o(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r}#e;#t;async initialize(e){new Ud(e,this.#e,this.#t)}};na.AuditLogPlugin=Dd;var ig=o(t=>{let e={};return t.forEach((r,n)=>{e[n]=r}),e},"serializableHeaders"),ZA={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Ud=class{static{o(this,"AuditPluginImpl")}constructor(e,r,n){this.#t=r;let i={...ZA};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 YA.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?ig(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?ig(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(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(n){return r.log.error(n),e}}}});var ia=g(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.getValueFromRequestUser=Sn.statusCodesStringToNumberArray=void 0;var sg=D(),ag=new Map;function XA(t){if(typeof t!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new Error("Malformed input string");let e=ag.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 ag.set(t,n),n}o(XA,"statusCodesStringToNumberArray");Sn.statusCodesStringToNumberArray=XA;function eP(t,e,r){if(!e.startsWith("."))throw new sg.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 sg.RuntimeError(`Error applying ${r} '${e}', reading '${s}'`);i=i[s]}),`${i}`}o(eP,"getValueFromRequestUser");Sn.getValueFromRequestUser=eP});var pg=g(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.AmberfloMeteringInboundPolicy=In.AmberfloMeteringPolicy=void 0;var cg=D(),tP=we(),ug=ia(),dg=new WeakMap,lg={},Md=class{static{o(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,r){dg.set(e,r)}};In.AmberfloMeteringPolicy=Md;async function rP(t,e,r,n){if(!r.statusCodes)throw new cg.ConfigurationError(`Invalid AmberfloMeterInboundPolicy '${n}': options.statusCodes must be an array of HTTP status code numbers`);let i=Array.isArray(r.statusCodes)?r.statusCodes:(0,ug.statusCodesStringToNumberArray)(r.statusCodes);return e.addResponseSendingFinalHook(async s=>{if(i.includes(s.status)){let a=dg.get(e),c=r.customerId;if(r.customerIdPropertyPath){if(!t.user)throw new cg.RuntimeError(`Unable to apply customerIdPropertyPath '${r.customerIdPropertyPath}' as request.user is 'undefined'.`);c=(0,ug.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)},m=lg[r.apiKey];if(!m){let f=r.apiKey,y=t.headers.get("zm-test-id")??"";m=new tP.BatchDispatch("amberflo-ingest-meter",10,async v=>{try{let T=r.url??"https://app.amberflo.io/ingest",S=await fetch(T,{method:"POST",body:JSON.stringify(v),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":y}});S.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${n}'. ${S.status}: ${await S.text()}`)}catch(T){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${n}': ${T.message}`),T}}),lg[f]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),t}o(rP,"AmberfloMeteringInboundPolicy");In.AmberfloMeteringInboundPolicy=rP});var lr=g(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.getPolicyCacheName=void 0;function nP(t){return`zuplo-policy-${t}`}o(nP,"getPolicyCacheName");oa.getPolicyCacheName=nP});var yg=g(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.ApiAuthKeyInboundPolicy=An.ApiKeyInboundPolicy=void 0;var iP=lr(),oP=br(),hg=nd(),kd=D(),sP=xt(),Fd=Ge(),Hd=te(),aP=_s(),fg="key-metadata-cache-type";function cP(t,e){return e.authScheme===""?t:t.replace(`${e.authScheme} `,"")}o(cP,"getKeyValue");async function mg(t,e,r,n){if(!r.bucketName)if(hg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)r.bucketName=hg.environment.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new kd.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 kd.ConfigurationError(`ApiKeyInboundPolicy '${n}' - minimum cacheTtlSeconds value is 60s, '${i.cacheTtlSeconds}' is invalid`);let s=o(v=>i.allowUnauthenticatedRequests?t:sP.HttpProblems.unauthorized(t,e,{detail:v}),"unauthorizedResponse"),a=t.headers.get(i.authHeader);if(!a)return s("No Authorization Header");if(!a.toLowerCase().startsWith(i.authScheme.toLowerCase()))return s("Invalid Authorization Scheme");let c=cP(a,i);if(!c||c==="")return s("No key present");let u=await uP(c),l=new oP.MemoryZoneReadThroughCache((0,iP.getPolicyCacheName)(n),{logger:Fd.SystemLogMap.getLogger(e)}),d=await l.get(u);if(d&&d.isValid===!0)return t.user=d.user,t;if(d&&!d.isValid)return d.typeId!==fg&&Fd.SystemLogMap.getLogger(e).error(`ApiKeyInboundPolicy '${n}' - cached metadata has invalid typeId '${d.typeId}'`,d),s("Authorization Failed");let p={key:c},m=await(0,aP.fetchRetry)({retryDelayMs:5,retries:2,logger:Fd.SystemLogMap.getLogger(e)},`${Hd.Environment.instance.apiKeyServiceUrl}/v1/$validate/${i.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":Hd.Environment.instance.deploymentName??"unknown","User-Agent":Hd.Environment.instance.systemUserAgent},body:JSON.stringify(p)});if(m.status===401)return e.log.info(`ApiKeyInboundPolicy '${n}' - 401 response from Key Service`),s("Authorization Failed");if(m.status!==200){try{let v=await m.text(),T=JSON.parse(v);e.log.error("Unexpected response from key service",T)}catch{e.log.error("Invalid response from key service")}throw new kd.RuntimeError(`ApiKeyInboundPolicy '${n}' - unexpected response from Key Service. Status: ${m.status}`)}let f=await m.json(),y={isValid:!0,typeId:fg,user:{sub:f.name,data:f.metadata}};return t.user=y.user,l.put(u,y,i.cacheTtlSeconds),t}o(mg,"ApiKeyInboundPolicy");An.ApiKeyInboundPolicy=mg;async function uP(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(uP,"hashValue");An.ApiAuthKeyInboundPolicy=mg});var Mt=g(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.OpenIdJwtInboundPolicy=void 0;var $d=(ys(),Ji(ms)),jd=D(),lP=ve(),qd={},dP=o(async(t,e)=>{if(!e.jwkUrl||typeof e.jwkUrl!="string")throw new jd.ConfigurationError("Invalid State - jwkUrl not set");qd[e.jwkUrl]||(qd[e.jwkUrl]=(0,$d.createRemoteJWKSet)(new URL(e.jwkUrl),e.headers?{headers:e.headers}:void 0));let{payload:r}=await(0,$d.jwtVerify)(t,qd[e.jwkUrl],{issuer:e.issuer,audience:e.audience});return r},"jwkVerifier"),pP=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,$d.jwtVerify)(t,r,{issuer:e.issuer,audience:e.audience});return n},"secretVerifier"),hP=o(async(t,e,r,n)=>{let i=t.headers.get("Authorization"),s="bearer ",a=o(m=>lP.HttpProblems.unauthorized(t,e,{detail:m}),"unauthorizedResponse");if(!r.jwkUrl&&!r.secret)throw new jd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': One of 'jwkUrl' or 'secret' options are required.`);if(r.jwkUrl&&r.secret)throw new jd.ConfigurationError(`OpenIdJwtInboundPolicy policy '${n}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let c=r.jwkUrl?dP:pP,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 m=i.substring(s.length);if(!m||m.length===0)return a("No bearer token on authorization header");try{return await c(m,r)}catch(f){let y=new URL(t.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${y.pathname} `,f):e.log.warn(`Invalid token on: ${t.method} ${y.pathname}`,f),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");sa.OpenIdJwtInboundPolicy=hP});var gg=g(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.Auth0JwtInboundPolicy=void 0;var fP=Mt(),mP=o(async(t,e,r,n)=>(0,fP.OpenIdJwtInboundPolicy)(t,e,{issuer:`https://${r.auth0Domain}/`,audience:r.audience,jwkUrl:`https://${r.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"Auth0JwtInboundPolicy");aa.Auth0JwtInboundPolicy=mP});var _g=g(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.BasicAuthInboundPolicy=void 0;var yP=ve(),gP=o(async(t,e,r)=>{let n=t.headers.get("Authorization"),i="basic ",s=o(l=>yP.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 m=d.substring(0,p),f=d.substring(p+1),y=r.accounts.find(v=>v.username===m&&v.password===f);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");ca.BasicAuthInboundPolicy=gP});var bg=g(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.CachingInboundPolicy=void 0;var _P=lr(),bP=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function EP(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(EP,"digestMessage");var wP=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 EP(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 vP(t,e,r,n){let i=await caches.open(`${(0,_P.getPolicyCacheName)(n)}-${r.cacheId??""}`),s=r?.cacheHttpMethods?.map(u=>u.toUpperCase())??["GET"],a=await wP(t,r),c=await i.match(a);return c||(e.addEventListener("responseSent",u=>{try{let l=r.statusCodes??[200,206,301,302,303,404,410],d=u.response.clone();if(!l.includes(d.status)||!s.includes(t.method.toUpperCase()))return;let p=r?.expirationSecondsTtl??60,m=new Response(d.body,d);bP.forEach(f=>m.headers.delete(f)),m.headers.set("cache-control",`s-maxage=${p}`),e.waitUntil(i.put(a,m))}catch(l){e.log.error(`Error in caching-inbound-policy '${n}': "${l.message}"`,l)}}),t)}o(vP,"CachingInboundPolicy");ua.CachingInboundPolicy=vP});var Eg=g(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.ChangeMethodInboundPolicy=void 0;var TP=D(),SP=Yn(),IP=o(async(t,e,r,n)=>{if(!r.method)throw new TP.ConfigurationError(`ChangeMethodInboundPolicy '${n}' options.method must be valid HttpMethod`);return new SP.ZuploRequest(t,{method:r.method})},"ChangeMethodInboundPolicy");la.ChangeMethodInboundPolicy=IP});var wg=g(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.ClearHeadersInboundPolicy=void 0;var AP=ke(),PP=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 AP.ZuploRequest(t,{headers:i})},"ClearHeadersInboundPolicy");da.ClearHeadersInboundPolicy=PP});var vg=g(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.ClearHeadersOutboundPolicy=void 0;var RP=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");pa.ClearHeadersOutboundPolicy=RP});var Tg=g(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.ClerkJwtInboundPolicy=void 0;var OP=Mt(),xP=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,OP.OpenIdJwtInboundPolicy)(t,e,{issuer:i.href.slice(0,-1),jwkUrl:s.toString(),allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n)},"ClerkJwtInboundPolicy");ha.ClerkJwtInboundPolicy=xP});var Ig=g(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.CognitoJwtInboundPolicy=void 0;var Sg=D(),NP=Mt(),CP=o(async(t,e,r,n)=>{if(!r.userPoolId)throw new Sg.ConfigurationError("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!r.region)throw new Sg.ConfigurationError("region must be set in the options for CognitoJwtInboundPolicy");return(0,NP.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");fa.CognitoJwtInboundPolicy=CP});var Pg=g(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.CompositeInboundPolicy=void 0;var LP=D(),DP=dn(),Ag=Zn(),UP=o(async(t,e,r,n)=>{if(!r.policies||r.policies.length===0)throw new LP.ConfigurationError(`CompositeInboundPolicy '${n}' must have valid policies defined`);let i=DP.Gateway.instance,s=(0,Ag.getInboundPolicyHandlerAndOptions)(r.policies,i?.routeData.policies);return(0,Ag.toStackedInboundHandler)(s)(t,e)},"CompositeInboundPolicy");ma.CompositeInboundPolicy=UP});var dr=g(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.optionValidator=void 0;var Ei=D();function MP(t,e){let r=o((s,a,c)=>{let u=t[s];if(!(c&&u===void 0)){if(u===void 0)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(a==="array"&&Array.isArray(u))throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be an array. Received type ${typeof u}.`);if(typeof u!==a)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be of type ${a}. Received type ${typeof u}.`);if(typeof u=="string"&&u.length===0)throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof u=="number"&&isNaN(u))throw new Ei.ConfigurationError(`Value of '${String(s)}' on policy '${e}' must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),n=o((s,a)=>(r(s,a,!0),{optional:n,required:i}),"optional"),i=o((s,a)=>(r(s,a,!1),{optional:n,required:i}),"required");return{optional:n,required:i}}o(MP,"optionValidator");ya.optionValidator=MP});var Rg=g(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.FirebaseJwtInboundPolicy=void 0;var kP=dr(),FP=Mt(),HP=o(async(t,e,r,n)=>((0,kP.optionValidator)(r,n).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),(0,FP.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");ga.FirebaseJwtInboundPolicy=HP});var Og=g(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.FormDataToJsonInboundPolicy=void 0;var qP=ke(),$P=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 qP.ZuploRequest(t,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");_a.FormDataToJsonInboundPolicy=$P});var xg=g(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.GeoFilterInboundPolicy=void 0;var jP=D(),VP=ve(),Pn="__unknown__",GP=o(async(t,e,r,n)=>{let i={allow:{countries:On(r.allow?.countries,"allow.countries",n),regionCodes:On(r.allow?.regionCodes,"allow.regionCode",n),asns:On(r.allow?.asns,"allow.asOrganization",n)},block:{countries:On(r.block?.countries,"block.countries",n),regionCodes:On(r.block?.regionCodes,"block.regionCode",n),asns:On(r.block?.asns,"block.asOrganization",n)},ignoreUnknown:r.ignoreUnknown!==!1},s=e.incomingRequestProperties.country?.toLowerCase()??Pn,a=e.incomingRequestProperties.regionCode?.toLowerCase()??Pn,c=e.incomingRequestProperties.asn?.toString()??Pn,u=i.ignoreUnknown&&s===Pn,l=i.ignoreUnknown&&a===Pn,d=i.ignoreUnknown&&c===Pn,p=i.allow.countries,m=i.allow.regionCodes,f=i.allow.asns;if(p.length>0&&!p.includes(s)&&!u||m.length>0&&!m.includes(a)&&!l||f.length>0&&!f.includes(c)&&!d)return Rn(t,e,n,s,a,c);let y=i.block.countries,v=i.block.regionCodes,T=i.block.asns;return y.length>0&&y.includes(s)&&!u||v.length>0&&v.includes(a)&&!l||T.length>0&&T.includes(c)&&!d?Rn(t,e,n,s,a,c):t},"GeoFilterInboundPolicy");ba.GeoFilterInboundPolicy=GP;function Rn(t,e,r,n,i,s){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${r}' (country: '${n}', regionCode: '${i}', asn: '${s}')`),VP.HttpProblems.forbidden(t,e,{geographicContext:{country:n,regionCode:i,asn:s}})}o(Rn,"blockedResponse");function On(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 jP.ConfigurationError(`Invalid '${e}' for GeoFilterInboundPolicy '${r}': '${t}', must be a string or string[]`)}o(On,"toLowerStringArray")});var Ng=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.JWTScopeValidationInboundPolicy=void 0;var BP=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");Ea.JWTScopeValidationInboundPolicy=BP});var Lg=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.MockApiInboundPolicy=void 0;var KP=ve(),JP=o(async(t,e,r,n)=>{let i=e.route.raw().responses;if(!i)return Vd(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 Vd(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(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),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 Cg(a[c])}else return a.length>0?Cg(a[0]):Vd(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");wa.MockApiInboundPolicy=JP;function Cg(t){let e=JSON.stringify(t.exampleValue,null,2),r=new Headers;switch(r.append("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(Cg,"generateResponse");var Vd=o((t,e,r,n)=>{let i=`Error in policy: ${t} - On route ${e.method} ${r.route.path}. ${n}`;return KP.HttpProblems.internalServerError(e,r,{detail:i})},"getProblemDetailResponse")});var Fg=g(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.MoesifInboundPolicy=xn.setMoesifContext=void 0;var zP=D(),WP=we(),QP="Incoming",YP={logRequestBody:!0,logResponseBody:!0};function Dg(t){let e={};return t.forEach((r,n)=>{e[n]=r}),e}o(Dg,"headersToObject");function Ug(){return new Date().toISOString()}o(Ug,"timestamp");var Gd=new WeakMap,ZP={};function XP(t,e){let r=Gd.get(t);r||(r=ZP);let n=Object.assign({...r},e);Gd.set(t,n)}o(XP,"setMoesifContext");xn.setMoesifContext=XP;async function Mg(t,e){let r=t.headers.get("content-type"),n=t.clone();if(r&&r.indexOf("json")!==0)try{return await n.json()}catch(s){e.log.error(s)}let i=await n.text();return e.log.debug({textBody:i}),i}o(Mg,"readBody");var eR={},Bd;function kg(){if(!Bd)throw new zP.RuntimeError("Invalid State - no _lastLogger");return Bd}o(kg,"getLastLogger");function tR(t){let e=eR[t];return e||(e=new WP.BatchDispatch("moesif-inbound",100,async r=>{let n=JSON.stringify(r);kg().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||kg().error({status:i.status,body:await i.text()})})),e}o(tR,"getDispatcher");async function rR(t,e,r,n){Bd=e.log;let i=Ug(),s=Object.assign(YP,r);if(!s.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${n}' - applicationId is required`);let a=s.logRequestBody?await Mg(t,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=tR(s.applicationId),d=t.headers.get("true-client-ip"),p=Gd.get(e)??{},m={time:i,uri:t.url,verb:t.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Dg(t.headers)},f=s.logResponseBody?await Mg(c,e):void 0,y={time:Ug(),status:c.status,headers:Dg(c.headers),body:f},v={request:m,response:y,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:QP};l.enqueue(v),e.waitUntil(l.waitUntilFlushed())}),t}o(rR,"MoesifInboundPolicy");xn.MoesifInboundPolicy=rR});var Hg=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.OktaJwtInboundPolicy=void 0;var nR=Mt(),iR=o(async(t,e,r,n)=>(0,nR.OpenIdJwtInboundPolicy)(t,e,{issuer:r.issuerUrl,audience:r.audience,jwkUrl:`${r.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests},n),"OktaJwtInboundPolicy");va.OktaJwtInboundPolicy=iR});var qg=g(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.PropelAuthJwtInboundPolicy=void 0;var oR=(ys(),Ji(ms)),sR=Mt(),Kd,aR=o(async(t,e,r,n)=>{if(!Kd)try{Kd=await(0,oR.importSPKI)(r.verifierKey,"RS256")}catch(i){throw e.log.error("Could not import verifier key"),i}return(0,sR.OpenIdJwtInboundPolicy)(t,e,{issuer:r.authUrl,secret:Kd,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests,subPropertyName:"user_id"},n)},"PropelAuthJwtInboundPolicy");Ta.PropelAuthJwtInboundPolicy=aR});var $g=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.throwIfStateNotObject=G.throwIfStateNotNumber=G.throwIfStateNotString=G.throwIfStateUndefinedOrNull=G.throwIfStateUndefined=G.throwIfOptionNotObject=G.throwIfOptionNotNumber=G.throwIfOptionNotString=G.throwIfOptionUndefinedOrNull=G.throwIfOptionUndefined=G.OptionTypeError=G.OptionUndefinedError=G.throwIfNotNumber=G.throwIfNotString=G.throwIfUndefinedOrNull=G.throwIfUndefined=G.ArgumentTypeError=G.ArgumentUndefinedError=G.ValidationError=void 0;var $e=Jr(),et=class extends Error{static{o(this,"ValidationError")}constructor(e){super(e)}};G.ValidationError=et;var wi=class extends et{static{o(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}};G.ArgumentUndefinedError=wi;var vi=class extends et{static{o(this,"ArgumentTypeError")}constructor(e,r){super(`The argument '${e}' must be of type '${r}'.`)}};G.ArgumentTypeError=vi;function cR(t,e){if((0,$e.isUndefined)(t))throw new wi(e)}o(cR,"throwIfUndefined");G.throwIfUndefined=cR;function Jd(t,e){if((0,$e.isUndefinedOrNull)(t))throw new wi(e)}o(Jd,"throwIfUndefinedOrNull");G.throwIfUndefinedOrNull=Jd;function uR(t,e){if(Jd(t,e),!(0,$e.isString)(t))throw new vi(e,"string")}o(uR,"throwIfNotString");G.throwIfNotString=uR;function lR(t,e){if(Jd(t,e),!(0,$e.isNumber)(t))throw new vi(e,"number")}o(lR,"throwIfNotNumber");G.throwIfNotNumber=lR;var Ti=class extends et{static{o(this,"OptionUndefinedError")}constructor(e,r,n){super(`The option '${n}' on the ${e} named '${r}' is undefined.`)}};G.OptionUndefinedError=Ti;var Nn=class extends et{static{o(this,"OptionTypeError")}constructor(e,r,n,i){super(`The option '${n}' on the ${e} named '${r}' must be of type '${i}'.`)}};G.OptionTypeError=Nn;function dR(t,e,r,n){if((0,$e.isUndefined)(n))throw new Ti(t,e,r)}o(dR,"throwIfOptionUndefined");G.throwIfOptionUndefined=dR;function Sa(t,e,r,n){if((0,$e.isUndefinedOrNull)(n))throw new Ti(t,e,r)}o(Sa,"throwIfOptionUndefinedOrNull");G.throwIfOptionUndefinedOrNull=Sa;function pR(t,e,r,n){if(Sa(t,e,r,n),!(0,$e.isString)(n))throw new Nn(t,e,r,"string")}o(pR,"throwIfOptionNotString");G.throwIfOptionNotString=pR;function hR(t,e,r,n){if(Sa(t,e,r,n),!(0,$e.isNumber)(n))throw new Nn(t,e,r,"number")}o(hR,"throwIfOptionNotNumber");G.throwIfOptionNotNumber=hR;function fR(t,e,r,n){if(Sa(t,e,r,n),!(0,$e.isObject)(n))throw new Nn(t,e,r,"object")}o(fR,"throwIfOptionNotObject");G.throwIfOptionNotObject=fR;function mR(t,e){if((0,$e.isUndefined)(t))throw new et(e)}o(mR,"throwIfStateUndefined");G.throwIfStateUndefined=mR;function Ia(t,e){if((0,$e.isUndefinedOrNull)(t))throw new et(e)}o(Ia,"throwIfStateUndefinedOrNull");G.throwIfStateUndefinedOrNull=Ia;function yR(t,e){if(Ia(t,e),!(0,$e.isString)(t))throw new et(e);return!0}o(yR,"throwIfStateNotString");G.throwIfStateNotString=yR;function gR(t,e){if(Ia(t,e),!(0,$e.isNumber)(t))throw new et(e);return!0}o(gR,"throwIfStateNotNumber");G.throwIfStateNotNumber=gR;function _R(t,e){if(Ia(t,e),!(0,$e.isObject)(t))throw new et(e);return!0}o(_R,"throwIfStateNotObject");G.throwIfStateNotObject=_R});var jg=g(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.InMemoryRedisClient=Cn.StandardRedisClient=void 0;var zd=D(),Aa=$g(),Wd=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,Aa.throwIfNotString)(e,"redisClientUrl"),(0,Aa.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,Aa.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 zd.SystemError("Redis client failed with 401: Unauthorized"):new zd.SystemError(`Redis client failed with (${s.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}};Cn.StandardRedisClient=Wd;var Qd=class{static{o(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:r,method:n}){if((0,Aa.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 zd.SystemError("The in-memory redis client only supports /rate-limit calls")}};Cn.InMemoryRedisClient=Qd});var Jg=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.RateLimitInboundPolicy=void 0;var bR=wr(),ER=ke(),wR=lr(),kt=D(),vR=ve(),Vg=Ge(),Si=te(),Gg=jg(),Bg=Jr(),Pa=(0,bR.debug)("zuplo:policies:RateLimitInboundPolicy"),TR="strict",SR=o(t=>{let e=t.headers.get("cf-connecting-ip")??t.headers.get("true-client-ip");if(e)return e;let r=t.headers.get("x-forwarded-for");return r?r.split(",")[0]:"127.0.0.1"},"getRealIP"),IR=o(async t=>({key:`ip-${SR(t)}`}),"getIP"),AR=o(async t=>({key:`user-${t.user?.sub??"anonymous"}`}),"getUser"),PR=o(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),Ra;function RR(t,e){let r;if(Ra)return Ra;if(Si.Environment.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),r=new Gg.InMemoryRedisClient,Ra=r,r;let{authApiJWT:n,redisURL:i}=Si.Environment.instance;if(!(0,Bg.isString)(i))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - rate limit service URL not configured`);if(!(0,Bg.isString)(n))throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - service authentication not configured`);if(i&&(r=Gg.StandardRedisClient.initialize(i,n,Si.Environment.instance.deploymentName??"unknown",Si.Environment.instance.systemUserAgent)),!r||!r.isEnabled())throw new kt.SystemError(`RateLimitInboundPolicy '${t}' - no redis ('${r}') or redis.isEnabled ('${r?.isEnabled}) is false`);return Ra=r,r}o(RR,"getRedisClient");async function Kg(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(Kg,"getCountAndUpdateExpiry");function OR(t,e){let r;if(t.rateLimitBy==="function"){if(!t.identifier)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!t.identifier.module)throw new kt.ConfigurationError(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!t.identifier.export)throw new kt.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 kt.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 kt.RuntimeError(u)}return c},"outerFunction")}o(OR,"wrapUserFunction");var xR="Retry-After",NR=o(async(t,e,r,n)=>{let i=Date.now(),s=Vg.SystemLogMap.getLogger(e),a=o((u,l)=>{if(r.throwOnFailure)throw new kt.SystemError(u,{cause:l});s.error(u,l)},"throwOrLog"),c=o((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[xR]=l.toString()),vR.HttpProblems.tooManyRequests(t,e,void 0,d)},"rateLimited");try{let l={function:OR(r,n),user:AR,ip:IR,all:PR}[r.rateLimitBy],d=await l(t,e,n),p=d.key,m=d.requestsAllowed??r.requestsAllowed,f=d.timeWindowMinutes??r.timeWindowMinutes,y=r.headerMode??"retry-after",v=RR(n,s),S=`bucket/${Si.Environment.instance.build.BUILD_ID}/${n}/${p}`;if((r.mode??TR)==="async"){let R=new ER.ZoneCache((0,wR.getPolicyCacheName)(n),{logger:Vg.SystemLogMap.getLogger(e)}),ne=Kg(S,f,v,s,e.requestId),Y=await R.get(S);if(Y!==void 0&&Y<=Date.now()){Pa(`RateLimitInboundPolicy '${n}' - returning 429 from cache for '${S}' (async mode)`);let fe=Math.round((Y-Date.now())/1e3);return c(y,fe)}return e.addEventListener("responseSending",fe=>{try{let Me=fe,E=Me.mutableResponse;Me.mutableResponse=(async()=>{let F=await ne;if(F.count>m){let Ye=Date.now()+F.ttlSeconds*1e3;return R.put(S,Ye,F.ttlSeconds).catch(Bi=>{throw s.error(Bi),Bi}),Pa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (async mode)`),c(y,F.ttlSeconds)}return E})()}catch(Me){s.error(`RateLimitInboundPolicy '${n}' -error in responseSending`,Me)}}),t}let H=await Kg(S,f,v,s,e.requestId);return H.count>m?(Pa(`RateLimitInboundPolicy '${n}' - returning 429 from redis for '${S}' (strict mode)`),c(y,H.ttlSeconds)):t}catch(u){return a(u.message,u),t}finally{let u=Date.now()-i;Pa(`RateLimitInboundPolicy '${n}' - latency ${u}ms`)}},"RateLimitInboundPolicy");Oa.RateLimitInboundPolicy=NR});var Yg=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.ReadmeMetricsInboundPolicy=void 0;var CR=we(),Yd=te(),zg=ia(),Zd;function Wg(t){let e=[];for(let[r,n]of t)e.push({name:r,value:n});return e}o(Wg,"headersToNameValuePairs");function LR(t){let e=[];return Object.entries(t).forEach(([r,n])=>{e.push({name:r,value:n})}),e}o(LR,"queryToNameValueParis");function DR(t){if(t===null)return;let e=parseFloat(t);if(!isNaN(e))return e}o(DR,"parseIntOrUndefined");var Qg={};async function UR(t,e,r,n){let i=new Date,s=Date.now();return Zd||(Zd={name:"zuplo",version:Yd.Environment.instance.build.ZUPLO_VERSION,comment:`zuplo/${Yd.Environment.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=r.userLabelPropertyPath&&t.user?(0,zg.getValueFromRequestUser)(t.user,r.userLabelPropertyPath,"userLabelPropertyPath"):t.user?.sub,u=r.userEmailPropertyPath&&t.user?(0,zg.getValueFromRequestUser)(t.user,r.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:t.headers.get("true-client-ip")??"",development:r.development!==void 0?r.development:Yd.Environment.instance.isDeno,group:{label:c,email:u,id:t.user?.sub??"anonymous"},request:{log:{creator:Zd,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:Wg(t.headers),queryString:LR(t.query)},response:{status:a.status,statusText:a.statusText,headers:Wg(a.headers),content:{size:DR(t.headers.get("content-length"))}}}]}}},d=Qg[r.apiKey];if(!d){let p=r.apiKey;d=new CR.BatchDispatch("readme-metering-inbound-policy",10,async m=>{try{let f=r.url??"https://metrics.readme.io/request",y=await fetch(f,{method:"POST",body:JSON.stringify(m),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(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${n}': '${f.message}'`),f}}),Qg[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),t}o(UR,"ReadmeMetricsInboundPolicy");xa.ReadmeMetricsInboundPolicy=UR});var Zg=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.RemoveHeadersInboundPolicy=void 0;var MR=ke(),kR=D(),FR=o(async(t,e,r,n)=>{let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new kR.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 MR.ZuploRequest(t,{headers:s})},"RemoveHeadersInboundPolicy");Na.RemoveHeadersInboundPolicy=FR});var Xg=g(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.RemoveHeadersOutboundPolicy=void 0;var HR=D(),qR=o(async(t,e,r,n,i)=>{let s=n?.headers;if(!s||!Array.isArray(s)||s.length===0)throw new HR.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");Ca.RemoveHeadersOutboundPolicy=qR});var e_=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.RemoveQueryParamsInboundPolicy=void 0;var $R=ke(),jR=D(),VR=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length===0)throw new jR.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 $R.ZuploRequest(s.toString(),t)},"RemoveQueryParamsInboundPolicy");La.RemoveQueryParamsInboundPolicy=VR});var t_=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.ReplaceStringOutboundPolicy=void 0;var GR=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");Da.ReplaceStringOutboundPolicy=GR});var n_=g(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.RequestSizeLimitInboundPolicy=void 0;var r_=o(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),BR=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?r_():s&&n?t:(await t.clone().text()).length>r.maxSizeInBytes?r_():t},"RequestSizeLimitInboundPolicy");Ua.RequestSizeLimitInboundPolicy=BR});var Ma=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.sanitizedIdentifierName=tt.getIdForRefSchema=tt.getIdForRequestBodySchema=tt.getIdForParameterSchema=tt.getRawOperationDataIdentifierName=void 0;function KR(t,e,r){return`_${Lr(t+"_"+e+"_"+r)}`}o(KR,"getRawOperationDataIdentifierName");tt.getRawOperationDataIdentifierName=KR;function JR(t,e,r,n){return`_${Lr(t.toLowerCase())}_`+e.toLowerCase()+"_"+r.toLowerCase()+`_${n.toLowerCase()}`}o(JR,"getIdForParameterSchema");tt.getIdForParameterSchema=JR;function zR(t,e,r){return`_${Lr(t.toLowerCase())}_`+e.toLowerCase()+`_rb_${Lr(r.toLowerCase())}`}o(zR,"getIdForRequestBodySchema");tt.getIdForRequestBodySchema=zR;function WR(t,e){return`_${Lr(t)}__${Lr(e)}`}o(WR,"getIdForRefSchema");tt.getIdForRefSchema=WR;function Lr(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(Lr,"sanitizedIdentifierName");tt.sanitizedIdentifierName=Lr});var Ii=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getErrorsFromValidator=Ce.shouldReject=Ce.shouldLog=Ce.logErrors=Ce.validateParameters=Ce.getParametersForOperation=void 0;var QR=dn(),ka=Dr(),YR=Ma(),ZR=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");Ce.getParametersForOperation=ZR;var XR=o((t,e,r,n,i)=>{let s=[],a=!0,c=[];return t.forEach(u=>{if(u.required&&!e[u.name])a=!1,s.push(`Required ${i} parameter '${u.name}' not found`);else{let l=(0,YR.getIdForParameterSchema)(r,n,i,u.name),d=QR.Gateway.instance.schemaValidator[l],p=d(e[u.name]),m=(0,Ce.getErrorsFromValidator)(d.errors);p||(a=!1,c.push(`${i} parameter: ${u.name} : ${e[u.name]}`),s.push(`Invalid value for ${i} parameter: '${u.name}' ${m.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:s}},"validateParameters");Ce.validateParameters=XR;var eO=o((t,e,r,n,i)=>{n?t.log[e](r,n,i):t.log[e](r,i)},"logErrors");Ce.logErrors=eO;var tO=o(t=>t===ka.ValidationOptions.logOnly||t===ka.ValidationOptions.rejectAndLog,"shouldLog");Ce.shouldLog=tO;var rO=o(t=>t===ka.ValidationOptions.rejectOnly||t===ka.ValidationOptions.rejectAndLog,"shouldReject");Ce.shouldReject=rO;var nO=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");Ce.getErrorsFromValidator=nO});var i_=g(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.handleBodyValidation=void 0;var iO=dn(),oO=Dr(),Fa=ve(),sO=Ma(),Ke=Ii();async function aO(t,e,r){if(!r.validateBody||r.validateBody===oO.ValidationOptions.none)return;let n;try{n=await e.clone().json()}catch(f){let y=`Error in request body for method : ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,v=Fa.HttpProblems.badRequest(e,t,{detail:`${y}, see errors property for more details`,errors:`${f}`});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",y,[n],f),(0,Ke.shouldReject)(r.validateBody))return v}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${t.route.path}`,y=Fa.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.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,sO.getIdForRequestBodySchema)(t.route.path,e.method,i),c=iO.Gateway.instance.schemaValidator[a];if(!c){let f=`No schema defined for method: ${e.method} in route: ${t.route.path} with content-type: ${e.headers.get("Content-Type")}`,y=Fa.HttpProblems.badRequest(e,t,{detail:f});return(0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",f,[n],[f]),(0,Ke.shouldReject)(r.validateBody)?y:void 0}if(c(n))return;let l=c.errors,d="Request body did not pass validation",p=(0,Ke.getErrorsFromValidator)(l),m=Fa.HttpProblems.badRequest(e,t,{detail:`${d}, see errors property for more details`,errors:p});if((0,Ke.shouldLog)(r.validateBody)&&(0,Ke.logErrors)(t,r.logLevel??"info",d,[n],p),(0,Ke.shouldReject)(r.validateBody))return m}o(aO,"handleBodyValidation");Ha.handleBodyValidation=aO});var o_=g(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.handleHeadersValidation=void 0;var cO=Dr(),uO=ve(),Ai=Ii();function lO(t,e,r){if(!r.validateHeaders||r.validateHeaders===cO.ValidationOptions.none)return;let n={};e.headers.forEach((a,c)=>{n[c]=a});let i=(0,Ai.getParametersForOperation)(t),s=(0,Ai.validateParameters)(i.filter(a=>a.location==="header"),n,t.route.path,e.method.toLowerCase(),"header");if(!s.isValid){let a="Header validation failed",c=uO.HttpProblems.badRequest(e,t,{detail:`${a}, see errors property for more details`,errors:s.errors});if((0,Ai.shouldLog)(r.validateHeaders)&&(0,Ai.logErrors)(t,r.logLevel??"info",a,s.invalidValues,s.errors),(0,Ai.shouldReject)(r.validateHeaders))return c}}o(lO,"handleHeadersValidation");qa.handleHeadersValidation=lO});var s_=g($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.handlePathParameterValidation=void 0;var dO=Dr(),pO=ve(),Pi=Ii();function hO(t,e,r){if(!r.validatePathParameters||r.validatePathParameters===dO.ValidationOptions.none)return;let n=(0,Pi.getParametersForOperation)(t),i=(0,Pi.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=pO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Pi.shouldLog)(r.validatePathParameters)&&(0,Pi.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Pi.shouldReject)(r.validatePathParameters))return a}}o(hO,"handlePathParameterValidation");$a.handlePathParameterValidation=hO});var a_=g(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.handleQueryParameterValidation=void 0;var fO=Dr(),mO=ve(),Ri=Ii();function yO(t,e,r){if(!r.validateQueryParameters||r.validateQueryParameters===fO.ValidationOptions.none)return;let n=(0,Ri.getParametersForOperation)(t),i=(0,Ri.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=mO.HttpProblems.badRequest(e,t,{detail:`${s}, see errors property for more details`,errors:i.errors});if((0,Ri.shouldLog)(r.validateQueryParameters)&&(0,Ri.logErrors)(t,r.logLevel??"info",s,i.invalidValues,i.errors),(0,Ri.shouldReject)(r.validateQueryParameters))return a}}o(yO,"handleQueryParameterValidation");ja.handleQueryParameterValidation=yO});var Dr=g(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy=Ft.ValidationOptions=void 0;var gO=i_(),_O=o_(),bO=s_(),EO=a_(),c_;(function(t){t.none="none",t.logOnly="log-only",t.rejectAndLog="reject-and-log",t.rejectOnly="reject-only"})(c_||(Ft.ValidationOptions=c_={}));var wO=o(async(t,e,r)=>{let n=(0,EO.handleQueryParameterValidation)(e,t,r);if(n!==void 0||(n=(0,bO.handlePathParameterValidation)(e,t,r),n!==void 0)||(n=(0,_O.handleHeadersValidation)(e,t,r),n!==void 0))return n;let i=await(0,gO.handleBodyValidation)(e,t,r);return i!==void 0?i:t},"RequestValidationInboundPolicy");Ft.RequestValidationInboundPolicy=wO;Ft.SchemaBasedRequestValidation=Ft.RequestValidationInboundPolicy});var u_=g(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.RequireOriginInboundPolicy=void 0;var vO=ke(),TO=D(),SO=o(async(t,e,r,n)=>{if(r.origins===void 0||r.origins.length===0)throw new TO.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 vO.HttpProblems.forbidden(t,e,{detail:a})}return t},"RequireOriginInboundPolicy");Va.RequireOriginInboundPolicy=SO});var l_=g(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.SetBodyInboundPolicy=void 0;var IO=ke(),AO=o(async(t,e,r)=>new IO.ZuploRequest(t,{body:r.body}),"SetBodyInboundPolicy");Ga.SetBodyInboundPolicy=AO});var p_=g(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.SetHeadersInboundPolicy=void 0;var PO=ke(),d_=D(),RO=o(async(t,e,r,n)=>{let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new d_.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 d_.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 PO.ZuploRequest(t,{headers:s})},"SetHeadersInboundPolicy");Ba.SetHeadersInboundPolicy=RO});var f_=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SetHeadersOutboundPolicy=void 0;var h_=D(),OO=o(async(t,e,r,n,i)=>{let s=n.headers;if(!s||!Array.isArray(s)||s.length==0)throw new h_.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 h_.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");Ka.SetHeadersOutboundPolicy=OO});var y_=g(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.SetQueryParamsInboundPolicy=void 0;var xO=ke(),m_=D(),NO=o(async(t,e,r,n)=>{let i=r.params;if(!i||!Array.isArray(i)||i.length==0)throw new m_.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 m_.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 xO.ZuploRequest(s.toString(),t)},"SetQueryParamsInboundPolicy");Ja.SetQueryParamsInboundPolicy=NO});var g_=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.SetStatusOutboundPolicy=void 0;var CO=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");za.SetStatusOutboundPolicy=CO});var __=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.SleepInboundPolicy=void 0;var LO=D(),DO=o(async t=>new Promise((r,n)=>{setTimeout(r,t)}),"sleep"),UO=o(async(t,e,r,n)=>{if(!r||r.sleepInMs===void 0||isNaN(r.sleepInMs))throw new LO.ConfigurationError(`SleepInboundPolicy '${n} must have a valid options.sleepInMs value`);return await DO(r.sleepInMs),t},"SleepInboundPolicy");Wa.SleepInboundPolicy=UO});var E_=g(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.SupabaseJwtInboundPolicy=void 0;var MO=ke(),b_=D(),kO=ve(),FO=dr(),HO=Mt(),qO=o(async(t,e,r,n)=>{(0,FO.optionValidator)(r,n).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let i={secret:r.secret,allowUnauthenticatedRequests:r.allowUnauthenticatedRequests??!1},s=await(0,HO.OpenIdJwtInboundPolicy)(t,e,i,n);if(s instanceof Response)return s;if(!(s instanceof MO.ZuploRequest))throw new b_.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 b_.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?kO.HttpProblems.unauthorized(t,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):s},"SupabaseJwtInboundPolicy");Qa.SupabaseJwtInboundPolicy=qO});var v_=g(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.UpstreamAzureAdServiceAuthInboundPolicy=void 0;var $O=lr(),jO=br(),w_=D(),VO=Ge(),GO=_s(),BO=dr(),KO=o(async(t,e,r,n)=>{(0,BO.optionValidator)(r,n).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let i=new jO.MemoryZoneReadThroughCache((0,$O.getPolicyCacheName)(n),{logger:VO.SystemLogMap.getLogger(e)}),s=await i.get(n);if(!s){let a=await JO(r,e);i.put(n,a.access_token,a.expires_in-(r.expirationOffsetSeconds??300)),s=a.access_token}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamAzureAdServiceAuthInboundPolicy");Ya.UpstreamAzureAdServiceAuthInboundPolicy=KO;async function JO(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,GO.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 w_.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 w_.RuntimeError("Response returned from Azure AD is not in the expected format.")}o(JO,"getAccessToken")});var S_=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.UpstreamFirebaseAdminAuthInboundPolicy=void 0;var zO=lr(),WO=br(),QO=D(),YO=Ge(),Xd=cn(),ZO=dr(),T_="https://accounts.google.com/o/oauth2/token",ep,XO=o(async(t,e,r,n)=>{(0,ZO.optionValidator)(r,n).required("serviceAccountJson","string"),ep||(ep=await Xd.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=new WO.MemoryZoneReadThroughCache((0,zO.getPolicyCacheName)(n),{logger:YO.SystemLogMap.getLogger(e)}),a=await s.get(n);if(!a){let c=await(0,Xd.getTokenFromGcpServiceAccount)({serviceAccount:ep,audience:T_,payload:i}),u=await(0,Xd.exchangeGgpJwtForIdToken)(T_,c,{retries:r.tokenRetries??3,retryDelayMs:10});if(!u.access_token)throw new QO.RuntimeError("Invalid OAuth response from Firebase");a=u.access_token,s.put(n,a,(u.expires_in??3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${a}`),t},"UpstreamFirebaseAdminAuthInboundPolicy");Za.UpstreamFirebaseAdminAuthInboundPolicy=XO});var I_=g(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.sha256=void 0;async function e0(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(e0,"sha256");Xa.sha256=e0});var A_=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.UpstreamFirebaseUserAuthInboundPolicy=void 0;var t0=lr(),r0=br(),Ln=D(),n0=Ge(),i0=I_(),tp=cn(),o0=ia(),s0=dr(),a0="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",c0=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],rp,u0=o(async(t,e,r,n)=>{if((0,s0.optionValidator)(r,n).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!r.userId&&!r.userIdPropertyPath)throw new Ln.ConfigurationError(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${n}'.`);let i={};if(typeof r.developerClaims<"u"){for(let d in r.developerClaims)if(Object.prototype.hasOwnProperty.call(r.developerClaims,d)){if(c0.indexOf(d)!==-1)throw new Ln.ConfigurationError(`Developer claim "${d}" is reserved and cannot be specified.`);i[d]=r.developerClaims[d]}}rp||(rp=await tp.GcpServiceAccount.init(r.serviceAccountJson));let s=r.userId;if(!s&&!r.userIdPropertyPath){if(!t.user)throw new Ln.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 Ln.RuntimeError(`Unable to apply userIdPropertyPath '${r.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);s=(0,o0.getValueFromRequestUser)(t.user,r.userIdPropertyPath,"userIdPropertyPath")}if(!s)throw new Ln.RuntimeError(`Unable to determine user from for the policy ${n}`);let a=new r0.MemoryZoneReadThroughCache((0,t0.getPolicyCacheName)(n),{logger:n0.SystemLogMap.getLogger(e)}),c={uid:s,claims:i},u=await(0,i0.sha256)(JSON.stringify(c)),l=await a.get(u);if(!l){let d=await(0,tp.getTokenFromGcpServiceAccount)({serviceAccount:rp,audience:a0,payload:c}),p=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${r.webApiKey}`,m=await(0,tp.exchangeFirebaseJwtForIdToken)(p,d,{retries:r.tokenRetries??3,retryDelayMs:10});if(!m.idToken)throw new Ln.RuntimeError("Invalid token response from Firebase");l=m.idToken,a.put(u,l,(m.expiresIn?parseInt(m.expiresIn):3600)-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${l}`),t},"UpstreamFirebaseUserAuthInboundPolicy");ec.UpstreamFirebaseUserAuthInboundPolicy=u0});var R_=g(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.UpstreamGcpJwtInboundPolicy=void 0;var P_=cn(),l0=dr(),np,d0=o(async(t,e,r,n)=>{(0,l0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string"),np||(np=await P_.GcpServiceAccount.init(r.serviceAccountJson));let i=await(0,P_.getTokenFromGcpServiceAccount)({serviceAccount:np,audience:r.audience});return t.headers.set("Authorization",`Bearer ${i}`),t},"UpstreamGcpJwtInboundPolicy");tc.UpstreamGcpJwtInboundPolicy=d0});var N_=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.UpstreamGcpServiceAuthInboundPolicy=void 0;var O_=lr(),p0=Wc(),h0=br(),f0=D(),ip=cn(),m0=dr(),x_="https://www.googleapis.com/oauth2/v4/token",op,y0=o(async(t,e,r,n)=>{(0,m0.optionValidator)(r,n).required("audience","string").required("serviceAccountJson","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),op||(op=await ip.GcpServiceAccount.init(r.serviceAccountJson));let i;r.useMemoryCacheOnly?i=new p0.MemoryCache((0,O_.getPolicyCacheName)(n)):i=new h0.MemoryZoneReadThroughCache((0,O_.getPolicyCacheName)(n),e);let s=await i.get(n);if(!s){let a=await(0,ip.getTokenFromGcpServiceAccount)({serviceAccount:op,audience:x_,payload:{target_audience:`${r.audience}`}}),{id_token:c}=await(0,ip.exchangeGgpJwtForIdToken)(x_,a,{retries:r.tokenRetries??3,retryDelayMs:10});if(!c)throw new f0.RuntimeError("Invalid token response from GCP");s=c,i.put(n,s,3600-(r.expirationOffsetSeconds??300))}return t.headers.set("Authorization",`Bearer ${s}`),t},"UpstreamGcpServiceAuthInboundPolicy");rc.UpstreamGcpServiceAuthInboundPolicy=y0});var L_=g(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.ValidateJsonSchemaInbound=void 0;var g0=D(),C_=ve(),_0=o(async(t,e,r)=>{let n=t.clone(),i;try{i=await n.json()}catch{return C_.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 g0.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 C_.HttpProblems.badRequest(t,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");nc.ValidateJsonSchemaInbound=_0});var D_=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.serialize=pr.ContentTypes=void 0;pr.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function b0(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(pr.ContentTypes.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(pr.ContentTypes.Json)||!e?JSON.stringify(t):t}o(b0,"serialize");pr.serialize=b0});var U_=g(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.ServiceProviderImpl=void 0;var E0=D(),sp=class t{static{o(this,"ServiceProviderImpl")}static#e;services=new Map;constructor(){}static getInstance(){return t.#e||(t.#e=new t),t.#e}setInstance(e){t.#e=e}addService(e,r){if(this.services.get(e))throw new E0.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)}};ic.ServiceProviderImpl=sp});var M_=g(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var w0={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"};ap.default=w0});var ke=g(h=>{"use strict";var v0=h&&h.__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]}),k_=h&&h.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&v0(e,t,r)},T0=h&&h.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(h,"__esModule",{value:!0});h.ReadmeMetricsInboundPolicy=h.RateLimitInboundPolicy=h.BasicRateLimitInboundPolicy=h.PropelAuthJwtInboundPolicy=h.OpenIdJwtInboundPolicy=h.OktaJwtInboundPolicy=h.setMoesifContext=h.MoesifInboundPolicy=h.MockApiInboundPolicy=h.JWTScopeValidationInboundPolicy=h.GeoFilterInboundPolicy=h.FormDataToJsonInboundPolicy=h.FirebaseJwtInboundPolicy=h.CompositeInboundPolicy=h.CognitoJwtInboundPolicy=h.ClerkJwtInboundPolicy=h.ClearHeadersOutboundPolicy=h.ClearHeadersInboundPolicy=h.ChangeMethodInboundPolicy=h.CachingInboundPolicy=h.BasicAuthInboundPolicy=h.Auth0JwtInboundPolicy=h.ApiKeyInboundPolicy=h.ApiAuthKeyInboundPolicy=h.AmberfloMeteringPolicy=h.AmberfloMeteringInboundPolicy=h.AuditLogPlugin=h.AuditLogDataStaxProvider=h.HttpStatusCode=h.webSocketPipelineHandler=h.webSocketHandler=h.urlRewriteHandler=h.urlForwardHandler=h.redirectHandler=h.openApiSpecHandler=h.awsLambdaHandler=h.AwsLambdaHandlerExtensions=h.purgeGatewayCache=h.Handler=h.originalFetch=h.ConfigurationError=h.isZuploReadableEnvVariableName=h.isRestrictedEnvVariableName=h.environment=h.ContextLocalStorage=h.ResponseSentEvent=h.ResponseSendingEvent=h.VALID_COMPATIBILITY_DATES=h.ZoneCache=h.MemoryZoneReadThroughCache=void 0;h.sanitizedIdentifierName=h.getRawOperationDataIdentifierName=h.getIdForRequestBodySchema=h.getIdForRefSchema=h.getIdForParameterSchema=h.SystemLogMap=h.httpStatuses=h.SYSTEM_LOGGER=h.API_KEY=h.ServiceProviderImpl=h.serialize=h.ContentTypes=h.Router=h.LookupResult=h.SystemRouteName=h.ZuploRequest=h.ProblemResponseFormatter=h.HttpProblems=h.ValidateJsonSchemaInbound=h.UpstreamGcpServiceAuthInboundPolicy=h.UpstreamGcpJwtInboundPolicy=h.UpstreamFirebaseUserAuthInboundPolicy=h.UpstreamFirebaseAdminAuthInboundPolicy=h.UpstreamAzureAdServiceAuthInboundPolicy=h.SupabaseJwtInboundPolicy=h.SleepInboundPolicy=h.SetStatusOutboundPolicy=h.SetQueryParamsInboundPolicy=h.SetHeadersOutboundPolicy=h.SetHeadersInboundPolicy=h.SetBodyInboundPolicy=h.RequireOriginInboundPolicy=h.SchemaBasedRequestValidation=h.RequestValidationInboundPolicy=h.RequestSizeLimitInboundPolicy=h.ReplaceStringOutboundPolicy=h.RemoveQueryParamsInboundPolicy=h.RemoveHeadersOutboundPolicy=h.RemoveHeadersInboundPolicy=void 0;jp();var S0=br();Object.defineProperty(h,"MemoryZoneReadThroughCache",{enumerable:!0,get:function(){return S0.MemoryZoneReadThroughCache}});var I0=Zc();Object.defineProperty(h,"ZoneCache",{enumerable:!0,get:function(){return I0.ZoneCache}});var A0=Gp();Object.defineProperty(h,"VALID_COMPATIBILITY_DATES",{enumerable:!0,get:function(){return A0.VALID_COMPATIBILITY_DATES}});var F_=vr();Object.defineProperty(h,"ResponseSendingEvent",{enumerable:!0,get:function(){return F_.ResponseSendingEvent}});Object.defineProperty(h,"ResponseSentEvent",{enumerable:!0,get:function(){return F_.ResponseSentEvent}});var P0=sy();Object.defineProperty(h,"ContextLocalStorage",{enumerable:!0,get:function(){return P0.ContextLocalStorage}});var cp=nd();Object.defineProperty(h,"environment",{enumerable:!0,get:function(){return cp.environment}});Object.defineProperty(h,"isRestrictedEnvVariableName",{enumerable:!0,get:function(){return cp.isRestrictedEnvVariableName}});Object.defineProperty(h,"isZuploReadableEnvVariableName",{enumerable:!0,get:function(){return cp.isZuploReadableEnvVariableName}});var R0=D();Object.defineProperty(h,"ConfigurationError",{enumerable:!0,get:function(){return R0.ConfigurationError}});var O0=id();Object.defineProperty(h,"originalFetch",{enumerable:!0,get:function(){return O0.originalFetch}});var H_=my();Object.defineProperty(h,"Handler",{enumerable:!0,get:function(){return H_.Handler}});Object.defineProperty(h,"purgeGatewayCache",{enumerable:!0,get:function(){return H_.purgeGatewayCache}});var q_=Cy();Object.defineProperty(h,"AwsLambdaHandlerExtensions",{enumerable:!0,get:function(){return q_.AwsLambdaHandlerExtensions}});Object.defineProperty(h,"awsLambdaHandler",{enumerable:!0,get:function(){return q_.awsLambdaHandler}});var x0=Dy();Object.defineProperty(h,"openApiSpecHandler",{enumerable:!0,get:function(){return x0.openApiSpecHandler}});var N0=Uy();Object.defineProperty(h,"redirectHandler",{enumerable:!0,get:function(){return N0.redirectHandler}});var C0=ky();Object.defineProperty(h,"urlForwardHandler",{enumerable:!0,get:function(){return C0.urlForwardHandler}});var L0=Hy();Object.defineProperty(h,"urlRewriteHandler",{enumerable:!0,get:function(){return L0.urlRewriteHandler}});var D0=$y();Object.defineProperty(h,"webSocketHandler",{enumerable:!0,get:function(){return D0.webSocketHandler}});var U0=By();Object.defineProperty(h,"webSocketPipelineHandler",{enumerable:!0,get:function(){return U0.webSocketPipelineHandler}});var M0=gu();Object.defineProperty(h,"HttpStatusCode",{enumerable:!0,get:function(){return M0.HttpStatusCode}});k_(Xy(),h);k_(rg(),h);var k0=ng();Object.defineProperty(h,"AuditLogDataStaxProvider",{enumerable:!0,get:function(){return k0.AuditLogDataStaxProvider}});var F0=og();Object.defineProperty(h,"AuditLogPlugin",{enumerable:!0,get:function(){return F0.AuditLogPlugin}});var $_=pg();Object.defineProperty(h,"AmberfloMeteringInboundPolicy",{enumerable:!0,get:function(){return $_.AmberfloMeteringInboundPolicy}});Object.defineProperty(h,"AmberfloMeteringPolicy",{enumerable:!0,get:function(){return $_.AmberfloMeteringPolicy}});var j_=yg();Object.defineProperty(h,"ApiAuthKeyInboundPolicy",{enumerable:!0,get:function(){return j_.ApiAuthKeyInboundPolicy}});Object.defineProperty(h,"ApiKeyInboundPolicy",{enumerable:!0,get:function(){return j_.ApiKeyInboundPolicy}});var H0=gg();Object.defineProperty(h,"Auth0JwtInboundPolicy",{enumerable:!0,get:function(){return H0.Auth0JwtInboundPolicy}});var q0=_g();Object.defineProperty(h,"BasicAuthInboundPolicy",{enumerable:!0,get:function(){return q0.BasicAuthInboundPolicy}});var $0=bg();Object.defineProperty(h,"CachingInboundPolicy",{enumerable:!0,get:function(){return $0.CachingInboundPolicy}});var j0=Eg();Object.defineProperty(h,"ChangeMethodInboundPolicy",{enumerable:!0,get:function(){return j0.ChangeMethodInboundPolicy}});var V0=wg();Object.defineProperty(h,"ClearHeadersInboundPolicy",{enumerable:!0,get:function(){return V0.ClearHeadersInboundPolicy}});var G0=vg();Object.defineProperty(h,"ClearHeadersOutboundPolicy",{enumerable:!0,get:function(){return G0.ClearHeadersOutboundPolicy}});var B0=Tg();Object.defineProperty(h,"ClerkJwtInboundPolicy",{enumerable:!0,get:function(){return B0.ClerkJwtInboundPolicy}});var K0=Ig();Object.defineProperty(h,"CognitoJwtInboundPolicy",{enumerable:!0,get:function(){return K0.CognitoJwtInboundPolicy}});var J0=Pg();Object.defineProperty(h,"CompositeInboundPolicy",{enumerable:!0,get:function(){return J0.CompositeInboundPolicy}});var z0=Rg();Object.defineProperty(h,"FirebaseJwtInboundPolicy",{enumerable:!0,get:function(){return z0.FirebaseJwtInboundPolicy}});var W0=Og();Object.defineProperty(h,"FormDataToJsonInboundPolicy",{enumerable:!0,get:function(){return W0.FormDataToJsonInboundPolicy}});var Q0=xg();Object.defineProperty(h,"GeoFilterInboundPolicy",{enumerable:!0,get:function(){return Q0.GeoFilterInboundPolicy}});var Y0=Ng();Object.defineProperty(h,"JWTScopeValidationInboundPolicy",{enumerable:!0,get:function(){return Y0.JWTScopeValidationInboundPolicy}});var Z0=Lg();Object.defineProperty(h,"MockApiInboundPolicy",{enumerable:!0,get:function(){return Z0.MockApiInboundPolicy}});var V_=Fg();Object.defineProperty(h,"MoesifInboundPolicy",{enumerable:!0,get:function(){return V_.MoesifInboundPolicy}});Object.defineProperty(h,"setMoesifContext",{enumerable:!0,get:function(){return V_.setMoesifContext}});var X0=Hg();Object.defineProperty(h,"OktaJwtInboundPolicy",{enumerable:!0,get:function(){return X0.OktaJwtInboundPolicy}});var ex=Mt();Object.defineProperty(h,"OpenIdJwtInboundPolicy",{enumerable:!0,get:function(){return ex.OpenIdJwtInboundPolicy}});var tx=qg();Object.defineProperty(h,"PropelAuthJwtInboundPolicy",{enumerable:!0,get:function(){return tx.PropelAuthJwtInboundPolicy}});var G_=Jg();Object.defineProperty(h,"BasicRateLimitInboundPolicy",{enumerable:!0,get:function(){return G_.RateLimitInboundPolicy}});Object.defineProperty(h,"RateLimitInboundPolicy",{enumerable:!0,get:function(){return G_.RateLimitInboundPolicy}});var rx=Yg();Object.defineProperty(h,"ReadmeMetricsInboundPolicy",{enumerable:!0,get:function(){return rx.ReadmeMetricsInboundPolicy}});var nx=Zg();Object.defineProperty(h,"RemoveHeadersInboundPolicy",{enumerable:!0,get:function(){return nx.RemoveHeadersInboundPolicy}});var ix=Xg();Object.defineProperty(h,"RemoveHeadersOutboundPolicy",{enumerable:!0,get:function(){return ix.RemoveHeadersOutboundPolicy}});var ox=e_();Object.defineProperty(h,"RemoveQueryParamsInboundPolicy",{enumerable:!0,get:function(){return ox.RemoveQueryParamsInboundPolicy}});var sx=t_();Object.defineProperty(h,"ReplaceStringOutboundPolicy",{enumerable:!0,get:function(){return sx.ReplaceStringOutboundPolicy}});var ax=n_();Object.defineProperty(h,"RequestSizeLimitInboundPolicy",{enumerable:!0,get:function(){return ax.RequestSizeLimitInboundPolicy}});var B_=Dr();Object.defineProperty(h,"RequestValidationInboundPolicy",{enumerable:!0,get:function(){return B_.RequestValidationInboundPolicy}});Object.defineProperty(h,"SchemaBasedRequestValidation",{enumerable:!0,get:function(){return B_.SchemaBasedRequestValidation}});var cx=u_();Object.defineProperty(h,"RequireOriginInboundPolicy",{enumerable:!0,get:function(){return cx.RequireOriginInboundPolicy}});var ux=l_();Object.defineProperty(h,"SetBodyInboundPolicy",{enumerable:!0,get:function(){return ux.SetBodyInboundPolicy}});var lx=p_();Object.defineProperty(h,"SetHeadersInboundPolicy",{enumerable:!0,get:function(){return lx.SetHeadersInboundPolicy}});var dx=f_();Object.defineProperty(h,"SetHeadersOutboundPolicy",{enumerable:!0,get:function(){return dx.SetHeadersOutboundPolicy}});var px=y_();Object.defineProperty(h,"SetQueryParamsInboundPolicy",{enumerable:!0,get:function(){return px.SetQueryParamsInboundPolicy}});var hx=g_();Object.defineProperty(h,"SetStatusOutboundPolicy",{enumerable:!0,get:function(){return hx.SetStatusOutboundPolicy}});var fx=__();Object.defineProperty(h,"SleepInboundPolicy",{enumerable:!0,get:function(){return fx.SleepInboundPolicy}});var mx=E_();Object.defineProperty(h,"SupabaseJwtInboundPolicy",{enumerable:!0,get:function(){return mx.SupabaseJwtInboundPolicy}});var yx=v_();Object.defineProperty(h,"UpstreamAzureAdServiceAuthInboundPolicy",{enumerable:!0,get:function(){return yx.UpstreamAzureAdServiceAuthInboundPolicy}});var gx=S_();Object.defineProperty(h,"UpstreamFirebaseAdminAuthInboundPolicy",{enumerable:!0,get:function(){return gx.UpstreamFirebaseAdminAuthInboundPolicy}});var _x=A_();Object.defineProperty(h,"UpstreamFirebaseUserAuthInboundPolicy",{enumerable:!0,get:function(){return _x.UpstreamFirebaseUserAuthInboundPolicy}});var bx=R_();Object.defineProperty(h,"UpstreamGcpJwtInboundPolicy",{enumerable:!0,get:function(){return bx.UpstreamGcpJwtInboundPolicy}});var Ex=N_();Object.defineProperty(h,"UpstreamGcpServiceAuthInboundPolicy",{enumerable:!0,get:function(){return Ex.UpstreamGcpServiceAuthInboundPolicy}});var wx=L_();Object.defineProperty(h,"ValidateJsonSchemaInbound",{enumerable:!0,get:function(){return wx.ValidateJsonSchemaInbound}});var vx=ve();Object.defineProperty(h,"HttpProblems",{enumerable:!0,get:function(){return vx.HttpProblems}});var Tx=ao();Object.defineProperty(h,"ProblemResponseFormatter",{enumerable:!0,get:function(){return Tx.ProblemResponseFormatter}});var Sx=Yn();Object.defineProperty(h,"ZuploRequest",{enumerable:!0,get:function(){return Sx.ZuploRequest}});var Ix=Ir();Object.defineProperty(h,"SystemRouteName",{enumerable:!0,get:function(){return Ix.SystemRouteName}});var K_=zl();Object.defineProperty(h,"LookupResult",{enumerable:!0,get:function(){return K_.LookupResult}});Object.defineProperty(h,"Router",{enumerable:!0,get:function(){return K_.Router}});var J_=D_();Object.defineProperty(h,"ContentTypes",{enumerable:!0,get:function(){return J_.ContentTypes}});Object.defineProperty(h,"serialize",{enumerable:!0,get:function(){return J_.serialize}});var Ax=U_();Object.defineProperty(h,"ServiceProviderImpl",{enumerable:!0,get:function(){return Ax.ServiceProviderImpl}});var z_=Pu();Object.defineProperty(h,"API_KEY",{enumerable:!0,get:function(){return z_.API_KEY}});Object.defineProperty(h,"SYSTEM_LOGGER",{enumerable:!0,get:function(){return z_.SYSTEM_LOGGER}});var Px=M_();Object.defineProperty(h,"httpStatuses",{enumerable:!0,get:function(){return T0(Px).default}});var Rx=Ge();Object.defineProperty(h,"SystemLogMap",{enumerable:!0,get:function(){return Rx.SystemLogMap}});var Oi=Ma();Object.defineProperty(h,"getIdForParameterSchema",{enumerable:!0,get:function(){return Oi.getIdForParameterSchema}});Object.defineProperty(h,"getIdForRefSchema",{enumerable:!0,get:function(){return Oi.getIdForRefSchema}});Object.defineProperty(h,"getIdForRequestBodySchema",{enumerable:!0,get:function(){return Oi.getIdForRequestBodySchema}});Object.defineProperty(h,"getRawOperationDataIdentifierName",{enumerable:!0,get:function(){return Oi.getRawOperationDataIdentifierName}});Object.defineProperty(h,"sanitizedIdentifierName",{enumerable:!0,get:function(){return Oi.sanitizedIdentifierName}})});var W_=g(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.BaseCryptoBeta=Dn.supportedDigests=void 0;Dn.supportedDigests=["sha-1","sha-256","sha-384","sha-512"];var up=class{static{o(this,"BaseCryptoBeta")}};Dn.BaseCryptoBeta=up});var Q_=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.WorkerCryptoBeta=void 0;var lp=W_(),Ox=D(),dp=class extends lp.BaseCryptoBeta{static{o(this,"WorkerCryptoBeta")}async digest(e,r){if(!lp.supportedDigests.includes(e.toLowerCase()))throw new Ox.RuntimeError(`Algorithm ${e} is not supported. Try using ${lp.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("")}};oc.WorkerCryptoBeta=dp});var Y_=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.BaseKeyValueStore=void 0;var pp=class{static{o(this,"BaseKeyValueStore")}context;constructor(e){this.context=e}};sc.BaseKeyValueStore=pp});var X_=g(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.WorkerKeyValueStore=void 0;var Z_=D(),xx=Y_(),hp=class extends xx.BaseKeyValueStore{static{o(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let n=globalThis.ZUPLO_KV;if(!n)throw new Z_.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 Z_.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)}};ac.WorkerKeyValueStore=hp});var xt=g(ct=>{"use strict";var Nx=ct&&ct.__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]}),Cx=ct&&ct.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nx(e,t,r)};Object.defineProperty(ct,"__esModule",{value:!0});ct.KeyValueStore=ct.CryptoBeta=void 0;Cx(ke(),ct);var Lx=Q_();Object.defineProperty(ct,"CryptoBeta",{enumerable:!0,get:function(){return Lx.WorkerCryptoBeta}});var Dx=X_();Object.defineProperty(ct,"KeyValueStore",{enumerable:!0,get:function(){return Dx.WorkerKeyValueStore}})});var $N={};Ki($N,{GraphQLComplexityLimitInboundPolicy:()=>Nb,GraphQLDisableIntrospectionInboundPolicy:()=>Lb});module.exports=Ji($N);var Kn=Fp(xt());function B(t,e){if(!!!t)throw new Error(e)}o(B,"devAssert");function be(t){return typeof t=="object"&&t!==null}o(be,"isObjectLike");function St(t,e){if(!!!t)throw new Error(e??"Unexpected invariant triggered.")}o(St,"invariant");var Ux=/\r\n|[\n\r]/g;function Un(t,e){let r=0,n=1;for(let i of t.body.matchAll(Ux)){if(typeof i.index=="number"||St(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}o(Un,"getLocation");function fp(t){return cc(t.source,Un(t.source,t.start))}o(fp,"printLocation");function cc(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}
66
+ `,d=n.split(/\r\n|[\n\r]/g),p=d[i];if(p.length>120){let m=Math.floor(u/80),f=u%80,y=[];for(let v=0;v<p.length;v+=80)y.push(p.slice(v,v+80));return l+eb([[`${a} |`,y[0]],...y.slice(1,m+1).map(v=>["|",v]),["|","^".padStart(f)],["|",y[m+1]]])}return l+eb([[`${a-1} |`,d[i-1]],[`${a} |`,p],["|","^".padStart(u)],[`${a+1} |`,d[i+1]]])}o(cc,"printSourceLocation");function eb(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(`
67
+ `)}o(eb,"printPrefixedLines");function Mx(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(Mx,"toNormalizedOptions");var C=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}=Mx(r);super(e),this.name="GraphQLError",this.path=l??void 0,this.originalError=d??void 0,this.nodes=tb(Array.isArray(a)?a:a?[a]:void 0);let m=tb((n=this.nodes)===null||n===void 0?void 0:n.map(y=>y.loc).filter(y=>y!=null));this.source=c??(m==null||(i=m[0])===null||i===void 0?void 0:i.source),this.positions=u??m?.map(y=>y.start),this.locations=u&&c?u.map(y=>Un(c,y)):m?.map(y=>Un(y.source,y.start));let f=be(d?.extensions)?d?.extensions:void 0;this.extensions=(s=p??f)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,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+=`
68
68
 
69
- `+hp(r.loc));else if(this.source&&this.locations)for(let r of this.locations)e+=`
69
+ `+fp(r.loc));else if(this.source&&this.locations)for(let r of this.locations)e+=`
70
70
 
71
- `+ac(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 X_(t){return t===void 0||t.length===0?void 0:t}o(X_,"undefinedIfEmpty");function le(t,e,r){return new C(`Syntax Error: ${r}`,{source:t,positions:[e]})}o(le,"syntaxError");var xi=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}}},Mn=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}}},fp={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"]},Cx=new Set(Object.keys(fp));function Ni(t){let e=t?.kind;return typeof e=="string"&&Cx.has(e)}o(Ni,"isNode");var rt;(function(t){t.QUERY="query",t.MUTATION="mutation",t.SUBSCRIPTION="subscription"})(rt||(rt={}));var K;(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"})(K||(K={}));var _;(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"})(_||(_={}));function cc(t){return t===9||t===32}o(cc,"isWhiteSpace");function kn(t){return t>=48&&t<=57}o(kn,"isDigit");function eb(t){return t>=97&&t<=122||t>=65&&t<=90}o(eb,"isLetter");function Ci(t){return eb(t)||t===95}o(Ci,"isNameStart");function uc(t){return eb(t)||kn(t)||t===95}o(uc,"isNameContinue");function tb(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=Lx(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(tb,"dedentBlockStringLines");function Lx(t){let e=0;for(;e<t.length&&cc(t.charCodeAt(e));)++e;return e}o(Lx,"leadingWhitespace");function rb(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(f=>f.length===0||cc(f.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="",m=i&&cc(t.charCodeAt(0));return(d&&!m||s)&&(p+=`
71
+ `+cc(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 tb(t){return t===void 0||t.length===0?void 0:t}o(tb,"undefinedIfEmpty");function le(t,e,r){return new C(`Syntax Error: ${r}`,{source:t,positions:[e]})}o(le,"syntaxError");var xi=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}}},Mn=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}}},mp={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"]},kx=new Set(Object.keys(mp));function Ni(t){let e=t?.kind;return typeof e=="string"&&kx.has(e)}o(Ni,"isNode");var rt;(function(t){t.QUERY="query",t.MUTATION="mutation",t.SUBSCRIPTION="subscription"})(rt||(rt={}));var K;(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"})(K||(K={}));var _;(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"})(_||(_={}));function uc(t){return t===9||t===32}o(uc,"isWhiteSpace");function kn(t){return t>=48&&t<=57}o(kn,"isDigit");function rb(t){return t>=97&&t<=122||t>=65&&t<=90}o(rb,"isLetter");function Ci(t){return rb(t)||t===95}o(Ci,"isNameStart");function lc(t){return rb(t)||kn(t)||t===95}o(lc,"isNameContinue");function nb(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=Fx(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(nb,"dedentBlockStringLines");function Fx(t){let e=0;for(;e<t.length&&uc(t.charCodeAt(e));)++e;return e}o(Fx,"leadingWhitespace");function ib(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(f=>f.length===0||uc(f.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="",m=i&&uc(t.charCodeAt(0));return(d&&!m||s)&&(p+=`
72
72
  `),p+=r,(d||l)&&(p+=`
73
- `),'"""'+p+'"""'}o(rb,"printBlockString");var b;(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"})(b||(b={}));var Di=class{static{o(this,"Lexer")}constructor(e){let r=new Mn(b.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!==b.EOF)do if(e.next)e=e.next;else{let r=Dx(this,e.end);e.next=r,r.prev=e,e=r}while(e.kind===b.COMMENT);return e}};function ib(t){return t===b.BANG||t===b.DOLLAR||t===b.AMP||t===b.PAREN_L||t===b.PAREN_R||t===b.SPREAD||t===b.COLON||t===b.EQUALS||t===b.AT||t===b.BRACKET_L||t===b.BRACKET_R||t===b.BRACE_L||t===b.PIPE||t===b.BRACE_R}o(ib,"isPunctuatorTokenKind");function Fn(t){return t>=0&&t<=55295||t>=57344&&t<=1114111}o(Fn,"isUnicodeScalarValue");function lc(t,e){return ob(t.charCodeAt(e))&&sb(t.charCodeAt(e+1))}o(lc,"isSupplementaryCodePoint");function ob(t){return t>=55296&&t<=56319}o(ob,"isLeadingSurrogate");function sb(t){return t>=56320&&t<=57343}o(sb,"isTrailingSurrogate");function Ur(t,e){let r=t.source.body.codePointAt(e);if(r===void 0)return b.EOF;if(r>=32&&r<=126){let n=String.fromCodePoint(r);return n==='"'?`'"'`:`"${n}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}o(Ur,"printCodePointAt");function he(t,e,r,n,i){let s=t.line,a=1+r-t.lineStart;return new Mn(e,r,n,s,a,i)}o(he,"createToken");function Dx(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 Ux(t,i);case 33:return he(t,b.BANG,i,i+1);case 36:return he(t,b.DOLLAR,i,i+1);case 38:return he(t,b.AMP,i,i+1);case 40:return he(t,b.PAREN_L,i,i+1);case 41:return he(t,b.PAREN_R,i,i+1);case 46:if(r.charCodeAt(i+1)===46&&r.charCodeAt(i+2)===46)return he(t,b.SPREAD,i,i+3);break;case 58:return he(t,b.COLON,i,i+1);case 61:return he(t,b.EQUALS,i,i+1);case 64:return he(t,b.AT,i,i+1);case 91:return he(t,b.BRACKET_L,i,i+1);case 93:return he(t,b.BRACKET_R,i,i+1);case 123:return he(t,b.BRACE_L,i,i+1);case 124:return he(t,b.PIPE,i,i+1);case 125:return he(t,b.BRACE_R,i,i+1);case 34:return r.charCodeAt(i+1)===34&&r.charCodeAt(i+2)===34?$x(t,i):kx(t,i)}if(kn(s)||s===45)return Mx(t,i,s);if(Ci(s))return jx(t,i);throw le(t.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:Fn(s)||lc(r,i)?`Unexpected character: ${Ur(t,i)}.`:`Invalid character: ${Ur(t,i)}.`)}return he(t,b.EOF,n,n)}o(Dx,"readNextToken");function Ux(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(Fn(s))++i;else if(lc(r,i))i+=2;else break}return he(t,b.COMMENT,e,i,r.slice(e+1,i))}o(Ux,"readComment");function Mx(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),kn(s))throw le(t.source,i,`Invalid number, unexpected digit after 0: ${Ur(t,i)}.`)}else i=mp(t,i,s),s=n.charCodeAt(i);if(s===46&&(a=!0,s=n.charCodeAt(++i),i=mp(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=mp(t,i,s),s=n.charCodeAt(i)),s===46||Ci(s))throw le(t.source,i,`Invalid number, expected digit but got: ${Ur(t,i)}.`);return he(t,a?b.FLOAT:b.INT,e,i,n.slice(e,i))}o(Mx,"readNumber");function mp(t,e,r){if(!kn(r))throw le(t.source,e,`Invalid number, expected digit but got: ${Ur(t,e)}.`);let n=t.source.body,i=e+1;for(;kn(n.charCodeAt(i));)++i;return i}o(mp,"readDigits");function kx(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),he(t,b.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?Fx(t,i):Hx(t,i):qx(t,i);a+=u.value,i+=u.size,s=i;continue}if(c===10||c===13)break;if(Fn(c))++i;else if(lc(r,i))i+=2;else throw le(t.source,i,`Invalid character within String: ${Ur(t,i)}.`)}throw le(t.source,i,"Unterminated string.")}o(kx,"readString");function Fx(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||!Fn(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|Li(s),n<0)break}throw le(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+i)}".`)}o(Fx,"readEscapedUnicodeVariableWidth");function Hx(t,e){let r=t.source.body,n=nb(r,e+2);if(Fn(n))return{value:String.fromCodePoint(n),size:6};if(ob(n)&&r.charCodeAt(e+6)===92&&r.charCodeAt(e+7)===117){let i=nb(r,e+8);if(sb(i))return{value:String.fromCodePoint(n,i),size:12}}throw le(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+6)}".`)}o(Hx,"readEscapedUnicodeFixedWidth");function nb(t,e){return Li(t.charCodeAt(e))<<12|Li(t.charCodeAt(e+1))<<8|Li(t.charCodeAt(e+2))<<4|Li(t.charCodeAt(e+3))}o(nb,"read16BitHexCode");function Li(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:-1}o(Li,"readHexDigit");function qx(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:`
74
- `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw le(t.source,e,`Invalid character escape sequence: "${r.slice(e,e+2)}".`)}o(qx,"readEscapedCharacter");function $x(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=he(t,b.BLOCK_STRING,e,s+3,tb(u).join(`
75
- `));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(Fn(l))++s;else if(lc(r,s))s+=2;else throw le(t.source,s,`Invalid character within String: ${Ur(t,s)}.`)}throw le(t.source,s,"Unterminated string.")}o($x,"readBlockString");function jx(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(uc(s))++i;else break}return he(t,b.NAME,e,i,r.slice(e,i))}o(jx,"readName");function A(t){return dc(t,[])}o(A,"inspect");function dc(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return Vx(t,e);default:return String(t)}}o(dc,"formatValue");function Vx(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(Gx(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:dc(n,r)}else if(Array.isArray(t))return Kx(t,r);return Bx(t,r)}o(Vx,"formatObjectValue");function Gx(t){return typeof t.toJSON=="function"}o(Gx,"isJSONable");function Bx(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+Jx(t)+"]":"{ "+r.map(([i,s])=>i+": "+dc(s,e)).join(", ")+" }"}o(Bx,"formatObject");function Kx(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(dc(t[s],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}o(Kx,"formatArray");function Jx(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(Jx,"getObjectTag");var Je=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=A(e);throw new Error(`Cannot use ${i} "${a}" from another module or realm.
73
+ `),'"""'+p+'"""'}o(ib,"printBlockString");var b;(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"})(b||(b={}));var Di=class{static{o(this,"Lexer")}constructor(e){let r=new Mn(b.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!==b.EOF)do if(e.next)e=e.next;else{let r=Hx(this,e.end);e.next=r,r.prev=e,e=r}while(e.kind===b.COMMENT);return e}};function sb(t){return t===b.BANG||t===b.DOLLAR||t===b.AMP||t===b.PAREN_L||t===b.PAREN_R||t===b.SPREAD||t===b.COLON||t===b.EQUALS||t===b.AT||t===b.BRACKET_L||t===b.BRACKET_R||t===b.BRACE_L||t===b.PIPE||t===b.BRACE_R}o(sb,"isPunctuatorTokenKind");function Fn(t){return t>=0&&t<=55295||t>=57344&&t<=1114111}o(Fn,"isUnicodeScalarValue");function dc(t,e){return ab(t.charCodeAt(e))&&cb(t.charCodeAt(e+1))}o(dc,"isSupplementaryCodePoint");function ab(t){return t>=55296&&t<=56319}o(ab,"isLeadingSurrogate");function cb(t){return t>=56320&&t<=57343}o(cb,"isTrailingSurrogate");function Ur(t,e){let r=t.source.body.codePointAt(e);if(r===void 0)return b.EOF;if(r>=32&&r<=126){let n=String.fromCodePoint(r);return n==='"'?`'"'`:`"${n}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}o(Ur,"printCodePointAt");function he(t,e,r,n,i){let s=t.line,a=1+r-t.lineStart;return new Mn(e,r,n,s,a,i)}o(he,"createToken");function Hx(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 qx(t,i);case 33:return he(t,b.BANG,i,i+1);case 36:return he(t,b.DOLLAR,i,i+1);case 38:return he(t,b.AMP,i,i+1);case 40:return he(t,b.PAREN_L,i,i+1);case 41:return he(t,b.PAREN_R,i,i+1);case 46:if(r.charCodeAt(i+1)===46&&r.charCodeAt(i+2)===46)return he(t,b.SPREAD,i,i+3);break;case 58:return he(t,b.COLON,i,i+1);case 61:return he(t,b.EQUALS,i,i+1);case 64:return he(t,b.AT,i,i+1);case 91:return he(t,b.BRACKET_L,i,i+1);case 93:return he(t,b.BRACKET_R,i,i+1);case 123:return he(t,b.BRACE_L,i,i+1);case 124:return he(t,b.PIPE,i,i+1);case 125:return he(t,b.BRACE_R,i,i+1);case 34:return r.charCodeAt(i+1)===34&&r.charCodeAt(i+2)===34?Kx(t,i):jx(t,i)}if(kn(s)||s===45)return $x(t,i,s);if(Ci(s))return Jx(t,i);throw le(t.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:Fn(s)||dc(r,i)?`Unexpected character: ${Ur(t,i)}.`:`Invalid character: ${Ur(t,i)}.`)}return he(t,b.EOF,n,n)}o(Hx,"readNextToken");function qx(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(Fn(s))++i;else if(dc(r,i))i+=2;else break}return he(t,b.COMMENT,e,i,r.slice(e+1,i))}o(qx,"readComment");function $x(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),kn(s))throw le(t.source,i,`Invalid number, unexpected digit after 0: ${Ur(t,i)}.`)}else i=yp(t,i,s),s=n.charCodeAt(i);if(s===46&&(a=!0,s=n.charCodeAt(++i),i=yp(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=yp(t,i,s),s=n.charCodeAt(i)),s===46||Ci(s))throw le(t.source,i,`Invalid number, expected digit but got: ${Ur(t,i)}.`);return he(t,a?b.FLOAT:b.INT,e,i,n.slice(e,i))}o($x,"readNumber");function yp(t,e,r){if(!kn(r))throw le(t.source,e,`Invalid number, expected digit but got: ${Ur(t,e)}.`);let n=t.source.body,i=e+1;for(;kn(n.charCodeAt(i));)++i;return i}o(yp,"readDigits");function jx(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),he(t,b.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?Vx(t,i):Gx(t,i):Bx(t,i);a+=u.value,i+=u.size,s=i;continue}if(c===10||c===13)break;if(Fn(c))++i;else if(dc(r,i))i+=2;else throw le(t.source,i,`Invalid character within String: ${Ur(t,i)}.`)}throw le(t.source,i,"Unterminated string.")}o(jx,"readString");function Vx(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||!Fn(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|Li(s),n<0)break}throw le(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+i)}".`)}o(Vx,"readEscapedUnicodeVariableWidth");function Gx(t,e){let r=t.source.body,n=ob(r,e+2);if(Fn(n))return{value:String.fromCodePoint(n),size:6};if(ab(n)&&r.charCodeAt(e+6)===92&&r.charCodeAt(e+7)===117){let i=ob(r,e+8);if(cb(i))return{value:String.fromCodePoint(n,i),size:12}}throw le(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+6)}".`)}o(Gx,"readEscapedUnicodeFixedWidth");function ob(t,e){return Li(t.charCodeAt(e))<<12|Li(t.charCodeAt(e+1))<<8|Li(t.charCodeAt(e+2))<<4|Li(t.charCodeAt(e+3))}o(ob,"read16BitHexCode");function Li(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:-1}o(Li,"readHexDigit");function Bx(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:`
74
+ `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw le(t.source,e,`Invalid character escape sequence: "${r.slice(e,e+2)}".`)}o(Bx,"readEscapedCharacter");function Kx(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=he(t,b.BLOCK_STRING,e,s+3,nb(u).join(`
75
+ `));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(Fn(l))++s;else if(dc(r,s))s+=2;else throw le(t.source,s,`Invalid character within String: ${Ur(t,s)}.`)}throw le(t.source,s,"Unterminated string.")}o(Kx,"readBlockString");function Jx(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let s=r.charCodeAt(i);if(lc(s))++i;else break}return he(t,b.NAME,e,i,r.slice(e,i))}o(Jx,"readName");function A(t){return pc(t,[])}o(A,"inspect");function pc(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return zx(t,e);default:return String(t)}}o(pc,"formatValue");function zx(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(Wx(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:pc(n,r)}else if(Array.isArray(t))return Yx(t,r);return Qx(t,r)}o(zx,"formatObjectValue");function Wx(t){return typeof t.toJSON=="function"}o(Wx,"isJSONable");function Qx(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+Zx(t)+"]":"{ "+r.map(([i,s])=>i+": "+pc(s,e)).join(", ")+" }"}o(Qx,"formatObject");function Yx(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(pc(t[s],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}o(Yx,"formatArray");function Zx(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(Zx,"getObjectTag");var Je=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=A(e);throw new Error(`Cannot use ${i} "${a}" from another module or realm.
76
76
 
77
77
  Ensure that there is only one instance of "graphql" in the node_modules
78
78
  directory. If different versions of "graphql" are the dependencies of other
@@ -83,17 +83,17 @@ https://yarnpkg.com/en/docs/selective-version-resolutions
83
83
  Duplicate "graphql" modules cannot be used at the same time since different
84
84
  versions may have different capabilities and behavior. The data from one
85
85
  version used in the function from another could produce confusing and
86
- spurious results.`)}}return!1},"instanceOf");var Hn=class{static{o(this,"Source")}constructor(e,r="GraphQL request",n={line:1,column:1}){typeof e=="string"||B(!1,`Body must be a string. Received: ${A(e)}.`),this.body=e,this.name=r,this.locationOffset=n,this.locationOffset.line>0||B(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||B(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}};function ab(t){return Je(t,Hn)}o(ab,"isSource");function fc(t,e){return new hc(t,e).parseDocument()}o(fc,"parse");function mc(t,e){let r=new hc(t,e);r.expectToken(b.SOF);let n=r.parseValueLiteral(!1);return r.expectToken(b.EOF),n}o(mc,"parseValue");var hc=class{static{o(this,"Parser")}constructor(e,r={}){let n=ab(e)?e:new Hn(e);this._lexer=new Di(n),this._options=r,this._tokenCounter=0}parseName(){let e=this.expectToken(b.NAME);return this.node(e,{kind:_.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:_.DOCUMENT,definitions:this.many(b.SOF,this.parseDefinition,b.EOF)})}parseDefinition(){if(this.peek(b.BRACE_L))return this.parseOperationDefinition();let e=this.peekDescription(),r=e?this._lexer.lookahead():this._lexer.token;if(r.kind===b.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 le(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(b.BRACE_L))return this.node(e,{kind:_.OPERATION_DEFINITION,operation:rt.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});let r=this.parseOperationType(),n;return this.peek(b.NAME)&&(n=this.parseName()),this.node(e,{kind:_.OPERATION_DEFINITION,operation:r,name:n,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){let e=this.expectToken(b.NAME);switch(e.value){case"query":return rt.QUERY;case"mutation":return rt.MUTATION;case"subscription":return rt.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(b.PAREN_L,this.parseVariableDefinition,b.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:_.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(b.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(b.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){let e=this._lexer.token;return this.expectToken(b.DOLLAR),this.node(e,{kind:_.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:_.SELECTION_SET,selections:this.many(b.BRACE_L,this.parseSelection,b.BRACE_R)})}parseSelection(){return this.peek(b.SPREAD)?this.parseFragment():this.parseField()}parseField(){let e=this._lexer.token,r=this.parseName(),n,i;return this.expectOptionalToken(b.COLON)?(n=r,i=this.parseName()):i=r,this.node(e,{kind:_.FIELD,alias:n,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(b.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){let r=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(b.PAREN_L,r,b.PAREN_R)}parseArgument(e=!1){let r=this._lexer.token,n=this.parseName();return this.expectToken(b.COLON),this.node(r,{kind:_.ARGUMENT,name:n,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){let e=this._lexer.token;this.expectToken(b.SPREAD);let r=this.expectOptionalKeyword("on");return!r&&this.peek(b.NAME)?this.node(e,{kind:_.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(e,{kind:_.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:_.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:_.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 b.BRACKET_L:return this.parseList(e);case b.BRACE_L:return this.parseObject(e);case b.INT:return this.advanceLexer(),this.node(r,{kind:_.INT,value:r.value});case b.FLOAT:return this.advanceLexer(),this.node(r,{kind:_.FLOAT,value:r.value});case b.STRING:case b.BLOCK_STRING:return this.parseStringLiteral();case b.NAME:switch(this.advanceLexer(),r.value){case"true":return this.node(r,{kind:_.BOOLEAN,value:!0});case"false":return this.node(r,{kind:_.BOOLEAN,value:!1});case"null":return this.node(r,{kind:_.NULL});default:return this.node(r,{kind:_.ENUM,value:r.value})}case b.DOLLAR:if(e)if(this.expectToken(b.DOLLAR),this._lexer.token.kind===b.NAME){let n=this._lexer.token.value;throw le(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:_.STRING,value:e.value,block:e.kind===b.BLOCK_STRING})}parseList(e){let r=o(()=>this.parseValueLiteral(e),"item");return this.node(this._lexer.token,{kind:_.LIST,values:this.any(b.BRACKET_L,r,b.BRACKET_R)})}parseObject(e){let r=o(()=>this.parseObjectField(e),"item");return this.node(this._lexer.token,{kind:_.OBJECT,fields:this.any(b.BRACE_L,r,b.BRACE_R)})}parseObjectField(e){let r=this._lexer.token,n=this.parseName();return this.expectToken(b.COLON),this.node(r,{kind:_.OBJECT_FIELD,name:n,value:this.parseValueLiteral(e)})}parseDirectives(e){let r=[];for(;this.peek(b.AT);)r.push(this.parseDirective(e));return r}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){let r=this._lexer.token;return this.expectToken(b.AT),this.node(r,{kind:_.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){let e=this._lexer.token,r;if(this.expectOptionalToken(b.BRACKET_L)){let n=this.parseTypeReference();this.expectToken(b.BRACKET_R),r=this.node(e,{kind:_.LIST_TYPE,type:n})}else r=this.parseNamedType();return this.expectOptionalToken(b.BANG)?this.node(e,{kind:_.NON_NULL_TYPE,type:r}):r}parseNamedType(){return this.node(this._lexer.token,{kind:_.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(b.STRING)||this.peek(b.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(b.BRACE_L,this.parseOperationTypeDefinition,b.BRACE_R);return this.node(e,{kind:_.SCHEMA_DEFINITION,description:r,directives:n,operationTypes:i})}parseOperationTypeDefinition(){let e=this._lexer.token,r=this.parseOperationType();this.expectToken(b.COLON);let n=this.parseNamedType();return this.node(e,{kind:_.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:_.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:_.OBJECT_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(b.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(b.BRACE_L,this.parseFieldDefinition,b.BRACE_R)}parseFieldDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName(),i=this.parseArgumentDefs();this.expectToken(b.COLON);let s=this.parseTypeReference(),a=this.parseConstDirectives();return this.node(e,{kind:_.FIELD_DEFINITION,description:r,name:n,arguments:i,type:s,directives:a})}parseArgumentDefs(){return this.optionalMany(b.PAREN_L,this.parseInputValueDef,b.PAREN_R)}parseInputValueDef(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName();this.expectToken(b.COLON);let i=this.parseTypeReference(),s;this.expectOptionalToken(b.EQUALS)&&(s=this.parseConstValueLiteral());let a=this.parseConstDirectives();return this.node(e,{kind:_.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:_.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:_.UNION_TYPE_DEFINITION,description:r,name:n,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(b.EQUALS)?this.delimitedMany(b.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:_.ENUM_TYPE_DEFINITION,description:r,name:n,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(b.BRACE_L,this.parseEnumValueDefinition,b.BRACE_R)}parseEnumValueDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(e,{kind:_.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 le(this._lexer.source,this._lexer.token.start,`${pc(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:_.INPUT_OBJECT_TYPE_DEFINITION,description:r,name:n,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(b.BRACE_L,this.parseInputValueDef,b.BRACE_R)}parseTypeSystemExtension(){let e=this._lexer.lookahead();if(e.kind===b.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(b.BRACE_L,this.parseOperationTypeDefinition,b.BRACE_R);if(r.length===0&&n.length===0)throw this.unexpected();return this.node(e,{kind:_.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:_.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:_.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:_.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:_.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:_.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:_.INPUT_OBJECT_TYPE_EXTENSION,name:r,directives:n,fields:i})}parseDirectiveDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("directive"),this.expectToken(b.AT);let n=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");let a=this.parseDirectiveLocations();return this.node(e,{kind:_.DIRECTIVE_DEFINITION,description:r,name:n,arguments:i,repeatable:s,locations:a})}parseDirectiveLocations(){return this.delimitedMany(b.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){let e=this._lexer.token,r=this.parseName();if(Object.prototype.hasOwnProperty.call(K,r.value))return r;throw this.unexpected(e)}node(e,r){return this._options.noLocation!==!0&&(r.loc=new xi(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 le(this._lexer.source,r.start,`Expected ${cb(e)}, found ${pc(r)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e?(this.advanceLexer(),!0):!1}expectKeyword(e){let r=this._lexer.token;if(r.kind===b.NAME&&r.value===e)this.advanceLexer();else throw le(this._lexer.source,r.start,`Expected "${e}", found ${pc(r)}.`)}expectOptionalKeyword(e){let r=this._lexer.token;return r.kind===b.NAME&&r.value===e?(this.advanceLexer(),!0):!1}unexpected(e){let r=e??this._lexer.token;return le(this._lexer.source,r.start,`Unexpected ${pc(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!==b.EOF&&(++this._tokenCounter,this._tokenCounter>e))throw le(this._lexer.source,r.start,`Document contains more that ${e} tokens. Parsing aborted.`)}};function pc(t){let e=t.value;return cb(t.kind)+(e!=null?` "${e}"`:"")}o(pc,"getTokenDesc");function cb(t){return ib(t)?`"${t}"`:t}o(cb,"getTokenKindDesc");function yc(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(yc,"didYouMean");function yp(t){return t}o(yp,"identityFunc");function qn(t,e){let r=Object.create(null);for(let n of t)r[e(n)]=n;return r}o(qn,"keyMap");function It(t,e,r){let n=Object.create(null);for(let i of t)n[e(i)]=r(i);return n}o(It,"keyValMap");function Ui(t,e){let r=Object.create(null);for(let n of Object.keys(t))r[n]=e(t[n],n);return r}o(Ui,"mapValue");function ub(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let i=t.charCodeAt(r),s=e.charCodeAt(n);if(gc(i)&&gc(s)){let a=0;do++r,a=a*10+i-gp,i=t.charCodeAt(r);while(gc(i)&&a>0);let c=0;do++n,c=c*10+s-gp,s=e.charCodeAt(n);while(gc(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(ub,"naturalCompare");var gp=48,zx=57;function gc(t){return!isNaN(t)&&gp<=t&&t<=zx}o(gc,"isDigit");function _c(t,e){let r=Object.create(null),n=new _p(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:ub(s,a)})}o(_c,"suggestionList");var _p=class{static{o(this,"LexicalDistance")}constructor(e){this._input=e,this._inputLowerCase=e.toLowerCase(),this._inputArray=lb(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=lb(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],m=u[d%3],f=m[0]=d;for(let y=1;y<=c;y++){let v=i[d-1]===s[y-1]?0:1,T=Math.min(p[y]+1,m[y-1]+1,p[y-1]+v);if(d>1&&y>1&&i[d-1]===s[y-2]&&i[d-2]===s[y-1]){let S=u[(d-2)%3][y-2];T=Math.min(T,S+1)}T<f&&(f=T),m[y]=T}if(f>r)return}let l=u[a%3][c];return l<=r?l:void 0}};function lb(t){let e=t.length,r=new Array(e);for(let n=0;n<e;++n)r[n]=t.charCodeAt(n);return r}o(lb,"stringToArray");function Le(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(Le,"toObjMap");function db(t){return`"${t.replace(Wx,Qx)}"`}o(db,"printString");var Wx=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Qx(t){return Yx[t.charCodeAt(0)]}o(Qx,"escapedReplacer");var Yx=["\\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 bp=Object.freeze({});function hr(t,e,r=fp){let n=new Map;for(let S of Object.values(_))n.set(S,$n(e,S));let i,s=Array.isArray(t),a=[t],c=-1,u=[],l=t,d,p,m=[],f=[];do{c++;let S=c===a.length,M=S&&u.length!==0;if(S){if(d=f.length===0?void 0:m[m.length-1],l=p,p=f.pop(),M)if(s){l=l.slice();let R=0;for(let[ne,Y]of u){let fe=ne-R;Y===null?(l.splice(fe,1),R++):l[fe]=Y}}else{l=Object.defineProperties({},Object.getOwnPropertyDescriptors(l));for(let[R,ne]of u)l[R]=ne}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;m.push(d)}let H;if(!Array.isArray(l)){var y,v;Ni(l)||B(!1,`Invalid AST Node: ${A(l)}.`);let R=S?(y=n.get(l.kind))===null||y===void 0?void 0:y.leave:(v=n.get(l.kind))===null||v===void 0?void 0:v.enter;if(H=R?.call(e,l,d,p,m,f),H===bp)break;if(H===!1){if(!S){m.pop();continue}}else if(H!==void 0&&(u.push([d,H]),!S))if(Ni(H))l=H;else{m.pop();continue}}if(H===void 0&&M&&u.push([d,l]),S)m.pop();else{var T;i={inArray:s,index:c,keys:a,edits:u,prev:i},s=Array.isArray(l),a=s?l:(T=r[l.kind])!==null&&T!==void 0?T:[],c=-1,u=[],p&&f.push(p),p=l}}while(i!==void 0);return u.length!==0?u[u.length-1][1]:t}o(hr,"visit");function $n(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($n,"getEnterLeaveForKind");function De(t){return hr(t,Xx)}o(De,"print");var Zx=80,Xx={Name:{leave:t=>t.value},Variable:{leave:t=>"$"+t.name},Document:{leave:t=>x(t.definitions,`
86
+ spurious results.`)}}return!1},"instanceOf");var Hn=class{static{o(this,"Source")}constructor(e,r="GraphQL request",n={line:1,column:1}){typeof e=="string"||B(!1,`Body must be a string. Received: ${A(e)}.`),this.body=e,this.name=r,this.locationOffset=n,this.locationOffset.line>0||B(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||B(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}};function ub(t){return Je(t,Hn)}o(ub,"isSource");function mc(t,e){return new fc(t,e).parseDocument()}o(mc,"parse");function yc(t,e){let r=new fc(t,e);r.expectToken(b.SOF);let n=r.parseValueLiteral(!1);return r.expectToken(b.EOF),n}o(yc,"parseValue");var fc=class{static{o(this,"Parser")}constructor(e,r={}){let n=ub(e)?e:new Hn(e);this._lexer=new Di(n),this._options=r,this._tokenCounter=0}parseName(){let e=this.expectToken(b.NAME);return this.node(e,{kind:_.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:_.DOCUMENT,definitions:this.many(b.SOF,this.parseDefinition,b.EOF)})}parseDefinition(){if(this.peek(b.BRACE_L))return this.parseOperationDefinition();let e=this.peekDescription(),r=e?this._lexer.lookahead():this._lexer.token;if(r.kind===b.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 le(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(b.BRACE_L))return this.node(e,{kind:_.OPERATION_DEFINITION,operation:rt.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});let r=this.parseOperationType(),n;return this.peek(b.NAME)&&(n=this.parseName()),this.node(e,{kind:_.OPERATION_DEFINITION,operation:r,name:n,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){let e=this.expectToken(b.NAME);switch(e.value){case"query":return rt.QUERY;case"mutation":return rt.MUTATION;case"subscription":return rt.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(b.PAREN_L,this.parseVariableDefinition,b.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:_.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(b.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(b.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){let e=this._lexer.token;return this.expectToken(b.DOLLAR),this.node(e,{kind:_.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:_.SELECTION_SET,selections:this.many(b.BRACE_L,this.parseSelection,b.BRACE_R)})}parseSelection(){return this.peek(b.SPREAD)?this.parseFragment():this.parseField()}parseField(){let e=this._lexer.token,r=this.parseName(),n,i;return this.expectOptionalToken(b.COLON)?(n=r,i=this.parseName()):i=r,this.node(e,{kind:_.FIELD,alias:n,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(b.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){let r=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(b.PAREN_L,r,b.PAREN_R)}parseArgument(e=!1){let r=this._lexer.token,n=this.parseName();return this.expectToken(b.COLON),this.node(r,{kind:_.ARGUMENT,name:n,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){let e=this._lexer.token;this.expectToken(b.SPREAD);let r=this.expectOptionalKeyword("on");return!r&&this.peek(b.NAME)?this.node(e,{kind:_.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(e,{kind:_.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:_.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:_.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 b.BRACKET_L:return this.parseList(e);case b.BRACE_L:return this.parseObject(e);case b.INT:return this.advanceLexer(),this.node(r,{kind:_.INT,value:r.value});case b.FLOAT:return this.advanceLexer(),this.node(r,{kind:_.FLOAT,value:r.value});case b.STRING:case b.BLOCK_STRING:return this.parseStringLiteral();case b.NAME:switch(this.advanceLexer(),r.value){case"true":return this.node(r,{kind:_.BOOLEAN,value:!0});case"false":return this.node(r,{kind:_.BOOLEAN,value:!1});case"null":return this.node(r,{kind:_.NULL});default:return this.node(r,{kind:_.ENUM,value:r.value})}case b.DOLLAR:if(e)if(this.expectToken(b.DOLLAR),this._lexer.token.kind===b.NAME){let n=this._lexer.token.value;throw le(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:_.STRING,value:e.value,block:e.kind===b.BLOCK_STRING})}parseList(e){let r=o(()=>this.parseValueLiteral(e),"item");return this.node(this._lexer.token,{kind:_.LIST,values:this.any(b.BRACKET_L,r,b.BRACKET_R)})}parseObject(e){let r=o(()=>this.parseObjectField(e),"item");return this.node(this._lexer.token,{kind:_.OBJECT,fields:this.any(b.BRACE_L,r,b.BRACE_R)})}parseObjectField(e){let r=this._lexer.token,n=this.parseName();return this.expectToken(b.COLON),this.node(r,{kind:_.OBJECT_FIELD,name:n,value:this.parseValueLiteral(e)})}parseDirectives(e){let r=[];for(;this.peek(b.AT);)r.push(this.parseDirective(e));return r}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){let r=this._lexer.token;return this.expectToken(b.AT),this.node(r,{kind:_.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){let e=this._lexer.token,r;if(this.expectOptionalToken(b.BRACKET_L)){let n=this.parseTypeReference();this.expectToken(b.BRACKET_R),r=this.node(e,{kind:_.LIST_TYPE,type:n})}else r=this.parseNamedType();return this.expectOptionalToken(b.BANG)?this.node(e,{kind:_.NON_NULL_TYPE,type:r}):r}parseNamedType(){return this.node(this._lexer.token,{kind:_.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(b.STRING)||this.peek(b.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(b.BRACE_L,this.parseOperationTypeDefinition,b.BRACE_R);return this.node(e,{kind:_.SCHEMA_DEFINITION,description:r,directives:n,operationTypes:i})}parseOperationTypeDefinition(){let e=this._lexer.token,r=this.parseOperationType();this.expectToken(b.COLON);let n=this.parseNamedType();return this.node(e,{kind:_.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:_.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:_.OBJECT_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:s,fields:a})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(b.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(b.BRACE_L,this.parseFieldDefinition,b.BRACE_R)}parseFieldDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName(),i=this.parseArgumentDefs();this.expectToken(b.COLON);let s=this.parseTypeReference(),a=this.parseConstDirectives();return this.node(e,{kind:_.FIELD_DEFINITION,description:r,name:n,arguments:i,type:s,directives:a})}parseArgumentDefs(){return this.optionalMany(b.PAREN_L,this.parseInputValueDef,b.PAREN_R)}parseInputValueDef(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName();this.expectToken(b.COLON);let i=this.parseTypeReference(),s;this.expectOptionalToken(b.EQUALS)&&(s=this.parseConstValueLiteral());let a=this.parseConstDirectives();return this.node(e,{kind:_.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:_.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:_.UNION_TYPE_DEFINITION,description:r,name:n,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(b.EQUALS)?this.delimitedMany(b.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:_.ENUM_TYPE_DEFINITION,description:r,name:n,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(b.BRACE_L,this.parseEnumValueDefinition,b.BRACE_R)}parseEnumValueDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(e,{kind:_.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 le(this._lexer.source,this._lexer.token.start,`${hc(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:_.INPUT_OBJECT_TYPE_DEFINITION,description:r,name:n,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(b.BRACE_L,this.parseInputValueDef,b.BRACE_R)}parseTypeSystemExtension(){let e=this._lexer.lookahead();if(e.kind===b.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(b.BRACE_L,this.parseOperationTypeDefinition,b.BRACE_R);if(r.length===0&&n.length===0)throw this.unexpected();return this.node(e,{kind:_.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:_.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:_.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:_.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:_.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:_.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:_.INPUT_OBJECT_TYPE_EXTENSION,name:r,directives:n,fields:i})}parseDirectiveDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("directive"),this.expectToken(b.AT);let n=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");let a=this.parseDirectiveLocations();return this.node(e,{kind:_.DIRECTIVE_DEFINITION,description:r,name:n,arguments:i,repeatable:s,locations:a})}parseDirectiveLocations(){return this.delimitedMany(b.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){let e=this._lexer.token,r=this.parseName();if(Object.prototype.hasOwnProperty.call(K,r.value))return r;throw this.unexpected(e)}node(e,r){return this._options.noLocation!==!0&&(r.loc=new xi(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 le(this._lexer.source,r.start,`Expected ${lb(e)}, found ${hc(r)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e?(this.advanceLexer(),!0):!1}expectKeyword(e){let r=this._lexer.token;if(r.kind===b.NAME&&r.value===e)this.advanceLexer();else throw le(this._lexer.source,r.start,`Expected "${e}", found ${hc(r)}.`)}expectOptionalKeyword(e){let r=this._lexer.token;return r.kind===b.NAME&&r.value===e?(this.advanceLexer(),!0):!1}unexpected(e){let r=e??this._lexer.token;return le(this._lexer.source,r.start,`Unexpected ${hc(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!==b.EOF&&(++this._tokenCounter,this._tokenCounter>e))throw le(this._lexer.source,r.start,`Document contains more that ${e} tokens. Parsing aborted.`)}};function hc(t){let e=t.value;return lb(t.kind)+(e!=null?` "${e}"`:"")}o(hc,"getTokenDesc");function lb(t){return sb(t)?`"${t}"`:t}o(lb,"getTokenKindDesc");function gc(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(gc,"didYouMean");function gp(t){return t}o(gp,"identityFunc");function qn(t,e){let r=Object.create(null);for(let n of t)r[e(n)]=n;return r}o(qn,"keyMap");function It(t,e,r){let n=Object.create(null);for(let i of t)n[e(i)]=r(i);return n}o(It,"keyValMap");function Ui(t,e){let r=Object.create(null);for(let n of Object.keys(t))r[n]=e(t[n],n);return r}o(Ui,"mapValue");function db(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let i=t.charCodeAt(r),s=e.charCodeAt(n);if(_c(i)&&_c(s)){let a=0;do++r,a=a*10+i-_p,i=t.charCodeAt(r);while(_c(i)&&a>0);let c=0;do++n,c=c*10+s-_p,s=e.charCodeAt(n);while(_c(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(db,"naturalCompare");var _p=48,Xx=57;function _c(t){return!isNaN(t)&&_p<=t&&t<=Xx}o(_c,"isDigit");function bc(t,e){let r=Object.create(null),n=new bp(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:db(s,a)})}o(bc,"suggestionList");var bp=class{static{o(this,"LexicalDistance")}constructor(e){this._input=e,this._inputLowerCase=e.toLowerCase(),this._inputArray=pb(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=pb(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],m=u[d%3],f=m[0]=d;for(let y=1;y<=c;y++){let v=i[d-1]===s[y-1]?0:1,T=Math.min(p[y]+1,m[y-1]+1,p[y-1]+v);if(d>1&&y>1&&i[d-1]===s[y-2]&&i[d-2]===s[y-1]){let S=u[(d-2)%3][y-2];T=Math.min(T,S+1)}T<f&&(f=T),m[y]=T}if(f>r)return}let l=u[a%3][c];return l<=r?l:void 0}};function pb(t){let e=t.length,r=new Array(e);for(let n=0;n<e;++n)r[n]=t.charCodeAt(n);return r}o(pb,"stringToArray");function Le(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(Le,"toObjMap");function hb(t){return`"${t.replace(eN,tN)}"`}o(hb,"printString");var eN=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function tN(t){return rN[t.charCodeAt(0)]}o(tN,"escapedReplacer");var rN=["\\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 Ep=Object.freeze({});function hr(t,e,r=mp){let n=new Map;for(let S of Object.values(_))n.set(S,$n(e,S));let i,s=Array.isArray(t),a=[t],c=-1,u=[],l=t,d,p,m=[],f=[];do{c++;let S=c===a.length,M=S&&u.length!==0;if(S){if(d=f.length===0?void 0:m[m.length-1],l=p,p=f.pop(),M)if(s){l=l.slice();let R=0;for(let[ne,Y]of u){let fe=ne-R;Y===null?(l.splice(fe,1),R++):l[fe]=Y}}else{l=Object.defineProperties({},Object.getOwnPropertyDescriptors(l));for(let[R,ne]of u)l[R]=ne}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;m.push(d)}let H;if(!Array.isArray(l)){var y,v;Ni(l)||B(!1,`Invalid AST Node: ${A(l)}.`);let R=S?(y=n.get(l.kind))===null||y===void 0?void 0:y.leave:(v=n.get(l.kind))===null||v===void 0?void 0:v.enter;if(H=R?.call(e,l,d,p,m,f),H===Ep)break;if(H===!1){if(!S){m.pop();continue}}else if(H!==void 0&&(u.push([d,H]),!S))if(Ni(H))l=H;else{m.pop();continue}}if(H===void 0&&M&&u.push([d,l]),S)m.pop();else{var T;i={inArray:s,index:c,keys:a,edits:u,prev:i},s=Array.isArray(l),a=s?l:(T=r[l.kind])!==null&&T!==void 0?T:[],c=-1,u=[],p&&f.push(p),p=l}}while(i!==void 0);return u.length!==0?u[u.length-1][1]:t}o(hr,"visit");function $n(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($n,"getEnterLeaveForKind");function De(t){return hr(t,iN)}o(De,"print");var nN=80,iN={Name:{leave:t=>t.value},Variable:{leave:t=>"$"+t.name},Document:{leave:t=>x(t.definitions,`
87
87
 
88
- `)},OperationDefinition:{leave(t){let e=J("(",x(t.variableDefinitions,", "),")"),r=x([t.operation,x([t.name,e]),x(t.directives," ")]," ");return(r==="query"?"":r+" ")+t.selectionSet}},VariableDefinition:{leave:({variable:t,type:e,defaultValue:r,directives:n})=>t+": "+e+J(" = ",r)+J(" ",x(n," "))},SelectionSet:{leave:({selections:t})=>ut(t)},Field:{leave({alias:t,name:e,arguments:r,directives:n,selectionSet:i}){let s=J("",t,": ")+e,a=s+J("(",x(r,", "),")");return a.length>Zx&&(a=s+J(`(
89
- `,bc(x(r,`
88
+ `)},OperationDefinition:{leave(t){let e=J("(",x(t.variableDefinitions,", "),")"),r=x([t.operation,x([t.name,e]),x(t.directives," ")]," ");return(r==="query"?"":r+" ")+t.selectionSet}},VariableDefinition:{leave:({variable:t,type:e,defaultValue:r,directives:n})=>t+": "+e+J(" = ",r)+J(" ",x(n," "))},SelectionSet:{leave:({selections:t})=>ut(t)},Field:{leave({alias:t,name:e,arguments:r,directives:n,selectionSet:i}){let s=J("",t,": ")+e,a=s+J("(",x(r,", "),")");return a.length>nN&&(a=s+J(`(
89
+ `,Ec(x(r,`
90
90
  `)),`
91
- )`)),x([a,x(n," "),i]," ")}},Argument:{leave:({name:t,value:e})=>t+": "+e},FragmentSpread:{leave:({name:t,directives:e})=>"..."+t+J(" ",x(e," "))},InlineFragment:{leave:({typeCondition:t,directives:e,selectionSet:r})=>x(["...",J("on ",t),x(e," "),r]," ")},FragmentDefinition:{leave:({name:t,typeCondition:e,variableDefinitions:r,directives:n,selectionSet:i})=>`fragment ${t}${J("(",x(r,", "),")")} on ${e} ${J("",x(n," ")," ")}`+i},IntValue:{leave:({value:t})=>t},FloatValue:{leave:({value:t})=>t},StringValue:{leave:({value:t,block:e})=>e?rb(t):db(t)},BooleanValue:{leave:({value:t})=>t?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:t})=>t},ListValue:{leave:({values:t})=>"["+x(t,", ")+"]"},ObjectValue:{leave:({fields:t})=>"{"+x(t,", ")+"}"},ObjectField:{leave:({name:t,value:e})=>t+": "+e},Directive:{leave:({name:t,arguments:e})=>"@"+t+J("(",x(e,", "),")")},NamedType:{leave:({name:t})=>t},ListType:{leave:({type:t})=>"["+t+"]"},NonNullType:{leave:({type:t})=>t+"!"},SchemaDefinition:{leave:({description:t,directives:e,operationTypes:r})=>J("",t,`
91
+ )`)),x([a,x(n," "),i]," ")}},Argument:{leave:({name:t,value:e})=>t+": "+e},FragmentSpread:{leave:({name:t,directives:e})=>"..."+t+J(" ",x(e," "))},InlineFragment:{leave:({typeCondition:t,directives:e,selectionSet:r})=>x(["...",J("on ",t),x(e," "),r]," ")},FragmentDefinition:{leave:({name:t,typeCondition:e,variableDefinitions:r,directives:n,selectionSet:i})=>`fragment ${t}${J("(",x(r,", "),")")} on ${e} ${J("",x(n," ")," ")}`+i},IntValue:{leave:({value:t})=>t},FloatValue:{leave:({value:t})=>t},StringValue:{leave:({value:t,block:e})=>e?ib(t):hb(t)},BooleanValue:{leave:({value:t})=>t?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:t})=>t},ListValue:{leave:({values:t})=>"["+x(t,", ")+"]"},ObjectValue:{leave:({fields:t})=>"{"+x(t,", ")+"}"},ObjectField:{leave:({name:t,value:e})=>t+": "+e},Directive:{leave:({name:t,arguments:e})=>"@"+t+J("(",x(e,", "),")")},NamedType:{leave:({name:t})=>t},ListType:{leave:({type:t})=>"["+t+"]"},NonNullType:{leave:({type:t})=>t+"!"},SchemaDefinition:{leave:({description:t,directives:e,operationTypes:r})=>J("",t,`
92
92
  `)+x(["schema",x(e," "),ut(r)]," ")},OperationTypeDefinition:{leave:({operation:t,type:e})=>t+": "+e},ScalarTypeDefinition:{leave:({description:t,name:e,directives:r})=>J("",t,`
93
93
  `)+x(["scalar",e,x(r," ")]," ")},ObjectTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>J("",t,`
94
94
  `)+x(["type",e,J("implements ",x(r," & ")),x(n," "),ut(i)]," ")},FieldDefinition:{leave:({description:t,name:e,arguments:r,type:n,directives:i})=>J("",t,`
95
- `)+e+(pb(r)?J(`(
96
- `,bc(x(r,`
95
+ `)+e+(fb(r)?J(`(
96
+ `,Ec(x(r,`
97
97
  `)),`
98
98
  )`):J("(",x(r,", "),")"))+": "+n+J(" ",x(i," "))},InputValueDefinition:{leave:({description:t,name:e,type:r,defaultValue:n,directives:i})=>J("",t,`
99
99
  `)+x([e+": "+r,J("= ",n),x(i," ")]," ")},InterfaceTypeDefinition:{leave:({description:t,name:e,interfaces:r,directives:n,fields:i})=>J("",t,`
@@ -102,17 +102,17 @@ spurious results.`)}}return!1},"instanceOf");var Hn=class{static{o(this,"Source"
102
102
  `)+x(["enum",e,x(r," "),ut(n)]," ")},EnumValueDefinition:{leave:({description:t,name:e,directives:r})=>J("",t,`
103
103
  `)+x([e,x(r," ")]," ")},InputObjectTypeDefinition:{leave:({description:t,name:e,directives:r,fields:n})=>J("",t,`
104
104
  `)+x(["input",e,x(r," "),ut(n)]," ")},DirectiveDefinition:{leave:({description:t,name:e,arguments:r,repeatable:n,locations:i})=>J("",t,`
105
- `)+"directive @"+e+(pb(r)?J(`(
106
- `,bc(x(r,`
105
+ `)+"directive @"+e+(fb(r)?J(`(
106
+ `,Ec(x(r,`
107
107
  `)),`
108
108
  )`):J("(",x(r,", "),")"))+(n?" repeatable":"")+" on "+x(i," | ")},SchemaExtension:{leave:({directives:t,operationTypes:e})=>x(["extend schema",x(t," "),ut(e)]," ")},ScalarTypeExtension:{leave:({name:t,directives:e})=>x(["extend scalar",t,x(e," ")]," ")},ObjectTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>x(["extend type",t,J("implements ",x(e," & ")),x(r," "),ut(n)]," ")},InterfaceTypeExtension:{leave:({name:t,interfaces:e,directives:r,fields:n})=>x(["extend interface",t,J("implements ",x(e," & ")),x(r," "),ut(n)]," ")},UnionTypeExtension:{leave:({name:t,directives:e,types:r})=>x(["extend union",t,x(e," "),J("= ",x(r," | "))]," ")},EnumTypeExtension:{leave:({name:t,directives:e,values:r})=>x(["extend enum",t,x(e," "),ut(r)]," ")},InputObjectTypeExtension:{leave:({name:t,directives:e,fields:r})=>x(["extend input",t,x(e," "),ut(r)]," ")}};function x(t,e=""){var r;return(r=t?.filter(n=>n).join(e))!==null&&r!==void 0?r:""}o(x,"join");function ut(t){return J(`{
109
- `,bc(x(t,`
109
+ `,Ec(x(t,`
110
110
  `)),`
111
- }`)}o(ut,"block");function J(t,e,r=""){return e!=null&&e!==""?t+e+r:""}o(J,"wrap");function bc(t){return J(" ",t.replace(/\n/g,`
112
- `))}o(bc,"indent");function pb(t){var e;return(e=t?.some(r=>r.includes(`
113
- `)))!==null&&e!==void 0?e:!1}o(pb,"hasMultilineItems");function Mi(t,e){switch(t.kind){case _.NULL:return null;case _.INT:return parseInt(t.value,10);case _.FLOAT:return parseFloat(t.value);case _.STRING:case _.ENUM:case _.BOOLEAN:return t.value;case _.LIST:return t.values.map(r=>Mi(r,e));case _.OBJECT:return It(t.fields,r=>r.name.value,r=>Mi(r.value,e));case _.VARIABLE:return e?.[t.name.value]}}o(Mi,"valueFromASTUntyped");function je(t){if(t!=null||B(!1,"Must provide name."),typeof t=="string"||B(!1,"Expected name to be a string."),t.length===0)throw new C("Expected name to be a non-empty string.");for(let e=1;e<t.length;++e)if(!uc(t.charCodeAt(e)))throw new C(`Names must only contain [_a-zA-Z0-9] but "${t}" does not.`);if(!Ci(t.charCodeAt(0)))throw new C(`Names must start with [_a-zA-Z] but "${t}" does not.`);return t}o(je,"assertName");function Ep(t){if(t==="true"||t==="false"||t==="null")throw new C(`Enum values cannot be named: ${t}`);return je(t)}o(Ep,"assertEnumValueName");function wc(t){return fr(t)||Ne(t)||Ee(t)||nt(t)||We(t)||Pe(t)||Ve(t)||ae(t)}o(wc,"isType");function fr(t){return Je(t,ze)}o(fr,"isScalarType");function Ne(t){return Je(t,xe)}o(Ne,"isObjectType");function vc(t){if(!Ne(t))throw new Error(`Expected ${A(t)} to be a GraphQL Object type.`);return t}o(vc,"assertObjectType");function Ee(t){return Je(t,Ft)}o(Ee,"isInterfaceType");function Tc(t){if(!Ee(t))throw new Error(`Expected ${A(t)} to be a GraphQL Interface type.`);return t}o(Tc,"assertInterfaceType");function nt(t){return Je(t,Mr)}o(nt,"isUnionType");function We(t){return Je(t,At)}o(We,"isEnumType");function Pe(t){return Je(t,kr)}o(Pe,"isInputObjectType");function Ve(t){return Je(t,de)}o(Ve,"isListType");function ae(t){return Je(t,j)}o(ae,"isNonNullType");function Qe(t){return fr(t)||We(t)||Pe(t)||ki(t)&&Qe(t.ofType)}o(Qe,"isInputType");function Ht(t){return fr(t)||Ne(t)||Ee(t)||nt(t)||We(t)||ki(t)&&Ht(t.ofType)}o(Ht,"isOutputType");function mr(t){return fr(t)||We(t)}o(mr,"isLeafType");function Pt(t){return Ne(t)||Ee(t)||nt(t)}o(Pt,"isCompositeType");function yr(t){return Ee(t)||nt(t)}o(yr,"isAbstractType");var de=class{static{o(this,"GraphQLList")}constructor(e){wc(e)||B(!1,`Expected ${A(e)} to be a GraphQL type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLList"}toString(){return"["+String(this.ofType)+"]"}toJSON(){return this.toString()}},j=class{static{o(this,"GraphQLNonNull")}constructor(e){Sc(e)||B(!1,`Expected ${A(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 ki(t){return Ve(t)||ae(t)}o(ki,"isWrappingType");function Sc(t){return wc(t)&&!ae(t)}o(Sc,"isNullableType");function Ic(t){if(!Sc(t))throw new Error(`Expected ${A(t)} to be a GraphQL nullable type.`);return t}o(Ic,"assertNullableType");function Ac(t){if(t)return ae(t)?t.ofType:t}o(Ac,"getNullableType");function lt(t){if(t){let e=t;for(;ki(e);)e=e.ofType;return e}}o(lt,"getNamedType");function Pc(t){return typeof t=="function"?t():t}o(Pc,"resolveReadonlyArrayThunk");function Rc(t){return typeof t=="function"?t():t}o(Rc,"resolveObjMapThunk");var ze=class{static{o(this,"GraphQLScalarType")}constructor(e){var r,n,i,s;let a=(r=e.parseValue)!==null&&r!==void 0?r:yp;this.name=je(e.name),this.description=e.description,this.specifiedByURL=e.specifiedByURL,this.serialize=(n=e.serialize)!==null&&n!==void 0?n:yp,this.parseValue=a,this.parseLiteral=(i=e.parseLiteral)!==null&&i!==void 0?i:(c,u)=>a(Mi(c,u)),this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(s=e.extensionASTNodes)!==null&&s!==void 0?s:[],e.specifiedByURL==null||typeof e.specifiedByURL=="string"||B(!1,`${this.name} must provide "specifiedByURL" as a string, but got: ${A(e.specifiedByURL)}.`),e.serialize==null||typeof e.serialize=="function"||B(!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"||B(!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()}},xe=class{static{o(this,"GraphQLObjectType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.isTypeOf=e.isTypeOf,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=()=>fb(e),this._interfaces=()=>hb(e),e.isTypeOf==null||typeof e.isTypeOf=="function"||B(!1,`${this.name} must provide "isTypeOf" as a function, but got: ${A(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:mb(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function hb(t){var e;let r=Pc((e=t.interfaces)!==null&&e!==void 0?e:[]);return Array.isArray(r)||B(!1,`${t.name} interfaces must be an Array or a function which returns an Array.`),r}o(hb,"defineInterfaces");function fb(t){let e=Rc(t.fields);return jn(e)||B(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),Ui(e,(r,n)=>{var i;jn(r)||B(!1,`${t.name}.${n} field config must be an object.`),r.resolve==null||typeof r.resolve=="function"||B(!1,`${t.name}.${n} field resolver must be a function if provided, but got: ${A(r.resolve)}.`);let s=(i=r.args)!==null&&i!==void 0?i:{};return jn(s)||B(!1,`${t.name}.${n} args must be an object with argument names as keys.`),{name:je(n),description:r.description,type:r.type,args:wp(s),resolve:r.resolve,subscribe:r.subscribe,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}})}o(fb,"defineFieldMap");function wp(t){return Object.entries(t).map(([e,r])=>({name:je(e),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}))}o(wp,"defineArguments");function jn(t){return be(t)&&!Array.isArray(t)}o(jn,"isPlainObj");function mb(t){return Ui(t,e=>({description:e.description,type:e.type,args:vp(e.args),resolve:e.resolve,subscribe:e.subscribe,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(mb,"fieldsToFieldsConfig");function vp(t){return It(t,e=>e.name,e=>({description:e.description,type:e.type,defaultValue:e.defaultValue,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(vp,"argsToArgsConfig");var Ft=class{static{o(this,"GraphQLInterfaceType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=fb.bind(void 0,e),this._interfaces=hb.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||B(!1,`${this.name} must provide "resolveType" as a function, but got: ${A(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:mb(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},Mr=class{static{o(this,"GraphQLUnionType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._types=eN.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||B(!1,`${this.name} must provide "resolveType" as a function, but got: ${A(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 eN(t){let e=Pc(t.types);return Array.isArray(e)||B(!1,`Must provide Array of types or a function which returns such an array for Union ${t.name}.`),e}o(eN,"defineTypes");var At=class{static{o(this,"GraphQLEnumType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._values=tN(this.name,e.values),this._valueLookup=new Map(this._values.map(n=>[n.value,n])),this._nameLookup=qn(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 C(`Enum "${this.name}" cannot represent value: ${A(e)}`);return r.name}parseValue(e){if(typeof e!="string"){let n=A(e);throw new C(`Enum "${this.name}" cannot represent non-string value: ${n}.`+Ec(this,n))}let r=this.getValue(e);if(r==null)throw new C(`Value "${e}" does not exist in "${this.name}" enum.`+Ec(this,e));return r.value}parseLiteral(e,r){if(e.kind!==_.ENUM){let i=De(e);throw new C(`Enum "${this.name}" cannot represent non-enum value: ${i}.`+Ec(this,i),{nodes:e})}let n=this.getValue(e.value);if(n==null){let i=De(e);throw new C(`Value "${i}" does not exist in "${this.name}" enum.`+Ec(this,i),{nodes:e})}return n.value}toConfig(){let e=It(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 Ec(t,e){let r=t.getValues().map(i=>i.name),n=_c(e,r);return yc("the enum value",n)}o(Ec,"didYouMeanEnumValue");function tN(t,e){return jn(e)||B(!1,`${t} values must be an object with value names as keys.`),Object.entries(e).map(([r,n])=>(jn(n)||B(!1,`${t}.${r} must refer to an object with a "value" key representing an internal value but got: ${A(n)}.`),{name:Ep(r),description:n.description,value:n.value!==void 0?n.value:r,deprecationReason:n.deprecationReason,extensions:Le(n.extensions),astNode:n.astNode}))}o(tN,"defineEnumValues");var kr=class{static{o(this,"GraphQLInputObjectType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=rN.bind(void 0,e)}get[Symbol.toStringTag](){return"GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let e=Ui(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 rN(t){let e=Rc(t.fields);return jn(e)||B(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),Ui(e,(r,n)=>(!("resolve"in r)||B(!1,`${t.name}.${n} field has a resolve property, but Input Types cannot define resolvers.`),{name:je(n),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}))}o(rN,"defineInputFieldMap");var Oc=2147483647,xc=-2147483648,Tp=new ze({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=Fi(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 C(`Int cannot represent non-integer value: ${A(e)}`);if(r>Oc||r<xc)throw new C("Int cannot represent non 32-bit signed integer value: "+A(e));return r},parseValue(t){if(typeof t!="number"||!Number.isInteger(t))throw new C(`Int cannot represent non-integer value: ${A(t)}`);if(t>Oc||t<xc)throw new C(`Int cannot represent non 32-bit signed integer value: ${t}`);return t},parseLiteral(t){if(t.kind!==_.INT)throw new C(`Int cannot represent non-integer value: ${De(t)}`,{nodes:t});let e=parseInt(t.value,10);if(e>Oc||e<xc)throw new C(`Int cannot represent non 32-bit signed integer value: ${t.value}`,{nodes:t});return e}}),yb=new ze({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=Fi(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 C(`Float cannot represent non numeric value: ${A(e)}`);return r},parseValue(t){if(typeof t!="number"||!Number.isFinite(t))throw new C(`Float cannot represent non numeric value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.FLOAT&&t.kind!==_.INT)throw new C(`Float cannot represent non numeric value: ${De(t)}`,t);return parseFloat(t.value)}}),oe=new ze({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=Fi(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 C(`String cannot represent value: ${A(t)}`)},parseValue(t){if(typeof t!="string")throw new C(`String cannot represent a non string value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.STRING)throw new C(`String cannot represent a non string value: ${De(t)}`,{nodes:t});return t.value}}),Ue=new ze({name:"Boolean",description:"The `Boolean` scalar type represents `true` or `false`.",serialize(t){let e=Fi(t);if(typeof e=="boolean")return e;if(Number.isFinite(e))return e!==0;throw new C(`Boolean cannot represent a non boolean value: ${A(e)}`)},parseValue(t){if(typeof t!="boolean")throw new C(`Boolean cannot represent a non boolean value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.BOOLEAN)throw new C(`Boolean cannot represent a non boolean value: ${De(t)}`,{nodes:t});return t.value}}),Nc=new ze({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=Fi(t);if(typeof e=="string")return e;if(Number.isInteger(e))return String(e);throw new C(`ID cannot represent value: ${A(t)}`)},parseValue(t){if(typeof t=="string")return t;if(typeof t=="number"&&Number.isInteger(t))return t.toString();throw new C(`ID cannot represent value: ${A(t)}`)},parseLiteral(t){if(t.kind!==_.STRING&&t.kind!==_.INT)throw new C("ID cannot represent a non-string and non-integer value: "+De(t),{nodes:t});return t.value}}),Sp=Object.freeze([oe,Tp,yb,Ue,Nc]);function Fi(t){if(be(t)){if(typeof t.valueOf=="function"){let e=t.valueOf();if(!be(e))return e}if(typeof t.toJSON=="function")return t.toJSON()}return t}o(Fi,"serializeObject");function Ip(t){return Je(t,dt)}o(Ip,"isDirective");var dt=class{static{o(this,"GraphQLDirective")}constructor(e){var r,n;this.name=je(e.name),this.description=e.description,this.locations=e.locations,this.isRepeatable=(r=e.isRepeatable)!==null&&r!==void 0?r:!1,this.extensions=Le(e.extensions),this.astNode=e.astNode,Array.isArray(e.locations)||B(!1,`@${e.name} locations must be an Array.`);let i=(n=e.args)!==null&&n!==void 0?n:{};be(i)&&!Array.isArray(i)||B(!1,`@${e.name} args must be an object with argument names as keys.`),this.args=wp(i)}get[Symbol.toStringTag](){return"GraphQLDirective"}toConfig(){return{name:this.name,description:this.description,locations:this.locations,args:vp(this.args),isRepeatable:this.isRepeatable,extensions:this.extensions,astNode:this.astNode}}toString(){return"@"+this.name}toJSON(){return this.toString()}},gb=new dt({name:"include",description:"Directs the executor to include this field or fragment only when the `if` argument is true.",locations:[K.FIELD,K.FRAGMENT_SPREAD,K.INLINE_FRAGMENT],args:{if:{type:new j(Ue),description:"Included when true."}}}),_b=new dt({name:"skip",description:"Directs the executor to skip this field or fragment when the `if` argument is true.",locations:[K.FIELD,K.FRAGMENT_SPREAD,K.INLINE_FRAGMENT],args:{if:{type:new j(Ue),description:"Skipped when true."}}}),bb="No longer supported",Eb=new dt({name:"deprecated",description:"Marks an element of a GraphQL schema as no longer supported.",locations:[K.FIELD_DEFINITION,K.ARGUMENT_DEFINITION,K.INPUT_FIELD_DEFINITION,K.ENUM_VALUE],args:{reason:{type:oe,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:bb}}}),wb=new dt({name:"specifiedBy",description:"Exposes a URL that specifies the behavior of this scalar.",locations:[K.SCALAR],args:{url:{type:new j(oe),description:"The URL that specifies the behavior of this scalar."}}}),Ap=Object.freeze([gb,_b,Eb,wb]);function Cc(t){return typeof t=="object"&&typeof t?.[Symbol.iterator]=="function"}o(Cc,"isIterableObject");function Fr(t,e){if(ae(e)){let r=Fr(t,e.ofType);return r?.kind===_.NULL?null:r}if(t===null)return{kind:_.NULL};if(t===void 0)return null;if(Ve(e)){let r=e.ofType;if(Cc(t)){let n=[];for(let i of t){let s=Fr(i,r);s!=null&&n.push(s)}return{kind:_.LIST,values:n}}return Fr(t,r)}if(Pe(e)){if(!be(t))return null;let r=[];for(let n of Object.values(e.getFields())){let i=Fr(t[n.name],n.type);i&&r.push({kind:_.OBJECT_FIELD,name:{kind:_.NAME,value:n.name},value:i})}return{kind:_.OBJECT,fields:r}}if(mr(e)){let r=e.serialize(t);if(r==null)return null;if(typeof r=="boolean")return{kind:_.BOOLEAN,value:r};if(typeof r=="number"&&Number.isFinite(r)){let n=String(r);return vb.test(n)?{kind:_.INT,value:n}:{kind:_.FLOAT,value:n}}if(typeof r=="string")return We(e)?{kind:_.ENUM,value:r}:e===Nc&&vb.test(r)?{kind:_.INT,value:r}:{kind:_.STRING,value:r};throw new TypeError(`Cannot convert value to AST: ${A(r)}.`)}St(!1,"Unexpected input type: "+A(e))}o(Fr,"astFromValue");var vb=/^-?(?:0|[1-9][0-9]*)$/;var Hi=new xe({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:oe,resolve:t=>t.description},types:{description:"A list of all types supported by this server.",type:new j(new de(new j(it))),resolve(t){return Object.values(t.getTypeMap())}},queryType:{description:"The type that query operations will be rooted at.",type:new j(it),resolve:t=>t.getQueryType()},mutationType:{description:"If this server supports mutation, the type that mutation operations will be rooted at.",type:it,resolve:t=>t.getMutationType()},subscriptionType:{description:"If this server support subscription, the type that subscription operations will be rooted at.",type:it,resolve:t=>t.getSubscriptionType()},directives:{description:"A list of all directives supported by this server.",type:new j(new de(new j(Pp))),resolve:t=>t.getDirectives()}})}),Pp=new xe({name:"__Directive",description:`A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
111
+ }`)}o(ut,"block");function J(t,e,r=""){return e!=null&&e!==""?t+e+r:""}o(J,"wrap");function Ec(t){return J(" ",t.replace(/\n/g,`
112
+ `))}o(Ec,"indent");function fb(t){var e;return(e=t?.some(r=>r.includes(`
113
+ `)))!==null&&e!==void 0?e:!1}o(fb,"hasMultilineItems");function Mi(t,e){switch(t.kind){case _.NULL:return null;case _.INT:return parseInt(t.value,10);case _.FLOAT:return parseFloat(t.value);case _.STRING:case _.ENUM:case _.BOOLEAN:return t.value;case _.LIST:return t.values.map(r=>Mi(r,e));case _.OBJECT:return It(t.fields,r=>r.name.value,r=>Mi(r.value,e));case _.VARIABLE:return e?.[t.name.value]}}o(Mi,"valueFromASTUntyped");function je(t){if(t!=null||B(!1,"Must provide name."),typeof t=="string"||B(!1,"Expected name to be a string."),t.length===0)throw new C("Expected name to be a non-empty string.");for(let e=1;e<t.length;++e)if(!lc(t.charCodeAt(e)))throw new C(`Names must only contain [_a-zA-Z0-9] but "${t}" does not.`);if(!Ci(t.charCodeAt(0)))throw new C(`Names must start with [_a-zA-Z] but "${t}" does not.`);return t}o(je,"assertName");function wp(t){if(t==="true"||t==="false"||t==="null")throw new C(`Enum values cannot be named: ${t}`);return je(t)}o(wp,"assertEnumValueName");function vc(t){return fr(t)||Ne(t)||Ee(t)||nt(t)||We(t)||Pe(t)||Ve(t)||ae(t)}o(vc,"isType");function fr(t){return Je(t,ze)}o(fr,"isScalarType");function Ne(t){return Je(t,xe)}o(Ne,"isObjectType");function Tc(t){if(!Ne(t))throw new Error(`Expected ${A(t)} to be a GraphQL Object type.`);return t}o(Tc,"assertObjectType");function Ee(t){return Je(t,Ht)}o(Ee,"isInterfaceType");function Sc(t){if(!Ee(t))throw new Error(`Expected ${A(t)} to be a GraphQL Interface type.`);return t}o(Sc,"assertInterfaceType");function nt(t){return Je(t,Mr)}o(nt,"isUnionType");function We(t){return Je(t,At)}o(We,"isEnumType");function Pe(t){return Je(t,kr)}o(Pe,"isInputObjectType");function Ve(t){return Je(t,de)}o(Ve,"isListType");function ae(t){return Je(t,j)}o(ae,"isNonNullType");function Qe(t){return fr(t)||We(t)||Pe(t)||ki(t)&&Qe(t.ofType)}o(Qe,"isInputType");function qt(t){return fr(t)||Ne(t)||Ee(t)||nt(t)||We(t)||ki(t)&&qt(t.ofType)}o(qt,"isOutputType");function mr(t){return fr(t)||We(t)}o(mr,"isLeafType");function Pt(t){return Ne(t)||Ee(t)||nt(t)}o(Pt,"isCompositeType");function yr(t){return Ee(t)||nt(t)}o(yr,"isAbstractType");var de=class{static{o(this,"GraphQLList")}constructor(e){vc(e)||B(!1,`Expected ${A(e)} to be a GraphQL type.`),this.ofType=e}get[Symbol.toStringTag](){return"GraphQLList"}toString(){return"["+String(this.ofType)+"]"}toJSON(){return this.toString()}},j=class{static{o(this,"GraphQLNonNull")}constructor(e){Ic(e)||B(!1,`Expected ${A(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 ki(t){return Ve(t)||ae(t)}o(ki,"isWrappingType");function Ic(t){return vc(t)&&!ae(t)}o(Ic,"isNullableType");function Ac(t){if(!Ic(t))throw new Error(`Expected ${A(t)} to be a GraphQL nullable type.`);return t}o(Ac,"assertNullableType");function Pc(t){if(t)return ae(t)?t.ofType:t}o(Pc,"getNullableType");function lt(t){if(t){let e=t;for(;ki(e);)e=e.ofType;return e}}o(lt,"getNamedType");function Rc(t){return typeof t=="function"?t():t}o(Rc,"resolveReadonlyArrayThunk");function Oc(t){return typeof t=="function"?t():t}o(Oc,"resolveObjMapThunk");var ze=class{static{o(this,"GraphQLScalarType")}constructor(e){var r,n,i,s;let a=(r=e.parseValue)!==null&&r!==void 0?r:gp;this.name=je(e.name),this.description=e.description,this.specifiedByURL=e.specifiedByURL,this.serialize=(n=e.serialize)!==null&&n!==void 0?n:gp,this.parseValue=a,this.parseLiteral=(i=e.parseLiteral)!==null&&i!==void 0?i:(c,u)=>a(Mi(c,u)),this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(s=e.extensionASTNodes)!==null&&s!==void 0?s:[],e.specifiedByURL==null||typeof e.specifiedByURL=="string"||B(!1,`${this.name} must provide "specifiedByURL" as a string, but got: ${A(e.specifiedByURL)}.`),e.serialize==null||typeof e.serialize=="function"||B(!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"||B(!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()}},xe=class{static{o(this,"GraphQLObjectType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.isTypeOf=e.isTypeOf,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=()=>yb(e),this._interfaces=()=>mb(e),e.isTypeOf==null||typeof e.isTypeOf=="function"||B(!1,`${this.name} must provide "isTypeOf" as a function, but got: ${A(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:gb(this.getFields()),isTypeOf:this.isTypeOf,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}};function mb(t){var e;let r=Rc((e=t.interfaces)!==null&&e!==void 0?e:[]);return Array.isArray(r)||B(!1,`${t.name} interfaces must be an Array or a function which returns an Array.`),r}o(mb,"defineInterfaces");function yb(t){let e=Oc(t.fields);return jn(e)||B(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),Ui(e,(r,n)=>{var i;jn(r)||B(!1,`${t.name}.${n} field config must be an object.`),r.resolve==null||typeof r.resolve=="function"||B(!1,`${t.name}.${n} field resolver must be a function if provided, but got: ${A(r.resolve)}.`);let s=(i=r.args)!==null&&i!==void 0?i:{};return jn(s)||B(!1,`${t.name}.${n} args must be an object with argument names as keys.`),{name:je(n),description:r.description,type:r.type,args:vp(s),resolve:r.resolve,subscribe:r.subscribe,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}})}o(yb,"defineFieldMap");function vp(t){return Object.entries(t).map(([e,r])=>({name:je(e),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}))}o(vp,"defineArguments");function jn(t){return be(t)&&!Array.isArray(t)}o(jn,"isPlainObj");function gb(t){return Ui(t,e=>({description:e.description,type:e.type,args:Tp(e.args),resolve:e.resolve,subscribe:e.subscribe,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(gb,"fieldsToFieldsConfig");function Tp(t){return It(t,e=>e.name,e=>({description:e.description,type:e.type,defaultValue:e.defaultValue,deprecationReason:e.deprecationReason,extensions:e.extensions,astNode:e.astNode}))}o(Tp,"argsToArgsConfig");var Ht=class{static{o(this,"GraphQLInterfaceType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=yb.bind(void 0,e),this._interfaces=mb.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||B(!1,`${this.name} must provide "resolveType" as a function, but got: ${A(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:gb(this.getFields()),resolveType:this.resolveType,extensions:this.extensions,astNode:this.astNode,extensionASTNodes:this.extensionASTNodes}}toString(){return this.name}toJSON(){return this.toString()}},Mr=class{static{o(this,"GraphQLUnionType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.resolveType=e.resolveType,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._types=oN.bind(void 0,e),e.resolveType==null||typeof e.resolveType=="function"||B(!1,`${this.name} must provide "resolveType" as a function, but got: ${A(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 oN(t){let e=Rc(t.types);return Array.isArray(e)||B(!1,`Must provide Array of types or a function which returns such an array for Union ${t.name}.`),e}o(oN,"defineTypes");var At=class{static{o(this,"GraphQLEnumType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._values=sN(this.name,e.values),this._valueLookup=new Map(this._values.map(n=>[n.value,n])),this._nameLookup=qn(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 C(`Enum "${this.name}" cannot represent value: ${A(e)}`);return r.name}parseValue(e){if(typeof e!="string"){let n=A(e);throw new C(`Enum "${this.name}" cannot represent non-string value: ${n}.`+wc(this,n))}let r=this.getValue(e);if(r==null)throw new C(`Value "${e}" does not exist in "${this.name}" enum.`+wc(this,e));return r.value}parseLiteral(e,r){if(e.kind!==_.ENUM){let i=De(e);throw new C(`Enum "${this.name}" cannot represent non-enum value: ${i}.`+wc(this,i),{nodes:e})}let n=this.getValue(e.value);if(n==null){let i=De(e);throw new C(`Value "${i}" does not exist in "${this.name}" enum.`+wc(this,i),{nodes:e})}return n.value}toConfig(){let e=It(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 wc(t,e){let r=t.getValues().map(i=>i.name),n=bc(e,r);return gc("the enum value",n)}o(wc,"didYouMeanEnumValue");function sN(t,e){return jn(e)||B(!1,`${t} values must be an object with value names as keys.`),Object.entries(e).map(([r,n])=>(jn(n)||B(!1,`${t}.${r} must refer to an object with a "value" key representing an internal value but got: ${A(n)}.`),{name:wp(r),description:n.description,value:n.value!==void 0?n.value:r,deprecationReason:n.deprecationReason,extensions:Le(n.extensions),astNode:n.astNode}))}o(sN,"defineEnumValues");var kr=class{static{o(this,"GraphQLInputObjectType")}constructor(e){var r;this.name=je(e.name),this.description=e.description,this.extensions=Le(e.extensions),this.astNode=e.astNode,this.extensionASTNodes=(r=e.extensionASTNodes)!==null&&r!==void 0?r:[],this._fields=aN.bind(void 0,e)}get[Symbol.toStringTag](){return"GraphQLInputObjectType"}getFields(){return typeof this._fields=="function"&&(this._fields=this._fields()),this._fields}toConfig(){let e=Ui(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 aN(t){let e=Oc(t.fields);return jn(e)||B(!1,`${t.name} fields must be an object with field names as keys or a function which returns such an object.`),Ui(e,(r,n)=>(!("resolve"in r)||B(!1,`${t.name}.${n} field has a resolve property, but Input Types cannot define resolvers.`),{name:je(n),description:r.description,type:r.type,defaultValue:r.defaultValue,deprecationReason:r.deprecationReason,extensions:Le(r.extensions),astNode:r.astNode}))}o(aN,"defineInputFieldMap");var xc=2147483647,Nc=-2147483648,Sp=new ze({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=Fi(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 C(`Int cannot represent non-integer value: ${A(e)}`);if(r>xc||r<Nc)throw new C("Int cannot represent non 32-bit signed integer value: "+A(e));return r},parseValue(t){if(typeof t!="number"||!Number.isInteger(t))throw new C(`Int cannot represent non-integer value: ${A(t)}`);if(t>xc||t<Nc)throw new C(`Int cannot represent non 32-bit signed integer value: ${t}`);return t},parseLiteral(t){if(t.kind!==_.INT)throw new C(`Int cannot represent non-integer value: ${De(t)}`,{nodes:t});let e=parseInt(t.value,10);if(e>xc||e<Nc)throw new C(`Int cannot represent non 32-bit signed integer value: ${t.value}`,{nodes:t});return e}}),_b=new ze({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=Fi(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 C(`Float cannot represent non numeric value: ${A(e)}`);return r},parseValue(t){if(typeof t!="number"||!Number.isFinite(t))throw new C(`Float cannot represent non numeric value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.FLOAT&&t.kind!==_.INT)throw new C(`Float cannot represent non numeric value: ${De(t)}`,t);return parseFloat(t.value)}}),oe=new ze({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=Fi(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 C(`String cannot represent value: ${A(t)}`)},parseValue(t){if(typeof t!="string")throw new C(`String cannot represent a non string value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.STRING)throw new C(`String cannot represent a non string value: ${De(t)}`,{nodes:t});return t.value}}),Ue=new ze({name:"Boolean",description:"The `Boolean` scalar type represents `true` or `false`.",serialize(t){let e=Fi(t);if(typeof e=="boolean")return e;if(Number.isFinite(e))return e!==0;throw new C(`Boolean cannot represent a non boolean value: ${A(e)}`)},parseValue(t){if(typeof t!="boolean")throw new C(`Boolean cannot represent a non boolean value: ${A(t)}`);return t},parseLiteral(t){if(t.kind!==_.BOOLEAN)throw new C(`Boolean cannot represent a non boolean value: ${De(t)}`,{nodes:t});return t.value}}),Cc=new ze({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=Fi(t);if(typeof e=="string")return e;if(Number.isInteger(e))return String(e);throw new C(`ID cannot represent value: ${A(t)}`)},parseValue(t){if(typeof t=="string")return t;if(typeof t=="number"&&Number.isInteger(t))return t.toString();throw new C(`ID cannot represent value: ${A(t)}`)},parseLiteral(t){if(t.kind!==_.STRING&&t.kind!==_.INT)throw new C("ID cannot represent a non-string and non-integer value: "+De(t),{nodes:t});return t.value}}),Ip=Object.freeze([oe,Sp,_b,Ue,Cc]);function Fi(t){if(be(t)){if(typeof t.valueOf=="function"){let e=t.valueOf();if(!be(e))return e}if(typeof t.toJSON=="function")return t.toJSON()}return t}o(Fi,"serializeObject");function Ap(t){return Je(t,dt)}o(Ap,"isDirective");var dt=class{static{o(this,"GraphQLDirective")}constructor(e){var r,n;this.name=je(e.name),this.description=e.description,this.locations=e.locations,this.isRepeatable=(r=e.isRepeatable)!==null&&r!==void 0?r:!1,this.extensions=Le(e.extensions),this.astNode=e.astNode,Array.isArray(e.locations)||B(!1,`@${e.name} locations must be an Array.`);let i=(n=e.args)!==null&&n!==void 0?n:{};be(i)&&!Array.isArray(i)||B(!1,`@${e.name} args must be an object with argument names as keys.`),this.args=vp(i)}get[Symbol.toStringTag](){return"GraphQLDirective"}toConfig(){return{name:this.name,description:this.description,locations:this.locations,args:Tp(this.args),isRepeatable:this.isRepeatable,extensions:this.extensions,astNode:this.astNode}}toString(){return"@"+this.name}toJSON(){return this.toString()}},bb=new dt({name:"include",description:"Directs the executor to include this field or fragment only when the `if` argument is true.",locations:[K.FIELD,K.FRAGMENT_SPREAD,K.INLINE_FRAGMENT],args:{if:{type:new j(Ue),description:"Included when true."}}}),Eb=new dt({name:"skip",description:"Directs the executor to skip this field or fragment when the `if` argument is true.",locations:[K.FIELD,K.FRAGMENT_SPREAD,K.INLINE_FRAGMENT],args:{if:{type:new j(Ue),description:"Skipped when true."}}}),wb="No longer supported",vb=new dt({name:"deprecated",description:"Marks an element of a GraphQL schema as no longer supported.",locations:[K.FIELD_DEFINITION,K.ARGUMENT_DEFINITION,K.INPUT_FIELD_DEFINITION,K.ENUM_VALUE],args:{reason:{type:oe,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:wb}}}),Tb=new dt({name:"specifiedBy",description:"Exposes a URL that specifies the behavior of this scalar.",locations:[K.SCALAR],args:{url:{type:new j(oe),description:"The URL that specifies the behavior of this scalar."}}}),Pp=Object.freeze([bb,Eb,vb,Tb]);function Lc(t){return typeof t=="object"&&typeof t?.[Symbol.iterator]=="function"}o(Lc,"isIterableObject");function Fr(t,e){if(ae(e)){let r=Fr(t,e.ofType);return r?.kind===_.NULL?null:r}if(t===null)return{kind:_.NULL};if(t===void 0)return null;if(Ve(e)){let r=e.ofType;if(Lc(t)){let n=[];for(let i of t){let s=Fr(i,r);s!=null&&n.push(s)}return{kind:_.LIST,values:n}}return Fr(t,r)}if(Pe(e)){if(!be(t))return null;let r=[];for(let n of Object.values(e.getFields())){let i=Fr(t[n.name],n.type);i&&r.push({kind:_.OBJECT_FIELD,name:{kind:_.NAME,value:n.name},value:i})}return{kind:_.OBJECT,fields:r}}if(mr(e)){let r=e.serialize(t);if(r==null)return null;if(typeof r=="boolean")return{kind:_.BOOLEAN,value:r};if(typeof r=="number"&&Number.isFinite(r)){let n=String(r);return Sb.test(n)?{kind:_.INT,value:n}:{kind:_.FLOAT,value:n}}if(typeof r=="string")return We(e)?{kind:_.ENUM,value:r}:e===Cc&&Sb.test(r)?{kind:_.INT,value:r}:{kind:_.STRING,value:r};throw new TypeError(`Cannot convert value to AST: ${A(r)}.`)}St(!1,"Unexpected input type: "+A(e))}o(Fr,"astFromValue");var Sb=/^-?(?:0|[1-9][0-9]*)$/;var Hi=new xe({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:oe,resolve:t=>t.description},types:{description:"A list of all types supported by this server.",type:new j(new de(new j(it))),resolve(t){return Object.values(t.getTypeMap())}},queryType:{description:"The type that query operations will be rooted at.",type:new j(it),resolve:t=>t.getQueryType()},mutationType:{description:"If this server supports mutation, the type that mutation operations will be rooted at.",type:it,resolve:t=>t.getMutationType()},subscriptionType:{description:"If this server support subscription, the type that subscription operations will be rooted at.",type:it,resolve:t=>t.getSubscriptionType()},directives:{description:"A list of all directives supported by this server.",type:new j(new de(new j(Rp))),resolve:t=>t.getDirectives()}})}),Rp=new xe({name:"__Directive",description:`A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
114
114
 
115
- 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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},isRepeatable:{type:new j(Ue),resolve:t=>t.isRepeatable},locations:{type:new j(new de(new j(Rp))),resolve:t=>t.locations},args:{type:new j(new de(new j(qi))),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}}})}),Rp=new At({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:K.QUERY,description:"Location adjacent to a query operation."},MUTATION:{value:K.MUTATION,description:"Location adjacent to a mutation operation."},SUBSCRIPTION:{value:K.SUBSCRIPTION,description:"Location adjacent to a subscription operation."},FIELD:{value:K.FIELD,description:"Location adjacent to a field."},FRAGMENT_DEFINITION:{value:K.FRAGMENT_DEFINITION,description:"Location adjacent to a fragment definition."},FRAGMENT_SPREAD:{value:K.FRAGMENT_SPREAD,description:"Location adjacent to a fragment spread."},INLINE_FRAGMENT:{value:K.INLINE_FRAGMENT,description:"Location adjacent to an inline fragment."},VARIABLE_DEFINITION:{value:K.VARIABLE_DEFINITION,description:"Location adjacent to a variable definition."},SCHEMA:{value:K.SCHEMA,description:"Location adjacent to a schema definition."},SCALAR:{value:K.SCALAR,description:"Location adjacent to a scalar definition."},OBJECT:{value:K.OBJECT,description:"Location adjacent to an object type definition."},FIELD_DEFINITION:{value:K.FIELD_DEFINITION,description:"Location adjacent to a field definition."},ARGUMENT_DEFINITION:{value:K.ARGUMENT_DEFINITION,description:"Location adjacent to an argument definition."},INTERFACE:{value:K.INTERFACE,description:"Location adjacent to an interface definition."},UNION:{value:K.UNION,description:"Location adjacent to a union definition."},ENUM:{value:K.ENUM,description:"Location adjacent to an enum definition."},ENUM_VALUE:{value:K.ENUM_VALUE,description:"Location adjacent to an enum value definition."},INPUT_OBJECT:{value:K.INPUT_OBJECT,description:"Location adjacent to an input object type definition."},INPUT_FIELD_DEFINITION:{value:K.INPUT_FIELD_DEFINITION,description:"Location adjacent to an input object field definition."}}}),it=new xe({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 j(Np),resolve(t){if(fr(t))return ee.SCALAR;if(Ne(t))return ee.OBJECT;if(Ee(t))return ee.INTERFACE;if(nt(t))return ee.UNION;if(We(t))return ee.ENUM;if(Pe(t))return ee.INPUT_OBJECT;if(Ve(t))return ee.LIST;if(ae(t))return ee.NON_NULL;St(!1,`Unexpected type: "${A(t)}".`)}},name:{type:oe,resolve:t=>"name"in t?t.name:void 0},description:{type:oe,resolve:t=>"description"in t?t.description:void 0},specifiedByURL:{type:oe,resolve:t=>"specifiedByURL"in t?t.specifiedByURL:void 0},fields:{type:new de(new j(Op)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Ne(t)||Ee(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},interfaces:{type:new de(new j(it)),resolve(t){if(Ne(t)||Ee(t))return t.getInterfaces()}},possibleTypes:{type:new de(new j(it)),resolve(t,e,r,{schema:n}){if(yr(t))return n.getPossibleTypes(t)}},enumValues:{type:new de(new j(xp)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(We(t)){let r=t.getValues();return e?r:r.filter(n=>n.deprecationReason==null)}}},inputFields:{type:new de(new j(qi)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Pe(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},ofType:{type:it,resolve:t=>"ofType"in t?t.ofType:void 0}})}),Op=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},args:{type:new j(new de(new j(qi))),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}},type:{type:new j(it),resolve:t=>t.type},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),qi=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},type:{type:new j(it),resolve:t=>t.type},defaultValue:{type:oe,description:"A GraphQL-formatted string representing the default value for this input value.",resolve(t){let{type:e,defaultValue:r}=t,n=Fr(r,e);return n?De(n):null}},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),xp=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),ee;(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"})(ee||(ee={}));var Np=new At({name:"__TypeKind",description:"An enum describing what kind of type a given `__Type` is.",values:{SCALAR:{value:ee.SCALAR,description:"Indicates this type is a scalar."},OBJECT:{value:ee.OBJECT,description:"Indicates this type is an object. `fields` and `interfaces` are valid fields."},INTERFACE:{value:ee.INTERFACE,description:"Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields."},UNION:{value:ee.UNION,description:"Indicates this type is a union. `possibleTypes` is a valid field."},ENUM:{value:ee.ENUM,description:"Indicates this type is an enum. `enumValues` is a valid field."},INPUT_OBJECT:{value:ee.INPUT_OBJECT,description:"Indicates this type is an input object. `inputFields` is a valid field."},LIST:{value:ee.LIST,description:"Indicates this type is a list. `ofType` is a valid field."},NON_NULL:{value:ee.NON_NULL,description:"Indicates this type is a non-null. `ofType` is a valid field."}}}),Lc={name:"__schema",type:new j(Hi),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},Dc={name:"__type",type:it,description:"Request the type information of a single type.",args:[{name:"name",description:void 0,type:new j(oe),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},Uc={name:"__typename",type:new j(oe),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},Cp=Object.freeze([Hi,Pp,Rp,it,Op,qi,xp,Np]);var $i=class{static{o(this,"GraphQLSchema")}constructor(e){var r,n;this.__validationErrors=e.assumeValid===!0?[]:void 0,be(e)||B(!1,"Must provide configuration object."),!e.types||Array.isArray(e.types)||B(!1,`"types" must be Array if provided but got: ${A(e.types)}.`),!e.directives||Array.isArray(e.directives)||B(!1,`"directives" must be Array if provided but got: ${A(e.directives)}.`),this.description=e.description,this.extensions=Le(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:Ap;let i=new Set(e.types);if(e.types!=null)for(let s of e.types)i.delete(s),pt(s,i);this._queryType!=null&&pt(this._queryType,i),this._mutationType!=null&&pt(this._mutationType,i),this._subscriptionType!=null&&pt(this._subscriptionType,i);for(let s of this._directives)if(Ip(s))for(let a of s.args)pt(a.type,i);pt(Hi,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||B(!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,Ee(s)){for(let c of s.getInterfaces())if(Ee(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.interfaces.push(s)}}else if(Ne(s)){for(let c of s.getInterfaces())if(Ee(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 rt.QUERY:return this.getQueryType();case rt.MUTATION:return this.getMutationType();case rt.SUBSCRIPTION:return this.getSubscriptionType()}}getTypeMap(){return this._typeMap}getType(e){return this.getTypeMap()[e]}getPossibleTypes(e){return nt(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),nt(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 pt(t,e){let r=lt(t);if(!e.has(r)){if(e.add(r),nt(r))for(let n of r.getTypes())pt(n,e);else if(Ne(r)||Ee(r)){for(let n of r.getInterfaces())pt(n,e);for(let n of Object.values(r.getFields())){pt(n.type,e);for(let i of n.args)pt(i.type,e)}}else if(Pe(r))for(let n of Object.values(r.getFields()))pt(n.type,e)}return e}o(pt,"collectReferencedTypes");function gr(t,e){switch(e.kind){case _.LIST_TYPE:{let r=gr(t,e.type);return r&&new de(r)}case _.NON_NULL_TYPE:{let r=gr(t,e.type);return r&&new j(r)}case _.NAMED_TYPE:return t.getType(e.name.value)}}o(gr,"typeFromAST");var _r=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??nN,r&&(Qe(r)&&this._inputTypeStack.push(r),Pt(r)&&this._parentTypeStack.push(r),Ht(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 _.SELECTION_SET:{let i=lt(this.getType());this._parentTypeStack.push(Pt(i)?i:void 0);break}case _.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(Ht(a)?a:void 0);break}case _.DIRECTIVE:this._directive=r.getDirective(e.name.value);break;case _.OPERATION_DEFINITION:{let i=r.getRootType(e.operation);this._typeStack.push(Ne(i)?i:void 0);break}case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:{let i=e.typeCondition,s=i?gr(r,i):lt(this.getType());this._typeStack.push(Ht(s)?s:void 0);break}case _.VARIABLE_DEFINITION:{let i=gr(r,e.type);this._inputTypeStack.push(Qe(i)?i:void 0);break}case _.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(Qe(s)?s:void 0);break}case _.LIST:{let i=Ac(this.getInputType()),s=Ve(i)?i.ofType:i;this._defaultValueStack.push(void 0),this._inputTypeStack.push(Qe(s)?s:void 0);break}case _.OBJECT_FIELD:{let i=lt(this.getInputType()),s,a;Pe(i)&&(a=i.getFields()[e.name.value],a&&(s=a.type)),this._defaultValueStack.push(a?a.defaultValue:void 0),this._inputTypeStack.push(Qe(s)?s:void 0);break}case _.ENUM:{let i=lt(this.getInputType()),s;We(i)&&(s=i.getValue(e.value)),this._enumValue=s;break}default:}}leave(e){switch(e.kind){case _.SELECTION_SET:this._parentTypeStack.pop();break;case _.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case _.DIRECTIVE:this._directive=null;break;case _.OPERATION_DEFINITION:case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:this._typeStack.pop();break;case _.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case _.ARGUMENT:this._argument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case _.LIST:case _.OBJECT_FIELD:this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case _.ENUM:this._enumValue=null;break;default:}}};function nN(t,e,r){let n=r.name.value;if(n===Lc.name&&t.getQueryType()===e)return Lc;if(n===Dc.name&&t.getQueryType()===e)return Dc;if(n===Uc.name&&Pt(e))return Uc;if(Ne(e)||Ee(e))return e.getFields()[n]}o(nN,"getFieldDef");function Vn(t,e){return{enter(...r){let n=r[0];t.enter(n);let i=$n(e,n.kind).enter;if(i){let s=i.apply(e,r);return s!==void 0&&(t.leave(n),Ni(s)&&t.enter(s)),s}},leave(...r){let n=r[0],i=$n(e,n.kind).leave,s;return i&&(s=i.apply(e,r)),t.leave(n),s}}}o(Vn,"visitWithTypeInfo");function Mc(t){return t.map(e=>typeof e=="number"?"["+e.toString()+"]":"."+e).join("")}o(Mc,"printPathArray");function Lp(t,e,r){return{prev:t,key:e,typename:r}}o(Lp,"addPath");function qt(t){let e=[],r=t;for(;r;)e.push(r.key),r=r.prev;return e.reverse()}o(qt,"pathToArray");function Dp(t,e,r=iN){return ji(t,e,r,void 0)}o(Dp,"coerceInputValue");function iN(t,e,r){let n="Invalid value "+A(e);throw t.length>0&&(n+=` at "value${Mc(t)}"`),r.message=n+": "+r.message,r}o(iN,"defaultOnError");function ji(t,e,r,n){if(ae(e)){if(t!=null)return ji(t,e.ofType,r,n);r(qt(n),t,new C(`Expected non-nullable type "${A(e)}" not to be null.`));return}if(t==null)return null;if(Ve(e)){let i=e.ofType;return Cc(t)?Array.from(t,(s,a)=>{let c=Lp(n,a,void 0);return ji(s,i,r,c)}):[ji(t,i,r,n)]}if(Pe(e)){if(!be(t)){r(qt(n),t,new C(`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(ae(a.type)){let u=A(a.type);r(qt(n),t,new C(`Field "${a.name}" of required type "${u}" was not provided.`))}continue}i[a.name]=ji(c,a.type,r,Lp(n,a.name,e.name))}for(let a of Object.keys(t))if(!s[a]){let c=_c(a,Object.keys(e.getFields()));r(qt(n),t,new C(`Field "${a}" is not defined by type "${e.name}".`+yc(c)))}return i}if(mr(e)){let i;try{i=e.parseValue(t)}catch(s){s instanceof C?r(qt(n),t,s):r(qt(n),t,new C(`Expected type "${e.name}". `+s.message,{originalError:s}));return}return i===void 0&&r(qt(n),t,new C(`Expected type "${e.name}".`)),i}St(!1,"Unexpected input type: "+A(e))}o(ji,"coerceInputValueImpl");function Rt(t,e,r){if(t){if(t.kind===_.VARIABLE){let n=t.name.value;if(r==null||r[n]===void 0)return;let i=r[n];return i===null&&ae(e)?void 0:i}if(ae(e))return t.kind===_.NULL?void 0:Rt(t,e.ofType,r);if(t.kind===_.NULL)return null;if(Ve(e)){let n=e.ofType;if(t.kind===_.LIST){let s=[];for(let a of t.values)if(Tb(a,r)){if(ae(n))return;s.push(null)}else{let c=Rt(a,n,r);if(c===void 0)return;s.push(c)}return s}let i=Rt(t,n,r);return i===void 0?void 0:[i]}if(Pe(e)){if(t.kind!==_.OBJECT)return;let n=Object.create(null),i=qn(t.fields,s=>s.name.value);for(let s of Object.values(e.getFields())){let a=i[s.name];if(!a||Tb(a.value,r)){if(s.defaultValue!==void 0)n[s.name]=s.defaultValue;else if(ae(s.type))return;continue}let c=Rt(a.value,s.type,r);if(c===void 0)return;n[s.name]=c}return n}if(mr(e)){let n;try{n=e.parseLiteral(t,r)}catch{return}return n===void 0?void 0:n}St(!1,"Unexpected input type: "+A(e))}}o(Rt,"valueFromAST");function Tb(t,e){return t.kind===_.VARIABLE&&(e==null||e[t.name.value]===void 0)}o(Tb,"isMissingVariable");function kc(t,e,r,n){let i=[],s=n?.maxErrors;try{let a=oN(t,e,r,c=>{if(s!=null&&i.length>=s)throw new C("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(kc,"getVariableValues");function oN(t,e,r,n){let i={};for(let s of e){let a=s.variable.name.value,c=gr(t,s.type);if(!Qe(c)){let l=De(s.type);n(new C(`Variable "$${a}" expected value of type "${l}" which cannot be used as an input type.`,{nodes:s.type}));continue}if(!Sb(r,a)){if(s.defaultValue)i[a]=Rt(s.defaultValue,c);else if(ae(c)){let l=A(c);n(new C(`Variable "$${a}" of required type "${l}" was not provided.`,{nodes:s}))}continue}let u=r[a];if(u===null&&ae(c)){let l=A(c);n(new C(`Variable "$${a}" of non-null type "${l}" must not be null.`,{nodes:s}));continue}i[a]=Dp(u,c,(l,d,p)=>{let m=`Variable "$${a}" got invalid value `+A(d);l.length>0&&(m+=` at "${a}${Mc(l)}"`),n(new C(m+"; "+p.message,{nodes:s,originalError:p}))})}return i}o(oN,"coerceVariableValues");function Vi(t,e,r){var n;let i={},s=(n=e.arguments)!==null&&n!==void 0?n:[],a=qn(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(ae(l))throw new C(`Argument "${u}" of required type "${A(l)}" was not provided.`,{nodes:e});continue}let p=d.value,m=p.kind===_.NULL;if(p.kind===_.VARIABLE){let y=p.name.value;if(r==null||!Sb(r,y)){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ae(l))throw new C(`Argument "${u}" of required type "${A(l)}" was provided the variable "$${y}" which was not provided a runtime value.`,{nodes:p});continue}m=r[y]==null}if(m&&ae(l))throw new C(`Argument "${u}" of non-null type "${A(l)}" must not be null.`,{nodes:p});let f=Rt(p,l,r);if(f===void 0)throw new C(`Argument "${u}" has invalid value ${De(p)}.`,{nodes:p});i[u]=f}return i}o(Vi,"getArgumentValues");function Gi(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 Vi(t,i,r)}o(Gi,"getDirectiveValues");function Sb(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(Sb,"hasOwnProperty");var Fc=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===_.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===_.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}},Ib=class extends Fc{static{o(this,"SDLValidationContext")}constructor(e,r,n){super(e,n),this._schema=r}get[Symbol.toStringTag](){return"SDLValidationContext"}getSchema(){return this._schema}},Gn=class extends Fc{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 _r(this._schema);hr(e,Vn(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 Hc(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"),`
115
+ 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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},isRepeatable:{type:new j(Ue),resolve:t=>t.isRepeatable},locations:{type:new j(new de(new j(Op))),resolve:t=>t.locations},args:{type:new j(new de(new j(qi))),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}}})}),Op=new At({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:K.QUERY,description:"Location adjacent to a query operation."},MUTATION:{value:K.MUTATION,description:"Location adjacent to a mutation operation."},SUBSCRIPTION:{value:K.SUBSCRIPTION,description:"Location adjacent to a subscription operation."},FIELD:{value:K.FIELD,description:"Location adjacent to a field."},FRAGMENT_DEFINITION:{value:K.FRAGMENT_DEFINITION,description:"Location adjacent to a fragment definition."},FRAGMENT_SPREAD:{value:K.FRAGMENT_SPREAD,description:"Location adjacent to a fragment spread."},INLINE_FRAGMENT:{value:K.INLINE_FRAGMENT,description:"Location adjacent to an inline fragment."},VARIABLE_DEFINITION:{value:K.VARIABLE_DEFINITION,description:"Location adjacent to a variable definition."},SCHEMA:{value:K.SCHEMA,description:"Location adjacent to a schema definition."},SCALAR:{value:K.SCALAR,description:"Location adjacent to a scalar definition."},OBJECT:{value:K.OBJECT,description:"Location adjacent to an object type definition."},FIELD_DEFINITION:{value:K.FIELD_DEFINITION,description:"Location adjacent to a field definition."},ARGUMENT_DEFINITION:{value:K.ARGUMENT_DEFINITION,description:"Location adjacent to an argument definition."},INTERFACE:{value:K.INTERFACE,description:"Location adjacent to an interface definition."},UNION:{value:K.UNION,description:"Location adjacent to a union definition."},ENUM:{value:K.ENUM,description:"Location adjacent to an enum definition."},ENUM_VALUE:{value:K.ENUM_VALUE,description:"Location adjacent to an enum value definition."},INPUT_OBJECT:{value:K.INPUT_OBJECT,description:"Location adjacent to an input object type definition."},INPUT_FIELD_DEFINITION:{value:K.INPUT_FIELD_DEFINITION,description:"Location adjacent to an input object field definition."}}}),it=new xe({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 j(Cp),resolve(t){if(fr(t))return ee.SCALAR;if(Ne(t))return ee.OBJECT;if(Ee(t))return ee.INTERFACE;if(nt(t))return ee.UNION;if(We(t))return ee.ENUM;if(Pe(t))return ee.INPUT_OBJECT;if(Ve(t))return ee.LIST;if(ae(t))return ee.NON_NULL;St(!1,`Unexpected type: "${A(t)}".`)}},name:{type:oe,resolve:t=>"name"in t?t.name:void 0},description:{type:oe,resolve:t=>"description"in t?t.description:void 0},specifiedByURL:{type:oe,resolve:t=>"specifiedByURL"in t?t.specifiedByURL:void 0},fields:{type:new de(new j(xp)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Ne(t)||Ee(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},interfaces:{type:new de(new j(it)),resolve(t){if(Ne(t)||Ee(t))return t.getInterfaces()}},possibleTypes:{type:new de(new j(it)),resolve(t,e,r,{schema:n}){if(yr(t))return n.getPossibleTypes(t)}},enumValues:{type:new de(new j(Np)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(We(t)){let r=t.getValues();return e?r:r.filter(n=>n.deprecationReason==null)}}},inputFields:{type:new de(new j(qi)),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){if(Pe(t)){let r=Object.values(t.getFields());return e?r:r.filter(n=>n.deprecationReason==null)}}},ofType:{type:it,resolve:t=>"ofType"in t?t.ofType:void 0}})}),xp=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},args:{type:new j(new de(new j(qi))),args:{includeDeprecated:{type:Ue,defaultValue:!1}},resolve(t,{includeDeprecated:e}){return e?t.args:t.args.filter(r=>r.deprecationReason==null)}},type:{type:new j(it),resolve:t=>t.type},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),qi=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},type:{type:new j(it),resolve:t=>t.type},defaultValue:{type:oe,description:"A GraphQL-formatted string representing the default value for this input value.",resolve(t){let{type:e,defaultValue:r}=t,n=Fr(r,e);return n?De(n):null}},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),Np=new xe({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 j(oe),resolve:t=>t.name},description:{type:oe,resolve:t=>t.description},isDeprecated:{type:new j(Ue),resolve:t=>t.deprecationReason!=null},deprecationReason:{type:oe,resolve:t=>t.deprecationReason}})}),ee;(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"})(ee||(ee={}));var Cp=new At({name:"__TypeKind",description:"An enum describing what kind of type a given `__Type` is.",values:{SCALAR:{value:ee.SCALAR,description:"Indicates this type is a scalar."},OBJECT:{value:ee.OBJECT,description:"Indicates this type is an object. `fields` and `interfaces` are valid fields."},INTERFACE:{value:ee.INTERFACE,description:"Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields."},UNION:{value:ee.UNION,description:"Indicates this type is a union. `possibleTypes` is a valid field."},ENUM:{value:ee.ENUM,description:"Indicates this type is an enum. `enumValues` is a valid field."},INPUT_OBJECT:{value:ee.INPUT_OBJECT,description:"Indicates this type is an input object. `inputFields` is a valid field."},LIST:{value:ee.LIST,description:"Indicates this type is a list. `ofType` is a valid field."},NON_NULL:{value:ee.NON_NULL,description:"Indicates this type is a non-null. `ofType` is a valid field."}}}),Dc={name:"__schema",type:new j(Hi),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},Uc={name:"__type",type:it,description:"Request the type information of a single type.",args:[{name:"name",description:void 0,type:new j(oe),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},Mc={name:"__typename",type:new j(oe),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},Lp=Object.freeze([Hi,Rp,Op,it,xp,qi,Np,Cp]);var $i=class{static{o(this,"GraphQLSchema")}constructor(e){var r,n;this.__validationErrors=e.assumeValid===!0?[]:void 0,be(e)||B(!1,"Must provide configuration object."),!e.types||Array.isArray(e.types)||B(!1,`"types" must be Array if provided but got: ${A(e.types)}.`),!e.directives||Array.isArray(e.directives)||B(!1,`"directives" must be Array if provided but got: ${A(e.directives)}.`),this.description=e.description,this.extensions=Le(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:Pp;let i=new Set(e.types);if(e.types!=null)for(let s of e.types)i.delete(s),pt(s,i);this._queryType!=null&&pt(this._queryType,i),this._mutationType!=null&&pt(this._mutationType,i),this._subscriptionType!=null&&pt(this._subscriptionType,i);for(let s of this._directives)if(Ap(s))for(let a of s.args)pt(a.type,i);pt(Hi,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||B(!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,Ee(s)){for(let c of s.getInterfaces())if(Ee(c)){let u=this._implementationsMap[c.name];u===void 0&&(u=this._implementationsMap[c.name]={objects:[],interfaces:[]}),u.interfaces.push(s)}}else if(Ne(s)){for(let c of s.getInterfaces())if(Ee(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 rt.QUERY:return this.getQueryType();case rt.MUTATION:return this.getMutationType();case rt.SUBSCRIPTION:return this.getSubscriptionType()}}getTypeMap(){return this._typeMap}getType(e){return this.getTypeMap()[e]}getPossibleTypes(e){return nt(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),nt(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 pt(t,e){let r=lt(t);if(!e.has(r)){if(e.add(r),nt(r))for(let n of r.getTypes())pt(n,e);else if(Ne(r)||Ee(r)){for(let n of r.getInterfaces())pt(n,e);for(let n of Object.values(r.getFields())){pt(n.type,e);for(let i of n.args)pt(i.type,e)}}else if(Pe(r))for(let n of Object.values(r.getFields()))pt(n.type,e)}return e}o(pt,"collectReferencedTypes");function gr(t,e){switch(e.kind){case _.LIST_TYPE:{let r=gr(t,e.type);return r&&new de(r)}case _.NON_NULL_TYPE:{let r=gr(t,e.type);return r&&new j(r)}case _.NAMED_TYPE:return t.getType(e.name.value)}}o(gr,"typeFromAST");var _r=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??cN,r&&(Qe(r)&&this._inputTypeStack.push(r),Pt(r)&&this._parentTypeStack.push(r),qt(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 _.SELECTION_SET:{let i=lt(this.getType());this._parentTypeStack.push(Pt(i)?i:void 0);break}case _.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(qt(a)?a:void 0);break}case _.DIRECTIVE:this._directive=r.getDirective(e.name.value);break;case _.OPERATION_DEFINITION:{let i=r.getRootType(e.operation);this._typeStack.push(Ne(i)?i:void 0);break}case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:{let i=e.typeCondition,s=i?gr(r,i):lt(this.getType());this._typeStack.push(qt(s)?s:void 0);break}case _.VARIABLE_DEFINITION:{let i=gr(r,e.type);this._inputTypeStack.push(Qe(i)?i:void 0);break}case _.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(Qe(s)?s:void 0);break}case _.LIST:{let i=Pc(this.getInputType()),s=Ve(i)?i.ofType:i;this._defaultValueStack.push(void 0),this._inputTypeStack.push(Qe(s)?s:void 0);break}case _.OBJECT_FIELD:{let i=lt(this.getInputType()),s,a;Pe(i)&&(a=i.getFields()[e.name.value],a&&(s=a.type)),this._defaultValueStack.push(a?a.defaultValue:void 0),this._inputTypeStack.push(Qe(s)?s:void 0);break}case _.ENUM:{let i=lt(this.getInputType()),s;We(i)&&(s=i.getValue(e.value)),this._enumValue=s;break}default:}}leave(e){switch(e.kind){case _.SELECTION_SET:this._parentTypeStack.pop();break;case _.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case _.DIRECTIVE:this._directive=null;break;case _.OPERATION_DEFINITION:case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:this._typeStack.pop();break;case _.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case _.ARGUMENT:this._argument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case _.LIST:case _.OBJECT_FIELD:this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case _.ENUM:this._enumValue=null;break;default:}}};function cN(t,e,r){let n=r.name.value;if(n===Dc.name&&t.getQueryType()===e)return Dc;if(n===Uc.name&&t.getQueryType()===e)return Uc;if(n===Mc.name&&Pt(e))return Mc;if(Ne(e)||Ee(e))return e.getFields()[n]}o(cN,"getFieldDef");function Vn(t,e){return{enter(...r){let n=r[0];t.enter(n);let i=$n(e,n.kind).enter;if(i){let s=i.apply(e,r);return s!==void 0&&(t.leave(n),Ni(s)&&t.enter(s)),s}},leave(...r){let n=r[0],i=$n(e,n.kind).leave,s;return i&&(s=i.apply(e,r)),t.leave(n),s}}}o(Vn,"visitWithTypeInfo");function kc(t){return t.map(e=>typeof e=="number"?"["+e.toString()+"]":"."+e).join("")}o(kc,"printPathArray");function Dp(t,e,r){return{prev:t,key:e,typename:r}}o(Dp,"addPath");function $t(t){let e=[],r=t;for(;r;)e.push(r.key),r=r.prev;return e.reverse()}o($t,"pathToArray");function Up(t,e,r=uN){return ji(t,e,r,void 0)}o(Up,"coerceInputValue");function uN(t,e,r){let n="Invalid value "+A(e);throw t.length>0&&(n+=` at "value${kc(t)}"`),r.message=n+": "+r.message,r}o(uN,"defaultOnError");function ji(t,e,r,n){if(ae(e)){if(t!=null)return ji(t,e.ofType,r,n);r($t(n),t,new C(`Expected non-nullable type "${A(e)}" not to be null.`));return}if(t==null)return null;if(Ve(e)){let i=e.ofType;return Lc(t)?Array.from(t,(s,a)=>{let c=Dp(n,a,void 0);return ji(s,i,r,c)}):[ji(t,i,r,n)]}if(Pe(e)){if(!be(t)){r($t(n),t,new C(`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(ae(a.type)){let u=A(a.type);r($t(n),t,new C(`Field "${a.name}" of required type "${u}" was not provided.`))}continue}i[a.name]=ji(c,a.type,r,Dp(n,a.name,e.name))}for(let a of Object.keys(t))if(!s[a]){let c=bc(a,Object.keys(e.getFields()));r($t(n),t,new C(`Field "${a}" is not defined by type "${e.name}".`+gc(c)))}return i}if(mr(e)){let i;try{i=e.parseValue(t)}catch(s){s instanceof C?r($t(n),t,s):r($t(n),t,new C(`Expected type "${e.name}". `+s.message,{originalError:s}));return}return i===void 0&&r($t(n),t,new C(`Expected type "${e.name}".`)),i}St(!1,"Unexpected input type: "+A(e))}o(ji,"coerceInputValueImpl");function Rt(t,e,r){if(t){if(t.kind===_.VARIABLE){let n=t.name.value;if(r==null||r[n]===void 0)return;let i=r[n];return i===null&&ae(e)?void 0:i}if(ae(e))return t.kind===_.NULL?void 0:Rt(t,e.ofType,r);if(t.kind===_.NULL)return null;if(Ve(e)){let n=e.ofType;if(t.kind===_.LIST){let s=[];for(let a of t.values)if(Ib(a,r)){if(ae(n))return;s.push(null)}else{let c=Rt(a,n,r);if(c===void 0)return;s.push(c)}return s}let i=Rt(t,n,r);return i===void 0?void 0:[i]}if(Pe(e)){if(t.kind!==_.OBJECT)return;let n=Object.create(null),i=qn(t.fields,s=>s.name.value);for(let s of Object.values(e.getFields())){let a=i[s.name];if(!a||Ib(a.value,r)){if(s.defaultValue!==void 0)n[s.name]=s.defaultValue;else if(ae(s.type))return;continue}let c=Rt(a.value,s.type,r);if(c===void 0)return;n[s.name]=c}return n}if(mr(e)){let n;try{n=e.parseLiteral(t,r)}catch{return}return n===void 0?void 0:n}St(!1,"Unexpected input type: "+A(e))}}o(Rt,"valueFromAST");function Ib(t,e){return t.kind===_.VARIABLE&&(e==null||e[t.name.value]===void 0)}o(Ib,"isMissingVariable");function Fc(t,e,r,n){let i=[],s=n?.maxErrors;try{let a=lN(t,e,r,c=>{if(s!=null&&i.length>=s)throw new C("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(Fc,"getVariableValues");function lN(t,e,r,n){let i={};for(let s of e){let a=s.variable.name.value,c=gr(t,s.type);if(!Qe(c)){let l=De(s.type);n(new C(`Variable "$${a}" expected value of type "${l}" which cannot be used as an input type.`,{nodes:s.type}));continue}if(!Ab(r,a)){if(s.defaultValue)i[a]=Rt(s.defaultValue,c);else if(ae(c)){let l=A(c);n(new C(`Variable "$${a}" of required type "${l}" was not provided.`,{nodes:s}))}continue}let u=r[a];if(u===null&&ae(c)){let l=A(c);n(new C(`Variable "$${a}" of non-null type "${l}" must not be null.`,{nodes:s}));continue}i[a]=Up(u,c,(l,d,p)=>{let m=`Variable "$${a}" got invalid value `+A(d);l.length>0&&(m+=` at "${a}${kc(l)}"`),n(new C(m+"; "+p.message,{nodes:s,originalError:p}))})}return i}o(lN,"coerceVariableValues");function Vi(t,e,r){var n;let i={},s=(n=e.arguments)!==null&&n!==void 0?n:[],a=qn(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(ae(l))throw new C(`Argument "${u}" of required type "${A(l)}" was not provided.`,{nodes:e});continue}let p=d.value,m=p.kind===_.NULL;if(p.kind===_.VARIABLE){let y=p.name.value;if(r==null||!Ab(r,y)){if(c.defaultValue!==void 0)i[u]=c.defaultValue;else if(ae(l))throw new C(`Argument "${u}" of required type "${A(l)}" was provided the variable "$${y}" which was not provided a runtime value.`,{nodes:p});continue}m=r[y]==null}if(m&&ae(l))throw new C(`Argument "${u}" of non-null type "${A(l)}" must not be null.`,{nodes:p});let f=Rt(p,l,r);if(f===void 0)throw new C(`Argument "${u}" has invalid value ${De(p)}.`,{nodes:p});i[u]=f}return i}o(Vi,"getArgumentValues");function Gi(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 Vi(t,i,r)}o(Gi,"getDirectiveValues");function Ab(t,e){return Object.prototype.hasOwnProperty.call(t,e)}o(Ab,"hasOwnProperty");var Hc=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===_.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===_.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}},Pb=class extends Hc{static{o(this,"SDLValidationContext")}constructor(e,r,n){super(e,n),this._schema=r}get[Symbol.toStringTag](){return"SDLValidationContext"}getSchema(){return this._schema}},Gn=class extends Hc{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 _r(this._schema);hr(e,Vn(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 qc(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"),`
116
116
  query IntrospectionQuery {
117
117
  __schema {
118
118
  ${s}
@@ -217,5 +217,5 @@ In some cases, you need to provide options to alter GraphQL's execution behavior
217
217
  }
218
218
  }
219
219
  }
220
- `}o(Hc,"getIntrospectionQuery");function qc(t,e){be(t)&&be(t.__schema)||B(!1,`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${A(t)}.`);let r=t.__schema,n=It(r.types,E=>E.name,E=>m(E));for(let E of[...Sp,...Cp])n[E.name]&&(n[E.name]=E);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(Me):[];return new $i({description:r.description,query:i,mutation:s,subscription:a,types:Object.values(n),directives:c,assumeValid:e?.assumeValid});function u(E){if(E.kind===ee.LIST){let F=E.ofType;if(!F)throw new Error("Decorated type deeper than introspection query.");return new de(u(F))}if(E.kind===ee.NON_NULL){let F=E.ofType;if(!F)throw new Error("Decorated type deeper than introspection query.");let Ye=u(F);return new j(Ic(Ye))}return l(E)}function l(E){let F=E.name;if(!F)throw new Error(`Unknown type reference: ${A(E)}.`);let Ye=n[F];if(!Ye)throw new Error(`Invalid or incomplete schema, unknown type: ${F}. Ensure that a full introspection query is used in order to build a client schema.`);return Ye}function d(E){return vc(l(E))}function p(E){return Tc(l(E))}function m(E){if(E!=null&&E.name!=null&&E.kind!=null)switch(E.kind){case ee.SCALAR:return f(E);case ee.OBJECT:return v(E);case ee.INTERFACE:return T(E);case ee.UNION:return S(E);case ee.ENUM:return M(E);case ee.INPUT_OBJECT:return H(E)}let F=A(E);throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${F}.`)}function f(E){return new ze({name:E.name,description:E.description,specifiedByURL:E.specifiedByURL})}function y(E){if(E.interfaces===null&&E.kind===ee.INTERFACE)return[];if(!E.interfaces){let F=A(E);throw new Error(`Introspection result missing interfaces: ${F}.`)}return E.interfaces.map(p)}function v(E){return new xe({name:E.name,description:E.description,interfaces:()=>y(E),fields:()=>R(E)})}function T(E){return new Ft({name:E.name,description:E.description,interfaces:()=>y(E),fields:()=>R(E)})}function S(E){if(!E.possibleTypes){let F=A(E);throw new Error(`Introspection result missing possibleTypes: ${F}.`)}return new Mr({name:E.name,description:E.description,types:()=>E.possibleTypes.map(d)})}function M(E){if(!E.enumValues){let F=A(E);throw new Error(`Introspection result missing enumValues: ${F}.`)}return new At({name:E.name,description:E.description,values:It(E.enumValues,F=>F.name,F=>({description:F.description,deprecationReason:F.deprecationReason}))})}function H(E){if(!E.inputFields){let F=A(E);throw new Error(`Introspection result missing inputFields: ${F}.`)}return new kr({name:E.name,description:E.description,fields:()=>Y(E.inputFields)})}function R(E){if(!E.fields)throw new Error(`Introspection result missing fields: ${A(E)}.`);return It(E.fields,F=>F.name,ne)}function ne(E){let F=u(E.type);if(!Ht(F)){let Ye=A(F);throw new Error(`Introspection must provide output type for fields, but received: ${Ye}.`)}if(!E.args){let Ye=A(E);throw new Error(`Introspection result missing field args: ${Ye}.`)}return{description:E.description,deprecationReason:E.deprecationReason,type:F,args:Y(E.args)}}function Y(E){return It(E,F=>F.name,fe)}function fe(E){let F=u(E.type);if(!Qe(F)){let Bi=A(F);throw new Error(`Introspection must provide input type for arguments, but received: ${Bi}.`)}let Ye=E.defaultValue!=null?Rt(mc(E.defaultValue),F):void 0;return{description:E.description,type:F,defaultValue:Ye,deprecationReason:E.deprecationReason}}function Me(E){if(!E.args){let F=A(E);throw new Error(`Introspection result missing directive args: ${F}.`)}if(!E.locations){let F=A(E);throw new Error(`Introspection result missing directive locations: ${F}.`)}return new dt({name:E.name,description:E.description,isRepeatable:E.isRepeatable,locations:E.locations.slice(),args:Y(E.args)})}}o(qc,"buildClientSchema");function ON(t,e){return`The query exceeds the maximum complexity of ${t}. Actual complexity is ${e}`}o(ON,"queryComplexityMessage");function Ab(t){let e=new _r(t.schema),r=[],n=new Gn(t.schema,t.query,e,s=>r.push(s)),i=new Up(n,{maximumComplexity:t.maximumComplexity??1/0,estimators:t.estimators,variables:t.variables,operationName:t.operationName,context:t.context});if(hr(t.query,Vn(e,i)),r.length)throw r.pop();return i.complexity}o(Ab,"getComplexity");var Up=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}=kc(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 xe||r instanceof Ft)&&(n=r.getFields());let i;yr(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 f=this.includeDirectiveDef&&Gi(this.includeDirectiveDef,c,this.variableValues||{});typeof f?.if=="boolean"&&(l=f.if);break}case"skip":{let f=this.skipDirectiveDef&&Gi(this.skipDirectiveDef,c,this.variableValues||{});typeof f?.if=="boolean"&&(d=f.if);break}}if(!l||d)return a;switch(c.kind){case _.FIELD:{let p=n[c.name.value];if(!p)break;let m=lt(p.type),f;try{f=Vi(p,c,this.variableValues||{})}catch(S){return this.context.reportError(S),a}let y=0;Pt(m)&&(y=this.nodeComplexity(c,m));let v={childComplexity:y,args:f,field:p,node:c,type:r,context:this.requestContext};if(!this.estimators.find(S=>{let M=S(v);return typeof M=="number"&&!isNaN(M)?(u=Bn(M,a,i),!0):!1}))return this.context.reportError(new C(`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 _.FRAGMENT_SPREAD:{let p=this.context.getFragment(c.name.value);if(!p)break;let m=this.context.getSchema().getType(p.typeCondition.name.value);if(!Pt(m))break;let f=this.nodeComplexity(p,m);yr(m)?u=Bn(f,a,this.context.getSchema().getPossibleTypes(m).map(y=>y.name)):u=Bn(f,a,[m.name]);break}case _.INLINE_FRAGMENT:{let p=r;if(c.typeCondition&&c.typeCondition.name&&(p=this.context.getSchema().getType(c.typeCondition.name.value)||p,!Pt(p)))break;let m=this.nodeComplexity(c,p);yr(p)?u=Bn(m,a,this.context.getSchema().getPossibleTypes(p).map(f=>f.name)):u=Bn(m,a,[p.name]);break}default:{u=Bn(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 C(ON(this.options.maximumComplexity,this.complexity))}};function Bn(t,e,r){for(let n of r)Object.prototype.hasOwnProperty.call(e,n)?e[n]+=t:e[n]=t;return e}o(Bn,"addComplexities");function Pb(t){let e=t?.defaultComplexity??1;return r=>e+r.childComplexity}o(Pb,"simpleEstimator");var Rb=o((t,e,r={})=>{let{definitions:n}=t,i=xN(n),s=NN(n);return Object.entries(s).map(([a,c])=>$c(c,i,0,e,a,r))},"depthLimit");function xN(t){return t.reduce((e,r)=>(r.kind===_.FRAGMENT_DEFINITION&&(e[r?.name?.value??""]=r),e),{})}o(xN,"getFragments");function NN(t){return t.reduce((e,r)=>{if(r.kind===_.OPERATION_DEFINITION){let n=r?.name?.value??"";e[n]=r}return e},{})}o(NN,"getQueriesAndMutations");function $c(t,e,r,n,i,s){if(r>n)throw s?.onLimitReached?.(r,i),new C(`${i||"Your query"} exceeds maximum operation depth of ${n}`,{nodes:[t]});let a=s?.ignore??[/^__/];switch(t.kind){case _.FIELD:return CN(t,a)||!t.selectionSet?0:1+Math.max(...t.selectionSet.selections.map(c=>$c(c,e,r+1,n,i,s)));case _.FRAGMENT_SPREAD:return $c(e[t.name.value],e,r,n,i,s);case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:case _.OPERATION_DEFINITION:return Math.max(...t.selectionSet.selections.map(c=>$c(c,e,r,n,i,s)));default:throw new Error("uh oh! depth crawler cannot handle: "+t.kind)}}o($c,"determineDepth");var CN=o((t,e)=>e.find(r=>t.name.value.match(r)!==null)||!1,"isIgnored");var LN=o(async(t,e)=>{if(!e.complexityLimit)throw new Kn.ConfigurationError("No complexity maximum defined, you need to pass a maxComplexity to the policy");let n=e.endpointUrl;if(!n)throw new Kn.ConfigurationError("No GraphQL endpoint, you need to pass a endpointUrl to the policy");let i=Hc(),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 C("GraphQL introspection query failed, enable introspection or pass a schema url in configuration.");let u=qc(c,{assumeValid:!0}),l=Ab({estimators:[Pb({defaultComplexity:1})],schema:u,query:t,variables:{count:10}});if(e.complexityLimit&&l>e.complexityLimit)throw new C(`Query is too complex (${l}/${e.complexityLimit}), remove some fields and try again`)},"applyComplexityLimitPolicy"),DN=o(async(t,e)=>{let r=e.depthLimit;if(!r)throw new Kn.ConfigurationError("No maximum depth defined, you need to pass a maxDepth to the policy");return Math.max(...Rb(t,r))},"applyDepthLimitPolicy"),Ob=o(async(t,e,r)=>{let n=Kn.SystemLogMap.getLogger(e);try{let s=await t.clone().json(),a=fc(s.query);r.useDepthLimit&&await DN(a,r.useDepthLimit),r.useComplexityLimit&&await LN(a,r.useComplexityLimit)}catch(i){if(i instanceof C)return n.info(i),new Response(JSON.stringify(i.toJSON()),{status:400,headers:{"Content-Type":"application/json"}});throw i}return t},"GraphQLComplexityLimitInboundPolicy");var xb=kp(xt());function UN(t){if(!t)return!1;let e=t.replace(/\s/g,"");return e.includes("__schema")||e.includes("__type")}o(UN,"isIntrospectionQuery");var Nb=o(async(t,e,r)=>{let i=await t.clone().json();return UN(i.query)?xb.HttpProblems.forbidden(t,e,{detail:"Introspection queries are not allowed"}):t},"GraphQLDisableIntrospectionInboundPolicy");
220
+ `}o(qc,"getIntrospectionQuery");function $c(t,e){be(t)&&be(t.__schema)||B(!1,`Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${A(t)}.`);let r=t.__schema,n=It(r.types,E=>E.name,E=>m(E));for(let E of[...Ip,...Lp])n[E.name]&&(n[E.name]=E);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(Me):[];return new $i({description:r.description,query:i,mutation:s,subscription:a,types:Object.values(n),directives:c,assumeValid:e?.assumeValid});function u(E){if(E.kind===ee.LIST){let F=E.ofType;if(!F)throw new Error("Decorated type deeper than introspection query.");return new de(u(F))}if(E.kind===ee.NON_NULL){let F=E.ofType;if(!F)throw new Error("Decorated type deeper than introspection query.");let Ye=u(F);return new j(Ac(Ye))}return l(E)}function l(E){let F=E.name;if(!F)throw new Error(`Unknown type reference: ${A(E)}.`);let Ye=n[F];if(!Ye)throw new Error(`Invalid or incomplete schema, unknown type: ${F}. Ensure that a full introspection query is used in order to build a client schema.`);return Ye}function d(E){return Tc(l(E))}function p(E){return Sc(l(E))}function m(E){if(E!=null&&E.name!=null&&E.kind!=null)switch(E.kind){case ee.SCALAR:return f(E);case ee.OBJECT:return v(E);case ee.INTERFACE:return T(E);case ee.UNION:return S(E);case ee.ENUM:return M(E);case ee.INPUT_OBJECT:return H(E)}let F=A(E);throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${F}.`)}function f(E){return new ze({name:E.name,description:E.description,specifiedByURL:E.specifiedByURL})}function y(E){if(E.interfaces===null&&E.kind===ee.INTERFACE)return[];if(!E.interfaces){let F=A(E);throw new Error(`Introspection result missing interfaces: ${F}.`)}return E.interfaces.map(p)}function v(E){return new xe({name:E.name,description:E.description,interfaces:()=>y(E),fields:()=>R(E)})}function T(E){return new Ht({name:E.name,description:E.description,interfaces:()=>y(E),fields:()=>R(E)})}function S(E){if(!E.possibleTypes){let F=A(E);throw new Error(`Introspection result missing possibleTypes: ${F}.`)}return new Mr({name:E.name,description:E.description,types:()=>E.possibleTypes.map(d)})}function M(E){if(!E.enumValues){let F=A(E);throw new Error(`Introspection result missing enumValues: ${F}.`)}return new At({name:E.name,description:E.description,values:It(E.enumValues,F=>F.name,F=>({description:F.description,deprecationReason:F.deprecationReason}))})}function H(E){if(!E.inputFields){let F=A(E);throw new Error(`Introspection result missing inputFields: ${F}.`)}return new kr({name:E.name,description:E.description,fields:()=>Y(E.inputFields)})}function R(E){if(!E.fields)throw new Error(`Introspection result missing fields: ${A(E)}.`);return It(E.fields,F=>F.name,ne)}function ne(E){let F=u(E.type);if(!qt(F)){let Ye=A(F);throw new Error(`Introspection must provide output type for fields, but received: ${Ye}.`)}if(!E.args){let Ye=A(E);throw new Error(`Introspection result missing field args: ${Ye}.`)}return{description:E.description,deprecationReason:E.deprecationReason,type:F,args:Y(E.args)}}function Y(E){return It(E,F=>F.name,fe)}function fe(E){let F=u(E.type);if(!Qe(F)){let Bi=A(F);throw new Error(`Introspection must provide input type for arguments, but received: ${Bi}.`)}let Ye=E.defaultValue!=null?Rt(yc(E.defaultValue),F):void 0;return{description:E.description,type:F,defaultValue:Ye,deprecationReason:E.deprecationReason}}function Me(E){if(!E.args){let F=A(E);throw new Error(`Introspection result missing directive args: ${F}.`)}if(!E.locations){let F=A(E);throw new Error(`Introspection result missing directive locations: ${F}.`)}return new dt({name:E.name,description:E.description,isRepeatable:E.isRepeatable,locations:E.locations.slice(),args:Y(E.args)})}}o($c,"buildClientSchema");function DN(t,e){return`The query exceeds the maximum complexity of ${t}. Actual complexity is ${e}`}o(DN,"queryComplexityMessage");function Rb(t){let e=new _r(t.schema),r=[],n=new Gn(t.schema,t.query,e,s=>r.push(s)),i=new Mp(n,{maximumComplexity:t.maximumComplexity??1/0,estimators:t.estimators,variables:t.variables,operationName:t.operationName,context:t.context});if(hr(t.query,Vn(e,i)),r.length)throw r.pop();return i.complexity}o(Rb,"getComplexity");var Mp=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}=Fc(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 xe||r instanceof Ht)&&(n=r.getFields());let i;yr(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 f=this.includeDirectiveDef&&Gi(this.includeDirectiveDef,c,this.variableValues||{});typeof f?.if=="boolean"&&(l=f.if);break}case"skip":{let f=this.skipDirectiveDef&&Gi(this.skipDirectiveDef,c,this.variableValues||{});typeof f?.if=="boolean"&&(d=f.if);break}}if(!l||d)return a;switch(c.kind){case _.FIELD:{let p=n[c.name.value];if(!p)break;let m=lt(p.type),f;try{f=Vi(p,c,this.variableValues||{})}catch(S){return this.context.reportError(S),a}let y=0;Pt(m)&&(y=this.nodeComplexity(c,m));let v={childComplexity:y,args:f,field:p,node:c,type:r,context:this.requestContext};if(!this.estimators.find(S=>{let M=S(v);return typeof M=="number"&&!isNaN(M)?(u=Bn(M,a,i),!0):!1}))return this.context.reportError(new C(`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 _.FRAGMENT_SPREAD:{let p=this.context.getFragment(c.name.value);if(!p)break;let m=this.context.getSchema().getType(p.typeCondition.name.value);if(!Pt(m))break;let f=this.nodeComplexity(p,m);yr(m)?u=Bn(f,a,this.context.getSchema().getPossibleTypes(m).map(y=>y.name)):u=Bn(f,a,[m.name]);break}case _.INLINE_FRAGMENT:{let p=r;if(c.typeCondition&&c.typeCondition.name&&(p=this.context.getSchema().getType(c.typeCondition.name.value)||p,!Pt(p)))break;let m=this.nodeComplexity(c,p);yr(p)?u=Bn(m,a,this.context.getSchema().getPossibleTypes(p).map(f=>f.name)):u=Bn(m,a,[p.name]);break}default:{u=Bn(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 C(DN(this.options.maximumComplexity,this.complexity))}};function Bn(t,e,r){for(let n of r)Object.prototype.hasOwnProperty.call(e,n)?e[n]+=t:e[n]=t;return e}o(Bn,"addComplexities");function Ob(t){let e=t?.defaultComplexity??1;return r=>e+r.childComplexity}o(Ob,"simpleEstimator");var xb=o((t,e,r={})=>{let{definitions:n}=t,i=UN(n),s=MN(n);return Object.entries(s).map(([a,c])=>jc(c,i,0,e,a,r))},"depthLimit");function UN(t){return t.reduce((e,r)=>(r.kind===_.FRAGMENT_DEFINITION&&(e[r?.name?.value??""]=r),e),{})}o(UN,"getFragments");function MN(t){return t.reduce((e,r)=>{if(r.kind===_.OPERATION_DEFINITION){let n=r?.name?.value??"";e[n]=r}return e},{})}o(MN,"getQueriesAndMutations");function jc(t,e,r,n,i,s){if(r>n)throw s?.onLimitReached?.(r,i),new C(`${i||"Your query"} exceeds maximum operation depth of ${n}`,{nodes:[t]});let a=s?.ignore??[/^__/];switch(t.kind){case _.FIELD:return kN(t,a)||!t.selectionSet?0:1+Math.max(...t.selectionSet.selections.map(c=>jc(c,e,r+1,n,i,s)));case _.FRAGMENT_SPREAD:return jc(e[t.name.value],e,r,n,i,s);case _.INLINE_FRAGMENT:case _.FRAGMENT_DEFINITION:case _.OPERATION_DEFINITION:return Math.max(...t.selectionSet.selections.map(c=>jc(c,e,r,n,i,s)));default:throw new Error("uh oh! depth crawler cannot handle: "+t.kind)}}o(jc,"determineDepth");var kN=o((t,e)=>e.find(r=>t.name.value.match(r)!==null)||!1,"isIgnored");var FN=o(async(t,e)=>{if(!e.complexityLimit)throw new Kn.ConfigurationError("No complexity maximum defined, you need to pass a maxComplexity to the policy");let n=e.endpointUrl;if(!n)throw new Kn.ConfigurationError("No GraphQL endpoint, you need to pass a endpointUrl to the policy");let i=qc(),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 C("GraphQL introspection query failed, enable introspection or pass a schema url in configuration.");let u=$c(c,{assumeValid:!0}),l=Rb({estimators:[Ob({defaultComplexity:1})],schema:u,query:t,variables:{count:10}});if(e.complexityLimit&&l>e.complexityLimit)throw new C(`Query is too complex (${l}/${e.complexityLimit}), remove some fields and try again`)},"applyComplexityLimitPolicy"),HN=o(async(t,e)=>{let r=e.depthLimit;if(!r)throw new Kn.ConfigurationError("No maximum depth defined, you need to pass a maxDepth to the policy");return Math.max(...xb(t,r))},"applyDepthLimitPolicy"),Nb=o(async(t,e,r)=>{let n=Kn.SystemLogMap.getLogger(e);try{let s=await t.clone().json(),a=mc(s.query);r.useDepthLimit&&await HN(a,r.useDepthLimit),r.useComplexityLimit&&await FN(a,r.useComplexityLimit)}catch(i){if(i instanceof C)return n.info(i),new Response(JSON.stringify(i.toJSON()),{status:400,headers:{"Content-Type":"application/json"}});throw i}return t},"GraphQLComplexityLimitInboundPolicy");var Cb=Fp(xt());function qN(t){if(!t)return!1;let e=t.replace(/\s/g,"");return e.includes("__schema")||e.includes("__type")}o(qN,"isIntrospectionQuery");var Lb=o(async(t,e,r)=>{let i=await t.clone().json();return qN(i.query)?Cb.HttpProblems.forbidden(t,e,{detail:"Introspection queries are not allowed"}):t},"GraphQLDisableIntrospectionInboundPolicy");
221
221
  /*! For license information please see index.minified.js.LEGAL.txt */