@zuplo/runtime 6.2.12 → 6.2.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as i}from"./chunk-OQPRFCK5.js";var N=(g=>(g.Build="build-data",g.CorsPreflight="cors-preflight",g.DeveloperPortal="developer-portal",g.DeveloperPortalLegacy="developer-portal-legacy",g.StripePlugin="stripe-plugin",g.EmptyGatewayCatchall="empty-gateway-catchall",g.Ping="ping",g.UnmatchedPath="unmatched-path",g))(N||{});function b(n){if(n.length>=255)throw new TypeError("Alphabet too long");let r=new Uint8Array(256);for(let e=0;e<r.length;e++)r[e]=255;for(let e=0;e<n.length;e++){let o=n.charAt(e),d=o.charCodeAt(0);if(r[d]!==255)throw new TypeError(o+" is ambiguous");r[d]=e}let t=n.length,s=n.charAt(0),O=Math.log(t)/Math.log(256),h=Math.log(256)/Math.log(t);function P(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let o=0,d=0,u=0,c=e.length;for(;u!==c&&e[u]===0;)u++,o++;let f=(c-u)*h+1>>>0,_=new Uint8Array(f);for(;u!==c;){let a=e[u],
|
|
26
|
-
/*! For license information please see chunk-
|
|
25
|
+
import{a as i}from"./chunk-OQPRFCK5.js";var N=(g=>(g.Build="build-data",g.CorsPreflight="cors-preflight",g.DeveloperPortal="developer-portal",g.DeveloperPortalLegacy="developer-portal-legacy",g.StripePlugin="stripe-plugin",g.EmptyGatewayCatchall="empty-gateway-catchall",g.Ping="ping",g.UnmatchedPath="unmatched-path",g))(N||{});function b(n){if(n.length>=255)throw new TypeError("Alphabet too long");let r=new Uint8Array(256);for(let e=0;e<r.length;e++)r[e]=255;for(let e=0;e<n.length;e++){let o=n.charAt(e),d=o.charCodeAt(0);if(r[d]!==255)throw new TypeError(o+" is ambiguous");r[d]=e}let t=n.length,s=n.charAt(0),O=Math.log(t)/Math.log(256),h=Math.log(256)/Math.log(t);function P(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let o=0,d=0,u=0,c=e.length;for(;u!==c&&e[u]===0;)u++,o++;let f=(c-u)*h+1>>>0,_=new Uint8Array(f);for(;u!==c;){let a=e[u],L=0;for(let m=f-1;(a!==0||L<d)&&m!==-1;m--,L++)a+=256*_[m]>>>0,_[m]=a%t>>>0,a=a/t>>>0;if(a!==0)throw new Error("Non-zero carry");d=L,u++}let p=f-d;for(;p!==f&&_[p]===0;)p++;let U=s.repeat(o);for(;p<f;++p)U+=n.charAt(_[p]);return U}i(P,"encode");function T(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let o=0,d=0,u=0;for(;e[o]===s;)d++,o++;let c=(e.length-o)*O+1>>>0,f=new Uint8Array(c);for(;e[o];){let a=r[e.charCodeAt(o)];if(a===255)return;let L=0;for(let m=c-1;(a!==0||L<u)&&m!==-1;m--,L++)a+=t*f[m]>>>0,f[m]=a%256>>>0,a=a/256>>>0;if(a!==0)throw new Error("Non-zero carry");u=L,o++}let _=c-u;for(;_!==c&&f[_]===0;)_++;let p=new Uint8Array(d+(c-_)),U=d;for(;_!==c;)p[U++]=f[_++];return p}i(T,"decodeUnsafe");function g(e){let o=T(e);if(o)return o;throw new Error("Non-base"+t+" character")}return i(g,"decode"),{encode:P,decodeUnsafe:T,decode:g}}i(b,"base");var R=b;var v="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",y=R(v);var A="2024-09-02",I=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function C(){return new l({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:A,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:I[A]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(C,"getMockEnvironment");var l=class n{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(r){this.#e||(this.#e=new n(r),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=C()),this.#e}constructor({build:r,runtime:t}){let s;try{if(t.__ZUPLO_CONFIG){let O=atob(t.__ZUPLO_CONFIG);s=JSON.parse(O)}if(t.ZUPLO_SYSTEM_CONFIGURATIONS){let O=new TextDecoder().decode(y.decode(t.ZUPLO_SYSTEM_CONFIGURATIONS)),h=JSON.parse(O);for(let P of Object.keys(h))t[P]=h[P]}}catch(O){console.error("Failed to parse runtime configuration",O)}this.config=s??{},this.build=r,this.runtime=t,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get enableRuntimeUserLogs(){return this.config.runtime_user_logs==="true"}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.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var w=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function S(n){return n.startsWith("__ZUPLO")||n.startsWith("ZUPLO_")?!w.includes(n)&&!n.startsWith("ZUPLO_PUBLIC_"):!1}i(S,"isRestrictedEnvVariableName");function M(n){return!!n.startsWith("ZUPLO_")}i(M,"isZuploReadableEnvVariableName");var X=new Proxy({},{get(n,r){let t=String(r);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return l.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return l.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return l.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return l.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return l.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return l.instance.build.BUILD_ID}if(!(S(t)&&!M(t)))return l.instance.runtime[t]}});function ne(n,r,t){return`_${E(n+"_"+r+"_"+t)}`}i(ne,"getRawOperationDataIdentifierName");function re(n,r,t,s){return`_${E(n.toLowerCase())}_`+r.toLowerCase()+"_"+t.toLowerCase()+`_${s.toLowerCase()}`}i(re,"getIdForParameterSchema");function ie(n,r,t){return`_${E(n.toLowerCase())}_`+r.toLowerCase()+`_rb_${E(t.toLowerCase())}`}i(ie,"getIdForRequestBodySchema");function oe(n,r){return`_${E(n)}__${E(r)}`}i(oe,"getIdForRefSchema");function E(n){let r=[];for(let t=0;t<n.length;t++){let s=n.charCodeAt(t);s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122?r.push(n.charAt(t)):r.push("_")}return r.join("")}i(E,"sanitizedIdentifierName");export{l as a,N as b,S as c,M as d,X as e,ne as f,re as g,ie as h,oe as i,E as j};
|
|
26
|
+
/*! For license information please see chunk-PBNUVAP3.js.LEGAL.txt */
|
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as f,b as $e,e as Pe,f as nu,g as Bn,h as Gn,i as ru,j as ou}from"./chunk-
|
|
25
|
+
import{a as f,b as $e,e as Pe,f as nu,g as Bn,h as Gn,i as ru,j as ou}from"./chunk-PBNUVAP3.js";import{a as i}from"./chunk-OQPRFCK5.js";var iu=!1;function ct(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}i(ct,"code");function lt(n,e){return iu?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}i(lt,"run");function su(n){return lt(n,ct([31],39))}i(su,"red");function au(n){return lt(n,ct([32],39))}i(au,"green");function uu(n){return lt(n,ct([33],39))}i(uu,"yellow");function cu(n){return lt(n,ct([34],39))}i(cu,"blue");function lu(n){return lt(n,ct([35],39))}i(lu,"magenta");function du(n){return lt(n,ct([36],39))}i(du,"cyan");var Nd=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var Oi=[su,au,uu,cu,lu,du];function pu(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}i(pu,"hashCode");function Si(n){let e=Math.abs(pu(n));return Oi[e%Oi.length]}i(Si,"generateColor");function Ai(n,e,...t){let r=0,o=t.length,s=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
|
|
26
26
|
`).map(u=>u.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?s+=" "+a:s+=" "+n(a);return s}i(Ai,"format");function Fe(n,e,t,r){let o={seen:[],stylize:mu,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=fu),tn(o,n,o.depth)}i(Fe,"inspect");Fe.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]};Fe.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function mu(n,e){return n}i(mu,"stylizeNoColor");function gu(n){return typeof n=="boolean"}i(gu,"isBoolean");function Li(n){return n===void 0}i(Li,"isUndefined");function fu(n,e){let t=Fe.styles[e];return t?"\x1B["+Fe.colors[t][0]+"m"+n+"\x1B["+Fe.colors[t][1]+"m":n}i(fu,"stylizeWithColor");function Vn(n){return typeof n=="function"}i(Vn,"isFunction");function _i(n){return typeof n=="string"}i(_i,"isString");function hu(n){return typeof n=="number"}i(hu,"isNumber");function Ni(n){return n===null}i(Ni,"isNull");function Di(n,e){return Object.prototype.hasOwnProperty.call(n,e)}i(Di,"hasOwn");function Wn(n){return Yn(n)&&Xn(n)==="[object RegExp]"}i(Wn,"isRegExp");function Yn(n){return typeof n=="object"&&n!==null}i(Yn,"isObject");function Kn(n){return Yn(n)&&(Xn(n)==="[object Error]"||n instanceof Error)}i(Kn,"isError");function ki(n){return Yn(n)&&Xn(n)==="[object Date]"}i(ki,"isDate");function Xn(n){return Object.prototype.toString.call(n)}i(Xn,"objectToString");function yu(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}i(yu,"arrayToHash");function bu(n,e,t,r,o){let s=[];for(let a=0,u=e.length;a<u;++a)Di(e,String(a))?s.push(Qn(n,e,t,r,String(a),!0)):s.push("");return o.forEach(function(a){a.match(/^\d+$/)||s.push(Qn(n,e,t,r,a,!0))}),s}i(bu,"formatArray");function Jn(n){return"["+Error.prototype.toString.call(n)+"]"}i(Jn,"formatError");function tn(n,e,t){if(n.customInspect&&e&&Vn(e.inspect)&&e.inspect!==Fe&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return _i(d)||(d=tn(n,d,t)),d}let r=wu(n,e);if(r)return r;let o=Object.keys(e),s=yu(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(Kn(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Jn(e);if(o.length===0){if(Vn(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Wn(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(ki(e))return n.stylize(Date.prototype.toString.call(e),"date");if(Kn(e))return Jn(e)}let a="",u=!1,c=["{","}"];if(Array.isArray(e)&&(u=!0,c=["[","]"]),Vn(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Wn(e)&&(a=" "+RegExp.prototype.toString.call(e)),ki(e)&&(a=" "+Date.prototype.toUTCString.call(e)),Kn(e)&&(a=" "+Jn(e)),o.length===0&&(!u||e.length==0))return c[0]+a+c[1];if(t<0)return Wn(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return u?l=bu(n,e,t,s,o):l=o.map(function(d){return Qn(n,e,t,s,d,u)}),n.seen.pop(),Ru(l,a,c)}i(tn,"formatValue");function Qn(n,e,t,r,o,s){let a,u,c;c={value:void 0};try{c.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(e,o)||c)}catch{}if(c.get?c.set?u=n.stylize("[Getter/Setter]","special"):u=n.stylize("[Getter]","special"):c.set&&(u=n.stylize("[Setter]","special")),Di(r,o)||(a="["+o+"]"),u||(n.seen.indexOf(c.value)<0?(Ni(t)?u=tn(n,c.value,null):u=tn(n,c.value,t-1),u.indexOf(`
|
|
27
27
|
`)>-1&&(s?u=u.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
@@ -53,7 +53,7 @@ import{a as f,b as $e,e as Pe,f as nu,g as Bn,h as Gn,i as ru,j as ou}from"./chu
|
|
|
53
53
|
`,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let h=i(y=>{if(u.inlineCharacterLimit===void 0)return y;let S=y.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return S.length<=u.inlineCharacterLimit?S:y.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
54
54
|
`).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||ys(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let y="["+p.newline+a.map((S,R)=>{let C=a.length-1===R?p.newline:","+p.newlineOrSpace,N=s(S,u,c+d,l+1);return u.transform&&(N=u.transform(a,R,N)),p.indent+N+C}).join("")+p.pad+"]";return r.pop(),h(y)}if(rt(a)){let y=bs(a);if(u.filter&&(y=y.filter(R=>u.filter?.(a,R))),y.length===0)return"{}";r.push(a);let S="{"+p.newline+y.map((R,C)=>{let N=y.length-1===C?p.newline:","+p.newlineOrSpace,k=typeof R=="symbol",$=!k&&/^[a-z$_][$\w]*$/i.test(R),U=k||$?R:s(R,u,"",l+1),F=s(a[R],u,c+d,l+1);return u.transform&&(F=u.transform(a,R,F)),p.indent+String(U)+": "+F+N}).join("")+p.pad+"}";return r.pop(),h(S)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,y=>y===`
|
|
55
55
|
`?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}i(wn,"stringifyObject");function We(n){return n.map(e=>Ie(e))}i(We,"makeErrorsSerializable");function mt(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:Ze(Ie(e))}i(mt,"extractBestMessage");function qs(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ut(t))if(t.stack)e.push(t.stack);else{let r=wn(Ie(t));e.push(r)}else if(typeof t=="object"){let r=wn(t);e.push(r)}else{let r=Br(t);e.push(r)}}),e.join(`
|
|
56
|
-
`)}i(qs,"messagesToMultilineText");function Ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ze,"stringifyNonString");function Br(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ar(n):"unknown"}i(Br,"stringifyNonStringToText");import{importPKCS8 as ec,SignJWT as tc}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.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,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new tc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Us(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Gr("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Us,"exchangeIDTokenForGcpWorkloadToken");async function Hs({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return $s(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Hs,"generateServiceAccountIDToken");async function Zs(n,e,t){return Gr(n,{token:e,returnSecureToken:!0},t)}i(Zs,"exchangeFirebaseJwtForIdToken");async function Rn(n,e,t){return Gr(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Rn,"exchangeGgpJwtForIdToken");async function Gr(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return $s(n,r,t)}i(Gr,"fetchTokenFromBody");async function $s(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i($s,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ec(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}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}};async function de(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await Fs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(de,"sendRemoteGlobalLog");async function Fs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:We(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Fs,"sendRemoteLogs");var nc=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Fs({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Pn,In=class{static{i(this,"RemoteLogTransport")}constructor(e){Pn||(Pn=new Y("remote-log-transport",1,nc(e)))}log(e,t){Pn.enqueue(e),t.waitUntil(Pn.waitUntilFlushed())}};var Vr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},rc="https://logging.googleapis.com/v2/entries:write?alt=json",Wr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:We(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(rc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await de({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await de({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var En="gcp";function xn(n){let e={allMessages:We(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Wr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(xn,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e.log(JSON.stringify(e))}};var Yr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Kr="__ddtags",Jr="__ddattr",Qr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),oc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Qr(r)):t.push(`${Qr(r)}:${Qr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Kr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Kr]!==void 0);a>-1&&(Object.assign(r,s[a][Kr]),s.splice(a,1));let u={},c=t.custom[Jr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Jr]!==void 0);l>-1&&(Object.assign(u,s[l][Jr]),s.splice(l,1));let d=We(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:oc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await de({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await de({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(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}])}};var ic={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},js=i((n,e)=>t=>{let r={};return r.accountName=e.ACCOUNT_NAME,r.projectName=e.PROJECT_NAME,r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ic[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var sc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=js(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Tn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Tn||(Tn=new Y("unified-log-transport",1,sc(e)))}async log(e,t){Tn.enqueue(e),t.waitUntil(Tn.waitUntilFlushed())}};var Xr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Xr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(sn);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Xr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(sn);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new In({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),e.build.ACCOUNT_NAME==="nate-totten"&&e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Xr("Gateway.createRequestLoggers");let a=new bn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(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};var eo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Wt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},to=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Kt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof le))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new eo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new to(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Wt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Wt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var no;function zs(n){no=n}i(zs,"setGlobalZuploEventContext");function Cn(){if(no===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return no}i(Cn,"getGlobalZuploEventContext");function Bs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);rs.includes(o.toLowerCase())&&!os.includes(r.toLowerCase())&&t.delete(r)}t.delete(zi)}else ns.forEach(r=>{t.delete(r)});return t}i(Bs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),uc=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:Is(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[yn,fn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=uc(e.versions),r=new Kt(t);if(e.routes.length===0)return Sr(r,this),Mr(r,this),Nr(r,this),Es(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ns(r,this),_s(r,this)),Sr(r,this),Mr(r,this),Nr(r,this);for(let s of Ue)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),xs(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=Ms(s.stack)),o={cause:s}}}return E.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;zs(r);let a=Bs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(et,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(sr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let S=new On(e.headers),R=new te(u,{params:y.params}),C=new Sn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:S}),N=y.routeConfiguration.raw();ac.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(C,R);if(y.routeConfiguration===Dr&&Nt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=$.map(U=>U.routeConfiguration).filter(U=>U instanceof it)}try{if(Q.addLogger(C,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let v=await ps(R,C);if(v instanceof Response)return v;{let H=be.getContextExtensions(C);R=v,H.latestRequest=R}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let $=y.executableHandler;cc($,y,u),De("Gateway.handleRequest - call user handler");let U=await $(R,C);if(De("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let F;if(U.headers.get(et)===null&&!U.webSocket){let v=new Headers(U.headers);v.set(et,o),F=new Response(U.body,{status:U.status,statusText:U.statusText,headers:v,cf:U.cf})}else F=U;return F}catch($){return De("Gateway - error executing handler",$),$ instanceof A?(l.error($),d.warn($)):d.error($),await this.#i(R,C,$)}}};function cc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cc,"checkHandler");var Gs=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ht([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),Vs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new A(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(pr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(mr)??void 0}get city(){return this.#e.get(ar)??this.#e.get(Ji)??void 0}get continent(){return this.#e.get(ur)??this.#e.get(Qi)??void 0}get country(){return this.#e.get(cr)??this.#e.get(Yi)??void 0}get latitude(){return this.#e.get(dr)??this.#e.get(es)??void 0}get longitude(){return this.#e.get(lr)??this.#e.get(Xi)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(Wi)??this.#e.get(fr)??void 0}get metroCode(){return this.#e.get(Vi)??this.#e.get(hr)??void 0}get region(){return this.#e.get(Bi)??this.#e.get(yr)??void 0}get regionCode(){return this.#e.get(Gi)??this.#e.get(br)??void 0}get timezone(){return this.#e.get(Ki)??this.#e.get(wr)??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}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Gs(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Vs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as lc}from"node:async_hooks";var Ws={request:new lc};var dc="Error initializing gateway. Check your configuration for errors or contact support.",pc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",ro=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(et)??e.headers.get(ji)??crypto.randomUUID(),s=e.headers.get(tt),a={requestId:o,rayId:s};return Ws.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await fs(this.runtimeInit)}catch(c){this.handleError(c,pc,e)}return as(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function mc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(mc,"lexer");function io(n,e){e===void 0&&(e={});for(var t=mc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(z){if(l<t.length&&t[l].type===z)return t[l++].value},"tryConsume"),h=i(function(z){var x=p(z);if(x!==void 0)return x;var I=t[l],M=I.type,ue=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ue,", expected ").concat(z))},"mustConsume"),y=i(function(){for(var z="",x;x=p("CHAR")||p("ESCAPED_CHAR");)z+=x;return z},"consumeText"),S=i(function(z){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(z.indexOf(M)>-1)return!0}return!1},"isSafe"),R=i(function(z){var x=u[u.length-1],I=z||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||S(I)?"[^".concat(oo(a),"]+?"):"(?:(?!".concat(oo(I),")[^").concat(oo(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),N=p("NAME"),k=p("PATTERN");if(N||k){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:$,suffix:"",pattern:k||R($),modifier:p("MODIFIER")||""});continue}var U=C||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var $=y(),v=p("NAME")||"",H=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(H?c++:""),pattern:v&&!H?R($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(io,"parse");function Ks(n,e){return gc(io(n,e),e)}i(Ks,"compile");function gc(n,e){e===void 0&&(e={});var t=fc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",S=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!S)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var C=o(h[R],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var N=S?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(gc,"tokensToFunction");function oo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(oo,"escapeString");function fc(n){return n&&n.sensitive?"":"i"}i(fc,"flags");var hc=he("zuplo:runtime"),ao=new TextEncoder,Js={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"},yc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new uo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},uo=class{static{i(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:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:S,singleEncode:R}){if(t==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||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,N;(!c||!l)&&([C,N]=bc(this.url,this.headers)),this.service=c||C||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=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"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>S||!yc.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
|
|
56
|
+
`)}i(qs,"messagesToMultilineText");function Ze(n){return typeof n=="string"?n:JSON.stringify(n)}i(Ze,"stringifyNonString");function Br(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?Ar(n):"unknown"}i(Br,"stringifyNonStringToText");import{importPKCS8 as ec,SignJWT as tc}from"jose";async function ye(n,e,t){for(let r=0;r<=n.retries;r++){let o=Z.fetch(e,t);if(r===n.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;n?.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,n.retryDelayMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}i(ye,"fetchRetry");async function Ne({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:s,privateKey:a}=n;return await new tc(r).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}i(Ne,"getTokenFromGcpServiceAccount");async function Us(n,e,t){if(!n.startsWith("projects/"))throw new m(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Gr("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}i(Us,"exchangeIDTokenForGcpWorkloadToken");async function Hs({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return $s(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}i(Hs,"generateServiceAccountIDToken");async function Zs(n,e,t){return Gr(n,{token:e,returnSecureToken:!0},t)}i(Zs,"exchangeFirebaseJwtForIdToken");async function Rn(n,e,t){return Gr(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}i(Rn,"exchangeGgpJwtForIdToken");async function Gr(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return $s(n,r,t)}i(Gr,"fetchTokenFromBody");async function $s(n,e,t){let r=await ye(t,n,e);if(r.status!==200){let s;try{let a=await r.text(),u=JSON.parse(a);s={cause:u.error_description??u.error??u}}catch{}throw new A({message:"Could not get token from Google Identity",extensionMembers:s})}return await r.json()}i($s,"fetchToken");var Te=class n{static{i(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ec(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}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}};async function de(n){if(n.level==="error"&&console.error(n.messages),!f.instance.remoteLogURL||!f.instance.loggingId||!f.instance.remoteLogToken){console.warn("Remote logger is not configured. Skipping log entry.");return}try{let e={logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:f.instance.build.BUILD_ID,loggingId:f.instance.loggingId,...n,vectorClock:0};await Fs({loggingUrl:f.instance.remoteLogURL,loggingId:f.instance.loggingId,loggingToken:f.instance.remoteLogToken},[e])}catch(e){console.error(e)}}i(de,"sendRemoteGlobalLog");async function Fs({loggingUrl:n,loggingId:e,loggingToken:t},r){try{await Z.fetch(`${n}/publish/${e}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:r.map(o=>({...o,messages:We(o.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(o){console.error(o)}}i(Fs,"sendRemoteLogs");var nc=i(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let s;r===!0?s=o.filter(a=>a.level==="error"):s=o,s.length!==0&&await Fs({loggingUrl:n,loggingId:t,loggingToken:e},s)},"dispatchFunction"),Pn,In=class{static{i(this,"RemoteLogTransport")}constructor(e){Pn||(Pn=new Y("remote-log-transport",1,nc(e)))}log(e,t){Pn.enqueue(e),t.waitUntil(Pn.waitUntilFlushed())}};var Vr=class extends fe{constructor(t){super();this.options=t}static{i(this,"GoogleCloudLoggingPlugin")}getTransport(){return new jt(this.options)}},rc="https://logging.googleapis.com/v2/entries:write?alt=json",Wr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},jt=class{static{i(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=f.instance.loggingEnvironmentType,this.#i=f.instance.loggingEnvironmentStage,this.#r=f.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Te.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:We(e.messages)},o=this.#t.projectId??"zuplo-production",s={logName:this.#n,resource:{type:"global"},severity:Wr[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(s.labels.rayId=e.rayId);let a=mt(r.allMessages);s.jsonPayload={...r,message:a},this.batcher.enqueue(s),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length===0)return;this.#t||(this.#t=await Te.init(this.#e));let t=await Ne({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await Z.fetch(rc,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});if(!r.ok){let o="";try{o=await r.text()}catch{}await de({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`,o]})}}catch{await de({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("google-log-transport",1,this.dispatchFunction)};var En="gcp";function xn(n){let e={allMessages:We(n.messages)},t="zuplo-production",r=mt(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Wr[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}i(xn,"gcpLogFormat");var zt=class{static{i(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(e)])}else this.#e.log(JSON.stringify(e))}};var Yr=class extends fe{constructor(t){super();this.options=t}static{i(this,"DataDogLoggingPlugin")}getTransport(){return new Bt(this.options)}},Kr="__ddtags",Jr="__ddattr",Qr=i(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),oc=i(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Qr(r)):t.push(`${Qr(r)}:${Qr(o.toString())}`)}),t.join(",")},"formatTags"),Bt=class{static{i(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=f.instance.loggingEnvironmentType,this.#o=f.instance.loggingEnvironmentStage,this.#n=f.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Kr];o&&typeof o=="object"&&Object.assign(r,o);let s=[...e.messages],a=e.messages.findIndex(y=>y[Kr]!==void 0);a>-1&&(Object.assign(r,s[a][Kr]),s.splice(a,1));let u={},c=t.custom[Jr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(y=>y[Jr]!==void 0);l>-1&&(Object.assign(u,s[l][Jr]),s.splice(l,1));let d=We(s),h={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:mt(d),service:e.loggingId,ddtags:oc(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(h,u),this.batcher.enqueue(h),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let t=await Z.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!t.ok){let r="";try{r=await t.text()}catch{}await de({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`,r]})}}catch{await de({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new Y("data-dog-transport",10,this.dispatchFunction)};var Gt=class{static{i(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===En){if(e.messages.length===0)return;this.#e[e.level].apply(null,[xn(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}])}};var ic={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},js=i((n,e)=>t=>{let r={};return r.accountName=e.ACCOUNT_NAME,r.projectName=e.PROJECT_NAME,r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:ic[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var sc=i(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let s=js(t,r);try{await Z.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":f.instance.systemUserAgent,"zp-dn":f.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),Tn,Vt=class{static{i(this,"UnifiedLogTransport")}constructor(e){Tn||(Tn=new Y("unified-log-transport",1,sc(e)))}async log(e,t){Tn.enqueue(e),t.waitUntil(Tn.waitUntilFlushed())}};var Xr=he("zuplo:logging"),vn=class n{static{i(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(f.instance,e),r=await n.setupUserCoreLogger(f.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Xr("Gateway.setupSystemCoreLogger");let o=[],s=t.getService(sn);return s?o.push(new Gt(s.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new zt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new $t(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Xr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:s}=e,a=t.getService(sn);if(a&&a.captureUserLogs===!0?r.push(new Gt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new zt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new In({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),e.enableRuntimeUserLogs&&e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new Vt({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new jt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){g("logging.datadog.legacy-initialization");let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Bt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Ue.forEach(u=>{u instanceof fe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new $t(e.userLogLevel,"user",e.loggingId,s.BUILD_ID,r)}createRequestLoggers(e,t,r,o,s){Xr("Gateway.createRequestLoggers");let a=new bn(r,o,s),u=new Ft(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ft(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var it=class{static{i(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};var eo=class{static{i(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Wt=class{static{i(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},to=class extends Error{static{i(this,"RouterError")}constructor(e,t){super(e,t)}},Kt=class{static{i(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof it||e instanceof le))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(s=>s.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let s=new URLPattern({pathname:o}),a=new eo(o,s,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new to(`addRoute-error: Invalid path '${o}'. '${s.message}'`,{cause:s})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let s=r[o],u=s.urlPattern.exec({pathname:t});if(u!==null)return new Wt(s.config,s.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Wt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var no;function zs(n){no=n}i(zs,"setGlobalZuploEventContext");function Cn(){if(no===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return no}i(Cn,"getGlobalZuploEventContext");function Bs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);rs.includes(o.toLowerCase())&&!os.includes(r.toLowerCase())&&t.delete(r)}t.delete(zi)}else ns.forEach(r=>{t.delete(r)});return t}i(Bs,"normalizeIncomingRequestHeaders");var De=he("zuplo:runtime"),uc=i(n=>{let e=n.findIndex(t=>t.name===qt.name);return e>-1?[...n.splice(e),qt]:[...n,qt]},"setupSystemNoVersion"),ge=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;De("Gateway.constructor"),_e,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{i(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(De("Gateway.initialize"),!n.#e){let s=await vn.init(r),a=await e(),u={...a,corsPolicies:Is(a.corsPolicies)},c=new n(u,t,s,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){De("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[yn,fn,we];#o;setupRoutes=i(()=>{De("Gateway.setupRoutes");let e=this.routeData,t=uc(e.versions),r=new Kt(t);if(e.routes.length===0)return Sr(r,this),Mr(r,this),Nr(r,this),Es(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Ns(r,this),_s(r,this)),Sr(r,this),Mr(r,this),Nr(r,this);for(let s of Ue)s instanceof qe&&s.registerRoutes(r,this);return e.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new m(`Invalid state - No handler on route for path '${s.path}'`);let u=new me({processors:this.#r,handler:a,gateway:this}),c=new it(s);r.addRoute(c,u.execute)}),xs(r,this),r},"setupRoutes");setupErrorHandler=i(()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=i((t,r,o)=>this.#i(t,r,o),"errorHandler");return e},"setupErrorHandler");errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return De("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){De("Gateway.internalErrorResponse");let o={};if(f.instance.isLocalDevelopment||f.instance.isWorkingCopy){if(r instanceof A&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let s=Ie(r.cause);"stack"in s&&(s.stack=Ms(s.stack)),o={cause:s}}}return E.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:s}=t;zs(r);let a=Bs({headers:e.headers,removeAllVendorHeadersExceptListed:f.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(et,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(sr,"true"),u=new Request(u,{headers:$,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,s,r,c,u),p=new URL(u.url),h=p.pathname,y=this.#n.lookup(u.method,h);if(!y)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${h}'`);let S=new On(e.headers),R=new te(u,{params:y.params}),C=new Sn({logger:l,route:y.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:S}),N=y.routeConfiguration.raw();ac.getActiveSpan()?.setAttributes({"http.route":C.route.path??C.route.pathPattern,"cloud.region":C.incomingRequestProperties.colo,[_e.RoutePathPattern]:C.route.pathPattern,[_e.RouteOperationId]:N.operationId,[_e.RouteTrace]:N["x-zuplo-trace"],[_e.RouteSystem]:dt(p)?!0:void 0});let k=be.initialize(C,R);if(y.routeConfiguration===Dr&&Nt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(h);k.pathOnlyMatches=$.map(U=>U.routeConfiguration).filter(U=>U instanceof it)}try{if(Q.addLogger(C,d),f.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!dt(p):!p.pathname.startsWith("/__zuplo")){let v=await ps(R,C);if(v instanceof Response)return v;{let H=be.getContextExtensions(C);R=v,H.latestRequest=R}}dt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:y.routeConfiguration.path});let $=y.executableHandler;cc($,y,u),De("Gateway.handleRequest - call user handler");let U=await $(R,C);if(De("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new A(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new A("The response object has already been used. Return a new response instead.");let F;if(U.headers.get(et)===null&&!U.webSocket){let v=new Headers(U.headers);v.set(et,o),F=new Response(U.body,{status:U.status,statusText:U.statusText,headers:v,cf:U.cf})}else F=U;return F}catch($){return De("Gateway - error executing handler",$),$ instanceof A?(l.error($),d.warn($)):d.error($),await this.#i(R,C,$)}}};function cc(n,e,t){if(De("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}i(cc,"checkHandler");var Gs=i(async(n,e,t)=>{let r=ge.instance.routeData.policies,o=Ht([n],r);if(o.length===0)throw new A(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy"),Vs=i(async(n,e,t,r)=>{let o=ge.instance.routeData.policies,s=Zt([n],o);if(s.length===0)throw new A(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);return s[0].handler(e,t,r)},"invokeOutboundPolicy");var On=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(pr);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(mr)??void 0}get city(){return this.#e.get(ar)??this.#e.get(Ji)??void 0}get continent(){return this.#e.get(ur)??this.#e.get(Qi)??void 0}get country(){return this.#e.get(cr)??this.#e.get(Yi)??void 0}get latitude(){return this.#e.get(dr)??this.#e.get(es)??void 0}get longitude(){return this.#e.get(lr)??this.#e.get(Xi)??void 0}get colo(){return this.#e.get(gr)??void 0}get postalCode(){return this.#e.get(Wi)??this.#e.get(fr)??void 0}get metroCode(){return this.#e.get(Vi)??this.#e.get(hr)??void 0}get region(){return this.#e.get(Bi)??this.#e.get(yr)??void 0}get regionCode(){return this.#e.get(Gi)??this.#e.get(br)??void 0}get timezone(){return this.#e.get(Ki)??this.#e.get(wr)??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}}},Dt=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Mt=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},be=class n{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new A(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=i(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=i(async(e,t,r)=>{let o=e;for(let s of this.#n)o=await s(e,t,r);return o},"onResponseSending")},Sn=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=s,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>Gs(u,c,this),this.invokeOutboundPolicy=(u,c,l)=>Vs(u,c,l,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{be.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{be.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;invokeOutboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=i(s=>{try{typeof t=="function"?t(s):t.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};import{AsyncLocalStorage as lc}from"node:async_hooks";var Ws={request:new lc};var dc="Error initializing gateway. Check your configuration for errors or contact support.",pc="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",ro=class{constructor(e,t,r,o,s,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=s;this.runtimeInit=a}static{i(this,"Handler")}requestHandler=i(async(e,t,r)=>{let o=e.headers.get(et)??e.headers.get(ji)??crypto.randomUUID(),s=e.headers.get(tt),a={requestId:o,rayId:s};return Ws.request.run(a,async()=>{f.initialize({build:this.buildEnvironment,runtime:t});try{await fs(this.runtimeInit)}catch(c){this.handleError(c,pc,e)}return as(i(async(c,l)=>{let d;try{d=await ge.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,dc,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:f.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function mc(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",s=t+1;s<n.length;){var a=n.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[s++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=s;continue}if(r==="("){var u=1,c="",s=t+1;if(n[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<n.length;){if(n[s]==="\\"){c+=n[s++]+n[s++];continue}if(n[s]===")"){if(u--,u===0){s++;break}}else if(n[s]==="("&&(u++,n[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));c+=n[s++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=s;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}i(mc,"lexer");function io(n,e){e===void 0&&(e={});for(var t=mc(n),r=e.prefixes,o=r===void 0?"./":r,s=e.delimiter,a=s===void 0?"/#?":s,u=[],c=0,l=0,d="",p=i(function(z){if(l<t.length&&t[l].type===z)return t[l++].value},"tryConsume"),h=i(function(z){var x=p(z);if(x!==void 0)return x;var I=t[l],M=I.type,ue=I.index;throw new TypeError("Unexpected ".concat(M," at ").concat(ue,", expected ").concat(z))},"mustConsume"),y=i(function(){for(var z="",x;x=p("CHAR")||p("ESCAPED_CHAR");)z+=x;return z},"consumeText"),S=i(function(z){for(var x=0,I=a;x<I.length;x++){var M=I[x];if(z.indexOf(M)>-1)return!0}return!1},"isSafe"),R=i(function(z){var x=u[u.length-1],I=z||(x&&typeof x=="string"?x:"");if(x&&!I)throw new TypeError('Must have text between two parameters, missing text after "'.concat(x.name,'"'));return!I||S(I)?"[^".concat(oo(a),"]+?"):"(?:(?!".concat(oo(I),")[^").concat(oo(a),"])+?")},"safePattern");l<t.length;){var C=p("CHAR"),N=p("NAME"),k=p("PATTERN");if(N||k){var $=C||"";o.indexOf($)===-1&&(d+=$,$=""),d&&(u.push(d),d=""),u.push({name:N||c++,prefix:$,suffix:"",pattern:k||R($),modifier:p("MODIFIER")||""});continue}var U=C||p("ESCAPED_CHAR");if(U){d+=U;continue}d&&(u.push(d),d="");var F=p("OPEN");if(F){var $=y(),v=p("NAME")||"",H=p("PATTERN")||"",V=y();h("CLOSE"),u.push({name:v||(H?c++:""),pattern:v&&!H?R($):H,prefix:$,suffix:V,modifier:p("MODIFIER")||""});continue}h("END")}return u}i(io,"parse");function Ks(n,e){return gc(io(n,e),e)}i(Ks,"compile");function gc(n,e){e===void 0&&(e={});var t=fc(e),r=e.encode,o=r===void 0?function(c){return c}:r,s=e.validate,a=s===void 0?!0:s,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var h=c?c[p.name]:void 0,y=p.modifier==="?"||p.modifier==="*",S=p.modifier==="*"||p.modifier==="+";if(Array.isArray(h)){if(!S)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(h.length===0){if(y)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var R=0;R<h.length;R++){var C=o(h[R],p);if(a&&!u[d].test(C))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix}continue}if(typeof h=="string"||typeof h=="number"){var C=o(String(h),p);if(a&&!u[d].test(C))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(C,'"'));l+=p.prefix+C+p.suffix;continue}if(!y){var N=S?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}i(gc,"tokensToFunction");function oo(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}i(oo,"escapeString");function fc(n){return n&&n.sensitive?"":"i"}i(fc,"flags");var hc=he("zuplo:runtime"),ao=new TextEncoder,Js={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"},yc=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],gt=class{static{i(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:s,cache:a,retries:u,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=s,this.cache=a||new Map,this.retries=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new uo(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){hc("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:s}=await this.sign(e,t),a=Z.fetch(o,s);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},uo=class{static{i(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:t,headers:r,body:o,accessKeyId:s,secretAccessKey:a,sessionToken:u,service:c,region:l,cache:d,datetime:p,signQuery:h,appendSessionToken:y,allHeaders:S,singleEncode:R}){if(t==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||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=u;let C,N;(!c||!l)&&([C,N]=bc(this.url,this.headers)),this.service=c||C||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=h,this.appendSessionToken=y||this.service==="iotdevicegateway",this.headers.delete("Host");let k=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"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>S||!yc.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
|
|
57
57
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.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,"/");R||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Ys(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if($.has(U))return!1;$.add(U)}return!0}).map(U=>U.map(F=>Ys(encodeURIComponent(F)))).sort(([U,F],[v,H])=>U<v?-1:U>v?1:F<H?-1:F>H?1:0).map(U=>U.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),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Jt("AWS4"+this.secretAccessKey,e),s=await Jt(o,this.region),a=await Jt(s,this.service);r=await Jt(a,"aws4_request"),this.cache.set(t,r)}return so(await Jt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,so(await Qs(await this.canonicalString()))].join(`
|
|
58
58
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
59
59
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{c as e,d as t,f as a,g as o,h as r,i,j as n}from"../chunk-
|
|
25
|
+
import{c as e,d as t,f as a,g as o,h as r,i,j as n}from"../chunk-PBNUVAP3.js";import"../chunk-OQPRFCK5.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
|
|
26
26
|
/*! For license information please see index.js.LEGAL.txt */
|
package/package.json
CHANGED
|
File without changes
|