@zuplo/cli 7.15.26 → 7.15.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/source/ai-gateway/catalog.json +170 -1
- package/dist/source/ai-gateway/planner.d.ts +2 -2
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/encrypt.js +5 -8
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +2 -2
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/key.js +2 -0
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/package.json +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/encrypt.js +5 -8
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +2 -2
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key.js +2 -0
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
- package/node_modules/@posthog/core/dist/gzip.d.ts +2 -0
- package/node_modules/@posthog/core/dist/gzip.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/gzip.js +17 -1
- package/node_modules/@posthog/core/dist/gzip.mjs +15 -2
- package/node_modules/@posthog/core/package.json +2 -2
- package/node_modules/@posthog/core/src/gzip.ts +21 -4
- package/node_modules/@posthog/types/dist/posthog-config.d.ts +82 -0
- package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
- package/node_modules/@posthog/types/package.json +1 -1
- package/node_modules/@posthog/types/src/posthog-config.ts +84 -0
- package/node_modules/@zuplo/core/customer.cli.minified.js +296 -296
- package/node_modules/@zuplo/core/index.minified.js +305 -305
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/{chunk-I65Y62VQ.js → chunk-3ITT2MYM.js} +10 -10
- package/node_modules/@zuplo/runtime/out/esm/chunk-3ITT2MYM.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-5XXEIH5B.js → chunk-A7HRIAHJ.js} +2 -2
- package/node_modules/@zuplo/runtime/out/esm/{chunk-6KHAYHSW.js → chunk-C4ZTXG6P.js} +4 -4
- package/node_modules/@zuplo/runtime/out/esm/chunk-C4ZTXG6P.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-APWLPHXH.js → chunk-JAY7SQGG.js} +2 -2
- package/node_modules/@zuplo/runtime/out/esm/{chunk-MWNVPFFM.js → chunk-YTDIY7PP.js} +2 -2
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp/messages/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +16 -0
- package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +16 -0
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/node_modules/express-rate-limit/dist/index.cjs +6 -4
- package/node_modules/express-rate-limit/dist/index.mjs +6 -4
- package/node_modules/express-rate-limit/package.json +1 -1
- package/node_modules/fast-copy/README.md +15 -0
- package/node_modules/fast-copy/dist/cjs/index.cjs +33 -8
- package/node_modules/fast-copy/dist/cjs/index.cjs.map +1 -1
- package/node_modules/fast-copy/dist/es/index.mjs +33 -8
- package/node_modules/fast-copy/dist/es/index.mjs.map +1 -1
- package/node_modules/fast-copy/dist/umd/index.js +33 -8
- package/node_modules/fast-copy/dist/umd/index.js.map +1 -1
- package/node_modules/fast-copy/package.json +1 -1
- package/node_modules/object-inspect/CHANGELOG.md +31 -0
- package/node_modules/object-inspect/index.js +326 -24
- package/node_modules/object-inspect/package.json +22 -13
- package/node_modules/object-inspect/readme.markdown +4 -1
- package/node_modules/object-inspect/stringWidth.js +68 -0
- package/node_modules/object-inspect/stringWidthRanges.js +38 -0
- package/package.json +11 -11
- package/node_modules/@zuplo/runtime/out/esm/chunk-6KHAYHSW.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-I65Y62VQ.js.map +0 -1
- package/node_modules/object-inspect/.eslintrc +0 -53
- package/node_modules/object-inspect/.nycrc +0 -13
- package/node_modules/object-inspect/example/all.js +0 -23
- package/node_modules/object-inspect/example/circular.js +0 -6
- package/node_modules/object-inspect/example/fn.js +0 -5
- package/node_modules/object-inspect/example/inspect.js +0 -10
- package/node_modules/object-inspect/test/bigint.js +0 -58
- package/node_modules/object-inspect/test/browser/dom.js +0 -15
- package/node_modules/object-inspect/test/circular.js +0 -16
- package/node_modules/object-inspect/test/deep.js +0 -12
- package/node_modules/object-inspect/test/element.js +0 -53
- package/node_modules/object-inspect/test/err.js +0 -48
- package/node_modules/object-inspect/test/fakes.js +0 -29
- package/node_modules/object-inspect/test/fn.js +0 -76
- package/node_modules/object-inspect/test/global.js +0 -17
- package/node_modules/object-inspect/test/has.js +0 -15
- package/node_modules/object-inspect/test/holes.js +0 -15
- package/node_modules/object-inspect/test/indent-option.js +0 -271
- package/node_modules/object-inspect/test/inspect.js +0 -139
- package/node_modules/object-inspect/test/lowbyte.js +0 -12
- package/node_modules/object-inspect/test/number.js +0 -58
- package/node_modules/object-inspect/test/quoteStyle.js +0 -26
- package/node_modules/object-inspect/test/toStringTag.js +0 -40
- package/node_modules/object-inspect/test/undef.js +0 -12
- package/node_modules/object-inspect/test/values.js +0 -261
- package/node_modules/object-inspect/test-core-js.js +0 -26
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-I65Y62VQ.js.LEGAL.txt → chunk-3ITT2MYM.js.LEGAL.txt} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-5XXEIH5B.js.map → chunk-A7HRIAHJ.js.map} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-6KHAYHSW.js.LEGAL.txt → chunk-C4ZTXG6P.js.LEGAL.txt} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-APWLPHXH.js.map → chunk-JAY7SQGG.js.map} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-MWNVPFFM.js.map → chunk-YTDIY7PP.js.map} +0 -0
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* See https://zuplo.com/legal/eula for more information.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import{$ as mk,A as cf,D as gR,E as Fn,F as tk,G as yR,H as nk,I as bR,J as ok,K as fi,L as He,M as RR,N as Aa,O as wR,P as Ia,Q as SR,R as cs,S as mf,T as Bn,U as ck,V as ff,W as uk,X as lk,Y as dk,Z as pk,a as UP,aa as fk,b as qP,ba as hk,c as me,ca as gk,d as FP,da as yk,e as mR,ea as bk,f as BP,fa as Rk,g as Ar,ga as wk,h as ZP,ha as Sk,i as VP,ia as Ck,j as JP,ja as vR,k as is,l as fR,la as TR,m as hR,n as KP,na as Tk,o as qu,pa as AR,q as WP,qa as IR,r as YP,s as QP,t as vo,u as XP,w as ss,x as ek,y as Ta,z as as}from"./chunk-KZBZ5KM5.js";import{a as Ge,b as df,c as hi,d as sk,h as ak,i as pf,j as $u,n as vk,r as Fo,s as CR}from"./chunk-APWLPHXH.js";import{A as m,B as rs,C as Qe,D as va,F as et,G as qt,H as uf,I as rk,J as lf,K as ik,L as Ak,M as Du,N as Ik,O as Ek,a as $P,b as pR,c as DP,d as C,e as zP,f as af,g as ae,h as Ce,i as ts,j as jP,k as Ne,l as z,m as L,n as Ue,o as ve,p as Ca,q as mi,r as Re,s as Ve,t as H,u as Me,v as Uu,w as ns,x as HP,y as os,z as GP}from"./chunk-5XXEIH5B.js";import{a as ge}from"./chunk-5JGLAPFA.js";import{A as wP,B as SP,C as CP,D as vP,E as TP,F as AP,G as ef,H as IP,I as EP,J as tf,K as nf,L as PP,M as of,N as rf,O as kP,P as _P,Q as xP,R as OP,S as MP,T as LP,U as Sa,V as NP,W as sf,X as k,Y as W,a as st,b as nP,c as es,d as oP,e as wa,f as rP,g as iP,h as sP,i as aP,j as cP,k as uP,l as lP,m as dP,n as pP,o as mP,p as fP,q as hP,r as gP,s as Km,t as Wm,u as Ym,v as Qm,w as Xm,x as yP,y as bP,z as RP}from"./chunk-I65Y62VQ.js";import{a as i,b as EB,d as PB,e as $e,f as dR,g as Z,h as T}from"./chunk-VXPFMOL5.js";var qx=EB(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});Qf.parse=DV;Qf.serialize=zV;var MV=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,LV=/^[\u0021-\u003A\u003C-\u007E]*$/,NV=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,UV=/^[\u0020-\u003A\u003D-\u007E]*$/,qV=Object.prototype.toString,$V=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function DV(t,e){let n=new $V,o=t.length;if(o<2)return n;let r=e?.decode||jV,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s),u=c===-1?o:c;if(a>u){s=t.lastIndexOf(";",a-1)+1;continue}let l=Nx(t,s,a),d=Ux(t,a,l),p=t.slice(l,d);if(n[p]===void 0){let f=Nx(t,a+1,u),h=Ux(t,u,f),g=r(t.slice(f,h));n[p]=g}s=u+1}while(s<o);return n}i(DV,"parse");function Nx(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(Nx,"startIndex");function Ux(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(Ux,"endIndex");function zV(t,e,n){let o=n?.encode||encodeURIComponent;if(!MV.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!LV.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+r;if(!n)return s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);s+="; Max-Age="+n.maxAge}if(n.domain){if(!NV.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!UV.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!HV(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);s+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.partitioned&&(s+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return s}i(zV,"serialize");function jV(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(jV,"decode");function HV(t){return qV.call(t)==="[object Date]"}i(HV,"isDate")});var Xe=new Proxy({},{get(t,e){let n=String(e);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return k.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return k.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return k.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return k.instance.accountName;case"ZUPLO_PROJECT_NAME":return k.instance.projectName;case"ZUPLO_BUILD_ID":return k.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return k.instance.build.COMPATIBILITY_DATE}if(!(UP(n)&&!qP(n)))return k.instance.runtime[n]}});var Pk=new Map([["input","input"],["cache-read-input","cache_read_input"],["cache-write-input","cache_write_input"],["output","output"]]),kB=new Set(["5m","1h"]);function kk(t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).filter(([,e])=>e!==null))}i(kk,"withoutNullFields");var _k=m.number().int().min(0).max(Number.MAX_SAFE_INTEGER),_B=m.object({category:m.enum(["input","cache_read_input","cache_write_input","output"]),costPerToken:m.number().nonnegative(),minInputTokens:_k.optional(),maxInputTokens:_k.optional(),cacheTtl:m.enum(["5m","1h"]).optional()}).superRefine((t,e)=>{t.minInputTokens!==void 0&&t.maxInputTokens!==void 0&&t.minInputTokens>t.maxInputTokens&&e.addIssue({code:"custom",path:["minInputTokens"],message:"must not exceed maxInputTokens"}),t.cacheTtl!==void 0&&t.category!=="cache_write_input"&&e.addIssue({code:"custom",path:["cacheTtl"],message:"is only valid for cache_write_input rates"})}),xB=m.object({revision:m.string().min(1),currency:m.literal("USD"),rates:m.array(_B)}).superRefine((t,e)=>{for(let n=0;n<t.rates.length;n++){let o=t.rates[n];for(let r=n+1;r<t.rates.length;r++){let s=t.rates[r];if(o.category!==s.category||o.cacheTtl!==s.cacheTtl)continue;let a=o.minInputTokens??0,c=o.maxInputTokens??Number.POSITIVE_INFINITY,u=s.minInputTokens??0,l=s.maxInputTokens??Number.POSITIVE_INFINITY;a<=l&&u<=c&&e.addIssue({code:"custom",path:["rates",r],message:`overlaps rates.${n} for the same category and qualifiers`})}}});function OB(t){let e=kk(t);if(typeof e!="object"||e===null||Array.isArray(e))return{card:e,ignoredRates:[]};let n=e.rates;if(!Array.isArray(n))return{card:e,ignoredRates:[]};let o=[],r=[];for(let s of n){let a=kk(s);if(typeof a!="object"||a===null||Array.isArray(a)){r.push(a);continue}let{category:c,cacheTtl:u}=a;if(typeof c=="string"&&!Pk.has(c)){o.push(`category ${JSON.stringify(c)}`);continue}if(typeof u=="string"&&!kB.has(u)){o.push(`cacheTtl ${JSON.stringify(u)}`);continue}r.push(typeof c=="string"?{...a,category:Pk.get(c)}:a)}return{card:{...e,rates:r},ignoredRates:o}}i(OB,"fromWireCard");function Mk(t){let e=xB.safeParse(t);if(e.success){let{revision:n,currency:o,rates:r}=e.data;return{tokenRateCard:{revision:n,currency:o,rates:r}}}return{error:e.error.issues.map(n=>`${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join("; ")}}i(Mk,"parseTokenRateCard");function xk(t){if(t==null)return{};let{card:e,ignoredRates:n}=OB(t),o=Mk(e);return o.tokenRateCard===void 0||n.length===0?o:{...o,ignoredRates:n}}i(xk,"validateTokenRateCard");function hf(t){return[t.category,t.cacheTtl??"",t.minInputTokens??"",t.maxInputTokens??""].join("\0")}i(hf,"rateSelector");function MB(t,e){let n=new Map(e.rates.map(r=>[hf(r),r])),o=new Set(t.rates.map(hf));return{revision:e.revision,currency:e.currency,rates:[...t.rates.map(r=>n.get(hf(r))??r),...e.rates.filter(r=>!o.has(hf(r)))]}}i(MB,"mergeTokenRateCards");function Lk(t,e){let n=xk(t);if(n.tokenRateCard===void 0)return n.error===void 0?{}:{error:n.error};let o=xk(e),r=[Ok("list",n),Ok("override",o,e)].filter(c=>c!==void 0),s=r.length===0?{}:{ignoredRates:r};if(o.error!==void 0)return{tokenRateCard:n.tokenRateCard,overrideError:o.error,...s};if(o.tokenRateCard===void 0)return{tokenRateCard:n.tokenRateCard,...s};let a=Mk(MB(n.tokenRateCard,o.tokenRateCard));return a.tokenRateCard===void 0?{tokenRateCard:n.tokenRateCard,overrideError:`merged card: ${a.error}`,...s}:{tokenRateCard:a.tokenRateCard,...s}}i(Lk,"resolveModelTokenRateCard");function Ok(t,e,n){if(e.ignoredRates===void 0)return;let o=typeof n=="object"&&n!==null?n.revision:void 0,r=e.tokenRateCard?.revision??(typeof o=="string"?o:void 0);return{card:t,...r===void 0?{}:{revision:r},values:e.ignoredRates}}i(Ok,"ignoredRatesOf");var le=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let o=`No system logger found for context with requestId '${e.requestId}'`;throw W.console.error(o),new $e(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function dt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${k.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",k.instance.deploymentName??"unknown"),t.set("User-Agent",k.instance.systemUserAgent),t.set("zp-compat-date",k.instance.build.COMPATIBILITY_DATE??"none")}i(dt,"setZuploHeaders");var Uk=["openai","anthropic","google","mistral","xai","bedrock-mantle","vertex-ai","openrouter","jev"];function Nk(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(Nk,"defineOwn");function LB(t,e,n){for(let[o,r]of Object.entries(e)){let s=r.deploymentModels;if(!s)continue;let a=t[o];if(!a){n.warn("AI provider assignment maps deployments but has no catalog models; deployment usage will not resolve a cost",{label:o,deployments:Object.keys(s)});continue}let c={...a};for(let[u,l]of Object.entries(s)){let d=Object.hasOwn(c,l)?c[l]:void 0;if(!d){n.warn("AI provider deployment maps to a model that is not in the catalog; usage against this deployment would be costed at zero",{label:o,deployment:u,model:l,available:Object.keys(c)});continue}let p={...d,model:u,aliasOf:d.model};Nk(a,u,p);let f=u.toLowerCase();f!==u&&!Object.hasOwn(a,f)&&Nk(a,f,{...p,model:f})}}}i(LB,"applyDeploymentModelAliases");var NB="openrouter",UB=[":nitro",":floor",":online",":exacto"],qB="bedrock-runtime",$B=/^arn:aws(?:-[a-z]+)*:bedrock:[a-z0-9-]+:\d*:(?:foundation-model|inference-profile)\/([^/]+)$/;function DB(t){return $B.exec(t)?.[1]}i(DB,"bedrockArnModelId");function Ir(t,e,n){if(!t)return;let o=i(u=>Object.hasOwn(t,u)?t[u]:void 0,"own"),r=i(u=>{let l=o(u.toLowerCase());return o(u)??(l?.aliasOf?l:void 0)},"resolve"),s=r(e);if(s)return s;let a=n?.toLowerCase();if(a===qB){let u=DB(e);return u===void 0?void 0:r(u)}if(a!==NB)return;let c=UB.find(u=>e.endsWith(u));if(c!==void 0)return r(e.slice(0,-c.length))}i(Ir,"resolveModelRow");var zB=60,qk="connections-v1";async function $k(t){let e=await Qe("supported-models",{});return new et(e,t)}i($k,"createSupportedModelsCache");async function zu(t){return(await $k(t)).get(qk)}i(zu,"getCachedSupportedModels");function ER(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(ER,"isRecord");function jB(t){return ER(t)&&Array.isArray(t.data)&&t.data.every(e=>ER(e)&&typeof e.label=="string"&&typeof e.providerType=="string"&&typeof e.isCustom=="boolean"&&Array.isArray(e.models)&&e.models.every(n=>ER(n)&&typeof n.model=="string"&&typeof n.kind=="string"&&typeof n.status=="string"))}i(jB,"isProviderAssignmentsResponse");function HB(t){let e={},n={};for(let o of t.data)e[o.label]=o.models.map(r=>({info:{...o.isCustom?{id:r.id}:{},model:r.model,kind:r.kind,status:r.status,...r.dialect==null?{}:{dialect:r.dialect},...r.basePath==null?{}:{basePath:r.basePath}},tokenRateCard:r.tokenRateCard,overriddenTokenRateCard:r.overriddenTokenRateCard})),n[o.label]={...o.isCustom?{id:o.providerId}:{},baseUrl:o.baseUrl??"",isCustom:o.isCustom,...o.envVarName==null?{}:{envVarName:o.envVarName},providerType:o.providerType,...o.deploymentModels==null?{}:{deploymentModels:o.deploymentModels},...o.gcpProjectId==null?{}:{gcpProjectId:o.gcpProjectId}};return{models:e,providers:n}}i(HB,"fromProviderAssignments");function GB(t){let e=typeof t=="object"&&t!==null?t.revision:void 0;return typeof e=="string"?e:void 0}i(GB,"overrideRevision");function FB(t,e){let n={};for(let[r,s]of Object.entries(t.models)){let a=r.toLowerCase();n[a]={};for(let c of s){let u=Lk(c.tokenRateCard,c.overriddenTokenRateCard);u.error!==void 0&&e.warn("Ignoring invalid AI model token rate card",{provider:r,model:c.info.model,error:u.error});for(let l of u.ignoredRates??[])e.warn("Ignoring AI model token rates with an unknown category or cache TTL",{provider:r,model:c.info.model,card:l.card,revision:l.revision,unknown:l.values});u.overrideError!==void 0&&e.error("Ignoring invalid AI model override token rate card; pricing at the list card",{provider:r,model:c.info.model,overrideRevision:GB(c.overriddenTokenRateCard),error:u.overrideError}),n[a][c.info.model]={...c.info,...u.tokenRateCard===void 0?{}:{tokenRateCard:u.tokenRateCard}}}}let o={};for(let[r,s]of Object.entries(t.providers))o[r.toLowerCase()]=s;return LB(n,o,e),{modelsByProvider:n,providerMetadata:o}}i(FB,"buildSupportedModels");async function io(t,e){let n=le.getLogger(t),o=await zu(t);if(o)return n.info("Using cached supported models data",{providersCount:Object.keys(o.modelsByProvider).length,providers:Object.keys(o.modelsByProvider)}),{modelsByProvider:o.modelsByProvider,providerMetadata:o.providerMetadata};let r=new Headers({"content-type":"application/json"});dt(r,t.requestId);let s=Xe.ZUPLO_SERVICE_BUCKET_ID,a=new URL(`/v1/buckets/${s}/provider-assignments?includeDeprecated=true`,k.instance.zuploEdgeApiUrl).toString(),c=await qt({retryDelayMs:100,retries:e?.retries??5,retryOn404:!0,logger:n},a,{method:"GET",headers:r,signal:e?.signal});if(c.status!==200){let f="Failed to fetch supported models from Gateway service";try{let h=await c.text(),g=JSON.parse(h);n.error(f,g),f=`${f}: ${g.message||c.statusText}`}catch{n.error(f,{status:c.status}),f=`${f}: ${c.status}`}throw new Error(f)}let u=await c.json();if(!jB(u)){let f="Gateway service returned an unexpected provider assignments body";throw n.error(f,{bucketId:s}),new Error(f)}let l=HB(u);n.info("Gateway service response received",{providersCount:Object.keys(l.models).length,providers:Object.keys(l.models),totalModels:Object.values(l.models).reduce((f,h)=>f+h.length,0)});let d=FB(l,n),p=await $k(t);return e?.signal.throwIfAborted(),p.put(qk,d,zB),d}i(io,"getSupportedModels");async function Dk(t){let e=new AbortController,n;try{return await Promise.race([io(t,{signal:e.signal,retries:0}),new Promise((o,r)=>{n=setTimeout(()=>{e.abort(),r(new Error("Model discovery catalog deadline exceeded"))},2e3)})])}finally{clearTimeout(n)}}i(Dk,"getDiscoverySupportedModels");function PR(t,e){let n=t.provider.toLowerCase();if(!t.environmentVariable)return n;for(let[o,r]of Object.entries(e))if(r.envVarName===t.environmentVariable)return o;return n}i(PR,"resolveProviderLabel");function zk(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(zk,"describeProviderAssignments");function jk(t,e,n,o){let r=e.toLowerCase(),s=o[r];if(!s)return!1;let a=s[t];return a?a.kind===n&&a.status==="active":!1}i(jk,"isModelSupported");function Hk(t,e,n){let o=t.toLowerCase(),r=n[o];return r?Object.values(r).filter(s=>s.kind===e&&s.status==="active").map(s=>s.model):[]}i(Hk,"getModelsByProviderAndKind");var Gk=new ge(Symbol("ai-gateway-provider-credential-passthrough"));function Fk(t,e){Gk.set(t,e)}i(Fk,"setProviderCredentialPassthrough");function kR(t){return Gk.get(t)}i(kR,"getProviderCredentialPassthrough");function gf(t){return kR(t)!==void 0}i(gf,"hasProviderCredentialPassthrough");function BB(t){return{revision:t.revision,currency:t.currency,rates:t.rates.map(e=>({category:e.category.replaceAll("_","-"),costPerToken:e.costPerToken,...e.cacheTtl===void 0?{}:{cacheTtl:e.cacheTtl},...e.minInputTokens===void 0?{}:{minInputTokens:e.minInputTokens},...e.maxInputTokens===void 0?{}:{maxInputTokens:e.maxInputTokens}}))}}i(BB,"publicTokenRateCard");var Kk=Symbol("ai-gateway-model-selection"),ZB="zuplodemo",VB="azure-ai",ju="https://demo.zuplo.ai";function JB(t){return t?.providerType?.toLowerCase()===ZB&&t.isCustom!==!0}i(JB,"isZuploDemoAssignment");var Bk=Symbol("ai-gateway-model-routing"),us='Use "providerName/model", for example "openai/gpt-5".',_R=["completions","embeddings"],Zk=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function Bo(t,e,n){throw new T(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(Bo,"invalid");function nn(t,e,n,o){return o?o(t,e,n):Bo(t,e,n)}i(nn,"reject");function xR(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(xR,"isRecord");function sn(t,e,n){if(typeof t!="string")return nn(e,"must be a string",us,n);if(t.length===0)return nn(e,"must not be empty",us,n);if(t.trim()!==t||/\s/.test(t))return nn(e,`contains whitespace in '${t}'`,us,n);let o=t.indexOf("/");if(o===-1)return nn(e,`'${t}' has no provider name separator`,us,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?nn(e,`'${t}' has an empty provider name`,us,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?nn(e,`'${t}' has an empty model`,us,n):s.startsWith("/")?nn(e,`'${t}' starts the model with an extra "/"`,us,n):{provider:r,model:s,raw:t}:nn(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(sn,"parseModelRef");function KB(t,e,n){let o=typeof t=="string"?{main:t}:xR(t)?t:{};if(typeof t!="string"&&!xR(t))return nn(e,"must be a model reference string or an object",'Set it to "providerName/model" or { main: "openai/gpt-5" }',n);let r=Object.keys(o).filter(l=>!Zk.includes(l));if(r.length>0)return nn(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${Zk.join(", ")}`,n);if(Object.keys(o).length===0)return nn(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=sn(o.main,`${e}.main`,n);if(o.backup===null)return nn(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return nn(`${e}.quotaFallback`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);let a=o.backup===void 0?void 0:sn(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:sn(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return nn(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return nn(`${e}.quotaFallback`,`must differ from '${e}.main'`,"Choose a different quota fallback model or omit 'quotaFallback'",n);let u=o.fallbackTimeoutSeconds;if(u!==void 0){if(a===void 0)return nn(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return nn(`${e}.fallbackTimeoutSeconds`,`is a string '${u}', not a number`,"Remove the quotes and set it to a number from 1 through 300",n);if(typeof u!="number"||!Number.isFinite(u)||u<1)return nn(`${e}.fallbackTimeoutSeconds`,"must be a finite number greater than or equal to 1","Set it to a number from 1 through 300",n);if(u>300)return nn(`${e}.fallbackTimeoutSeconds`,"must not exceed the platform request duration of 300 seconds","Set it to 300 or less so the backup can run before the request ends",n)}return{main:s.raw,...a===void 0?{}:{backup:a.raw},...u===void 0?{}:{fallbackTimeoutSeconds:u},...c===void 0?{}:{quotaFallback:c.raw}}}i(KB,"normalizeAIGatewayRouteTarget");async function ls(t){let{modelsByProvider:e,providerMetadata:n}=await io(t),r=[...new Set([...Object.keys(e),...Object.keys(n)])].map(a=>{let c=n[a],u=Object.values(e[a]??{}).map(l=>({model:l.model,capability:l.kind,status:l.status,...l.tokenRateCard===void 0?{}:{tokenRateCard:BB(l.tokenRateCard)}}));return{providerName:a,...c?.baseUrl===void 0?{}:{baseUrl:c.baseUrl},...c?.isCustom===void 0?{}:{isCustom:c.isCustom},...c?.providerType===void 0?{}:{providerType:c.providerType.toLowerCase()},models:u}}),s=new Map;for(let[a,c]of Object.entries(n))c.envVarName!==void 0&&s.set(a.toLowerCase(),c.envVarName);return{providers:r,providerEnvironmentVariables:s,modelsByProvider:e,providerMetadata:n}}i(ls,"loadProviders");function WB(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(WB,"conventionEnvironmentVariable");function Vk(t){return t&&Xe[t]?.trim()||void 0}i(Vk,"nonEmptyEnvironmentValue");function OR(t){let{provider:e,providerEnvironmentVariables:n,metadata:o,path:r,allowMissingApiKey:s,log:a}=t;if(JB(o)){let p;try{p=new URL(o.baseUrl).origin}catch{}return p!==ju?Bo(r,`ZuploDemo provider URL '${o.baseUrl}' is not the trusted demo provider origin '${ju}'`,`Set the ZuploDemo catalog base URL to '${ju}', or choose a keyed provider`):k.instance.authApiJWT?.trim()?{apiKeySource:"zuplodemo"}:Bo(r,"ZuploDemo requires a Zuplo deployment JWT, but this gateway does not have one","Deploy the gateway through Zuplo so it receives a deployment JWT, or choose a keyed provider")}let c=n.get(e.toLowerCase()),u=WB(e),l,d;if(c!==void 0){let p=Vk(c);p!==void 0&&(l=p,d=c)}if(l===void 0){let p=Vk(u);p!==void 0&&(l=p,d=u)}if(l===void 0){if(s===!0)return{};if(c!==void 0)throw a?.setLogProperties?.({aiProvider:e,aiProviderEnvironmentVariable:c,aiProviderConventionalEnvironmentVariable:u,aiRoutingField:r}),a?.error("AI provider key not present in this deployment. Provider changes redeploy the gateway automatically; if this persists, redeploy from AI Settings \u2192 General in the Zuplo Portal."),new T(`Provider '${e}' is not ready on this gateway yet. If a provider was recently added or changed, the gateway may still be updating; retry in a minute or two. If this persists, contact the gateway administrator.`);return Bo(r,`could not resolve an API key for provider name '${e}'. No key binding found in your account's AI providers and conventional environment variable '${u}' is not set`,`Add an AI provider named '${e}' with an API key in the Zuplo Portal, or set '${u}'`)}return{apiKey:l,environmentVariable:d}}i(OR,"resolveApiKey");function YB(t){let{provider:e,providers:n,path:o}=t,r=n.find(({providerName:a})=>a.toLowerCase()===e.toLowerCase());if(r!==void 0)return r.providerName;let s=n.map(({providerName:a})=>a).sort().join(", ");Bo(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(YB,"resolveCatalogEntryLabel");function QB(t){let{provider:e,model:n,capability:o,modelsByProvider:r,providerMetadata:s,path:a}=t,c=e.toLowerCase(),u=s[c],l=u?.providerType?.toLowerCase();if(l===void 0||u?.isCustom!==!1||l===VB)return;let d=Ir(r[c],n,l);d?.kind===o&&d.status==="active"||(d?.kind===o&&Bo(a,`model '${n}' is not active for provider name '${e}'`,`Update provider '${e}' model selections to use an active model, or use another provider name that offers it`),Bo(a,`model '${n}' is not included in model selections for provider name '${e}'`,`Update provider '${e}' model selections to include '${n}', or use another provider name that offers it`))}i(QB,"assertAssignmentOffersModel");function Jk(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(Jk,"cloneRouting");function XB(t,e){ge.set(t,Kk,e)}i(XB,"setModelSelection");function Mn(t){return ge.get(t,Kk)}i(Mn,"getModelSelection");var MR={async load(t){let{providers:e}=await ls(t);return e}},Cn={async set(t,e){if(!xR(e))return Bo("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!_R.includes(d));if(n.length>0)return Bo(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=_R.filter(d=>e[d]!==void 0);if(o.length===0)return Bo("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=KB(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await ls(t),l={};for(let d of _R){let p=r[d];if(typeof p!="object")continue;let f=sn(p.main,`routing.${d}.main`),h=p.backup?sn(p.backup,`routing.${d}.backup`):void 0,g=p.quotaFallback?sn(p.quotaFallback,`routing.${d}.quotaFallback`):void 0,w=new Map;for(let[S,v]of[["main",f],["backup",h],["quotaFallback",g]])if(v){let A=YB({provider:v.provider,providers:s,path:`routing.${d}.${S}`});QB({provider:A,model:v.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${S}`});let E={...v,provider:A};w.set(S,E)}let b=i(S=>{let v=w.get(S);if(v===void 0)throw new Error(`Missing resolved AI Gateway routing field '${S}'`);let A=u[v.provider.toLowerCase()];return{provider:v.provider,model:v.model,...OR({provider:v.provider,providerEnvironmentVariables:a,metadata:A,path:`routing.${d}.${S}`,allowMissingApiKey:S==="main"&&gf(t),log:t.log})}},"toCandidate");l[d]={candidates:[b("main"),...h?[b("backup")]:[]],...h?{fallbackTimeoutSeconds:p.fallbackTimeoutSeconds??60}:{},...g?{quotaFallback:b("quotaFallback")}:{}}}XB(t,{byCapability:l}),ge.set(t,Bk,Jk(r))},get(t){let e=ge.get(t,Bk);return e===void 0?void 0:Jk(e)}};var eZ=new Set(["converse","converse-stream","invoke","invoke-with-response-stream"]),tZ=new Set(["count-tokens","invoke-with-bidirectional-stream"]),nZ=/\/model\/(.+)\/([a-z-]+)$/;function gi(t){let e=t.replace(/\/{2,}/g,"/"),n=e.split("/"),o=n[1]==="a"||n[1]==="u"?3:2;if(n.length<o+3||n[o]!=="model")return null;let r=nZ.exec(e);if(!r)return null;let[,s,a]=r;return!s||!a?null:eZ.has(a)?{operation:a,requested:a,encodedModelId:s}:tZ.has(a)?{operation:"unsupported",requested:a,encodedModelId:s}:null}i(gi,"matchBedrockRuntimeRoute");function Ft(t){return gi(t)!==null}i(Ft,"isBedrockRuntimeRoute");function Wk(t){try{return decodeURIComponent(t)}catch{return t}}i(Wk,"decodeBedrockModelId");function so(t,e,n,o){if(Ft(t))return on(e,oZ(e),n,o)}i(so,"bedrockPolicyErrorResponse");function oZ(t){return t===401||t===403?"AccessDeniedException":t===404?"ResourceNotFoundException":t===429?"ThrottlingException":t>=500?t===503?"ServiceUnavailableException":"InternalServerException":"ValidationException"}i(oZ,"bedrockExceptionForStatus");function on(t,e,n,o){let r={"content-type":"application/json","x-amzn-errortype":e};return o&&(r["x-amzn-requestid"]=o),new Response(JSON.stringify({message:n}),{status:t,headers:r})}i(on,"createBedrockErrorResponse");function LR(t,e,n){if(Ft(t))return on(400,"ServiceQuotaExceededException",e,n)}i(LR,"bedrockQuotaExceededResponse");function Hu(t){if(Ft(t))return null;let e=/\/v1\/models(?:\/|$)/.exec(t);return e?.index===void 0?null:t.slice(e.index)}i(Hu,"resolveModelsBasePath");function vt(t){return Hu(new URL(t.url).pathname)!==null}i(vt,"isModelsDiscoveryRoute");function Ea(t,e){return t.provider.toLowerCase()===e.provider.toLowerCase()&&t.model.toLowerCase()===e.model.toLowerCase()}i(Ea,"refsEqual");function Zo(t){let e=new URL(t.url).pathname;return Ft(e)?{capability:"completions",nativeProvider:"bedrock-runtime"}:e.endsWith("/v1/embeddings")?{capability:"embeddings"}:e.endsWith("/v1/messages/count_tokens")?{capability:"completions",nativeProvider:"anthropic"}:e.endsWith("/v1/messages")?{capability:"completions",nativeProvider:"anthropic"}:e.endsWith("/v1/systemone")?{capability:"completions",nativeProvider:"jev"}:/\/v1\/responses(?:\/|$)/.test(e)?{capability:"completions",nativeProvider:"openai"}:{capability:"completions"}}i(Zo,"resolveAIGatewayRequestRoute");function Yk(t){let e;try{e=new URL(t.url).pathname}catch{return}let n=i(o=>e===o||e.endsWith(o),"matchesBase");if(!Ft(e)&&!n("/v1/systemone")){if(n("/v1/chat/completions")||n("/v1/responses")||n("/v1/messages")||n("/v1/messages/count_tokens"))return"completions";if(n("/v1/embeddings"))return"embeddings"}}i(Yk,"resolveMeteredCapability");function Pa(t,e,n,o){return Ir(n?.[t.toLowerCase()],e,o)?.dialect?.toLowerCase()}i(Pa,"catalogModelDialect");var rZ={openai:new Set(["xai"])};function ka(t){let e=t.nativeProvider.toLowerCase(),n=t.providerType?.toLowerCase();return n===e||n!==void 0&&rZ[e]?.has(n)===!0||t.dialect?.toLowerCase()===e}i(ka,"selectionSatisfiesNativeProvider");function iZ(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(iZ,"isRecord");async function sZ(t){try{let e=await t.clone().json();if(iZ(e)&&Object.hasOwn(e,"model"))return{present:!0,value:e.model}}catch{}return{present:!1,value:void 0}}i(sZ,"readAIGatewayRequestModel");async function Vo(t){let e=gi(new URL(t.url).pathname);return e!==null?{present:!0,value:Wk(e.encodedModelId)}:sZ(t)}i(Vo,"readAIGatewayRequestedModel");function yf(t){if(Ft(new URL(t.url).pathname)){let e='"bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0" (the AWS SDKs percent-encode it into one path segment for you)';return{source:"modelId",missing:`Send a qualified "providerName/model" as the modelId, for example ${e}.`,malformed:`The modelId must use "providerName/model", for example ${e}.`}}return{source:"request.body.model",missing:'Send "providerName/model", for example "openai/gpt-5".',malformed:'The request body model must use "providerName/model", for example "openai/gpt-5".'}}i(yf,"describeRequestModelSource");function _a(t,e="request.body.model"){let n=sn(t,e);return{ref:n,raw:n.raw}}i(_a,"parseAIGatewayRequestModel");var aZ=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),cZ=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Kt(t){if(vt(t))return null;let e=new URL(t.url).pathname;if(Ft(e))return null;for(let[n,o]of cZ)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Kt,"getFormat");async function Gu(t){let e=Kt(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(Gu,"getRequestBody");async function uZ(t,e){let n=Kt(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(uZ,"getResponseBody");function NR(t){let e=t?.usage;if(!e||typeof e!="object")return;let n=i(c=>typeof c=="number"?c:void 0,"num"),o=n(e.input_tokens)??n(e.prompt_tokens),r=n(e.output_tokens)??n(e.completion_tokens);if(o===void 0&&r===void 0)return;let s=o??0,a=r??0;return{promptTokens:s,completionTokens:a,totalTokens:n(e.total_tokens)??s+a}}i(NR,"getUsage");function ut(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>ut(e)).filter(Boolean).join(" ");if(t&&typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking;if(typeof e.input_text=="string")return e.input_text;if(e.content!==void 0)return ut(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(ut,"flattenMessageContent");function xa(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(ut(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(ut(e.system)),typeof e.instructions=="string"&&n.push(e.instructions),typeof e.input=="string")n.push(e.input);else if(Array.isArray(e.input))for(let o of e.input)n.push(ut(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(ut(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(ut(o.content));return Array.isArray(e.content)&&n.push(ut(e.content)),n.filter(Boolean).join(`
|
|
12
|
+
import{$ as mk,A as cf,D as gR,E as Fn,F as tk,G as yR,H as nk,I as bR,J as ok,K as fi,L as He,M as RR,N as Aa,O as wR,P as Ia,Q as SR,R as cs,S as mf,T as Bn,U as ck,V as ff,W as uk,X as lk,Y as dk,Z as pk,a as UP,aa as fk,b as qP,ba as hk,c as me,ca as gk,d as FP,da as yk,e as mR,ea as bk,f as BP,fa as Rk,g as Ar,ga as wk,h as ZP,ha as Sk,i as VP,ia as Ck,j as JP,ja as vR,k as is,l as fR,la as TR,m as hR,n as KP,na as Tk,o as qu,pa as AR,q as WP,qa as IR,r as YP,s as QP,t as vo,u as XP,w as ss,x as ek,y as Ta,z as as}from"./chunk-KZBZ5KM5.js";import{a as Ge,b as df,c as hi,d as sk,h as ak,i as pf,j as $u,n as vk,r as Fo,s as CR}from"./chunk-JAY7SQGG.js";import{A as m,B as rs,C as Qe,D as va,F as et,G as qt,H as uf,I as rk,J as lf,K as ik,L as Ak,M as Du,N as Ik,O as Ek,a as $P,b as pR,c as DP,d as C,e as zP,f as af,g as ae,h as Ce,i as ts,j as jP,k as Ne,l as z,m as L,n as Ue,o as ve,p as Ca,q as mi,r as Re,s as Ve,t as H,u as Me,v as Uu,w as ns,x as HP,y as os,z as GP}from"./chunk-A7HRIAHJ.js";import{a as ge}from"./chunk-5JGLAPFA.js";import{A as wP,B as SP,C as CP,D as vP,E as TP,F as AP,G as ef,H as IP,I as EP,J as tf,K as nf,L as PP,M as of,N as rf,O as kP,P as _P,Q as xP,R as OP,S as MP,T as LP,U as Sa,V as NP,W as sf,X as k,Y as W,a as st,b as nP,c as es,d as oP,e as wa,f as rP,g as iP,h as sP,i as aP,j as cP,k as uP,l as lP,m as dP,n as pP,o as mP,p as fP,q as hP,r as gP,s as Km,t as Wm,u as Ym,v as Qm,w as Xm,x as yP,y as bP,z as RP}from"./chunk-3ITT2MYM.js";import{a as i,b as EB,d as PB,e as $e,f as dR,g as Z,h as T}from"./chunk-VXPFMOL5.js";var qx=EB(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});Qf.parse=DV;Qf.serialize=zV;var MV=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,LV=/^[\u0021-\u003A\u003C-\u007E]*$/,NV=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,UV=/^[\u0020-\u003A\u003D-\u007E]*$/,qV=Object.prototype.toString,$V=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function DV(t,e){let n=new $V,o=t.length;if(o<2)return n;let r=e?.decode||jV,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let c=t.indexOf(";",s),u=c===-1?o:c;if(a>u){s=t.lastIndexOf(";",a-1)+1;continue}let l=Nx(t,s,a),d=Ux(t,a,l),p=t.slice(l,d);if(n[p]===void 0){let f=Nx(t,a+1,u),h=Ux(t,u,f),g=r(t.slice(f,h));n[p]=g}s=u+1}while(s<o);return n}i(DV,"parse");function Nx(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(Nx,"startIndex");function Ux(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(Ux,"endIndex");function zV(t,e,n){let o=n?.encode||encodeURIComponent;if(!MV.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!LV.test(r))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+r;if(!n)return s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);s+="; Max-Age="+n.maxAge}if(n.domain){if(!NV.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!UV.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!HV(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);s+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.partitioned&&(s+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return s}i(zV,"serialize");function jV(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(jV,"decode");function HV(t){return qV.call(t)==="[object Date]"}i(HV,"isDate")});var Xe=new Proxy({},{get(t,e){let n=String(e);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return k.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return k.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return k.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return k.instance.accountName;case"ZUPLO_PROJECT_NAME":return k.instance.projectName;case"ZUPLO_BUILD_ID":return k.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return k.instance.build.COMPATIBILITY_DATE}if(!(UP(n)&&!qP(n)))return k.instance.runtime[n]}});var Pk=new Map([["input","input"],["cache-read-input","cache_read_input"],["cache-write-input","cache_write_input"],["output","output"]]),kB=new Set(["5m","1h"]);function kk(t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).filter(([,e])=>e!==null))}i(kk,"withoutNullFields");var _k=m.number().int().min(0).max(Number.MAX_SAFE_INTEGER),_B=m.object({category:m.enum(["input","cache_read_input","cache_write_input","output"]),costPerToken:m.number().nonnegative(),minInputTokens:_k.optional(),maxInputTokens:_k.optional(),cacheTtl:m.enum(["5m","1h"]).optional()}).superRefine((t,e)=>{t.minInputTokens!==void 0&&t.maxInputTokens!==void 0&&t.minInputTokens>t.maxInputTokens&&e.addIssue({code:"custom",path:["minInputTokens"],message:"must not exceed maxInputTokens"}),t.cacheTtl!==void 0&&t.category!=="cache_write_input"&&e.addIssue({code:"custom",path:["cacheTtl"],message:"is only valid for cache_write_input rates"})}),xB=m.object({revision:m.string().min(1),currency:m.literal("USD"),rates:m.array(_B)}).superRefine((t,e)=>{for(let n=0;n<t.rates.length;n++){let o=t.rates[n];for(let r=n+1;r<t.rates.length;r++){let s=t.rates[r];if(o.category!==s.category||o.cacheTtl!==s.cacheTtl)continue;let a=o.minInputTokens??0,c=o.maxInputTokens??Number.POSITIVE_INFINITY,u=s.minInputTokens??0,l=s.maxInputTokens??Number.POSITIVE_INFINITY;a<=l&&u<=c&&e.addIssue({code:"custom",path:["rates",r],message:`overlaps rates.${n} for the same category and qualifiers`})}}});function OB(t){let e=kk(t);if(typeof e!="object"||e===null||Array.isArray(e))return{card:e,ignoredRates:[]};let n=e.rates;if(!Array.isArray(n))return{card:e,ignoredRates:[]};let o=[],r=[];for(let s of n){let a=kk(s);if(typeof a!="object"||a===null||Array.isArray(a)){r.push(a);continue}let{category:c,cacheTtl:u}=a;if(typeof c=="string"&&!Pk.has(c)){o.push(`category ${JSON.stringify(c)}`);continue}if(typeof u=="string"&&!kB.has(u)){o.push(`cacheTtl ${JSON.stringify(u)}`);continue}r.push(typeof c=="string"?{...a,category:Pk.get(c)}:a)}return{card:{...e,rates:r},ignoredRates:o}}i(OB,"fromWireCard");function Mk(t){let e=xB.safeParse(t);if(e.success){let{revision:n,currency:o,rates:r}=e.data;return{tokenRateCard:{revision:n,currency:o,rates:r}}}return{error:e.error.issues.map(n=>`${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join("; ")}}i(Mk,"parseTokenRateCard");function xk(t){if(t==null)return{};let{card:e,ignoredRates:n}=OB(t),o=Mk(e);return o.tokenRateCard===void 0||n.length===0?o:{...o,ignoredRates:n}}i(xk,"validateTokenRateCard");function hf(t){return[t.category,t.cacheTtl??"",t.minInputTokens??"",t.maxInputTokens??""].join("\0")}i(hf,"rateSelector");function MB(t,e){let n=new Map(e.rates.map(r=>[hf(r),r])),o=new Set(t.rates.map(hf));return{revision:e.revision,currency:e.currency,rates:[...t.rates.map(r=>n.get(hf(r))??r),...e.rates.filter(r=>!o.has(hf(r)))]}}i(MB,"mergeTokenRateCards");function Lk(t,e){let n=xk(t);if(n.tokenRateCard===void 0)return n.error===void 0?{}:{error:n.error};let o=xk(e),r=[Ok("list",n),Ok("override",o,e)].filter(c=>c!==void 0),s=r.length===0?{}:{ignoredRates:r};if(o.error!==void 0)return{tokenRateCard:n.tokenRateCard,overrideError:o.error,...s};if(o.tokenRateCard===void 0)return{tokenRateCard:n.tokenRateCard,...s};let a=Mk(MB(n.tokenRateCard,o.tokenRateCard));return a.tokenRateCard===void 0?{tokenRateCard:n.tokenRateCard,overrideError:`merged card: ${a.error}`,...s}:{tokenRateCard:a.tokenRateCard,...s}}i(Lk,"resolveModelTokenRateCard");function Ok(t,e,n){if(e.ignoredRates===void 0)return;let o=typeof n=="object"&&n!==null?n.revision:void 0,r=e.tokenRateCard?.revision??(typeof o=="string"?o:void 0);return{card:t,...r===void 0?{}:{revision:r},values:e.ignoredRates}}i(Ok,"ignoredRatesOf");var le=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let n=t.#e.get(e);if(!n){let o=`No system logger found for context with requestId '${e.requestId}'`;throw W.console.error(o),new $e(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function dt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${k.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",k.instance.deploymentName??"unknown"),t.set("User-Agent",k.instance.systemUserAgent),t.set("zp-compat-date",k.instance.build.COMPATIBILITY_DATE??"none")}i(dt,"setZuploHeaders");var Uk=["openai","anthropic","google","mistral","xai","bedrock-mantle","vertex-ai","openrouter","jev"];function Nk(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(Nk,"defineOwn");function LB(t,e,n){for(let[o,r]of Object.entries(e)){let s=r.deploymentModels;if(!s)continue;let a=t[o];if(!a){n.warn("AI provider assignment maps deployments but has no catalog models; deployment usage will not resolve a cost",{label:o,deployments:Object.keys(s)});continue}let c={...a};for(let[u,l]of Object.entries(s)){let d=Object.hasOwn(c,l)?c[l]:void 0;if(!d){n.warn("AI provider deployment maps to a model that is not in the catalog; usage against this deployment would be costed at zero",{label:o,deployment:u,model:l,available:Object.keys(c)});continue}let p={...d,model:u,aliasOf:d.model};Nk(a,u,p);let f=u.toLowerCase();f!==u&&!Object.hasOwn(a,f)&&Nk(a,f,{...p,model:f})}}}i(LB,"applyDeploymentModelAliases");var NB="openrouter",UB=[":nitro",":floor",":online",":exacto"],qB="bedrock-runtime",$B=/^arn:aws(?:-[a-z]+)*:bedrock:[a-z0-9-]+:\d*:(?:foundation-model|inference-profile)\/([^/]+)$/;function DB(t){return $B.exec(t)?.[1]}i(DB,"bedrockArnModelId");function Ir(t,e,n){if(!t)return;let o=i(u=>Object.hasOwn(t,u)?t[u]:void 0,"own"),r=i(u=>{let l=o(u.toLowerCase());return o(u)??(l?.aliasOf?l:void 0)},"resolve"),s=r(e);if(s)return s;let a=n?.toLowerCase();if(a===qB){let u=DB(e);return u===void 0?void 0:r(u)}if(a!==NB)return;let c=UB.find(u=>e.endsWith(u));if(c!==void 0)return r(e.slice(0,-c.length))}i(Ir,"resolveModelRow");var zB=60,qk="connections-v1";async function $k(t){let e=await Qe("supported-models",{});return new et(e,t)}i($k,"createSupportedModelsCache");async function zu(t){return(await $k(t)).get(qk)}i(zu,"getCachedSupportedModels");function ER(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(ER,"isRecord");function jB(t){return ER(t)&&Array.isArray(t.data)&&t.data.every(e=>ER(e)&&typeof e.label=="string"&&typeof e.providerType=="string"&&typeof e.isCustom=="boolean"&&Array.isArray(e.models)&&e.models.every(n=>ER(n)&&typeof n.model=="string"&&typeof n.kind=="string"&&typeof n.status=="string"))}i(jB,"isProviderAssignmentsResponse");function HB(t){let e={},n={};for(let o of t.data)e[o.label]=o.models.map(r=>({info:{...o.isCustom?{id:r.id}:{},model:r.model,kind:r.kind,status:r.status,...r.dialect==null?{}:{dialect:r.dialect},...r.basePath==null?{}:{basePath:r.basePath}},tokenRateCard:r.tokenRateCard,overriddenTokenRateCard:r.overriddenTokenRateCard})),n[o.label]={...o.isCustom?{id:o.providerId}:{},baseUrl:o.baseUrl??"",isCustom:o.isCustom,...o.envVarName==null?{}:{envVarName:o.envVarName},providerType:o.providerType,...o.deploymentModels==null?{}:{deploymentModels:o.deploymentModels},...o.gcpProjectId==null?{}:{gcpProjectId:o.gcpProjectId}};return{models:e,providers:n}}i(HB,"fromProviderAssignments");function GB(t){let e=typeof t=="object"&&t!==null?t.revision:void 0;return typeof e=="string"?e:void 0}i(GB,"overrideRevision");function FB(t,e){let n={};for(let[r,s]of Object.entries(t.models)){let a=r.toLowerCase();n[a]={};for(let c of s){let u=Lk(c.tokenRateCard,c.overriddenTokenRateCard);u.error!==void 0&&e.warn("Ignoring invalid AI model token rate card",{provider:r,model:c.info.model,error:u.error});for(let l of u.ignoredRates??[])e.warn("Ignoring AI model token rates with an unknown category or cache TTL",{provider:r,model:c.info.model,card:l.card,revision:l.revision,unknown:l.values});u.overrideError!==void 0&&e.error("Ignoring invalid AI model override token rate card; pricing at the list card",{provider:r,model:c.info.model,overrideRevision:GB(c.overriddenTokenRateCard),error:u.overrideError}),n[a][c.info.model]={...c.info,...u.tokenRateCard===void 0?{}:{tokenRateCard:u.tokenRateCard}}}}let o={};for(let[r,s]of Object.entries(t.providers))o[r.toLowerCase()]=s;return LB(n,o,e),{modelsByProvider:n,providerMetadata:o}}i(FB,"buildSupportedModels");async function io(t,e){let n=le.getLogger(t),o=await zu(t);if(o)return n.info("Using cached supported models data",{providersCount:Object.keys(o.modelsByProvider).length,providers:Object.keys(o.modelsByProvider)}),{modelsByProvider:o.modelsByProvider,providerMetadata:o.providerMetadata};let r=new Headers({"content-type":"application/json"});dt(r,t.requestId);let s=Xe.ZUPLO_SERVICE_BUCKET_ID,a=new URL(`/v1/buckets/${s}/provider-assignments?includeDeprecated=true`,k.instance.zuploEdgeApiUrl).toString(),c=await qt({retryDelayMs:100,retries:e?.retries??5,retryOn404:!0,logger:n},a,{method:"GET",headers:r,signal:e?.signal});if(c.status!==200){let f="Failed to fetch supported models from Gateway service";try{let h=await c.text(),g=JSON.parse(h);n.error(f,g),f=`${f}: ${g.message||c.statusText}`}catch{n.error(f,{status:c.status}),f=`${f}: ${c.status}`}throw new Error(f)}let u=await c.json();if(!jB(u)){let f="Gateway service returned an unexpected provider assignments body";throw n.error(f,{bucketId:s}),new Error(f)}let l=HB(u);n.info("Gateway service response received",{providersCount:Object.keys(l.models).length,providers:Object.keys(l.models),totalModels:Object.values(l.models).reduce((f,h)=>f+h.length,0)});let d=FB(l,n),p=await $k(t);return e?.signal.throwIfAborted(),p.put(qk,d,zB),d}i(io,"getSupportedModels");async function Dk(t){let e=new AbortController,n;try{return await Promise.race([io(t,{signal:e.signal,retries:0}),new Promise((o,r)=>{n=setTimeout(()=>{e.abort(),r(new Error("Model discovery catalog deadline exceeded"))},2e3)})])}finally{clearTimeout(n)}}i(Dk,"getDiscoverySupportedModels");function PR(t,e){let n=t.provider.toLowerCase();if(!t.environmentVariable)return n;for(let[o,r]of Object.entries(e))if(r.envVarName===t.environmentVariable)return o;return n}i(PR,"resolveProviderLabel");function zk(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(zk,"describeProviderAssignments");function jk(t,e,n,o){let r=e.toLowerCase(),s=o[r];if(!s)return!1;let a=s[t];return a?a.kind===n&&a.status==="active":!1}i(jk,"isModelSupported");function Hk(t,e,n){let o=t.toLowerCase(),r=n[o];return r?Object.values(r).filter(s=>s.kind===e&&s.status==="active").map(s=>s.model):[]}i(Hk,"getModelsByProviderAndKind");var Gk=new ge(Symbol("ai-gateway-provider-credential-passthrough"));function Fk(t,e){Gk.set(t,e)}i(Fk,"setProviderCredentialPassthrough");function kR(t){return Gk.get(t)}i(kR,"getProviderCredentialPassthrough");function gf(t){return kR(t)!==void 0}i(gf,"hasProviderCredentialPassthrough");function BB(t){return{revision:t.revision,currency:t.currency,rates:t.rates.map(e=>({category:e.category.replaceAll("_","-"),costPerToken:e.costPerToken,...e.cacheTtl===void 0?{}:{cacheTtl:e.cacheTtl},...e.minInputTokens===void 0?{}:{minInputTokens:e.minInputTokens},...e.maxInputTokens===void 0?{}:{maxInputTokens:e.maxInputTokens}}))}}i(BB,"publicTokenRateCard");var Kk=Symbol("ai-gateway-model-selection"),ZB="zuplodemo",VB="azure-ai",ju="https://demo.zuplo.ai";function JB(t){return t?.providerType?.toLowerCase()===ZB&&t.isCustom!==!0}i(JB,"isZuploDemoAssignment");var Bk=Symbol("ai-gateway-model-routing"),us='Use "providerName/model", for example "openai/gpt-5".',_R=["completions","embeddings"],Zk=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function Bo(t,e,n){throw new T(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(Bo,"invalid");function nn(t,e,n,o){return o?o(t,e,n):Bo(t,e,n)}i(nn,"reject");function xR(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(xR,"isRecord");function sn(t,e,n){if(typeof t!="string")return nn(e,"must be a string",us,n);if(t.length===0)return nn(e,"must not be empty",us,n);if(t.trim()!==t||/\s/.test(t))return nn(e,`contains whitespace in '${t}'`,us,n);let o=t.indexOf("/");if(o===-1)return nn(e,`'${t}' has no provider name separator`,us,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?nn(e,`'${t}' has an empty provider name`,us,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?nn(e,`'${t}' has an empty model`,us,n):s.startsWith("/")?nn(e,`'${t}' starts the model with an extra "/"`,us,n):{provider:r,model:s,raw:t}:nn(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(sn,"parseModelRef");function KB(t,e,n){let o=typeof t=="string"?{main:t}:xR(t)?t:{};if(typeof t!="string"&&!xR(t))return nn(e,"must be a model reference string or an object",'Set it to "providerName/model" or { main: "openai/gpt-5" }',n);let r=Object.keys(o).filter(l=>!Zk.includes(l));if(r.length>0)return nn(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${Zk.join(", ")}`,n);if(Object.keys(o).length===0)return nn(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=sn(o.main,`${e}.main`,n);if(o.backup===null)return nn(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return nn(`${e}.quotaFallback`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);let a=o.backup===void 0?void 0:sn(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:sn(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return nn(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return nn(`${e}.quotaFallback`,`must differ from '${e}.main'`,"Choose a different quota fallback model or omit 'quotaFallback'",n);let u=o.fallbackTimeoutSeconds;if(u!==void 0){if(a===void 0)return nn(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return nn(`${e}.fallbackTimeoutSeconds`,`is a string '${u}', not a number`,"Remove the quotes and set it to a number from 1 through 300",n);if(typeof u!="number"||!Number.isFinite(u)||u<1)return nn(`${e}.fallbackTimeoutSeconds`,"must be a finite number greater than or equal to 1","Set it to a number from 1 through 300",n);if(u>300)return nn(`${e}.fallbackTimeoutSeconds`,"must not exceed the platform request duration of 300 seconds","Set it to 300 or less so the backup can run before the request ends",n)}return{main:s.raw,...a===void 0?{}:{backup:a.raw},...u===void 0?{}:{fallbackTimeoutSeconds:u},...c===void 0?{}:{quotaFallback:c.raw}}}i(KB,"normalizeAIGatewayRouteTarget");async function ls(t){let{modelsByProvider:e,providerMetadata:n}=await io(t),r=[...new Set([...Object.keys(e),...Object.keys(n)])].map(a=>{let c=n[a],u=Object.values(e[a]??{}).map(l=>({model:l.model,capability:l.kind,status:l.status,...l.tokenRateCard===void 0?{}:{tokenRateCard:BB(l.tokenRateCard)}}));return{providerName:a,...c?.baseUrl===void 0?{}:{baseUrl:c.baseUrl},...c?.isCustom===void 0?{}:{isCustom:c.isCustom},...c?.providerType===void 0?{}:{providerType:c.providerType.toLowerCase()},models:u}}),s=new Map;for(let[a,c]of Object.entries(n))c.envVarName!==void 0&&s.set(a.toLowerCase(),c.envVarName);return{providers:r,providerEnvironmentVariables:s,modelsByProvider:e,providerMetadata:n}}i(ls,"loadProviders");function WB(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(WB,"conventionEnvironmentVariable");function Vk(t){return t&&Xe[t]?.trim()||void 0}i(Vk,"nonEmptyEnvironmentValue");function OR(t){let{provider:e,providerEnvironmentVariables:n,metadata:o,path:r,allowMissingApiKey:s,log:a}=t;if(JB(o)){let p;try{p=new URL(o.baseUrl).origin}catch{}return p!==ju?Bo(r,`ZuploDemo provider URL '${o.baseUrl}' is not the trusted demo provider origin '${ju}'`,`Set the ZuploDemo catalog base URL to '${ju}', or choose a keyed provider`):k.instance.authApiJWT?.trim()?{apiKeySource:"zuplodemo"}:Bo(r,"ZuploDemo requires a Zuplo deployment JWT, but this gateway does not have one","Deploy the gateway through Zuplo so it receives a deployment JWT, or choose a keyed provider")}let c=n.get(e.toLowerCase()),u=WB(e),l,d;if(c!==void 0){let p=Vk(c);p!==void 0&&(l=p,d=c)}if(l===void 0){let p=Vk(u);p!==void 0&&(l=p,d=u)}if(l===void 0){if(s===!0)return{};if(c!==void 0)throw a?.setLogProperties?.({aiProvider:e,aiProviderEnvironmentVariable:c,aiProviderConventionalEnvironmentVariable:u,aiRoutingField:r}),a?.error("AI provider key not present in this deployment. Provider changes redeploy the gateway automatically; if this persists, redeploy from AI Settings \u2192 General in the Zuplo Portal."),new T(`Provider '${e}' is not ready on this gateway yet. If a provider was recently added or changed, the gateway may still be updating; retry in a minute or two. If this persists, contact the gateway administrator.`);return Bo(r,`could not resolve an API key for provider name '${e}'. No key binding found in your account's AI providers and conventional environment variable '${u}' is not set`,`Add an AI provider named '${e}' with an API key in the Zuplo Portal, or set '${u}'`)}return{apiKey:l,environmentVariable:d}}i(OR,"resolveApiKey");function YB(t){let{provider:e,providers:n,path:o}=t,r=n.find(({providerName:a})=>a.toLowerCase()===e.toLowerCase());if(r!==void 0)return r.providerName;let s=n.map(({providerName:a})=>a).sort().join(", ");Bo(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(YB,"resolveCatalogEntryLabel");function QB(t){let{provider:e,model:n,capability:o,modelsByProvider:r,providerMetadata:s,path:a}=t,c=e.toLowerCase(),u=s[c],l=u?.providerType?.toLowerCase();if(l===void 0||u?.isCustom!==!1||l===VB)return;let d=Ir(r[c],n,l);d?.kind===o&&d.status==="active"||(d?.kind===o&&Bo(a,`model '${n}' is not active for provider name '${e}'`,`Update provider '${e}' model selections to use an active model, or use another provider name that offers it`),Bo(a,`model '${n}' is not included in model selections for provider name '${e}'`,`Update provider '${e}' model selections to include '${n}', or use another provider name that offers it`))}i(QB,"assertAssignmentOffersModel");function Jk(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(Jk,"cloneRouting");function XB(t,e){ge.set(t,Kk,e)}i(XB,"setModelSelection");function Mn(t){return ge.get(t,Kk)}i(Mn,"getModelSelection");var MR={async load(t){let{providers:e}=await ls(t);return e}},Cn={async set(t,e){if(!xR(e))return Bo("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!_R.includes(d));if(n.length>0)return Bo(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=_R.filter(d=>e[d]!==void 0);if(o.length===0)return Bo("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=KB(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await ls(t),l={};for(let d of _R){let p=r[d];if(typeof p!="object")continue;let f=sn(p.main,`routing.${d}.main`),h=p.backup?sn(p.backup,`routing.${d}.backup`):void 0,g=p.quotaFallback?sn(p.quotaFallback,`routing.${d}.quotaFallback`):void 0,w=new Map;for(let[S,v]of[["main",f],["backup",h],["quotaFallback",g]])if(v){let A=YB({provider:v.provider,providers:s,path:`routing.${d}.${S}`});QB({provider:A,model:v.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${S}`});let E={...v,provider:A};w.set(S,E)}let b=i(S=>{let v=w.get(S);if(v===void 0)throw new Error(`Missing resolved AI Gateway routing field '${S}'`);let A=u[v.provider.toLowerCase()];return{provider:v.provider,model:v.model,...OR({provider:v.provider,providerEnvironmentVariables:a,metadata:A,path:`routing.${d}.${S}`,allowMissingApiKey:S==="main"&&gf(t),log:t.log})}},"toCandidate");l[d]={candidates:[b("main"),...h?[b("backup")]:[]],...h?{fallbackTimeoutSeconds:p.fallbackTimeoutSeconds??60}:{},...g?{quotaFallback:b("quotaFallback")}:{}}}XB(t,{byCapability:l}),ge.set(t,Bk,Jk(r))},get(t){let e=ge.get(t,Bk);return e===void 0?void 0:Jk(e)}};var eZ=new Set(["converse","converse-stream","invoke","invoke-with-response-stream"]),tZ=new Set(["count-tokens","invoke-with-bidirectional-stream"]),nZ=/\/model\/(.+)\/([a-z-]+)$/;function gi(t){let e=t.replace(/\/{2,}/g,"/"),n=e.split("/"),o=n[1]==="a"||n[1]==="u"?3:2;if(n.length<o+3||n[o]!=="model")return null;let r=nZ.exec(e);if(!r)return null;let[,s,a]=r;return!s||!a?null:eZ.has(a)?{operation:a,requested:a,encodedModelId:s}:tZ.has(a)?{operation:"unsupported",requested:a,encodedModelId:s}:null}i(gi,"matchBedrockRuntimeRoute");function Ft(t){return gi(t)!==null}i(Ft,"isBedrockRuntimeRoute");function Wk(t){try{return decodeURIComponent(t)}catch{return t}}i(Wk,"decodeBedrockModelId");function so(t,e,n,o){if(Ft(t))return on(e,oZ(e),n,o)}i(so,"bedrockPolicyErrorResponse");function oZ(t){return t===401||t===403?"AccessDeniedException":t===404?"ResourceNotFoundException":t===429?"ThrottlingException":t>=500?t===503?"ServiceUnavailableException":"InternalServerException":"ValidationException"}i(oZ,"bedrockExceptionForStatus");function on(t,e,n,o){let r={"content-type":"application/json","x-amzn-errortype":e};return o&&(r["x-amzn-requestid"]=o),new Response(JSON.stringify({message:n}),{status:t,headers:r})}i(on,"createBedrockErrorResponse");function LR(t,e,n){if(Ft(t))return on(400,"ServiceQuotaExceededException",e,n)}i(LR,"bedrockQuotaExceededResponse");function Hu(t){if(Ft(t))return null;let e=/\/v1\/models(?:\/|$)/.exec(t);return e?.index===void 0?null:t.slice(e.index)}i(Hu,"resolveModelsBasePath");function vt(t){return Hu(new URL(t.url).pathname)!==null}i(vt,"isModelsDiscoveryRoute");function Ea(t,e){return t.provider.toLowerCase()===e.provider.toLowerCase()&&t.model.toLowerCase()===e.model.toLowerCase()}i(Ea,"refsEqual");function Zo(t){let e=new URL(t.url).pathname;return Ft(e)?{capability:"completions",nativeProvider:"bedrock-runtime"}:e.endsWith("/v1/embeddings")?{capability:"embeddings"}:e.endsWith("/v1/messages/count_tokens")?{capability:"completions",nativeProvider:"anthropic"}:e.endsWith("/v1/messages")?{capability:"completions",nativeProvider:"anthropic"}:e.endsWith("/v1/systemone")?{capability:"completions",nativeProvider:"jev"}:/\/v1\/responses(?:\/|$)/.test(e)?{capability:"completions",nativeProvider:"openai"}:{capability:"completions"}}i(Zo,"resolveAIGatewayRequestRoute");function Yk(t){let e;try{e=new URL(t.url).pathname}catch{return}let n=i(o=>e===o||e.endsWith(o),"matchesBase");if(!Ft(e)&&!n("/v1/systemone")){if(n("/v1/chat/completions")||n("/v1/responses")||n("/v1/messages")||n("/v1/messages/count_tokens"))return"completions";if(n("/v1/embeddings"))return"embeddings"}}i(Yk,"resolveMeteredCapability");function Pa(t,e,n,o){return Ir(n?.[t.toLowerCase()],e,o)?.dialect?.toLowerCase()}i(Pa,"catalogModelDialect");var rZ={openai:new Set(["xai"])};function ka(t){let e=t.nativeProvider.toLowerCase(),n=t.providerType?.toLowerCase();return n===e||n!==void 0&&rZ[e]?.has(n)===!0||t.dialect?.toLowerCase()===e}i(ka,"selectionSatisfiesNativeProvider");function iZ(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(iZ,"isRecord");async function sZ(t){try{let e=await t.clone().json();if(iZ(e)&&Object.hasOwn(e,"model"))return{present:!0,value:e.model}}catch{}return{present:!1,value:void 0}}i(sZ,"readAIGatewayRequestModel");async function Vo(t){let e=gi(new URL(t.url).pathname);return e!==null?{present:!0,value:Wk(e.encodedModelId)}:sZ(t)}i(Vo,"readAIGatewayRequestedModel");function yf(t){if(Ft(new URL(t.url).pathname)){let e='"bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0" (the AWS SDKs percent-encode it into one path segment for you)';return{source:"modelId",missing:`Send a qualified "providerName/model" as the modelId, for example ${e}.`,malformed:`The modelId must use "providerName/model", for example ${e}.`}}return{source:"request.body.model",missing:'Send "providerName/model", for example "openai/gpt-5".',malformed:'The request body model must use "providerName/model", for example "openai/gpt-5".'}}i(yf,"describeRequestModelSource");function _a(t,e="request.body.model"){let n=sn(t,e);return{ref:n,raw:n.raw}}i(_a,"parseAIGatewayRequestModel");var aZ=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),cZ=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Kt(t){if(vt(t))return null;let e=new URL(t.url).pathname;if(Ft(e))return null;for(let[n,o]of cZ)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Kt,"getFormat");async function Gu(t){let e=Kt(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(Gu,"getRequestBody");async function uZ(t,e){let n=Kt(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(uZ,"getResponseBody");function NR(t){let e=t?.usage;if(!e||typeof e!="object")return;let n=i(c=>typeof c=="number"?c:void 0,"num"),o=n(e.input_tokens)??n(e.prompt_tokens),r=n(e.output_tokens)??n(e.completion_tokens);if(o===void 0&&r===void 0)return;let s=o??0,a=r??0;return{promptTokens:s,completionTokens:a,totalTokens:n(e.total_tokens)??s+a}}i(NR,"getUsage");function ut(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>ut(e)).filter(Boolean).join(" ");if(t&&typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking;if(typeof e.input_text=="string")return e.input_text;if(e.content!==void 0)return ut(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(ut,"flattenMessageContent");function xa(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(ut(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(ut(e.system)),typeof e.instructions=="string"&&n.push(e.instructions),typeof e.input=="string")n.push(e.input);else if(Array.isArray(e.input))for(let o of e.input)n.push(ut(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(ut(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(ut(o.content));return Array.isArray(e.content)&&n.push(ut(e.content)),n.filter(Boolean).join(`
|
|
13
13
|
`)}i(xa,"extractAllText");async function*lZ(t,e){let n=Kt(t),o=e.clone().body;if(!o||!n)return;let r=o.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await r.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
|
|
14
14
|
|
|
15
15
|
`))!==-1;){let d=a.slice(0,l);a=a.slice(l+2);let p=dZ(d,n);p&&(yield p)}}}finally{r.releaseLock()}}i(lZ,"getStreamEvents");function dZ(t,e){let n=t.split(`
|
|
@@ -36,7 +36,7 @@ ${n}`),t.terminated?`${n}
|
|
|
36
36
|
`),te(Y.raw.slice()),S=Y.raw[Y.raw.length-1];continue}let{event:oe}=Y,Ie;try{let ke=await e(oe,l);if(p)return;Ie=U(ke,oe)}catch(ke){if(p)return;if(E(ke,{mode:o,kind:"transform",event:oe}),o==="closed")throw ke;Ie={text:N(oe),terminate:!1}}if(Q(Ie.text),Ie.terminate){A("SSE stream terminated by its rewriter"),M.close();return}}if(D.done){if(n.end!==void 0){let Y;try{let oe=await n.end({...l,unterminated:J});if(p)return;Y=U(oe,void 0)}catch(oe){if(p)return;if(E(oe,{mode:o,kind:"end"}),o==="closed")throw oe;Y={text:"",terminate:!1}}if(ue&&Y.text!==""&&Q(S===Ku?`
|
|
37
37
|
`:`
|
|
38
38
|
|
|
39
|
-
`),Q(Y.text),Y.terminate){A("SSE stream terminated by its rewriter"),M.close();return}}p=!0,M.close();return}if(F)return}}catch(D){p||(A(D),(M.desiredSize??0)<0?v={error:D}:M.error(D))}},cancel(M){if(!p)return p=!0,u.abort(M),d.cancel(M)}},{highWaterMark:0})}i(KZ,"rewriteSseStream");function WZ(t){if(t.length===1)return t[0];let e=new Uint8Array(t.reduce((o,r)=>o+r.length,0)),n=0;for(let o of t)e.set(o,n),n+=o.length;return e}i(WZ,"concatBytes");function nle(t,e,n){if(t.body===null)return t;let o=Pf(new Headers(t.headers));return o.set("content-type","text/event-stream"),new Response(KZ(t.body,e,n),{status:t.status,statusText:t.statusText,headers:o})}i(nle,"rewriteSseResponse");var YZ={0:0,1:0,2:1,3:2,4:4,5:8,8:8,9:16},QZ=6,C_=7;function XZ(t){let e={},n=new DataView(t.buffer,t.byteOffset,t.byteLength),o=new TextDecoder,r=0;for(;r<t.byteLength;){let s=n.getUint8(r);if(r+=1,r+s+1>t.byteLength)return e;let a=o.decode(t.subarray(r,r+s));r+=s;let c=n.getUint8(r);if(r+=1,c===C_||c===QZ){if(r+2>t.byteLength)return e;let l=n.getUint16(r,!1);if(r+=2,r+l>t.byteLength)return e;c===C_&&(e[a]=o.decode(t.subarray(r,r+l))),r+=l;continue}let u=YZ[c];if(u===void 0)return e;r+=u}return e}i(XZ,"readEventStreamHeaders");function xf(){let t=[],e=0,n=!1,o=i(s=>{let a=0,c=4,u=s;for(let l of t){if(u>=l.byteLength){u-=l.byteLength;continue}for(let d=u;d<l.byteLength&&c>0;d++)a=(a<<8|l[d])>>>0,c--;if(u=0,c===0)break}return a},"peekUint32"),r=i(s=>{let a=new Uint8Array(s),c=0,u=0;for(;c<s;){let l=t[u],d=s-c;l.byteLength<=d?(a.set(l,c),c+=l.byteLength,u++):(a.set(l.subarray(0,d),c),c+=d,t[u]=l.subarray(d))}return u>0&&t.splice(0,u),e-=s,a},"takeFrame");return s=>{if(n||s.byteLength===0)return[];t.push(s),e+=s.byteLength;let a=[];for(;e>=12;){let c=o(0),u=o(4);if(c<16||c>16777216||u>c-16)return n=!0,t=[],e=0,a;if(e<c)break;let l=r(c);a.push({headers:XZ(l.subarray(12,12+u)),payload:l.subarray(12+u,c-4)})}return a}}i(xf,"createEventStreamFramer");function Ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(Ze,"isRecord");function De(t){return typeof t=="string"?t:void 0}i(De,"asString");function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Vn,"asFiniteNumber");function Jn(t){let e=Vn(t);return e!==void 0&&Number.isInteger(e)?e:void 0}i(Jn,"asInteger");function Of(t){if(typeof t=="string")return[t];if(Array.isArray(t)&&t.every(e=>typeof e=="string"))return t}i(Of,"asStringArray");function Pr(...t){for(let e of t)if(e!==void 0)return e}i(Pr,"firstDefined");function Yu(t,e){if(t.length<=e)return t;let n=Math.max(0,e);if(n>0){let o=t.charCodeAt(n-1);o>=55296&&o<=56319&&(n-=1)}return t.slice(0,n)}i(Yu,"truncateUtf16");function Wu(t,e){if(typeof t=="string")return Yu(t,e);if(Array.isArray(t))return t.map(n=>Wu(n,e));if(Ze(t)){let n={};for(let[o,r]of Object.entries(t))n[o]=Wu(r,e);return n}return t}i(Wu,"clipStrings");var e2=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[REDACTED:private_key]"],[/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[REDACTED:jwt]"],[/\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]{16,}=*/gi,"$1 [REDACTED]"],[/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:api_key]"],[/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,"[REDACTED:aws_access_key]"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"[REDACTED:google_api_key]"],[/\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g,"[REDACTED:github_token]"],[/\bxox[abposr]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack_token]"],[/\bzpka_[A-Za-z0-9_]{20,}/g,"[REDACTED:zuplo_api_key]"]];function t2(t){let e=t;for(let[n,o]of e2)e=e.replace(n,o);return e}i(t2,"redactSecrets");var n2=1024;function nw(t,e){if(typeof t=="string")return Yu(t2(Yu(t,e+n2)),e);if(Array.isArray(t))return t.map(n=>nw(n,e));if(Ze(t)){let n={};for(let[o,r]of Object.entries(t))n[o]=nw(r,e);return n}return t}i(nw,"redactAndCap");function Mf(t){try{return JSON.stringify(t)}catch{return}}i(Mf,"stringifyOrUndefined");function T_(t,e,n){let o=t.map(p=>nw(p,e)),r=Mf(o);if(r===void 0)return;if(r.length<=e)return r;let s=n==="first"?o:[...o].reverse(),a=[],c=2;for(let p of s){let f=(Mf(Wu(p,0))??"").length+1;if(c+f>e)break;c+=f,a.push(p)}n==="last"&&a.reverse();let u=0,l=e,d=Mf(Wu(a,0))??"[]";for(;u<=l;){let p=Math.floor((u+l)/2),f=Mf(Wu(a,p))??"";f.length<=e?(d=f,u=p+1):l=p-1}return d}i(T_,"serializeWithinBudget");function A_(t){let e;if(typeof t=="string"?e=t:t instanceof Uint8Array?e=new TextDecoder().decode(t):t instanceof ArrayBuffer&&(e=new TextDecoder().decode(new Uint8Array(t))),e!==void 0)try{return JSON.parse(e)}catch{return}}i(A_,"parseUpstreamRequestBody");function I_(t){if(!Ze(t))return{};let e=Ze(t.inferenceConfig)?t.inferenceConfig:{},n=Ze(t.generationConfig)?t.generationConfig:{},o={},r=i((a,c)=>{c!==void 0&&(o[a]=c)},"set");r("gen_ai.request.max_tokens",Pr(Jn(t.max_tokens),Jn(t.max_completion_tokens),Jn(t.max_output_tokens),Jn(e.maxTokens),Jn(n.maxOutputTokens))),r("gen_ai.request.temperature",Pr(Vn(t.temperature),Vn(e.temperature),Vn(n.temperature))),r("gen_ai.request.top_p",Pr(Vn(t.top_p),Vn(e.topP),Vn(n.topP))),r("gen_ai.request.top_k",Pr(Vn(t.top_k),Vn(n.topK))),r("gen_ai.request.stop_sequences",Pr(Of(t.stop),Of(t.stop_sequences),Of(e.stopSequences),Of(n.stopSequences))),r("gen_ai.request.frequency_penalty",Pr(Vn(t.frequency_penalty),Vn(n.frequencyPenalty))),r("gen_ai.request.presence_penalty",Pr(Vn(t.presence_penalty),Vn(n.presencePenalty))),r("gen_ai.request.seed",Pr(Jn(t.seed),Jn(n.seed)));let s=Pr(Jn(t.n),Jn(n.candidateCount));return s!==void 0&&s!==1&&(o["gen_ai.request.choice.count"]=s),o}i(I_,"readRequestParameterAttributes");function Na(t){return{type:"text",content:t}}i(Na,"textPart");function el(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(el,"parseArguments");function Ko(t){if(typeof t=="string")return[Na(t)];if(!Array.isArray(t))return[];let e=[];for(let n of t){if(typeof n=="string"){e.push(Na(n));continue}if(!Ze(n))continue;let o=De(n.type),r=De(n.text);if(r!==void 0&&(o===void 0||o==="text"||o==="input_text"||o==="output_text")){e.push(Na(r));continue}if(o==="tool_use"){e.push({type:"tool_call",id:De(n.id),name:De(n.name),arguments:n.input});continue}if(o==="tool_result"){e.push({type:"tool_call_response",id:De(n.tool_use_id),response:n.content});continue}if(Ze(n.toolUse)){e.push({type:"tool_call",id:De(n.toolUse.toolUseId),name:De(n.toolUse.name),arguments:n.toolUse.input});continue}if(Ze(n.toolResult)){e.push({type:"tool_call_response",id:De(n.toolResult.toolUseId),response:n.toolResult.content});continue}if(Ze(n.functionCall)){e.push({type:"tool_call",name:De(n.functionCall.name),arguments:n.functionCall.args});continue}if(Ze(n.functionResponse)){e.push({type:"tool_call_response",id:De(n.functionResponse.id),response:n.functionResponse.response});continue}if(o==="thinking"&&typeof n.thinking=="string"){e.push({type:"reasoning",content:n.thinking});continue}e.push({type:o??"unknown"})}return e}i(Ko,"toParts");function E_(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!Ze(n))continue;let o=Ze(n.function)?n.function:{};e.push({type:"tool_call",id:De(n.id),name:De(o.name),arguments:el(o.arguments)})}return e}i(E_,"toOpenAiToolCallParts");function Qu(t){return t==="model"?"assistant":De(t)??"user"}i(Qu,"normalizeRole");function v_(t,e){let n=[];for(let o of t){if(!Ze(o))continue;let r=De(o.role);if(r==="system"||r==="developer"){e.push(...Ko(o.content));continue}if(r==="tool"){n.push({role:"tool",parts:[{type:"tool_call_response",id:De(o.tool_call_id),response:o.content}]});continue}let s=[...Ko(o.content??o.parts),...E_(o.tool_calls)],a={role:Qu(r),parts:s},c=De(o.name);c!==void 0&&(a.name=c),n.push(a)}return n}i(v_,"readChatMessages");function o2(t){if(typeof t=="string")return[{role:"user",parts:[Na(t)]}];if(!Array.isArray(t))return[];let e=[];for(let n of t)if(Ze(n)){if(n.type==="function_call"){e.push({role:"assistant",parts:[{type:"tool_call",id:De(n.call_id),name:De(n.name),arguments:el(n.arguments)}]});continue}if(n.type==="function_call_output"){e.push({role:"tool",parts:[{type:"tool_call_response",id:De(n.call_id),response:n.output}]});continue}n.role!==void 0&&e.push({role:Qu(n.role),parts:Ko(n.content)})}return e}i(o2,"readResponsesInput");function P_(t){if(!Ze(t))return;let e=[];t.system!==void 0&&e.push(...Ko(t.system)),typeof t.instructions=="string"&&e.push(Na(t.instructions)),Ze(t.systemInstruction)&&e.push(...Ko(t.systemInstruction.parts));let n;if(Array.isArray(t.messages)?n=v_(t.messages,e):Array.isArray(t.contents)?n=v_(t.contents,e):t.input!==void 0&&t.model!==void 0&&(n=o2(t.input)),!(n===void 0&&e.length===0))return{systemInstructions:e,messages:n??[]}}i(P_,"readInputContent");function r2(t){let e=Ze(t.message)?t.message:{},n=[...Ko(e.content),...E_(e.tool_calls)];return{role:Qu(e.role??"assistant"),parts:n,finish_reason:De(t.finish_reason)??""}}i(r2,"readOpenAiChoiceOutput");function k_(t){if(!Array.isArray(t.output))return[];let e=[];for(let n of t.output)Ze(n)&&(n.type==="message"?e.push(...Ko(n.content)):n.type==="function_call"&&e.push({type:"tool_call",id:De(n.call_id),name:De(n.name),arguments:el(n.arguments)}));return[{role:"assistant",parts:e,finish_reason:ow(t)??""}]}i(k_,"readResponsesOutput");function ow(t){return(Ze(t.incomplete_details)?De(t.incomplete_details.reason):void 0)??De(t.status)}i(ow,"responsesFinishReason");function rw(t){let e={finishReasons:[]};if(!Ze(t))return e;if(e.id=De(t.id)??De(t.responseId),e.model=De(t.model)??De(t.modelVersion),Array.isArray(t.choices))for(let n of t.choices){let o=Ze(n)?De(n.finish_reason):void 0;o!==void 0&&e.finishReasons.push(o)}else if(Array.isArray(t.candidates))for(let n of t.candidates){let o=Ze(n)?De(n.finishReason):void 0;o!==void 0&&e.finishReasons.push(o)}else if(typeof t.stop_reason=="string")e.finishReasons.push(t.stop_reason);else if(typeof t.stopReason=="string")e.finishReasons.push(t.stopReason);else if(t.object==="response"){let n=ow(t);n!==void 0&&e.finishReasons.push(n)}return e}i(rw,"readResponseFields");function __(t){if(Ze(t)){if(Array.isArray(t.choices))return t.choices.filter(Ze).map(r2);if(Array.isArray(t.candidates))return t.candidates.filter(Ze).map(e=>({role:"assistant",parts:Ko(Ze(e.content)?e.content.parts:void 0),finish_reason:De(e.finishReason)??""}));if(t.object==="response")return k_(t);if(t.type==="message"&&Array.isArray(t.content))return[{role:Qu(t.role??"assistant"),parts:Ko(t.content),finish_reason:De(t.stop_reason)??""}];if(Ze(t.output)&&Ze(t.output.message))return[{role:Qu(t.output.message.role??"assistant"),parts:Ko(t.output.message.content),finish_reason:De(t.stopReason)??""}]}}i(__,"readOutputMessages");function i2(t,e){let n=e,o=i(r=>{let s=Yu(r,n);return n-=s.length,s},"take");return t.map(r=>({...r,parts:r.parts.map(s=>{let a={...s};return typeof s.content=="string"&&(a.content=o(s.content)),typeof s.arguments=="string"?a.arguments=o(s.arguments):s.arguments!==void 0&&(a.arguments=el(o(JSON.stringify(s.arguments)??""))),a})}))}i(i2,"clipMessages");var Xu=class{static{i(this,"StreamResponseAccumulator")}fields={finishReasons:[]};#e=new Map;#t;#o;#n=0;#r;errorType;constructor(e){this.#t=e.captureOutput,this.#o=e.maxOutputLength}#i(e){let n=this.#e.get(e);return n||(n={text:"",toolCalls:new Map},this.#e.set(e,n)),n}#s(e,n){if(!this.#t||this.#n>=this.#o)return;let o=this.#o-this.#n,r=n.length>o?n.slice(0,o):n;e.text+=r,this.#n+=r.length}#a(e,n){let o=e.toolCalls.get(n);return o||(o={arguments:""},e.toolCalls.set(n,o)),o}#c(e,n){if(!this.#t||this.#n>=this.#o)return;let o=this.#o-this.#n,r=n.length>o?n.slice(0,o):n;e.arguments+=r,this.#n+=r.length}observe(e){if(!Ze(e))return;if(typeof e.exceptionType=="string"){this.errorType??=e.exceptionType;return}if(typeof e.eventType=="string"){this.#l(e.eventType,e.body);return}if(Array.isArray(e.choices)){this.#u(e);return}let n=De(e.type);if(n==="error"||n===void 0&&Ze(e.error)){let o=Ze(e.error)?e.error:e;this.errorType??=De(o.type)??De(o.code)??(typeof o.code=="number"?String(o.code):void 0)??"error";return}if(n!==void 0){if(n.startsWith("response.")){this.#d(n,e);return}this.#p(n,e)}}#u(e){this.fields.id??=De(e.id),this.fields.model??=De(e.model);for(let n of e.choices){if(!Ze(n))continue;let o=this.#i(Jn(n.index)??0),r=De(n.finish_reason);r!==void 0&&(o.finishReason=r);let s=Ze(n.delta)?n.delta:void 0;if(s&&(typeof s.content=="string"&&this.#s(o,s.content),Array.isArray(s.tool_calls)))for(let a of s.tool_calls){if(!Ze(a))continue;let c=this.#a(o,Jn(a.index)??0);c.id??=De(a.id);let u=Ze(a.function)?a.function:{};c.name??=De(u.name),typeof u.arguments=="string"&&this.#c(c,u.arguments)}}}#p(e,n){let o=this.#i(0);if(e==="message_start"&&Ze(n.message)){this.fields.id??=De(n.message.id),this.fields.model??=De(n.message.model);return}if(e==="message_delta"&&Ze(n.delta)){let s=De(n.delta.stop_reason);s!==void 0&&(o.finishReason=s);return}let r=Jn(n.index)??0;if(e==="content_block_start"&&Ze(n.content_block)){let s=n.content_block;if(s.type==="tool_use"){let a=this.#a(o,r);a.id=De(s.id),a.name=De(s.name)}else typeof s.text=="string"&&this.#s(o,s.text);return}if(e==="content_block_delta"&&Ze(n.delta)){let s=n.delta;typeof s.text=="string"?this.#s(o,s.text):typeof s.partial_json=="string"&&this.#c(this.#a(o,r),s.partial_json)}}#d(e,n){let o=Ze(n.response)?n.response:void 0;if(o&&(this.fields.id??=De(o.id),this.fields.model??=De(o.model)),o&&(e==="response.completed"||e==="response.incomplete"||e==="response.failed")){let r=ow(o);if(r!==void 0&&(this.#i(0).finishReason=r),e==="response.failed"){let s=Ze(o.error)?o.error:{};this.errorType??=De(s.code)??"response.failed"}this.#t&&(this.#r=i2(k_(o),this.#o));return}e==="response.output_text.delta"&&typeof n.delta=="string"&&this.#s(this.#i(0),n.delta)}#l(e,n){if(e==="chunk"){let s=s2(n);Ze(s)&&typeof s.eventType!="string"&&this.observe(s);return}if(!Ze(n))return;let o=this.#i(0);if(e==="messageStop"){let s=De(n.stopReason);s!==void 0&&(o.finishReason=s);return}let r=Jn(n.contentBlockIndex)??0;if(e==="contentBlockStart"&&Ze(n.start)){if(Ze(n.start.toolUse)){let s=this.#a(o,r);s.id=De(n.start.toolUse.toolUseId),s.name=De(n.start.toolUse.name)}return}e==="contentBlockDelta"&&Ze(n.delta)&&(typeof n.delta.text=="string"?this.#s(o,n.delta.text):Ze(n.delta.toolUse)&&typeof n.delta.toolUse.input=="string"&&this.#c(this.#a(o,r),n.delta.toolUse.input))}finishReasons(){return this.fields.finishReasons.length>0?this.fields.finishReasons:[...this.#e.entries()].sort(([e],[n])=>e-n).map(([,e])=>e.finishReason).filter(e=>e!==void 0)}outputMessages(){if(this.#t){if(this.#r)return this.#r;if(this.#e.size!==0)return[...this.#e.entries()].sort(([e],[n])=>e-n).map(([,e])=>{let n=[];e.text.length>0&&n.push(Na(e.text));for(let[,o]of[...e.toolCalls.entries()].sort(([r],[s])=>r-s))n.push({type:"tool_call",id:o.id,name:o.name,arguments:el(o.arguments)});return{role:"assistant",parts:n,finish_reason:e.finishReason??""}})}}};function s2(t){let e=Ze(t)?t.bytes:void 0;if(typeof e=="string")try{let n=atob(e),o=new Uint8Array(n.length);for(let r=0;r<n.length;r++)o[r]=n.charCodeAt(r);return JSON.parse(new TextDecoder().decode(o))}catch{return}}i(s2,"decodeBedrockInvokeChunk");var l2="ai-gateway",L_=8*1024,d2=3e4,p2=1024*1024,m2={openai:"openai","openai-codex-backend":"openai",anthropic:"anthropic",google:"gcp.gemini","vertex-ai":"gcp.vertex_ai","bedrock-runtime":"aws.bedrock","bedrock-mantle":"aws.bedrock",mistral:"mistral_ai",xai:"x_ai"};function f2(t,e=!1){let n=t.toLowerCase();return n==="azure-ai"?e?"azure.ai.openai":"azure.ai.inference":m2[n]??n}i(f2,"toGenAiProviderName");function iw(t,e){return T_(t,L_,e)}i(iw,"serializeContent");var aw=!1;function N_(t){aw=t}i(N_,"setGenAiContentCapture");var x_;function h2(){return x_??=M_.getTracer(l2),x_}i(h2,"getTracer");var U_=new ge(Symbol("zuplo.ai_gateway.entry_span"));function q_(t,e){e.isRecording()&&U_.set(t,e)}i(q_,"setRequestEntrySpan");function $_(t){let e=U_.get(t);return e?.isRecording()?e:void 0}i($_,"getEntrySpan");function D_(t){return $_(t)!==void 0}i(D_,"isEntrySpanRecording");function qa(t,e){$_(t)?.setAttributes(e)}i(qa,"setAiGatewayEntryAttributes");function cw(t,e,n){let o=Da(t);o.refusedBy!==void 0&&n?.replacesEarlier!==!0||(o.refusedBy=e,qa(t,{"zuplo.ai_gateway.refused_by":e}))}i(cw,"recordAiGatewayRefusal");function $a(t,e,n,o){!z_(t)||!D_(t)||n.status>=400&&cw(t,e,o)}i($a,"noteInboundPolicyResponse");async function Lf(t,e){if(!z_(t)||!D_(t))return;let n=Da(t);if(!n.requestedModelRead){n.requestedModelRead=!0;try{let o=await Vo(e);typeof o.value=="string"&&o.value!==""&&qa(t,{"gen_ai.request.model":o.value})}catch{}}}i(Lf,"recordRequestedModel");var g2=new Set(["aiGatewayHandler","aiGatewayHandlerV2"]);function z_(t){return g2.has(t.route?.handler?.export??"")}i(z_,"isAiGatewayRoute");var Ua=new ge(Symbol("zuplo.ai_gateway.genai_state"));function Da(t){let e=Ua.get(t);return e||(e={startedAttempts:0},Ua.set(t,e)),e}i(Da,"getRequestState");function j_(t,e){Da(t).operationName=e}i(j_,"setGenAiOperation");function H_(t){return(Ua.get(t)?.startedAttempts??0)>0}i(H_,"hasInferenceAttempt");function y2(t){let e={"gen_ai.usage.input_tokens":t.promptTokens,"gen_ai.usage.output_tokens":t.completionTokens,"zuplo.ai_gateway.cost.usd":t.cost,"zuplo.ai_gateway.cost.source":t.costSource,"zuplo.ai_gateway.cost.accuracy":t.costAccuracy},n=t.canonicalUsage;return n?.cacheReadInputTokens!==void 0&&(e["gen_ai.usage.cache_read.input_tokens"]=n.cacheReadInputTokens),n!==void 0&&n.cacheWriteInput.length>0&&(e["gen_ai.usage.cache_write.input_tokens"]=n.cacheWriteInput.reduce((o,r)=>o+r.tokens,0)),n?.reasoningOutputTokens!==void 0&&(e["gen_ai.usage.reasoning.output_tokens"]=n.reasoningOutputTokens),e}i(y2,"usageAttributes");function b2(t,e){return e?"timeout":t instanceof Error&&"status"in t&&typeof t.status=="number"?String(t.status):t instanceof Error?t.name||"Error":"_OTHER"}i(b2,"errorTypeOf");function R2(t){return(t.headers.get("content-type")??"").toLowerCase().includes("json")}i(R2,"isJsonResponse");var sw=class{static{i(this,"InferenceAttempt")}span;recording;#e;#t;#o=!1;#n=!1;#r=!1;#i=!1;#s=!1;#a;#c=!1;#u;#p;#d;#l;#m;#y;#b=!1;constructor(e,n,o,r,s,a){this.#e=e,this.#t=r;let c=n.requestModel,u={"gen_ai.operation.name":r,"gen_ai.provider.name":f2(n.providerType,n.azureOpenAiSurface),"gen_ai.request.stream":n.stream,"zuplo.ai_gateway.attempt":o,"zuplo.ai_gateway.provider.label":n.providerLabel};c&&(u["gen_ai.request.model"]=c),a&&(u["server.address"]=a.hostname,u["server.port"]=a.port?Number(a.port):a.protocol==="http:"?80:443),this.span=h2().startSpan(c?`${r} ${c}`:r,{kind:c2.CLIENT,attributes:u},s),this.recording=this.span.isRecording();let l=this.recording&&aw;this.#u=l&&r!=="embeddings",this.#p=l&&r!=="embeddings"&&r!=="count_tokens"&&r!=="delete_response",this.#p&&(Da(e).captureOutput=!0,this.#d=new Promise(d=>{this.#l=d}))}get capturesOutput(){return this.#p&&!this.#s&&!this.#n}get ended(){return this.#o}markTimedOut(){this.#i=!0}noteUpstreamRequest(e){if(this.#a!==void 0||(this.#a=performance.now(),!this.recording))return;let n=A_(e);if(n===void 0)return;this.span.setAttributes(I_(n));let o=n.stream;typeof o=="boolean"&&this.span.setAttribute("gen_ai.request.stream",o),this.#u&&this.#R(P_(n))}async noteUpstreamResponse(e){if(!(this.#b||!this.recording||!e.ok||this.#t==="embeddings"||!R2(e))){this.#b=!0;try{this.#y=rw(await e.clone().json())}catch{}}}#R(e){if(!e)return;if(e.systemInstructions.length>0){let o=iw(e.systemInstructions,"first");o!==void 0&&this.span.setAttribute("gen_ai.system_instructions",o)}let n=iw(e.messages,"last");n!==void 0&&this.span.setAttribute("gen_ai.input.messages",n)}setOutputMessages(e){if(this.#p&&e!==void 0&&!this.#n){let n=iw(e,"first");n!==void 0&&this.span.setAttribute("gen_ai.output.messages",n)}this.#l?.()}observeResponseBody(e){if(!this.recording)return;let n=rw(e),o=this.#y;this.#f(o?.id??n.id,o?.model??n.model,o!==void 0&&o.finishReasons.length>0?o.finishReasons:n.finishReasons)}#f(e,n,o){e!==void 0&&this.span.setAttribute("gen_ai.response.id",e),n!==void 0&&this.span.setAttribute("gen_ai.response.model",n),o.length>0&&this.span.setAttribute("gen_ai.response.finish_reasons",o)}setUsage(e){if(!this.recording)return;let n=y2(e);this.#t==="embeddings"&&delete n["gen_ai.usage.output_tokens"],this.span.setAttributes(n)}failStatus(e){this.#g(String(e))}fail(e){this.#g(b2(e,this.#i))}#g(e){this.#o||(this.#s=!0,this.span.setAttribute("error.type",e),this.span.setStatus({code:u2.ERROR}),this.#l?.())}claimForStream(){this.#r=!0,this.recording&&(this.#m=new Xu({captureOutput:!1,maxOutputLength:0}))}get claimed(){return this.#r}noteStreamChunk(){this.#c||(this.#c=!0,this.recording&&this.#a!==void 0&&this.span.setAttribute("gen_ai.response.time_to_first_chunk",(performance.now()-this.#a)/1e3))}observeStreamEvent(e){this.#m?.observe(e)}get observesStream(){return this.#m!==void 0}end(e,n){if(this.#o)return;if(e!==void 0){let a=e;if(this.#m){let c=this.#m.fields;this.#f(c.id,c.model,this.#m.finishReasons());let u=this.#m.errorType;a!=="error"&&u!==void 0&&(a="error",this.#g(u))}this.span.setAttribute("zuplo.ai_gateway.stream.end",a),a==="error"&&!this.#s&&this.fail(n)}if(this.#o=!0,this.#d===void 0||this.#s){this.#h();return}let o=new Date,r,s=new Promise(a=>{r=setTimeout(a,d2)});this.#e.waitUntil(Promise.race([this.#d,s]).then(()=>{clearTimeout(r),this.#h(o)}))}#h(e){this.#n||(this.#n=!0,this.span.end(e))}outputSettled(){this.#l?.()}get operationName(){return this.#t}},uw=new a2;async function G_(t,e,n,o){let r=Da(t);r.pending&&(r.pending.end(),r.pending=void 0);let s={context:t,input:e,kind:n,parent:O_.active(),open:!0},a;try{a=await uw.run(s,o)}catch(u){throw s.open=!1,s.attempt?.fail(u),s.attempt?.end(),u}s.open=!1;let c=s.attempt;return!c||c.claimed?a:a instanceof Response&&!a.ok?(c.failStatus(a.status),c.end(),a):(r.pending=c,a)}i(G_,"runInferenceAttempt");var w2={markTimedOut(){}};function Nf(t,e,n){let o=uw.getStore();if(!o?.open)return n(w2);let r=o.attempt;if(!r){let c=Da(o.context);r=new sw(o.context,o.input,o.kind,c.operationName??"chat",o.parent,S2(t)),o.attempt=r,c.startedAttempts+=1,c.latest?.outputSettled(),c.latest=r}let s=r;s.noteUpstreamRequest(e?.body);let a={markTimedOut:i(()=>s.markTimedOut(),"markTimedOut")};return O_.with(M_.setSpan(o.parent,s.span),async()=>{let c=await n(a);return await s.noteUpstreamResponse(c),c})}i(Nf,"withUpstreamRequest");function S2(t){try{return t instanceof URL?t:new URL(typeof t=="string"?t:t.url)}catch{return}}i(S2,"parseUrl");function F_(){let t=uw.getStore()?.attempt;if(!(!t||t.claimed||t.ended))return t.claimForStream(),t}i(F_,"claimStreamInferenceAttempt");function za(t,e,n){let o=Ua.get(t),r=o?.pending;!o||!r||(o.pending=void 0,r.observeResponseBody(e),n&&r.setUsage(n),r.end())}i(za,"completePendingInferenceAttempt");function B_(t){let e=Ua.get(t);e?.pending&&(e.pending.end(),e.pending=void 0)}i(B_,"endPendingInferenceAttempts");async function Z_(t,e){if(!aw)return e;let n=Ua.get(t);if(!n?.captureOutput)return e;n.captureOutput=!1;let o=n.latest;if(!o?.capturesOutput)return o?.outputSettled(),e;if(!e.ok||!e.body)return o.outputSettled(),e;let r=(e.headers.get("content-type")??"").toLowerCase();if(r.includes("text/event-stream")){let s=V_();return w_(e,{event(a){if(!(a.data===void 0||a.data==="[DONE]"))try{s.observe(JSON.parse(a.data))}catch{}},end(){o.setOutputMessages(s.outputMessages())}},{maxEventChars:p2})}if(r.includes("application/vnd.amazon.eventstream"))return new Response(C2(e.body,o),{status:e.status,statusText:e.statusText,headers:e.headers});try{let s=JSON.parse(await e.clone().text());o.setOutputMessages(__(s))}catch{o.outputSettled()}return e}i(Z_,"observeGenAiOutputContent");function V_(){return new Xu({captureOutput:!0,maxOutputLength:L_})}i(V_,"outputAccumulator");function C2(t,e){let n=V_(),o=xf(),r=new TextDecoder,s=t.getReader(),a=!1,c=i(()=>{a||(a=!0,e.setOutputMessages(n.outputMessages()))},"settle");return new ReadableStream({async pull(u){try{let{done:l,value:d}=await s.read();if(l){c(),u.close();return}try{for(let p of o(d))p.headers[":message-type"]==="event"&&n.observe({eventType:p.headers[":event-type"],body:JSON.parse(r.decode(p.payload))})}catch{}u.enqueue(d)}catch(l){c(),u.error(l)}},async cancel(u){c(),await s.cancel(u)}},{highWaterMark:0})}i(C2,"observeEventStream");import{trace as q2}from"@opentelemetry/api";var v2="custom";function lw(t){return t.module?.[t.export]?.handlerType??v2}i(lw,"resolveHandlerType");function J_(t,e){t.setAttribute(Ln.HandlerType,lw(e)),t.setAttribute(Ln.HandlerExport,e.export)}i(J_,"applyHandlerSpanTelemetry");import{SpanStatusCode as T2}from"@opentelemetry/api";function Wo(t,e){t.recordException(A2(e)),t.setStatus({code:T2.ERROR})}i(Wo,"recordSpanError");function A2(t){return t instanceof Error||typeof t=="string"||typeof t=="object"&&t!==null&&("message"in t||"name"in t)?t:String(t)}i(A2,"toException");function I2(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof dR)return!0;e.add(n),n=n.cause}return!1}i(I2,"hasNetworkError");function Nn(t,e,n,o){e.log.error(n,o instanceof dR?o.cause:o);let r={};if(!I2(o)&&(k.instance.isLocalDevelopment||k.instance.isWorkingCopy))if(o instanceof Z&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let s=fs(o.cause);"stack"in s&&(s.stack=FR(s.stack)),r={cause:s}}else{let s=fs(o);"stack"in s&&(s.stack=FR(s.stack)),r={cause:s}}return V.internalServerError(t,e,{detail:o.message,...r})}i(Nn,"errorHandler");import{SpanStatusCode as hw,trace as E2}from"@opentelemetry/api";var K_=i(t=>(e,n)=>t(e,n),"globalRequestHandlerProxy");function W_(t){K_=t}i(W_,"setTelemetryInitFunction");var Y_=i(t=>K_(t),"proxyHandler");var Q_,Si=i(()=>(Q_??=E2.getTracer("extension"),Q_),"tracer"),gw={},ao=[],dw=[],pw=[],mw=[],fw=[];var Uf={addPlugin(t){ao.push(t)},addRequestHook(t){dw.push(t)},addResponseSendingHook(t){pw.push(t)},addResponseSendingFinalHook(t){mw.push(t)},addPreRoutingHook(t){fw.push(t)},addTelemetryRedactor(t){WP(t)}},ex=i(async(t,e)=>dw.length===0?t:Si().startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let r of dw){let s=await Si().startActiveSpan(r.name,async a=>{try{let c=await r(o,e);if(c instanceof Ge||c instanceof Response)return c;throw new T(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof c}.`)}catch(c){throw a.recordException(c),a.setStatus({code:hw.ERROR}),c}finally{a.end()}});if(s instanceof Ge)o=s;else return s}return o}finally{n.end()}}),"invokeOnRequestExtensions"),tx=i(async(t,e,n)=>{if(pw.length===0)return t;let o=k.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;return Si().startActiveSpan("hook:onResponseSending",async r=>{try{let s=t;for(let a of pw)await Si().startActiveSpan(a.name,async c=>{try{let u=await a(o?s:t,e,n);if(u instanceof Response)s=u;else throw new T(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof u}.`)}catch(u){throw c.recordException(u),c.setStatus({code:hw.ERROR}),u}finally{c.end()}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),nx=i(async(t,e,n)=>{if(mw.length!==0)return Si().startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let r of mw)await Si().startActiveSpan(r.name,async s=>{try{await r(t,e,n)}catch(a){throw s.recordException(a),s.setStatus({code:hw.ERROR}),s.end(),a}s.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ox=i(async t=>fw.length===0?t:Si().startActiveSpan("hook:preRouting",async e=>{try{let n=t;for(let o of fw)n=await Si().startActiveSpan(o.name,async s=>{try{let a=await o(n);if(a instanceof Request)return a;throw new Z(`Invalid state - the PreRouting hook must return a Request. Received ${typeof a}.`)}catch(a){throw Wo(s,a),a}finally{s.end()}});return n}finally{e.end()}}),"invokePreRoutingHooks"),X_=!1;async function rx(t){if(!X_){t&&(me("runtime.extensions"),await t(Uf)),gw.value=Uf;for(let e of ao)if(e instanceof ms){let n=e.instrument({accountName:k.instance.accountName,projectName:k.instance.projectName,buildId:k.instance.build.BUILD_ID,zuploVersion:k.instance.build.ZUPLO_VERSION,compatibilityDate:k.instance.build.COMPATIBILITY_DATE,instanceId:k.instance.instanceId,environmentType:k.instance.loggingEnvironmentType,environmentStage:k.instance.loggingEnvironmentStage,deploymentName:k.instance.deploymentName,__internalOnlyRemoteLogUrl:k.instance.remoteLogURL,__internalOnlyRemoteLogToken:k.instance.remoteLogToken});W_(n.requestHandlerProxy),N_(n.__internalOnlyGenAiCaptureContent===!0)}await Promise.all(ao.map(async e=>{e instanceof $t&&await e.initialize(Uf)})),Fu.setProblemResponseFormat(Uf.problemResponseFormat),YP(),X_=!0}}i(rx,"initializeRuntime");var $={AI_GATEWAY_COST_SUM:"ai_gateway_cost_sum",AI_GATEWAY_REQUEST_COUNT:"ai_gateway_request_count",AI_GATEWAY_TOKEN_SUM:"ai_gateway_token_sum",AI_GATEWAY_LATENCY_HISTOGRAM:"ai_gateway_latency_histogram",AI_GATEWAY_WARNING_COUNT:"ai_gateway_warning_count",AI_GATEWAY_BLOCKED_COUNT:"ai_gateway_blocked_count",AI_GATEWAY_FALLBACK_COUNT:"ai_gateway_fallback_count",MCP_REQUEST_RECEIVED:"mcp_request_received",MCP_REQUEST_COMPLETED:"mcp_request_completed",MCP_REQUEST_REJECTED:"mcp_request_rejected",MCP_INITIALIZE_NEGOTIATED:"mcp_initialize_negotiated",MCP_CLIENT_UNSUPPORTED_BEHAVIOR:"mcp_client_unsupported_behavior",MCP_CAPABILITY_LISTED:"mcp_capability_listed",MCP_CAPABILITY_INVOKED:"mcp_capability_invoked",MCP_CAPABILITY_COMPLETED:"mcp_capability_completed",MCP_CAPABILITY_FAILED:"mcp_capability_failed",MCP_CAPABILITY_CONNECT_REQUIRED:"mcp_capability_connect_required",MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED:"mcp_auth_downstream_token_validated",MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED:"mcp_auth_downstream_token_rejected",MCP_OAUTH_CLIENT_REGISTERED:"mcp_oauth_client_registered",MCP_OAUTH_AUTHORIZE_STARTED:"mcp_oauth_authorize_started",MCP_OAUTH_AUTHORIZE_AWAITING_SETUP:"mcp_oauth_authorize_awaiting_setup",MCP_OAUTH_TOKEN_ISSUED:"mcp_oauth_token_issued",MCP_OAUTH_TOKEN_REFRESH_ROTATED:"mcp_oauth_token_refresh_rotated",MCP_OAUTH_TOKEN_REVOKED:"mcp_oauth_token_revoked",MCP_AUTH_UPSTREAM_CONNECT_REQUIRED:"mcp_auth_upstream_connect_required",MCP_AUTH_UPSTREAM_CONNECT_STARTED:"mcp_auth_upstream_connect_started",MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED:"mcp_auth_upstream_callback_received",MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED:"mcp_auth_upstream_token_exchange_succeeded",MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED:"mcp_auth_upstream_token_exchange_failed",MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED:"mcp_auth_upstream_credential_resolved",MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING:"mcp_auth_upstream_credential_missing",MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED:"mcp_auth_upstream_reconsent_required",GRAPHQL_OPERATION:"graphql_operation",CACHE_OPERATION:"cache_operation",HANDLER_EXECUTION:"handler_execution",RATE_LIMIT_SERVICE_CALL:"rate_limit_service_call"};var P2=new Set([408,504]),k2=new Set(["TimeoutError","AbortError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError"]),_2=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ETIMEDOUT"]),x2=5;function O2(t){let e=t;for(let n=0;n<=x2;n++){if(typeof e!="object"||e===null)return!1;let o=e;if(typeof o.name=="string"&&k2.has(o.name)||typeof o.code=="string"&&_2.has(o.code))return!0;e=e.cause}return!1}i(O2,"isTimeoutError");function M2(t,e){return e?O2(e.thrown)?"timeout":"exception":t===null?"success":P2.has(t)?"timeout":t>=500?"server-error":t>=400?"client-error":"success"}i(M2,"classifyHandlerResult");function yw(t,e,n){try{let o={handlerType:lw(n.handler),handlerExport:n.handler.export,result:M2(n.statusCode,n.error),statusCode:n.statusCode,latencyMs:n.latencyMs,...L2(t),routePath:N2(e),method:t.method,errorName:U2(n.error)};e.analyticsContext.addAnalyticsEvent(1,$.HANDLER_EXECUTION,o,"count")}catch(o){try{le.getLogger(e).error(o,"Error emitting handler_execution analytics event")}catch{}}}i(yw,"emitHandlerExecution");function L2(t){try{let e=new URL(t.url);return{hostname:e.hostname===""?null:e.hostname,port:e.port===""?null:Number(e.port),scheme:e.protocol===""?null:e.protocol.replace(/:$/,"")}}catch{return{hostname:null,port:null,scheme:null}}}i(L2,"readUrlDimensions");function N2(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}i(N2,"readRoutePath");function U2(t){if(!t)return null;let e=t.thrown;if(typeof e=="object"&&e!==null){let n=e.name;if(typeof n=="string"&&n.length>0)return n}return null}i(U2,"readErrorName");function ja(t){let{developerPortal:e}=nt.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(ja,"isSystemRoute");var ix,$2=i(()=>(ix??=q2.getTracer("pipeline"),ix),"tracer"),rn=class{static{i(this,"Pipeline")}constructor(e){this.execute=D2(this.#t(e))}execute;#e=i((e,n)=>async(o,r)=>$2().startActiveSpan(`handler:${r.route.handler.export}`,async s=>{J_(s,r.route.handler);let a=performance.now();try{let c=await e(o,r);return n&&yw(o,r,{handler:r.route.handler,latencyMs:performance.now()-a,statusCode:c.status,error:null}),c}catch(c){let u=performance.now()-a,l=await Nn(o,r,"Error executing request handler.",c);return Wo(s,c),n&&yw(o,r,{handler:r.route.handler,latencyMs:u,statusCode:l.status,error:{thrown:c}}),l}finally{s.end()}}),"#errorWrappedHandler");#t=i(({processors:e,handler:n,emitHandlerAnalytics:o=!1})=>async(r,s)=>{let a=tt.getContextExtensions(s),c=[...e],u=i(async w=>{let b=c.pop();if(!b){let v=await this.#e(async A=>{let E=await n(A,s),P=j2(E);return z2(P,s),P},o)(w,s);try{await a.onHandlerResponse(v,w,s)}catch(A){return Nn(r,s,"Error invoking 'context.onHandlerResponse' hook",A)}return v}return b(w,s,u)},"nextPipe"),d=await u(r),p=new URL(r.url);if(ja(p)&&k.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let f=new tl(r,d);s.dispatchEvent(f);let h=a.latestRequest,g;try{g=await f.mutableResponse}catch(w){return Nn(r,s,"Error retrieving mutableResponse",w)}try{g=await a.onResponseSending(g,h,s)}catch(w){return Nn(r,s,"Error invoking 'context.onResponseSending' hook",w)}try{g=await tx(g,h,s)}catch(w){return Nn(r,s,"Error invoking 'context.onResponseSending' hook",w)}s.dispatchEvent(new nl(r,g));try{await a.onResponseSendingFinal(d,h,s)}catch(w){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",w),w}try{await nx(d,h,s)}catch(w){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",w),w}return await Z_(s,g)},"#toZuploPipeline")};function D2(t){return async(e,n)=>{let o=tt.getContextExtensions(n),r=o.startDeferringMetrics(),s;try{return s=await t(e,n),s}finally{if(r){for(let a of o.flushDeferredMetrics())W.console.error(`Error emitting the request metric row for requestId '${n.requestId}'`,a);for(let a of o.runPipelineExitHooks(s))W.console.error(`Error running a pipeline exit hook for requestId '${n.requestId}'`,a)}}}}i(D2,"withPipelineExit");function z2(t,e){let n=e.route.handler.export;if(t.bodyUsed)throw new Z(`The handler '${n}' read its own response body, so the response can no longer be sent. A body can only be read once. Read a clone instead, e.g. \`const data = await response.clone().json()\`, or return a new Response built from what you read.`);if(t.body?.locked===!0)throw new Z(`The handler '${n}' returned a response whose body still has a reader attached, so the response can no longer be sent. Call \`reader.releaseLock()\` before returning it - cloning does not work while the body is locked - or return a new Response built from what you read.`)}i(z2,"assertResponseBodyUnread");function j2(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(jR(t),{headers:{"content-type":"application/json"}})}i(j2,"resultToResponse");function sx(t){return{timestamp:t.timestamp.toISOString(),event_id:t.eventId,request_id:t.requestId,event_type:t.eventType,account_name:t.accountName,project_name:t.projectName,deployment_name:t.deploymentName,value:t.value,unit:t.unit,metadata:t.metadata,source:"zuplo-runtime",version:"v2"}}i(sx,"toVectorAnalyticsEventRow");var H2="/v1/runtime/telemetry",G2=1e3,F2=["resourceUri"];function B2(t){if(typeof t!="object"||t===null)return t;let e=t,n;for(let o of F2){let r=e[o];typeof r=="string"&&(n??={...e},n[o]=Ta(r,"analytics",`metadata.${o}`,o))}return n??t}i(B2,"redactEventMetadata");var bw=class{static{i(this,"RuntimeTelemetryShipper")}#e;#t;constructor(e){this.#t={batcherMsDelay:G2,retries:3,retryDelayMs:1e3,...e},this.#e=new Be({name:"runtime-telemetry-shipper",msDelay:this.#t.batcherMsDelay,dispatchFunction:this.dispatchFunction,systemLogger:W.console})}pushMetric(e,n){let{requestContentLength:o,responseContentLength:r,...s}=e;this.#e.enqueue({kind:"metric",row:s}),n.waitUntil(this.#e.waitUntilFlushed())}pushEvents(e,n){if(e.length===0)return;let o=vo();for(let r of e){let s=sx(r);o&&(s.metadata=B2(s.metadata)),this.#e.enqueue({kind:"event",row:s})}n.waitUntil(this.#e.waitUntilFlushed())}async flush(){await this.#e.waitUntilFlushed()}dispatchFunction=i(async e=>{let n=[],o=[];for(let d of e)d.kind==="metric"?n.push(d.row):o.push(d.row);let r=FP();if(n.length===0&&o.length===0&&r.length===0)return;let{accountName:s,projectName:a,deploymentName:c}=k.instance,u={schemaVersion:1,metadata:{timestamp:new Date().toISOString(),accountName:s,projectName:a,deploymentName:c},metrics:n,events:o,features:r},l=new Headers({"content-type":"application/json"});dt(l);try{let d=await qt({retries:this.#t.retries,retryDelayMs:this.#t.retryDelayMs,logger:W.console},this.#t.endpoint,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){mR(r);let p="";try{p=(await d.text()).slice(0,500)}catch{}W.console.error(`Runtime telemetry POST responded ${d.status}: ${d.statusText}; dropped ${n.length} metric row(s) and ${o.length} analytics event(s)`,p)}}catch(d){mR(r),W.console.error(`Failed to send runtime telemetry; dropped ${n.length} metric row(s) and ${o.length} analytics event(s)`,d)}},"dispatchFunction")},ax;function co(){let t=k.instance;if(t.remoteLogURL)return ax??=new bw({endpoint:new URL(H2,t.remoteLogURL).toString()}),ax}i(co,"getRuntimeTelemetryShipper");var uo=class extends yi{static{i(this,"MetricsPlugin")}};var Ha="SYSTEM_IGNORED";var Wt=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=o,this.corsPolicy=s,this.handler={export:Ha,module:Ha},this.systemRouteName=r}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Dn=i(async(t,e,n)=>{let o=new Date,r=Date.now(),s=await n(t),a=t.headers.get(wa)??void 0,c=e.incomingRequestProperties,u=c.ip,l;e.route instanceof Wt&&(l=e.route.systemRouteName);let d=tt.getContextExtensions(e),{latestRequest:p,receivedUrl:f}=d,h={timestamp:o,statusCode:s.status,durationMs:Date.now()-r,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:s.headers.get("content-length")?Number(s.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,url:f,method:t.method,asn:c.asn,asOrganization:c.asOrganization,colo:c.colo,continent:c.continent,country:c.country,city:c.city,latitude:c.latitude,longitude:c.longitude,rayId:a,instanceId:k.instance.instanceId,userSub:p.user?.sub,clientIp:u},g=i(()=>{let{requestLogProperties:w,systemRequestLogProperties:b}=d;if(vo()){cx(Z2(h,w,b),e);return}(w.size>0||b.size>0)&&(h.properties={...Object.fromEntries(w),...Object.fromEntries(b)}),cx(h,e)},"emit");return d.deferMetrics(g)||g(),s},"metricsProcessor");function Z2(t,e,n){let o=ss(),r={...t,url:t.url===void 0?void 0:Ta(t.url,"analytics","url","url",{budget:o})};return(e.size>0||n.size>0)&&(r.properties={...cf(Object.fromEntries(e),"analytics","properties",o),...Object.fromEntries(n)}),r}i(Z2,"redactMetricsData");function cx(t,e){let n=[];!k.instance.isLocalDevelopment&&k.instance.remoteLogURL&&k.instance.remoteLogToken&&k.instance.loggingId&&co()?.pushMetric(t,e),ao.forEach(o=>{if(o instanceof uo){let r=o.getTransport();n.push(r)}}),n.forEach(o=>{o.pushMetrics(t,e)})}i(cx,"pushMetricsData");var Rw=i(t=>{let e=i(async(r,s)=>{let a=new URL(r.url),c=k.instance.build,u={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&le.getLogger(s).error("Test System Log",u),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(u,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new rn({processors:[Dn],handler:e}),o=new Wt({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,n.execute)},"registerBuildRoute");var qf=class{static{i(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let n=this.items.keys().next().value;n&&this.items.delete(n)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};function V2(t){return t==="__proto__"||t==="constructor"||t==="prototype"}i(V2,"isBlockedProperty");function J2(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}i(J2,"isPlainObject");function K2(t,e){if(t instanceof Map)return Map.prototype.get.call(t,e);if(!V2(e)&&J2(t)&&Object.hasOwn(t,e)){let n=Object.getOwnPropertyDescriptor(t,e);return n!==void 0&&"value"in n?n.value:void 0}}i(K2,"read");function ol(t,e){let n=e[t.root];for(let o=0;o<t.segments.length;o+=1){let r=t.segments[o];if(n=K2(n,r),n===void 0||Array.isArray(n)&&o<t.segments.length-1)return}return n}i(ol,"evaluate");var W2=["bodyUsed","cache","credentials","destination","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","url"];function $f(t,e){let n=e[0];return t==="request"?W2.includes(n)?e.length===1?void 0:`request.${n} is a scalar value. Remove every property after it.`:["headers","params","query","searchParams"].includes(n)?e.length===2?void 0:`request.${n} must select exactly one value. Add one key or remove trailing properties.`:n==="user"?e[1]==="sub"&&e.length===2||e[1]==="data"&&e.length>=3?void 0:"request.user selectors must choose sub or a property below data. Try request.user.sub or request.user.data.accountId.":"That request property is not selectable. Choose headers, params, query, searchParams, user, or a documented scalar request property.":["contextId","requestId"].includes(n)?e.length===1?void 0:`context.${n} is a scalar value. Remove every property after it.`:["custom","incomingRequestProperties","route"].includes(n)?e.length>=2?void 0:`context.${n} must select a property. Add the property you want to read.`:"That context property is not selectable. Choose contextId, requestId, custom, incomingRequestProperties, or route."}i($f,"validateAddress");function Df(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){if(e+1>=t.length)return e;let o=t.charCodeAt(e+1);if(o<56320||o>57343)return e;e+=1}else if(n>=56320&&n<=57343)return e}}i(Df,"firstIllFormedPosition");var Y2=/^[A-Za-z_][A-Za-z0-9_]*$/,ux=32;function lx(t){if(t.length===0||Df(t)!==void 0||t.includes('"')||t.includes("\\"))throw new TypeError("Selector keys must be non-empty, valid UTF-8, and cannot contain double quotes or backslashes. Choose a well-formed key representable without string escapes.");for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n<=31||n>=127&&n<=159||n===8232||n===8233)throw new TypeError("Selector keys cannot contain control characters, U+2028, or U+2029. Remove that character from the key.")}}i(lx,"assertRepresentableString");function dx(t){if(t.segments.length===0||t.segments.length>ux)throw new TypeError(`Selectors need between 1 and ${ux} segments. Add a property segment or shorten the selector.`);let e=$f(t.root,t.segments);if(e!==void 0)throw new TypeError(e);let n=t.root;if(t.root==="request"&&t.segments[0]==="headers"){if(t.segments.length!==2)throw new TypeError("Header selectors need exactly one header-name segment after request.headers.");lx(t.segments[1]),n=`request.headers.get("${t.segments[1].toLowerCase()}")`}else for(let o of t.segments)lx(o),n+=Y2.test(o)?`.${o}`:`["${o}"]`;if(new TextEncoder().encode(n).byteLength>1024)throw new TypeError("Rendered selectors cannot exceed 1024 UTF-8 bytes. Shorten one or more property names.");return n}i(dx,"render");var Q2=["request","context"],X2=/^[A-Za-z_$][A-Za-z0-9_$-]*$/,px=32,mx=1024;function Bt(t,e){return{error:!0,position:t,message:e}}i(Bt,"failure");function hx(t,e){let n=t[e];if(n!=='"'&&n!=="'")return Bt(e,"Expected a quoted property name. Add a non-empty single- or double-quoted string.");let o="";for(let r=e+1;r<t.length;r+=1){let s=t[r],a=t.charCodeAt(r);if(s===n)return o.length===0?Bt(r,"Selector property names cannot be empty. Put a non-empty key between the quotes."):{value:o,next:r+1};if(s==="\\")return Bt(r,"Selector strings do not support escapes. Use a property name without a backslash.");if(n==="'"&&s==='"')return Bt(r,"Selector keys cannot contain double quotes because canonical rendering has no escapes. Use a key without double quotes.");if(a<=31||a>=127&&a<=159||a===8232||a===8233)return Bt(r,"Selector strings cannot contain control characters, U+2028, or U+2029. Remove that character from the key.");o+=s}return Bt(t.length,`Unterminated ${n} string. Add the matching closing quote.`)}i(hx,"parseString");function eV(t){return t===" "||t===" "||t===`
|
|
39
|
+
`),Q(Y.text),Y.terminate){A("SSE stream terminated by its rewriter"),M.close();return}}p=!0,M.close();return}if(F)return}}catch(D){p||(A(D),(M.desiredSize??0)<0?v={error:D}:M.error(D))}},cancel(M){if(!p)return p=!0,u.abort(M),d.cancel(M)}},{highWaterMark:0})}i(KZ,"rewriteSseStream");function WZ(t){if(t.length===1)return t[0];let e=new Uint8Array(t.reduce((o,r)=>o+r.length,0)),n=0;for(let o of t)e.set(o,n),n+=o.length;return e}i(WZ,"concatBytes");function nle(t,e,n){if(t.body===null)return t;let o=Pf(new Headers(t.headers));return o.set("content-type","text/event-stream"),new Response(KZ(t.body,e,n),{status:t.status,statusText:t.statusText,headers:o})}i(nle,"rewriteSseResponse");var YZ={0:0,1:0,2:1,3:2,4:4,5:8,8:8,9:16},QZ=6,C_=7;function XZ(t){let e={},n=new DataView(t.buffer,t.byteOffset,t.byteLength),o=new TextDecoder,r=0;for(;r<t.byteLength;){let s=n.getUint8(r);if(r+=1,r+s+1>t.byteLength)return e;let a=o.decode(t.subarray(r,r+s));r+=s;let c=n.getUint8(r);if(r+=1,c===C_||c===QZ){if(r+2>t.byteLength)return e;let l=n.getUint16(r,!1);if(r+=2,r+l>t.byteLength)return e;c===C_&&(e[a]=o.decode(t.subarray(r,r+l))),r+=l;continue}let u=YZ[c];if(u===void 0)return e;r+=u}return e}i(XZ,"readEventStreamHeaders");function xf(){let t=[],e=0,n=!1,o=i(s=>{let a=0,c=4,u=s;for(let l of t){if(u>=l.byteLength){u-=l.byteLength;continue}for(let d=u;d<l.byteLength&&c>0;d++)a=(a<<8|l[d])>>>0,c--;if(u=0,c===0)break}return a},"peekUint32"),r=i(s=>{let a=new Uint8Array(s),c=0,u=0;for(;c<s;){let l=t[u],d=s-c;l.byteLength<=d?(a.set(l,c),c+=l.byteLength,u++):(a.set(l.subarray(0,d),c),c+=d,t[u]=l.subarray(d))}return u>0&&t.splice(0,u),e-=s,a},"takeFrame");return s=>{if(n||s.byteLength===0)return[];t.push(s),e+=s.byteLength;let a=[];for(;e>=12;){let c=o(0),u=o(4);if(c<16||c>16777216||u>c-16)return n=!0,t=[],e=0,a;if(e<c)break;let l=r(c);a.push({headers:XZ(l.subarray(12,12+u)),payload:l.subarray(12+u,c-4)})}return a}}i(xf,"createEventStreamFramer");function Ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(Ze,"isRecord");function De(t){return typeof t=="string"?t:void 0}i(De,"asString");function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Vn,"asFiniteNumber");function Jn(t){let e=Vn(t);return e!==void 0&&Number.isInteger(e)?e:void 0}i(Jn,"asInteger");function Of(t){if(typeof t=="string")return[t];if(Array.isArray(t)&&t.every(e=>typeof e=="string"))return t}i(Of,"asStringArray");function Pr(...t){for(let e of t)if(e!==void 0)return e}i(Pr,"firstDefined");function Yu(t,e){if(t.length<=e)return t;let n=Math.max(0,e);if(n>0){let o=t.charCodeAt(n-1);o>=55296&&o<=56319&&(n-=1)}return t.slice(0,n)}i(Yu,"truncateUtf16");function Wu(t,e){if(typeof t=="string")return Yu(t,e);if(Array.isArray(t))return t.map(n=>Wu(n,e));if(Ze(t)){let n={};for(let[o,r]of Object.entries(t))n[o]=Wu(r,e);return n}return t}i(Wu,"clipStrings");var e2=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,"[REDACTED:private_key]"],[/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[REDACTED:jwt]"],[/\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]{16,}=*/gi,"$1 [REDACTED]"],[/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:api_key]"],[/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,"[REDACTED:aws_access_key]"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"[REDACTED:google_api_key]"],[/\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g,"[REDACTED:github_token]"],[/\bxox[abposr]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack_token]"],[/\bzpka_[A-Za-z0-9_]{20,}/g,"[REDACTED:zuplo_api_key]"]];function t2(t){let e=t;for(let[n,o]of e2)e=e.replace(n,o);return e}i(t2,"redactSecrets");var n2=1024;function nw(t,e){if(typeof t=="string")return Yu(t2(Yu(t,e+n2)),e);if(Array.isArray(t))return t.map(n=>nw(n,e));if(Ze(t)){let n={};for(let[o,r]of Object.entries(t))n[o]=nw(r,e);return n}return t}i(nw,"redactAndCap");function Mf(t){try{return JSON.stringify(t)}catch{return}}i(Mf,"stringifyOrUndefined");function T_(t,e,n){let o=t.map(p=>nw(p,e)),r=Mf(o);if(r===void 0)return;if(r.length<=e)return r;let s=n==="first"?o:[...o].reverse(),a=[],c=2;for(let p of s){let f=(Mf(Wu(p,0))??"").length+1;if(c+f>e)break;c+=f,a.push(p)}n==="last"&&a.reverse();let u=0,l=e,d=Mf(Wu(a,0))??"[]";for(;u<=l;){let p=Math.floor((u+l)/2),f=Mf(Wu(a,p))??"";f.length<=e?(d=f,u=p+1):l=p-1}return d}i(T_,"serializeWithinBudget");function A_(t){let e;if(typeof t=="string"?e=t:t instanceof Uint8Array?e=new TextDecoder().decode(t):t instanceof ArrayBuffer&&(e=new TextDecoder().decode(new Uint8Array(t))),e!==void 0)try{return JSON.parse(e)}catch{return}}i(A_,"parseUpstreamRequestBody");function I_(t){if(!Ze(t))return{};let e=Ze(t.inferenceConfig)?t.inferenceConfig:{},n=Ze(t.generationConfig)?t.generationConfig:{},o={},r=i((a,c)=>{c!==void 0&&(o[a]=c)},"set");r("gen_ai.request.max_tokens",Pr(Jn(t.max_tokens),Jn(t.max_completion_tokens),Jn(t.max_output_tokens),Jn(e.maxTokens),Jn(n.maxOutputTokens))),r("gen_ai.request.temperature",Pr(Vn(t.temperature),Vn(e.temperature),Vn(n.temperature))),r("gen_ai.request.top_p",Pr(Vn(t.top_p),Vn(e.topP),Vn(n.topP))),r("gen_ai.request.top_k",Pr(Vn(t.top_k),Vn(n.topK))),r("gen_ai.request.stop_sequences",Pr(Of(t.stop),Of(t.stop_sequences),Of(e.stopSequences),Of(n.stopSequences))),r("gen_ai.request.frequency_penalty",Pr(Vn(t.frequency_penalty),Vn(n.frequencyPenalty))),r("gen_ai.request.presence_penalty",Pr(Vn(t.presence_penalty),Vn(n.presencePenalty))),r("gen_ai.request.seed",Pr(Jn(t.seed),Jn(n.seed)));let s=Pr(Jn(t.n),Jn(n.candidateCount));return s!==void 0&&s!==1&&(o["gen_ai.request.choice.count"]=s),o}i(I_,"readRequestParameterAttributes");function Na(t){return{type:"text",content:t}}i(Na,"textPart");function el(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(el,"parseArguments");function Ko(t){if(typeof t=="string")return[Na(t)];if(!Array.isArray(t))return[];let e=[];for(let n of t){if(typeof n=="string"){e.push(Na(n));continue}if(!Ze(n))continue;let o=De(n.type),r=De(n.text);if(r!==void 0&&(o===void 0||o==="text"||o==="input_text"||o==="output_text")){e.push(Na(r));continue}if(o==="tool_use"){e.push({type:"tool_call",id:De(n.id),name:De(n.name),arguments:n.input});continue}if(o==="tool_result"){e.push({type:"tool_call_response",id:De(n.tool_use_id),response:n.content});continue}if(Ze(n.toolUse)){e.push({type:"tool_call",id:De(n.toolUse.toolUseId),name:De(n.toolUse.name),arguments:n.toolUse.input});continue}if(Ze(n.toolResult)){e.push({type:"tool_call_response",id:De(n.toolResult.toolUseId),response:n.toolResult.content});continue}if(Ze(n.functionCall)){e.push({type:"tool_call",name:De(n.functionCall.name),arguments:n.functionCall.args});continue}if(Ze(n.functionResponse)){e.push({type:"tool_call_response",id:De(n.functionResponse.id),response:n.functionResponse.response});continue}if(o==="thinking"&&typeof n.thinking=="string"){e.push({type:"reasoning",content:n.thinking});continue}e.push({type:o??"unknown"})}return e}i(Ko,"toParts");function E_(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!Ze(n))continue;let o=Ze(n.function)?n.function:{};e.push({type:"tool_call",id:De(n.id),name:De(o.name),arguments:el(o.arguments)})}return e}i(E_,"toOpenAiToolCallParts");function Qu(t){return t==="model"?"assistant":De(t)??"user"}i(Qu,"normalizeRole");function v_(t,e){let n=[];for(let o of t){if(!Ze(o))continue;let r=De(o.role);if(r==="system"||r==="developer"){e.push(...Ko(o.content));continue}if(r==="tool"){n.push({role:"tool",parts:[{type:"tool_call_response",id:De(o.tool_call_id),response:o.content}]});continue}let s=[...Ko(o.content??o.parts),...E_(o.tool_calls)],a={role:Qu(r),parts:s},c=De(o.name);c!==void 0&&(a.name=c),n.push(a)}return n}i(v_,"readChatMessages");function o2(t){if(typeof t=="string")return[{role:"user",parts:[Na(t)]}];if(!Array.isArray(t))return[];let e=[];for(let n of t)if(Ze(n)){if(n.type==="function_call"){e.push({role:"assistant",parts:[{type:"tool_call",id:De(n.call_id),name:De(n.name),arguments:el(n.arguments)}]});continue}if(n.type==="function_call_output"){e.push({role:"tool",parts:[{type:"tool_call_response",id:De(n.call_id),response:n.output}]});continue}n.role!==void 0&&e.push({role:Qu(n.role),parts:Ko(n.content)})}return e}i(o2,"readResponsesInput");function P_(t){if(!Ze(t))return;let e=[];t.system!==void 0&&e.push(...Ko(t.system)),typeof t.instructions=="string"&&e.push(Na(t.instructions)),Ze(t.systemInstruction)&&e.push(...Ko(t.systemInstruction.parts));let n;if(Array.isArray(t.messages)?n=v_(t.messages,e):Array.isArray(t.contents)?n=v_(t.contents,e):t.input!==void 0&&t.model!==void 0&&(n=o2(t.input)),!(n===void 0&&e.length===0))return{systemInstructions:e,messages:n??[]}}i(P_,"readInputContent");function r2(t){let e=Ze(t.message)?t.message:{},n=[...Ko(e.content),...E_(e.tool_calls)];return{role:Qu(e.role??"assistant"),parts:n,finish_reason:De(t.finish_reason)??""}}i(r2,"readOpenAiChoiceOutput");function k_(t){if(!Array.isArray(t.output))return[];let e=[];for(let n of t.output)Ze(n)&&(n.type==="message"?e.push(...Ko(n.content)):n.type==="function_call"&&e.push({type:"tool_call",id:De(n.call_id),name:De(n.name),arguments:el(n.arguments)}));return[{role:"assistant",parts:e,finish_reason:ow(t)??""}]}i(k_,"readResponsesOutput");function ow(t){return(Ze(t.incomplete_details)?De(t.incomplete_details.reason):void 0)??De(t.status)}i(ow,"responsesFinishReason");function rw(t){let e={finishReasons:[]};if(!Ze(t))return e;if(e.id=De(t.id)??De(t.responseId),e.model=De(t.model)??De(t.modelVersion),Array.isArray(t.choices))for(let n of t.choices){let o=Ze(n)?De(n.finish_reason):void 0;o!==void 0&&e.finishReasons.push(o)}else if(Array.isArray(t.candidates))for(let n of t.candidates){let o=Ze(n)?De(n.finishReason):void 0;o!==void 0&&e.finishReasons.push(o)}else if(typeof t.stop_reason=="string")e.finishReasons.push(t.stop_reason);else if(typeof t.stopReason=="string")e.finishReasons.push(t.stopReason);else if(t.object==="response"){let n=ow(t);n!==void 0&&e.finishReasons.push(n)}return e}i(rw,"readResponseFields");function __(t){if(Ze(t)){if(Array.isArray(t.choices))return t.choices.filter(Ze).map(r2);if(Array.isArray(t.candidates))return t.candidates.filter(Ze).map(e=>({role:"assistant",parts:Ko(Ze(e.content)?e.content.parts:void 0),finish_reason:De(e.finishReason)??""}));if(t.object==="response")return k_(t);if(t.type==="message"&&Array.isArray(t.content))return[{role:Qu(t.role??"assistant"),parts:Ko(t.content),finish_reason:De(t.stop_reason)??""}];if(Ze(t.output)&&Ze(t.output.message))return[{role:Qu(t.output.message.role??"assistant"),parts:Ko(t.output.message.content),finish_reason:De(t.stopReason)??""}]}}i(__,"readOutputMessages");function i2(t,e){let n=e,o=i(r=>{let s=Yu(r,n);return n-=s.length,s},"take");return t.map(r=>({...r,parts:r.parts.map(s=>{let a={...s};return typeof s.content=="string"&&(a.content=o(s.content)),typeof s.arguments=="string"?a.arguments=o(s.arguments):s.arguments!==void 0&&(a.arguments=el(o(JSON.stringify(s.arguments)??""))),a})}))}i(i2,"clipMessages");var Xu=class{static{i(this,"StreamResponseAccumulator")}fields={finishReasons:[]};#e=new Map;#t;#o;#n=0;#r;errorType;constructor(e){this.#t=e.captureOutput,this.#o=e.maxOutputLength}#i(e){let n=this.#e.get(e);return n||(n={text:"",toolCalls:new Map},this.#e.set(e,n)),n}#s(e,n){if(!this.#t||this.#n>=this.#o)return;let o=this.#o-this.#n,r=n.length>o?n.slice(0,o):n;e.text+=r,this.#n+=r.length}#a(e,n){let o=e.toolCalls.get(n);return o||(o={arguments:""},e.toolCalls.set(n,o)),o}#c(e,n){if(!this.#t||this.#n>=this.#o)return;let o=this.#o-this.#n,r=n.length>o?n.slice(0,o):n;e.arguments+=r,this.#n+=r.length}observe(e){if(!Ze(e))return;if(typeof e.exceptionType=="string"){this.errorType??=e.exceptionType;return}if(typeof e.eventType=="string"){this.#l(e.eventType,e.body);return}if(Array.isArray(e.choices)){this.#u(e);return}let n=De(e.type);if(n==="error"||n===void 0&&Ze(e.error)){let o=Ze(e.error)?e.error:e;this.errorType??=De(o.type)??De(o.code)??(typeof o.code=="number"?String(o.code):void 0)??"error";return}if(n!==void 0){if(n.startsWith("response.")){this.#d(n,e);return}this.#p(n,e)}}#u(e){this.fields.id??=De(e.id),this.fields.model??=De(e.model);for(let n of e.choices){if(!Ze(n))continue;let o=this.#i(Jn(n.index)??0),r=De(n.finish_reason);r!==void 0&&(o.finishReason=r);let s=Ze(n.delta)?n.delta:void 0;if(s&&(typeof s.content=="string"&&this.#s(o,s.content),Array.isArray(s.tool_calls)))for(let a of s.tool_calls){if(!Ze(a))continue;let c=this.#a(o,Jn(a.index)??0);c.id??=De(a.id);let u=Ze(a.function)?a.function:{};c.name??=De(u.name),typeof u.arguments=="string"&&this.#c(c,u.arguments)}}}#p(e,n){let o=this.#i(0);if(e==="message_start"&&Ze(n.message)){this.fields.id??=De(n.message.id),this.fields.model??=De(n.message.model);return}if(e==="message_delta"&&Ze(n.delta)){let s=De(n.delta.stop_reason);s!==void 0&&(o.finishReason=s);return}let r=Jn(n.index)??0;if(e==="content_block_start"&&Ze(n.content_block)){let s=n.content_block;if(s.type==="tool_use"){let a=this.#a(o,r);a.id=De(s.id),a.name=De(s.name)}else typeof s.text=="string"&&this.#s(o,s.text);return}if(e==="content_block_delta"&&Ze(n.delta)){let s=n.delta;typeof s.text=="string"?this.#s(o,s.text):typeof s.partial_json=="string"&&this.#c(this.#a(o,r),s.partial_json)}}#d(e,n){let o=Ze(n.response)?n.response:void 0;if(o&&(this.fields.id??=De(o.id),this.fields.model??=De(o.model)),o&&(e==="response.completed"||e==="response.incomplete"||e==="response.failed")){let r=ow(o);if(r!==void 0&&(this.#i(0).finishReason=r),e==="response.failed"){let s=Ze(o.error)?o.error:{};this.errorType??=De(s.code)??"response.failed"}this.#t&&(this.#r=i2(k_(o),this.#o));return}e==="response.output_text.delta"&&typeof n.delta=="string"&&this.#s(this.#i(0),n.delta)}#l(e,n){if(e==="chunk"){let s=s2(n);Ze(s)&&typeof s.eventType!="string"&&this.observe(s);return}if(!Ze(n))return;let o=this.#i(0);if(e==="messageStop"){let s=De(n.stopReason);s!==void 0&&(o.finishReason=s);return}let r=Jn(n.contentBlockIndex)??0;if(e==="contentBlockStart"&&Ze(n.start)){if(Ze(n.start.toolUse)){let s=this.#a(o,r);s.id=De(n.start.toolUse.toolUseId),s.name=De(n.start.toolUse.name)}return}e==="contentBlockDelta"&&Ze(n.delta)&&(typeof n.delta.text=="string"?this.#s(o,n.delta.text):Ze(n.delta.toolUse)&&typeof n.delta.toolUse.input=="string"&&this.#c(this.#a(o,r),n.delta.toolUse.input))}finishReasons(){return this.fields.finishReasons.length>0?this.fields.finishReasons:[...this.#e.entries()].sort(([e],[n])=>e-n).map(([,e])=>e.finishReason).filter(e=>e!==void 0)}outputMessages(){if(this.#t){if(this.#r)return this.#r;if(this.#e.size!==0)return[...this.#e.entries()].sort(([e],[n])=>e-n).map(([,e])=>{let n=[];e.text.length>0&&n.push(Na(e.text));for(let[,o]of[...e.toolCalls.entries()].sort(([r],[s])=>r-s))n.push({type:"tool_call",id:o.id,name:o.name,arguments:el(o.arguments)});return{role:"assistant",parts:n,finish_reason:e.finishReason??""}})}}};function s2(t){let e=Ze(t)?t.bytes:void 0;if(typeof e=="string")try{let n=atob(e),o=new Uint8Array(n.length);for(let r=0;r<n.length;r++)o[r]=n.charCodeAt(r);return JSON.parse(new TextDecoder().decode(o))}catch{return}}i(s2,"decodeBedrockInvokeChunk");var l2="ai-gateway",L_=8*1024,d2=3e4,p2=1024*1024,m2={openai:"openai","openai-codex-backend":"openai",anthropic:"anthropic",google:"gcp.gemini","vertex-ai":"gcp.vertex_ai","bedrock-runtime":"aws.bedrock","bedrock-mantle":"aws.bedrock",mistral:"mistral_ai",xai:"x_ai"};function f2(t,e=!1){let n=t.toLowerCase();return n==="azure-ai"?e?"azure.ai.openai":"azure.ai.inference":m2[n]??n}i(f2,"toGenAiProviderName");function iw(t,e){return T_(t,L_,e)}i(iw,"serializeContent");var aw=!1;function N_(t){aw=t}i(N_,"setGenAiContentCapture");var x_;function h2(){return x_??=M_.getTracer(l2),x_}i(h2,"getTracer");var U_=new ge(Symbol("zuplo.ai_gateway.entry_span"));function q_(t,e){e.isRecording()&&U_.set(t,e)}i(q_,"setRequestEntrySpan");function $_(t){let e=U_.get(t);return e?.isRecording()?e:void 0}i($_,"getEntrySpan");function D_(t){return $_(t)!==void 0}i(D_,"isEntrySpanRecording");function qa(t,e){$_(t)?.setAttributes(e)}i(qa,"setAiGatewayEntryAttributes");function cw(t,e,n){let o=Da(t);o.refusedBy!==void 0&&n?.replacesEarlier!==!0||(o.refusedBy=e,qa(t,{"zuplo.ai_gateway.refused_by":e}))}i(cw,"recordAiGatewayRefusal");function $a(t,e,n,o){!z_(t)||!D_(t)||n.status>=400&&cw(t,e,o)}i($a,"noteInboundPolicyResponse");async function Lf(t,e){if(!z_(t)||!D_(t))return;let n=Da(t);if(!n.requestedModelRead){n.requestedModelRead=!0;try{let o=await Vo(e);typeof o.value=="string"&&o.value!==""&&qa(t,{"gen_ai.request.model":o.value})}catch{}}}i(Lf,"recordRequestedModel");var g2=new Set(["aiGatewayHandler","aiGatewayHandlerV2"]);function z_(t){return g2.has(t.route?.handler?.export??"")}i(z_,"isAiGatewayRoute");var Ua=new ge(Symbol("zuplo.ai_gateway.genai_state"));function Da(t){let e=Ua.get(t);return e||(e={startedAttempts:0},Ua.set(t,e)),e}i(Da,"getRequestState");function j_(t,e){Da(t).operationName=e}i(j_,"setGenAiOperation");function H_(t){return(Ua.get(t)?.startedAttempts??0)>0}i(H_,"hasInferenceAttempt");function y2(t){let e={"gen_ai.usage.input_tokens":t.promptTokens,"gen_ai.usage.output_tokens":t.completionTokens,"zuplo.ai_gateway.cost.usd":t.cost,"zuplo.ai_gateway.cost.source":t.costSource,"zuplo.ai_gateway.cost.accuracy":t.costAccuracy},n=t.canonicalUsage;return n?.cacheReadInputTokens!==void 0&&(e["gen_ai.usage.cache_read.input_tokens"]=n.cacheReadInputTokens),n!==void 0&&n.cacheWriteInput.length>0&&(e["gen_ai.usage.cache_write.input_tokens"]=n.cacheWriteInput.reduce((o,r)=>o+r.tokens,0)),n?.reasoningOutputTokens!==void 0&&(e["gen_ai.usage.reasoning.output_tokens"]=n.reasoningOutputTokens),e}i(y2,"usageAttributes");function b2(t,e){return e?"timeout":t instanceof Error&&"status"in t&&typeof t.status=="number"?String(t.status):t instanceof Error?t.name||"Error":"_OTHER"}i(b2,"errorTypeOf");function R2(t){return(t.headers.get("content-type")??"").toLowerCase().includes("json")}i(R2,"isJsonResponse");var sw=class{static{i(this,"InferenceAttempt")}span;recording;#e;#t;#o=!1;#n=!1;#r=!1;#i=!1;#s=!1;#a;#c=!1;#u;#p;#d;#l;#m;#y;#b=!1;constructor(e,n,o,r,s,a){this.#e=e,this.#t=r;let c=n.requestModel,u={"gen_ai.operation.name":r,"gen_ai.provider.name":f2(n.providerType,n.azureOpenAiSurface),"gen_ai.request.stream":n.stream,"zuplo.ai_gateway.attempt":o,"zuplo.ai_gateway.provider.label":n.providerLabel};c&&(u["gen_ai.request.model"]=c),a&&(u["server.address"]=a.hostname,u["server.port"]=a.port?Number(a.port):a.protocol==="http:"?80:443),this.span=h2().startSpan(c?`${r} ${c}`:r,{kind:c2.CLIENT,attributes:u},s),this.recording=this.span.isRecording();let l=this.recording&&aw;this.#u=l&&r!=="embeddings",this.#p=l&&r!=="embeddings"&&r!=="count_tokens"&&r!=="delete_response",this.#p&&(Da(e).captureOutput=!0,this.#d=new Promise(d=>{this.#l=d}))}get capturesOutput(){return this.#p&&!this.#s&&!this.#n}get ended(){return this.#o}markTimedOut(){this.#i=!0}noteUpstreamRequest(e){if(this.#a!==void 0||(this.#a=performance.now(),!this.recording))return;let n=A_(e);if(n===void 0)return;this.span.setAttributes(I_(n));let o=n.stream;typeof o=="boolean"&&this.span.setAttribute("gen_ai.request.stream",o),this.#u&&this.#R(P_(n))}async noteUpstreamResponse(e){if(!(this.#b||!this.recording||!e.ok||this.#t==="embeddings"||!R2(e))){this.#b=!0;try{this.#y=rw(await e.clone().json())}catch{}}}#R(e){if(!e)return;if(e.systemInstructions.length>0){let o=iw(e.systemInstructions,"first");o!==void 0&&this.span.setAttribute("gen_ai.system_instructions",o)}let n=iw(e.messages,"last");n!==void 0&&this.span.setAttribute("gen_ai.input.messages",n)}setOutputMessages(e){if(this.#p&&e!==void 0&&!this.#n){let n=iw(e,"first");n!==void 0&&this.span.setAttribute("gen_ai.output.messages",n)}this.#l?.()}observeResponseBody(e){if(!this.recording)return;let n=rw(e),o=this.#y;this.#f(o?.id??n.id,o?.model??n.model,o!==void 0&&o.finishReasons.length>0?o.finishReasons:n.finishReasons)}#f(e,n,o){e!==void 0&&this.span.setAttribute("gen_ai.response.id",e),n!==void 0&&this.span.setAttribute("gen_ai.response.model",n),o.length>0&&this.span.setAttribute("gen_ai.response.finish_reasons",o)}setUsage(e){if(!this.recording)return;let n=y2(e);this.#t==="embeddings"&&delete n["gen_ai.usage.output_tokens"],this.span.setAttributes(n)}failStatus(e){this.#g(String(e))}fail(e){this.#g(b2(e,this.#i))}#g(e){this.#o||(this.#s=!0,this.span.setAttribute("error.type",e),this.span.setStatus({code:u2.ERROR}),this.#l?.())}claimForStream(){this.#r=!0,this.recording&&(this.#m=new Xu({captureOutput:!1,maxOutputLength:0}))}get claimed(){return this.#r}noteStreamChunk(){this.#c||(this.#c=!0,this.recording&&this.#a!==void 0&&this.span.setAttribute("gen_ai.response.time_to_first_chunk",(performance.now()-this.#a)/1e3))}observeStreamEvent(e){this.#m?.observe(e)}get observesStream(){return this.#m!==void 0}end(e,n){if(this.#o)return;if(e!==void 0){let a=e;if(this.#m){let c=this.#m.fields;this.#f(c.id,c.model,this.#m.finishReasons());let u=this.#m.errorType;a!=="error"&&u!==void 0&&(a="error",this.#g(u))}this.span.setAttribute("zuplo.ai_gateway.stream.end",a),a==="error"&&!this.#s&&this.fail(n)}if(this.#o=!0,this.#d===void 0||this.#s){this.#h();return}let o=new Date,r,s=new Promise(a=>{r=setTimeout(a,d2)});this.#e.waitUntil(Promise.race([this.#d,s]).then(()=>{clearTimeout(r),this.#h(o)}))}#h(e){this.#n||(this.#n=!0,this.span.end(e))}outputSettled(){this.#l?.()}get operationName(){return this.#t}},uw=new a2;async function G_(t,e,n,o){let r=Da(t);r.pending&&(r.pending.end(),r.pending=void 0);let s={context:t,input:e,kind:n,parent:O_.active(),open:!0},a;try{a=await uw.run(s,o)}catch(u){throw s.open=!1,s.attempt?.fail(u),s.attempt?.end(),u}s.open=!1;let c=s.attempt;return!c||c.claimed?a:a instanceof Response&&!a.ok?(c.failStatus(a.status),c.end(),a):(r.pending=c,a)}i(G_,"runInferenceAttempt");var w2={markTimedOut(){}};function Nf(t,e,n){let o=uw.getStore();if(!o?.open)return n(w2);let r=o.attempt;if(!r){let c=Da(o.context);r=new sw(o.context,o.input,o.kind,c.operationName??"chat",o.parent,S2(t)),o.attempt=r,c.startedAttempts+=1,c.latest?.outputSettled(),c.latest=r}let s=r;s.noteUpstreamRequest(e?.body);let a={markTimedOut:i(()=>s.markTimedOut(),"markTimedOut")};return O_.with(M_.setSpan(o.parent,s.span),async()=>{let c=await n(a);return await s.noteUpstreamResponse(c),c})}i(Nf,"withUpstreamRequest");function S2(t){try{return t instanceof URL?t:new URL(typeof t=="string"?t:t.url)}catch{return}}i(S2,"parseUrl");function F_(){let t=uw.getStore()?.attempt;if(!(!t||t.claimed||t.ended))return t.claimForStream(),t}i(F_,"claimStreamInferenceAttempt");function za(t,e,n){let o=Ua.get(t),r=o?.pending;!o||!r||(o.pending=void 0,r.observeResponseBody(e),n&&r.setUsage(n),r.end())}i(za,"completePendingInferenceAttempt");function B_(t){let e=Ua.get(t);e?.pending&&(e.pending.end(),e.pending=void 0)}i(B_,"endPendingInferenceAttempts");async function Z_(t,e){if(!aw)return e;let n=Ua.get(t);if(!n?.captureOutput)return e;n.captureOutput=!1;let o=n.latest;if(!o?.capturesOutput)return o?.outputSettled(),e;if(!e.ok||!e.body)return o.outputSettled(),e;let r=(e.headers.get("content-type")??"").toLowerCase();if(r.includes("text/event-stream")){let s=V_();return w_(e,{event(a){if(!(a.data===void 0||a.data==="[DONE]"))try{s.observe(JSON.parse(a.data))}catch{}},end(){o.setOutputMessages(s.outputMessages())}},{maxEventChars:p2})}if(r.includes("application/vnd.amazon.eventstream"))return new Response(C2(e.body,o),{status:e.status,statusText:e.statusText,headers:e.headers});try{let s=JSON.parse(await e.clone().text());o.setOutputMessages(__(s))}catch{o.outputSettled()}return e}i(Z_,"observeGenAiOutputContent");function V_(){return new Xu({captureOutput:!0,maxOutputLength:L_})}i(V_,"outputAccumulator");function C2(t,e){let n=V_(),o=xf(),r=new TextDecoder,s=t.getReader(),a=!1,c=i(()=>{a||(a=!0,e.setOutputMessages(n.outputMessages()))},"settle");return new ReadableStream({async pull(u){try{let{done:l,value:d}=await s.read();if(l){c(),u.close();return}try{for(let p of o(d))p.headers[":message-type"]==="event"&&n.observe({eventType:p.headers[":event-type"],body:JSON.parse(r.decode(p.payload))})}catch{}u.enqueue(d)}catch(l){c(),u.error(l)}},async cancel(u){c(),await s.cancel(u)}},{highWaterMark:0})}i(C2,"observeEventStream");import{trace as q2}from"@opentelemetry/api";var v2="custom";function lw(t){return t.module?.[t.export]?.handlerType??v2}i(lw,"resolveHandlerType");function J_(t,e){t.setAttribute(Ln.HandlerType,lw(e)),t.setAttribute(Ln.HandlerExport,e.export)}i(J_,"applyHandlerSpanTelemetry");import{SpanStatusCode as T2}from"@opentelemetry/api";function Wo(t,e){t.recordException(A2(e)),t.setStatus({code:T2.ERROR})}i(Wo,"recordSpanError");function A2(t){return t instanceof Error||typeof t=="string"||typeof t=="object"&&t!==null&&("message"in t||"name"in t)?t:String(t)}i(A2,"toException");function I2(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof dR)return!0;e.add(n),n=n.cause}return!1}i(I2,"hasNetworkError");function Nn(t,e,n,o){e.log.error(n,o instanceof dR?o.cause:o);let r={};if(!I2(o)&&(k.instance.isLocalDevelopment||k.instance.isWorkingCopy))if(o instanceof Z&&o.extensionMembers)r=o.extensionMembers;else if(o.cause){let s=fs(o.cause);"stack"in s&&(s.stack=FR(s.stack)),r={cause:s}}else{let s=fs(o);"stack"in s&&(s.stack=FR(s.stack)),r={cause:s}}return V.internalServerError(t,e,{detail:o.message,...r})}i(Nn,"errorHandler");import{SpanStatusCode as hw,trace as E2}from"@opentelemetry/api";var K_=i(t=>(e,n)=>t(e,n),"globalRequestHandlerProxy");function W_(t){K_=t}i(W_,"setTelemetryInitFunction");var Y_=i(t=>K_(t),"proxyHandler");var Q_,Si=i(()=>(Q_??=E2.getTracer("extension"),Q_),"tracer"),gw={},ao=[],dw=[],pw=[],mw=[],fw=[];var Uf={addPlugin(t){ao.push(t)},addRequestHook(t){dw.push(t)},addResponseSendingHook(t){pw.push(t)},addResponseSendingFinalHook(t){mw.push(t)},addPreRoutingHook(t){fw.push(t)},addTelemetryRedactor(t){WP(t)}};var ex=i(async(t,e)=>dw.length===0?t:Si().startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let r of dw){let s=await Si().startActiveSpan(r.name,async a=>{try{let c=await r(o,e);if(c instanceof Ge||c instanceof Response)return c;throw new T(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof c}.`)}catch(c){throw a.recordException(c),a.setStatus({code:hw.ERROR}),c}finally{a.end()}});if(s instanceof Ge)o=s;else return s}return o}finally{n.end()}}),"invokeOnRequestExtensions"),tx=i(async(t,e,n)=>{if(pw.length===0)return t;let o=k.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;return Si().startActiveSpan("hook:onResponseSending",async r=>{try{let s=t;for(let a of pw)await Si().startActiveSpan(a.name,async c=>{try{let u=await a(o?s:t,e,n);if(u instanceof Response)s=u;else throw new T(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof u}.`)}catch(u){throw c.recordException(u),c.setStatus({code:hw.ERROR}),u}finally{c.end()}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),nx=i(async(t,e,n)=>{if(mw.length!==0)return Si().startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let r of mw)await Si().startActiveSpan(r.name,async s=>{try{await r(t,e,n)}catch(a){throw s.recordException(a),s.setStatus({code:hw.ERROR}),s.end(),a}s.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),ox=i(async t=>fw.length===0?t:Si().startActiveSpan("hook:preRouting",async e=>{try{let n=t;for(let o of fw)n=await Si().startActiveSpan(o.name,async s=>{try{let a=await o(n);if(a instanceof Request)return a;throw new Z(`Invalid state - the PreRouting hook must return a Request. Received ${typeof a}.`)}catch(a){throw Wo(s,a),a}finally{s.end()}});return n}finally{e.end()}}),"invokePreRoutingHooks"),X_=!1;async function rx(t){if(!X_){t&&(me("runtime.extensions"),await t(Uf)),gw.value=Uf;for(let e of ao)if(e instanceof ms){let n=e.instrument({accountName:k.instance.accountName,projectName:k.instance.projectName,buildId:k.instance.build.BUILD_ID,zuploVersion:k.instance.build.ZUPLO_VERSION,compatibilityDate:k.instance.build.COMPATIBILITY_DATE,instanceId:k.instance.instanceId,environmentType:k.instance.loggingEnvironmentType,environmentStage:k.instance.loggingEnvironmentStage,deploymentName:k.instance.deploymentName,__internalOnlyRemoteLogUrl:k.instance.remoteLogURL,__internalOnlyRemoteLogToken:k.instance.remoteLogToken});W_(n.requestHandlerProxy),N_(n.__internalOnlyGenAiCaptureContent===!0)}await Promise.all(ao.map(async e=>{e instanceof $t&&await e.initialize(Uf)})),Fu.setProblemResponseFormat(Uf.problemResponseFormat),YP(),X_=!0}}i(rx,"initializeRuntime");var $={AI_GATEWAY_COST_SUM:"ai_gateway_cost_sum",AI_GATEWAY_REQUEST_COUNT:"ai_gateway_request_count",AI_GATEWAY_TOKEN_SUM:"ai_gateway_token_sum",AI_GATEWAY_LATENCY_HISTOGRAM:"ai_gateway_latency_histogram",AI_GATEWAY_WARNING_COUNT:"ai_gateway_warning_count",AI_GATEWAY_BLOCKED_COUNT:"ai_gateway_blocked_count",AI_GATEWAY_FALLBACK_COUNT:"ai_gateway_fallback_count",MCP_REQUEST_RECEIVED:"mcp_request_received",MCP_REQUEST_COMPLETED:"mcp_request_completed",MCP_REQUEST_REJECTED:"mcp_request_rejected",MCP_INITIALIZE_NEGOTIATED:"mcp_initialize_negotiated",MCP_CLIENT_UNSUPPORTED_BEHAVIOR:"mcp_client_unsupported_behavior",MCP_CAPABILITY_LISTED:"mcp_capability_listed",MCP_CAPABILITY_INVOKED:"mcp_capability_invoked",MCP_CAPABILITY_COMPLETED:"mcp_capability_completed",MCP_CAPABILITY_FAILED:"mcp_capability_failed",MCP_CAPABILITY_CONNECT_REQUIRED:"mcp_capability_connect_required",MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED:"mcp_auth_downstream_token_validated",MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED:"mcp_auth_downstream_token_rejected",MCP_OAUTH_CLIENT_REGISTERED:"mcp_oauth_client_registered",MCP_OAUTH_AUTHORIZE_STARTED:"mcp_oauth_authorize_started",MCP_OAUTH_AUTHORIZE_AWAITING_SETUP:"mcp_oauth_authorize_awaiting_setup",MCP_OAUTH_TOKEN_ISSUED:"mcp_oauth_token_issued",MCP_OAUTH_TOKEN_REFRESH_ROTATED:"mcp_oauth_token_refresh_rotated",MCP_OAUTH_TOKEN_REVOKED:"mcp_oauth_token_revoked",MCP_AUTH_UPSTREAM_CONNECT_REQUIRED:"mcp_auth_upstream_connect_required",MCP_AUTH_UPSTREAM_CONNECT_STARTED:"mcp_auth_upstream_connect_started",MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED:"mcp_auth_upstream_callback_received",MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED:"mcp_auth_upstream_token_exchange_succeeded",MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED:"mcp_auth_upstream_token_exchange_failed",MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED:"mcp_auth_upstream_credential_resolved",MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING:"mcp_auth_upstream_credential_missing",MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED:"mcp_auth_upstream_reconsent_required",GRAPHQL_OPERATION:"graphql_operation",CACHE_OPERATION:"cache_operation",HANDLER_EXECUTION:"handler_execution",RATE_LIMIT_SERVICE_CALL:"rate_limit_service_call"};var P2=new Set([408,504]),k2=new Set(["TimeoutError","AbortError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError"]),_2=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ETIMEDOUT"]),x2=5;function O2(t){let e=t;for(let n=0;n<=x2;n++){if(typeof e!="object"||e===null)return!1;let o=e;if(typeof o.name=="string"&&k2.has(o.name)||typeof o.code=="string"&&_2.has(o.code))return!0;e=e.cause}return!1}i(O2,"isTimeoutError");function M2(t,e){return e?O2(e.thrown)?"timeout":"exception":t===null?"success":P2.has(t)?"timeout":t>=500?"server-error":t>=400?"client-error":"success"}i(M2,"classifyHandlerResult");function yw(t,e,n){try{let o={handlerType:lw(n.handler),handlerExport:n.handler.export,result:M2(n.statusCode,n.error),statusCode:n.statusCode,latencyMs:n.latencyMs,...L2(t),routePath:N2(e),method:t.method,errorName:U2(n.error)};e.analyticsContext.addAnalyticsEvent(1,$.HANDLER_EXECUTION,o,"count")}catch(o){try{le.getLogger(e).error(o,"Error emitting handler_execution analytics event")}catch{}}}i(yw,"emitHandlerExecution");function L2(t){try{let e=new URL(t.url);return{hostname:e.hostname===""?null:e.hostname,port:e.port===""?null:Number(e.port),scheme:e.protocol===""?null:e.protocol.replace(/:$/,"")}}catch{return{hostname:null,port:null,scheme:null}}}i(L2,"readUrlDimensions");function N2(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}i(N2,"readRoutePath");function U2(t){if(!t)return null;let e=t.thrown;if(typeof e=="object"&&e!==null){let n=e.name;if(typeof n=="string"&&n.length>0)return n}return null}i(U2,"readErrorName");function ja(t){let{developerPortal:e}=nt.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(ja,"isSystemRoute");var ix,$2=i(()=>(ix??=q2.getTracer("pipeline"),ix),"tracer"),rn=class{static{i(this,"Pipeline")}constructor(e){this.execute=D2(this.#t(e))}execute;#e=i((e,n)=>async(o,r)=>$2().startActiveSpan(`handler:${r.route.handler.export}`,async s=>{J_(s,r.route.handler);let a=performance.now();try{let c=await e(o,r);return n&&yw(o,r,{handler:r.route.handler,latencyMs:performance.now()-a,statusCode:c.status,error:null}),c}catch(c){let u=performance.now()-a,l=await Nn(o,r,"Error executing request handler.",c);return Wo(s,c),n&&yw(o,r,{handler:r.route.handler,latencyMs:u,statusCode:l.status,error:{thrown:c}}),l}finally{s.end()}}),"#errorWrappedHandler");#t=i(({processors:e,handler:n,emitHandlerAnalytics:o=!1})=>async(r,s)=>{let a=tt.getContextExtensions(s),c=[...e],u=i(async b=>{let S=c.pop();if(!S){let A=await this.#e(async E=>{let P=await n(E,s),N=j2(P);return z2(N,s),N},o)(b,s);try{await a.onHandlerResponse(A,b,s)}catch(E){return Nn(r,s,"Error invoking 'context.onHandlerResponse' hook",E)}return A}return S(b,s,u)},"nextPipe"),d=await u(r),p=new URL(r.url);if(ja(p)&&k.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let f=new tl(r,d);s.dispatchEvent(f);let h=a.latestRequest,g;try{g=await f.mutableResponse}catch(b){return Nn(r,s,"Error retrieving mutableResponse",b)}try{g=await a.onResponseSending(g,h,s)}catch(b){return Nn(r,s,"Error invoking 'context.onResponseSending' hook",b)}try{g=await tx(g,h,s)}catch(b){return Nn(r,s,"Error invoking 'context.onResponseSending' hook",b)}s.dispatchEvent(new nl(r,g));let w=k.instance.build.COMPATIBILITY_FLAGS.passSentResponseToFinalHooks?g:d;try{await a.onResponseSendingFinal(w,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await nx(w,h,s)}catch(b){throw s.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return await Z_(s,g)},"#toZuploPipeline")};function D2(t){return async(e,n)=>{let o=tt.getContextExtensions(n),r=o.startDeferringMetrics(),s;try{return s=await t(e,n),s}finally{if(r){for(let a of o.flushDeferredMetrics())W.console.error(`Error emitting the request metric row for requestId '${n.requestId}'`,a);for(let a of o.runPipelineExitHooks(s))W.console.error(`Error running a pipeline exit hook for requestId '${n.requestId}'`,a)}}}}i(D2,"withPipelineExit");function z2(t,e){let n=e.route.handler.export;if(t.bodyUsed)throw new Z(`The handler '${n}' read its own response body, so the response can no longer be sent. A body can only be read once. Read a clone instead, e.g. \`const data = await response.clone().json()\`, or return a new Response built from what you read.`);if(t.body?.locked===!0)throw new Z(`The handler '${n}' returned a response whose body still has a reader attached, so the response can no longer be sent. Call \`reader.releaseLock()\` before returning it - cloning does not work while the body is locked - or return a new Response built from what you read.`)}i(z2,"assertResponseBodyUnread");function j2(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(jR(t),{headers:{"content-type":"application/json"}})}i(j2,"resultToResponse");function sx(t){return{timestamp:t.timestamp.toISOString(),event_id:t.eventId,request_id:t.requestId,event_type:t.eventType,account_name:t.accountName,project_name:t.projectName,deployment_name:t.deploymentName,value:t.value,unit:t.unit,metadata:t.metadata,source:"zuplo-runtime",version:"v2"}}i(sx,"toVectorAnalyticsEventRow");var H2="/v1/runtime/telemetry",G2=1e3,F2=["resourceUri"];function B2(t){if(typeof t!="object"||t===null)return t;let e=t,n;for(let o of F2){let r=e[o];typeof r=="string"&&(n??={...e},n[o]=Ta(r,"analytics",`metadata.${o}`,o))}return n??t}i(B2,"redactEventMetadata");var bw=class{static{i(this,"RuntimeTelemetryShipper")}#e;#t;constructor(e){this.#t={batcherMsDelay:G2,retries:3,retryDelayMs:1e3,...e},this.#e=new Be({name:"runtime-telemetry-shipper",msDelay:this.#t.batcherMsDelay,dispatchFunction:this.dispatchFunction,systemLogger:W.console})}pushMetric(e,n){let{requestContentLength:o,responseContentLength:r,...s}=e;this.#e.enqueue({kind:"metric",row:s}),n.waitUntil(this.#e.waitUntilFlushed())}pushEvents(e,n){if(e.length===0)return;let o=vo();for(let r of e){let s=sx(r);o&&(s.metadata=B2(s.metadata)),this.#e.enqueue({kind:"event",row:s})}n.waitUntil(this.#e.waitUntilFlushed())}async flush(){await this.#e.waitUntilFlushed()}dispatchFunction=i(async e=>{let n=[],o=[];for(let d of e)d.kind==="metric"?n.push(d.row):o.push(d.row);let r=FP();if(n.length===0&&o.length===0&&r.length===0)return;let{accountName:s,projectName:a,deploymentName:c}=k.instance,u={schemaVersion:1,metadata:{timestamp:new Date().toISOString(),accountName:s,projectName:a,deploymentName:c},metrics:n,events:o,features:r},l=new Headers({"content-type":"application/json"});dt(l);try{let d=await qt({retries:this.#t.retries,retryDelayMs:this.#t.retryDelayMs,logger:W.console},this.#t.endpoint,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){mR(r);let p="";try{p=(await d.text()).slice(0,500)}catch{}W.console.error(`Runtime telemetry POST responded ${d.status}: ${d.statusText}; dropped ${n.length} metric row(s) and ${o.length} analytics event(s)`,p)}}catch(d){mR(r),W.console.error(`Failed to send runtime telemetry; dropped ${n.length} metric row(s) and ${o.length} analytics event(s)`,d)}},"dispatchFunction")},ax;function co(){let t=k.instance;if(t.remoteLogURL)return ax??=new bw({endpoint:new URL(H2,t.remoteLogURL).toString()}),ax}i(co,"getRuntimeTelemetryShipper");var uo=class extends yi{static{i(this,"MetricsPlugin")}};var Ha="SYSTEM_IGNORED";var Wt=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:n,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=n,this.methods=o,this.corsPolicy=s,this.handler={export:Ha,module:Ha},this.systemRouteName=r}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Dn=i(async(t,e,n)=>{let o=new Date,r=Date.now(),s=await n(t),a=t.headers.get(wa)??void 0,c=e.incomingRequestProperties,u=c.ip,l;e.route instanceof Wt&&(l=e.route.systemRouteName);let d=tt.getContextExtensions(e),{latestRequest:p,receivedUrl:f}=d,h={timestamp:o,statusCode:s.status,durationMs:Date.now()-r,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:s.headers.get("content-length")?Number(s.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,url:f,method:t.method,asn:c.asn,asOrganization:c.asOrganization,colo:c.colo,continent:c.continent,country:c.country,city:c.city,latitude:c.latitude,longitude:c.longitude,rayId:a,instanceId:k.instance.instanceId,userSub:p.user?.sub,clientIp:u},g=i(()=>{let{requestLogProperties:w,systemRequestLogProperties:b}=d;if(vo()){cx(Z2(h,w,b),e);return}(w.size>0||b.size>0)&&(h.properties={...Object.fromEntries(w),...Object.fromEntries(b)}),cx(h,e)},"emit");return d.deferMetrics(g)||g(),s},"metricsProcessor");function Z2(t,e,n){let o=ss(),r={...t,url:t.url===void 0?void 0:Ta(t.url,"analytics","url","url",{budget:o})};return(e.size>0||n.size>0)&&(r.properties={...cf(Object.fromEntries(e),"analytics","properties",o),...Object.fromEntries(n)}),r}i(Z2,"redactMetricsData");function cx(t,e){let n=[];!k.instance.isLocalDevelopment&&k.instance.remoteLogURL&&k.instance.remoteLogToken&&k.instance.loggingId&&co()?.pushMetric(t,e),ao.forEach(o=>{if(o instanceof uo){let r=o.getTransport();n.push(r)}}),n.forEach(o=>{o.pushMetrics(t,e)})}i(cx,"pushMetricsData");var Rw=i(t=>{let e=i(async(r,s)=>{let a=new URL(r.url),c=k.instance.build,u={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&le.getLogger(s).error("Test System Log",u),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(u,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new rn({processors:[Dn],handler:e}),o=new Wt({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(o,n.execute)},"registerBuildRoute");var qf=class{static{i(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let n=this.items.keys().next().value;n&&this.items.delete(n)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};function V2(t){return t==="__proto__"||t==="constructor"||t==="prototype"}i(V2,"isBlockedProperty");function J2(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}i(J2,"isPlainObject");function K2(t,e){if(t instanceof Map)return Map.prototype.get.call(t,e);if(!V2(e)&&J2(t)&&Object.hasOwn(t,e)){let n=Object.getOwnPropertyDescriptor(t,e);return n!==void 0&&"value"in n?n.value:void 0}}i(K2,"read");function ol(t,e){let n=e[t.root];for(let o=0;o<t.segments.length;o+=1){let r=t.segments[o];if(n=K2(n,r),n===void 0||Array.isArray(n)&&o<t.segments.length-1)return}return n}i(ol,"evaluate");var W2=["bodyUsed","cache","credentials","destination","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","url"];function $f(t,e){let n=e[0];return t==="request"?W2.includes(n)?e.length===1?void 0:`request.${n} is a scalar value. Remove every property after it.`:["headers","params","query","searchParams"].includes(n)?e.length===2?void 0:`request.${n} must select exactly one value. Add one key or remove trailing properties.`:n==="user"?e[1]==="sub"&&e.length===2||e[1]==="data"&&e.length>=3?void 0:"request.user selectors must choose sub or a property below data. Try request.user.sub or request.user.data.accountId.":"That request property is not selectable. Choose headers, params, query, searchParams, user, or a documented scalar request property.":["contextId","requestId"].includes(n)?e.length===1?void 0:`context.${n} is a scalar value. Remove every property after it.`:["custom","incomingRequestProperties","route"].includes(n)?e.length>=2?void 0:`context.${n} must select a property. Add the property you want to read.`:"That context property is not selectable. Choose contextId, requestId, custom, incomingRequestProperties, or route."}i($f,"validateAddress");function Df(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){if(e+1>=t.length)return e;let o=t.charCodeAt(e+1);if(o<56320||o>57343)return e;e+=1}else if(n>=56320&&n<=57343)return e}}i(Df,"firstIllFormedPosition");var Y2=/^[A-Za-z_][A-Za-z0-9_]*$/,ux=32;function lx(t){if(t.length===0||Df(t)!==void 0||t.includes('"')||t.includes("\\"))throw new TypeError("Selector keys must be non-empty, valid UTF-8, and cannot contain double quotes or backslashes. Choose a well-formed key representable without string escapes.");for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n<=31||n>=127&&n<=159||n===8232||n===8233)throw new TypeError("Selector keys cannot contain control characters, U+2028, or U+2029. Remove that character from the key.")}}i(lx,"assertRepresentableString");function dx(t){if(t.segments.length===0||t.segments.length>ux)throw new TypeError(`Selectors need between 1 and ${ux} segments. Add a property segment or shorten the selector.`);let e=$f(t.root,t.segments);if(e!==void 0)throw new TypeError(e);let n=t.root;if(t.root==="request"&&t.segments[0]==="headers"){if(t.segments.length!==2)throw new TypeError("Header selectors need exactly one header-name segment after request.headers.");lx(t.segments[1]),n=`request.headers.get("${t.segments[1].toLowerCase()}")`}else for(let o of t.segments)lx(o),n+=Y2.test(o)?`.${o}`:`["${o}"]`;if(new TextEncoder().encode(n).byteLength>1024)throw new TypeError("Rendered selectors cannot exceed 1024 UTF-8 bytes. Shorten one or more property names.");return n}i(dx,"render");var Q2=["request","context"],X2=/^[A-Za-z_$][A-Za-z0-9_$-]*$/,px=32,mx=1024;function Bt(t,e){return{error:!0,position:t,message:e}}i(Bt,"failure");function hx(t,e){let n=t[e];if(n!=='"'&&n!=="'")return Bt(e,"Expected a quoted property name. Add a non-empty single- or double-quoted string.");let o="";for(let r=e+1;r<t.length;r+=1){let s=t[r],a=t.charCodeAt(r);if(s===n)return o.length===0?Bt(r,"Selector property names cannot be empty. Put a non-empty key between the quotes."):{value:o,next:r+1};if(s==="\\")return Bt(r,"Selector strings do not support escapes. Use a property name without a backslash.");if(n==="'"&&s==='"')return Bt(r,"Selector keys cannot contain double quotes because canonical rendering has no escapes. Use a key without double quotes.");if(a<=31||a>=127&&a<=159||a===8232||a===8233)return Bt(r,"Selector strings cannot contain control characters, U+2028, or U+2029. Remove that character from the key.");o+=s}return Bt(t.length,`Unterminated ${n} string. Add the matching closing quote.`)}i(hx,"parseString");function eV(t){return t===" "||t===" "||t===`
|
|
40
40
|
`||t==="\r"}i(eV,"isWhitespace");function fx(t,e){for(;e<t.length&&eV(t[e]);)e+=1;return e}i(fx,"skipWhitespace");function tV(t,e){let n=e+5,o=hx(t,n);return"error"in o?o:(n=o.next,t[n]!==")"?Bt(n,"Header get access must end with ')'. Add the closing parenthesis immediately after the quoted name."):n+1!==t.length?Bt(n+1,"Header access is terminal. Remove every property or call after the header name."):{...o,next:n+1})}i(tV,"parseHeaderGet");function nV(t){let e=Df(t);if(e!==void 0)return Bt(e,"Selectors must be valid UTF-8. Remove the unpaired surrogate code unit.");if(new TextEncoder().encode(t).byteLength>mx)return Bt(t.length,`Selectors cannot exceed ${mx} UTF-8 bytes. Shorten the selector before saving it.`)}i(nV,"validateSelectorInput");function oV(t,e,n){let o=[],r=e;for(;r<t.length;){if(o.length>=px)return Bt(r,`Selectors cannot exceed ${px} property segments. Remove one or more trailing segments.`);if(n==="request"&&o.length===1&&o[0]==="headers"&&t.startsWith(".get(",r)){let s=tV(t,r);if("error"in s)return s;o.push(s.value.toLowerCase()),r=s.next;break}if(t[r]==="."){let s=r+1;for(r=s;r<t.length&&t[r]!=="."&&t[r]!=="["&&t[r]!=="("&&t[r]!==")";)r+=1;let c=t.slice(s,r).trim();if(!X2.test(c))return Bt(s,'Dot properties must start with A-Z, a-z, "_", or "$" and may also contain digits or hyphens. Use quoted bracket access for other keys.');o.push(c);continue}if(t[r]==="["){r=fx(t,r+1);let s=hx(t,r);if("error"in s)return s;if(r=fx(t,s.next),t[r]!=="]")return Bt(r,"Bracket access must end with ']'. Add the closing bracket after the quoted key.");r+=1,o.push(s.value);continue}return Bt(r,'Expected a dot property or quoted bracket property. Try .userId or ["team-id"].')}return o.length===0?Bt(r,"A selector must choose at least one property. Add a property after the root."):{segments:o,position:r}}i(oV,"parseSegments");function ww(t){let e=[],n=0;for(;n<t.length;){if(t[n]==="."){n+=1;continue}if(t[n]==="["){for(n+=1;n<t.length&&/\s/.test(t[n]);)n+=1;let s=t[n];if(s!=='"'&&s!=="'")return Bt(n,`Invalid selector '${t}' - bracket segments must be quoted, e.g. ["my.key"]`);n+=1;let a=n;for(;n<t.length&&t[n]!==s;)n+=1;if(n>=t.length)return Bt(n,`Invalid selector '${t}' - unterminated quoted segment`);for(e.push(t.substring(a,n)),n+=1;n<t.length&&/\s/.test(t[n]);)n+=1;t[n]==="]"&&(n+=1);continue}let o=n;for(;n<t.length&&t[n]!=="."&&t[n]!=="[";)n+=1;let r=t.substring(o,n).trim();r.length>0&&e.push(r)}return{segments:e}}i(ww,"parsePropertyPath");function rl(t){let e=nV(t);if(e!==void 0)return e;let n=Q2.find(u=>t.startsWith(u)&&(t[u.length]==="."||t[u.length]==="["));if(n===void 0)return Bt(0,"Selectors must start with request or context and select a property. Try request.url or context.custom.accountId.");let o=oV(t,n.length,n);if("error"in o)return o;let{segments:r,position:s}=o,a=$f(n,r);if(a!==void 0)return Bt(s,a);n==="request"&&r[0]==="headers"&&(r[1]=r[1].toLowerCase());let c={root:n,segments:r,canonical:!1};try{c.canonical=dx(c)===t}catch(u){return u instanceof TypeError?Bt(t.length,u.message):Bt(t.length,"The selector cannot be rendered canonically. Shorten the selector or choose simpler property names.")}return c}i(rl,"parse");function gs(t){return"error"in t&&t.error===!0}i(gs,"isParseError");var gx=new Map;function Yo(t){if(Array.isArray(t)&&!t.some(r=>typeof r!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new T("Malformed input string");let e=gx.get(t);if(e)return e;let n=t.split(","),o=[];for(let r of n){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)o.push(u)}else o.push(parseInt(r,10))}return gx.set(t,o),o}i(Yo,"statusCodesStringToNumberArray");function kr(t,e,n){if(!e.startsWith("."))throw new T(`Invalid ${n} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=t;return o.forEach(s=>{if(r===void 0)throw new Z(`Error applying ${n} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(kr,"getValueFromRequestUser");var rV=1024,Ga;function Sw(t){Ga??=new Map;let e=Ga.get(t);if(e!==void 0)return e;let n=ww(t);if(gs(n))throw new T(n.message);if(Ga.size>=rV){let o=Ga.keys().next().value;o!==void 0&&Ga.delete(o)}return Ga.set(t,n),n}i(Sw,"parseJsonPathSelector");function Cw(t){return Sw(t).segments.slice()}i(Cw,"parseJsonPath");function zf(t,e){let n=t;for(let o of Sw(e).segments){if(n===null||typeof n!="object")return;n=Reflect.get(n,o)}return n}i(zf,"getValueAtPath");function yx(t,e){if(!e.startsWith(".")&&!e.startsWith("["))throw new T(`Invalid selector. must start with '.' - '${e}' does not`);let n=Sw(e).segments,o=t;return n.forEach(r=>{if(o===void 0)throw new Z(`Error applying'${e}', reading '${r}'`);if(o&&typeof o=="object")o=Reflect.get(o,r);else throw new Z(`Error applying'${e}', reading '${r}'`)}),`${o}`}i(yx,"selectPropertyUsingJsonPath");function ys(t){if(Array.isArray(t)){if(t.includes(n=>typeof n!="string"))throw new T("Received an array that contains non-string values.");return t}if(Ar(t))return t.includes(",")?t.split(",").map(n=>n.trim()).filter(n=>n!==","&&n!==""):[t];throw new T(`Expected type of string, received type '${typeof t}'`)}i(ys,"parseValueToStringArray");function bx(t){if(t==null)return[];if(!Array.isArray(t))throw new T(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(n=>{if(!is(n))throw new T(`Invalid custom cors policy is set. Expected an object, received '${typeof n}'`);if(!ZP(n.name))throw new T("Value of 'name' on custom cors policies must be a non-empty string.");if(n.maxAge!==void 0&&!fR(n.maxAge))throw new T(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof n.maxAge}'`);if(n.allowCredentials!==void 0&&!hR(n.allowCredentials))throw new T("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=vw(n,"allowedHeaders"),r=vw(n,"allowedMethods"),s=vw(n,"exposeHeaders"),a;try{a=ys(n.allowedOrigins)}catch(u){throw new T(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:n.name,allowCredentials:typeof n.allowCredentials=="boolean"?String(n.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof n.maxAge=="number"?n.maxAge.toString():void 0}})}i(bx,"parseCorsPolicies");function vw(t,e){let n;if(t[e]!==void 0)try{n=ys(t[e])}catch(o){throw new T(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return n}i(vw,"parseOptionalProperty");var Tw=new Map,iV=i((t,e,n)=>{for(let o of t){let r=o.trim().toLowerCase();if(r==="*")return e;if(r.includes("*.")){let a=r.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*\\\./g,"[^.]+\\.");if(new RegExp(`^${a}$`).test(n))return e}else{let s=r.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return e}}},"testMatchinOrigin"),jf=i((t,e,n)=>{if(n===null)return;let o=n.trim().toLowerCase(),r=Tw.get(t);if(r?.has(o))return n;let s=iV(e,n,o);return s&&(r||Tw.set(t,new qf(20)),Tw.get(t)?.add(o)),s},"findMatchingOrigin"),Hf=i((t,e)=>{let n={"access-control-allow-origin":e};t.allowedHeaders&&(n["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(n["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(n["access-control-expose-headers"]=t.exposeHeaders);let o=t.allowCredentials;o&&(n["access-control-allow-credentials"]=o);let r=t.maxAge?.toString()??void 0;return r&&(n["access-control-max-age"]=r),n},"generateCorsHeaders"),Gf=i((t,e)=>{if(!t)return!1;let{developerPortal:n}=e;return n.enabled&&n.type==="zudoku"&&n.urls?n.urls.urls.includes(t):!1},"isDevPortalOrigin");var sV=new Map([["McpProxyHandler","$import(@zuplo/runtime/mcp-gateway)"],["mcpServerHandler","$import(@zuplo/runtime)"]]),Rx={allow:"POST"};function Aw(t){let e=t.handler?.export;if(e===void 0)return!1;let n=sV.get(e);return n===void 0?!1:t.raw()?.["x-zuplo-route"]?.handler?.module===n}i(Aw,"isBuiltInMcpHandler");var Ff=i((t,e)=>t.lookupByPathOnly(e).find(n=>{let{routeConfiguration:o}=n;return Aw(o)&&o.methods.some(r=>r.toUpperCase()==="POST")})?.routeConfiguration,"findMcpPostRouteByPath");var Iw=i((t,e,n)=>{let o=i(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 V.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});if(Gf(p,e)){let S={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:S})}let h=t.lookup(u,l)?.routeConfiguration,w=(h instanceof Wt&&h.systemRouteName==="unmatched-path"?void 0:h)??(l==="GET"?Ff(t,u):void 0);if(!w)return V.notFound(a,c);let b=aV({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:w,customPolicies:n});return b.isValid?new Response(void 0,{status:200,statusText:"OK",headers:b.headers}):(b.error&&c.log.warn(b.error),V.notFound(a,c))},"optionsHandler"),r=new rn({processors:[Dn],handler:o}),s=new Wt({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,r.execute)},"registerCorsRoute"),aV=i(({requestedMethod:t,requestedHeaders:e,requestedOrigin:n,routeConfig:o,customPolicies:r})=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":n,"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(o.corsPolicy==="none")return{...s,error:`CORS policy 'none' blocks all cross-origin requests for route '${o.pathPattern}'.`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new T(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=jf(a.name,a.allowedOrigins,n);return c?{isValid:!0,headers:Hf(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${n}'`}},"validateAndBuildResponseHeaders");var wx=i(t=>{let e=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new rn({processors:[Dn],handler:e}),o=new Wt({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(o,n.execute)},"registerNoRoutes");var Ci=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.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var cV=new Wt({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Sx=i(t=>{let e=i(async(o,r)=>{let s=gw.value?.notFoundHandler;if(s){let u=new URL(o.url);return s(o,r,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(u.pathname).map(d=>d.routeConfiguration).filter(d=>d instanceof Ci)}})}let a=new URL(o.url);return Ff(t,a.pathname)&&o.method!=="POST"?V.methodNotAllowed(o,r,void 0,Rx):V.notFound(o,r)},"notFoundHandler"),n=new rn({processors:[Dn],handler:e});t.addRoute(cV,n.execute)},"registerNotMatchedHandler");function vi(t){if(!k.instance.isDeno)return new Headers(t);let e=new Headers;return t.forEach((n,o)=>{e.append(o,n)}),e}i(vi,"copyHeaders");function Fa(t){return k.instance.isDeno?Pw(t):t}i(Fa,"toHeadersInit");function il(t){return!k.instance.isDeno||lV()?t:Pw(t)}i(il,"toResponseHeadersInit");function uV(t){let[e,n,o]=t.split(".").map(r=>Number.parseInt(r,10));return e!==2?e>2:n!==9?n>9:o>=1}i(uV,"denoCopiesResponseHeaders");var Cx;function lV(){return Cx??=uV(String(globalThis.Deno?.version?.deno??"")),Cx}i(lV,"runningDenoCopiesResponseHeaders");var dV=["body","cache","credentials","duplex","integrity","keepalive","method","mode","priority","redirect","referrer","referrerPolicy","signal"];function Ew(t){if(!(t instanceof Request)||!k.instance.isDeno)return t;let e={};for(let n of dV){let o=t[n];o!==void 0&&(e[n]=o)}return e.headers=Pw(t.headers),e}i(Ew,"toRequestInit");function Pw(t){let e=[];return t.forEach((n,o)=>{e.push([o,n])}),e}i(Pw,"toEntries");var pV=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],vx=i(t=>{pV.forEach(e=>t.delete(e))},"stripCorsHeaders"),Ba=i(async(t,e,n)=>{let o=await n(t);if(k.instance.isDeno&&o.status===101&&[...o.headers.keys()].length===0&&!o.body)return o;let r=e.route,s=t.headers.get("origin"),a=Gf(s,nt.instance.runtimeSettings);if((!r.corsPolicy||r.corsPolicy==="none")&&!a){let p=vi(o.headers);return vx(p),new Response(o.body,{status:o.status,statusText:o.statusText,headers:il(p),webSocket:o.webSocket})}if(!(o instanceof Response))throw new $e(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof o}'`);let c=mV(r,nt.instance.routeData.corsPolicies,a),u=fV(s,c),l=vi(o.headers);return vx(l),Object.entries(u).forEach(([p,f])=>{l.set(p,f)}),new Response(o.body,{status:o.status,statusText:o.statusText,headers:il(l),webSocket:o.webSocket})},"corsProcessor"),mV=i((t,e,n)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(n)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let o=e?.find(r=>r.name===t.corsPolicy);if(o===void 0)throw new T(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return o},"getCorsPolicy"),fV=i((t,e)=>{let n=jf(e.name,e.allowedOrigins,t);return n?Hf(e,n):{}},"getCorsHeaders");var kw=i(t=>{let e=i(async()=>new Response(JSON.stringify({buildId:k.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),n=new rn({processors:[Ba],handler:e}),o=new Wt({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(o,n.execute)},"registerPingRoute");import{trace as _V}from"@opentelemetry/api";var hV="custom";function Za(t,e){t.setAttribute(Ln.PolicyName,e.policyName),t.setAttribute(Ln.PolicyDirection,e.direction),t.setAttribute(Ln.PolicyType,e.policyType??hV),e.policyType!==void 0&&me(`policy.${e.direction}.${e.policyType}`)}i(Za,"applyPolicySpanTelemetry");function sl(t){return t===null?"null":Array.isArray(t)?"array":typeof t}i(sl,"describeValueType");function _w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(_w,"isModuleObject");function al(t,e){return e===void 0?`Policy '${t}'`:`Policy '${t}' on route '${e}'`}i(al,"policySubject");function Bf(t,e,n){let o=Ax(t,(e??[]).map(s=>s.name)),r=o===void 0?"":` Did you mean '${o}'?`;return new T(`${al(t,n)} was not found in config/policies.json. Policy names are case-sensitive.${r}`)}i(Bf,"policyNotFoundError");function xw(t,e){return new T(`${t}: "module" is ${sl(e)}, not an imported module. Set "module" to "$import(<module path>)", for example "$import(@zuplo/runtime)".`)}i(xw,"invalidModuleError");function Ow(t,e,n,o){if(typeof n!="string"||n==="")return new T(`${t}: "export" is ${sl(n)}. Set it to the name of the module export to use.`);let r=yV(e)?"module '@zuplo/runtime'":"the configured module",s=Object.hasOwn(e,n)?e[n]:void 0;return s===void 0?new T(`${t}: export '${n}' was not found in ${r}.${gV(e,n)}`):new T(`${t}: export '${n}' in ${r} is ${sl(s)}, not ${o}.`)}i(Ow,"invalidExportError");function Tx(t){let e=`Route '${t.path}' handler`,n=t.handler?.module;if(!_w(n))throw xw(e,n);let o=n[t.handler?.export??""];if(typeof o!="function")throw Ow(e,n,t.handler?.export,"a request handler function");return o}i(Tx,"resolveRouteHandler");function gV(t,e){let n=Ax(e,Object.keys(t));return n===void 0?"":` Did you mean '${n}'?`}i(gV,"missingExportHint");function yV(t){return t.InboundPolicy===he&&t.OutboundPolicy===To&&t.ZuploRequest===Ge}i(yV,"isRuntimeRootModule");function Ax(t,e){let n=t.toLowerCase(),o=e.filter(u=>u!==t&&u.toLowerCase()===n);if(o.length>0)return o.length===1?o[0]:void 0;let r=Math.min(3,Math.floor(t.length/4)),s,a=r+1,c=!1;for(let u of e){if(u===t||Math.abs(u.length-t.length)>r)continue;let l=bV(n,u.toLowerCase());l<a?(s=u,a=l,c=!1):l===a&&(c=!0)}return s!==void 0&&!c?s:void 0}i(Ax,"findCloseMatch");function bV(t,e){let n=Array.from({length:e.length+1},(o,r)=>r);for(let o=1;o<=t.length;o++){let r=[o];for(let s=1;s<=e.length;s++)r[s]=Math.min(n[s]+1,r[s-1]+1,n[s-1]+(t[o-1]===e[s-1]?0:1));n=r}return n[e.length]}i(bV,"editDistance");import{AsyncLocalStorage as RV}from"node:async_hooks";import{trace as wV}from"@opentelemetry/api";var Ix,Ex=i(()=>(Ix??=wV.getTracer("pipeline"),Ix),"tracer"),Mw=new RV,SV="zuplo.pre_request_handler.name",CV="zuplo.policy.name",vV="zuplo.pre_request_handler.outcome",TV="zuplo.pre_request_handler.barrier_wait_ms",AV="zuplo.pre_request_handler.awaited_count",ul={kind:"none"};function Px(t,e,n,o){let r=Mw.getStore();if(r!==void 0)throw new Z(`Invalid state - addPreRequestHandler called from inside the pre-request handler registered by policy '${r.policyName}' on route '${t.route.path}'. Handlers race the inbound policy chain and cannot start more concurrent work, and a handler registered from here would be attributed to whichever policy the chain is running. Register every handler from an inbound policy instead.`);if(e.preRequestPhase==="closed")throw new Z(`Invalid state - addPreRequestHandler called after the inbound policy phase on route '${t.route.path}'. Pre-request handlers race the inbound policy chain, so registering one after the chain has finished can never take effect. Move the addPreRequestHandler call into an inbound policy.`);if(e.preRequestPhase!=="active")throw new Z(`Invalid state - addPreRequestHandler called outside the inbound policy phase on route '${t.route.path}'. The inbound policy chain is not running here (for example a runtime request hook), so a handler registered now would never be checked, awaited, or aborted. Move the addPreRequestHandler call into an inbound policy.`);let s=e.currentPolicyName??"(unattributed)";if(typeof n!="function")throw new Z(`Invalid state - addPreRequestHandler on policy '${s}' on route '${t.route.path}' was given ${Lw(n)} instead of a function. Pass an async function that resolves a Response, a commit function, or undefined.`);e.preRequestState===void 0&&(e.preRequestState={entries:[],resolved:!1});let a=e.preRequestState,c=new AbortController,u=o?.name!==void 0?`pre-request-handler:${s}/${o.name}`:`pre-request-handler:${s}`,l=Ex().startSpan(u);l.setAttribute(CV,s),o?.name!==void 0&&l.setAttribute(SV,o.name);let d={policyName:s,name:o?.name,status:"pending",settledValue:void 0,rejection:void 0,consumedAs:void 0,abortController:c,span:l,settledPromise:Promise.resolve()},p;try{p=Promise.resolve(Mw.run({policyName:s},()=>n({signal:c.signal})))}catch(h){p=Promise.reject(h)}d.settledPromise=p.then(h=>{d.status==="pending"&&(d.status="settled",IV(d,h,t,s,o?.name))},h=>{d.status==="pending"&&(d.status="settled",d.rejection={error:h},ll(d,"rejected"))});let f=new Promise(h=>{c.signal.addEventListener("abort",()=>h(),{once:!0})});t.waitUntil(Promise.race([d.settledPromise,f])),a.entries.push(d)}i(Px,"registerPreRequestHandler");function IV(t,e,n,o,r){e instanceof Response||typeof e=="function"?(t.settledValue=e,ll(t,e instanceof Response?"verdict":"commit")):e===void 0?ll(t,"abstain"):(t.rejection={error:new Z({message:`Invalid state - the pre-request handler ${kx(o,r)} on route '${n.route.path}' resolved an invalid value. A pre-request handler must resolve a Response, a commit function, or undefined.`,extensionMembers:{resolvedType:Lw(e)}})},ll(t,"rejected"))}i(IV,"recordSettledValue");function kx(t,e){return e===void 0?`registered by policy '${t}'`:`'${e}' registered by policy '${t}'`}i(kx,"describeHandler");function Lw(t){return t===null?"null":Array.isArray(t)?"array":typeof t}i(Lw,"describeType");function ll(t,e){try{t.span.setAttribute(vV,e),t.span.end()}catch{}}i(ll,"endEntrySpan");function cl(t,e){for(let n of t.entries)n.status==="pending"&&(n.status="consumed",n.consumedAs="aborted",ll(n,"aborted"),n.abortController.abort(e))}i(cl,"abortPending");async function Zf(t,e,n,o){let r=e.preRequestState;if(r===void 0||r.resolved)return ul;for(let s of r.entries){if(s.status==="consumed")continue;if(s.status==="pending"){if(n==="checkpoint")return ul;if(n==="exit")break;if(await s.settledPromise,s.status!=="settled")continue}if(s.rejection!==void 0)return s.status="consumed",s.consumedAs="rejected",r.resolved=!0,cl(r,"pipeline-error"),{kind:"error",error:s.rejection.error};let a=s.settledValue;if(a===void 0){s.status="consumed",s.consumedAs="abstained";continue}if(a instanceof Response)return s.status="consumed",s.consumedAs="served",r.resolved=!0,cl(r,"verdict-served"),{kind:"response",response:a,policyName:s.policyName};if(n==="exit"){s.status="consumed",s.consumedAs="lost";break}s.status="consumed";let c=await EV(t,e,s,a);if(c.kind==="error")return s.consumedAs="rejected",r.resolved=!0,cl(r,"pipeline-error"),c;if(c.kind==="response")return s.consumedAs="served",r.resolved=!0,cl(r,"verdict-served"),c;s.consumedAs="withdrawn"}return n==="exit"&&(r.resolved=!0,cl(r,o)),ul}i(Zf,"walk");async function EV(t,e,n,o){try{let r=await Mw.run({policyName:n.policyName},()=>o());return r instanceof Response?{kind:"response",response:r,policyName:n.policyName}:r===void 0?ul:{kind:"error",error:new Z({message:`Invalid state - the commit function of the pre-request handler ${kx(n.policyName,n.name)} on route '${t.route.path}' resolved an invalid value. A commit function must resolve a Response (serve it) or undefined (withdraw).`,extensionMembers:{resolvedType:Lw(r)}})}}catch(r){return{kind:"error",error:r}}}i(EV,"runCommit");function _x(t,e){return Zf(t,e,"checkpoint","verdict-served")}i(_x,"runPreRequestCheckpoint");function Nw(t,e,n){return Zf(t,e,"exit",n)}i(Nw,"runPreRequestExitWalk");async function xx(t,e){let n=e.preRequestState;if(n===void 0||n.resolved)return ul;let o=n.entries.filter(r=>r.status==="pending");return o.length===0?Zf(t,e,"barrier","verdict-served"):await Ex().startActiveSpan("pre-request-handlers:barrier",async r=>{let s=performance.now();try{return r.setAttribute(AV,o.length),await Zf(t,e,"barrier","verdict-served")}finally{try{r.setAttribute(TV,Math.round((performance.now()-s)*1e3)/1e3),r.end()}catch{}}})}i(xx,"awaitPreRequestBarrier");var Ox={"ai-gateway-akamai-firewall":["configurationId","api-key"],"ai-gateway-akamai-firewall-inbound":["configurationId","api-key"],"ai-gateway-galileo-tracing":["apiKey","projectId","logStreamId"],"ai-gateway-galileo-tracing-inbound":["apiKey","projectId","logStreamId"],"ai-gateway-opik-tracing":["apiKey","projectName","workspace"],"ai-gateway-opik-tracing-inbound":["apiKey","projectName","workspace"],"ai-gateway-smart-router":["modelsByComplexity.low","modelsByComplexity.medium","modelsByComplexity.high"],"ai-gateway-smart-router-inbound":["modelsByComplexity.low","modelsByComplexity.medium","modelsByComplexity.high"],"akamai-ai-firewall-inbound-v2":["configurationId","api-key"],"akamai-ai-firewall-v2":["configurationId","api-key"],"akamai-ai-firewall-v2-inbound":["configurationId","api-key"],"akamai-firewall-for-ai-inbound":["configurationId","api-key"],"akamai-firewall-for-ai-outbound":["configurationId","api-key"],"amberflo-metering-inbound":["apiKey"],"auth0-jwt-auth-inbound":["auth0Domain"],"authzen-inbound":["authorizerHostname","subject.type","subject.id","resource.type","resource.id","action.name"],"axiomatics-authz-inbound":["pdpUrl","pdpUsername","pdpPassword"],"cdn-cache-control-outbound":["cacheConfig.export","cacheConfig.module"],"change-method-inbound":["method"],"clerk-jwt-auth-inbound":["frontendApiUrl"],"cognito-jwt-auth-inbound":["region","userPoolId"],"comet-opik-tracing-inbound-v2":["apiKey","projectName","workspace"],"comet-opik-tracing-v2":["apiKey","projectName","workspace"],"comet-opik-tracing-v2-inbound":["apiKey","projectName","workspace"],"complex-rate-limit-inbound":["identifier.export","identifier.module"],"concurrency-limit-inbound":["identifier.export","identifier.module"],"curity-phantom-token-inbound":["clientId","clientSecret","introspectionUrl"],"firebase-jwt-inbound":["projectId"],"galileo-tracing-inbound-v2":["apiKey","projectId","logStreamId"],"galileo-tracing-v2":["apiKey","projectId","logStreamId"],"galileo-tracing-v2-inbound":["apiKey","projectId","logStreamId"],"ldap-auth-inbound":["ldapConnectorName"],"mcp-auth0-oauth-inbound":["auth0Domain","clientId","clientSecret"],"mcp-clerk-oauth-inbound":["frontendApiUrl","clientId","clientSecret"],"mcp-cognito-oauth-inbound":["awsRegion","userPoolId","userPoolDomain","clientId","clientSecret"],"mcp-entra-oauth-inbound":["tenantId","clientId","clientSecret"],"mcp-google-oauth-inbound":["clientId","clientSecret"],"mcp-keycloak-oauth-inbound":["keycloakBaseUrl","realm","clientId","clientSecret"],"mcp-logto-oauth-inbound":["logtoEndpoint","clientId","clientSecret"],"mcp-oauth-inbound":["oidc.issuer","oidc.jwksUrl","browserLogin.url"],"mcp-okta-oauth-inbound":["oktaDomain","clientId","clientSecret"],"mcp-onelogin-oauth-inbound":["oneLoginSubdomain","clientId","clientSecret"],"mcp-ping-oauth-inbound":["clientId","clientSecret"],"mcp-token-exchange-inbound":["displayName"],"mcp-workos-oauth-inbound":["clientId","clientSecret"],"moesif-inbound":["applicationId"],"okta-fga-authz-inbound":["storeId","authorizationModelId","credentials.clientId","credentials.clientSecret"],"okta-jwt-auth-inbound":["issuerUrl"],"openfga-authz-inbound":["apiUrl","storeId","authorizationModelId"],"openmeter-inbound":["apiKey"],"prompt-injection-outbound":["apiKey"],"propel-auth-jwt-inbound":["authUrl","verifierKey"],"query-param-to-header-inbound":["queryParam","headerName","headerValue"],"quota-inbound":["identifier.module"],"rate-limit-inbound":["identifier.export","identifier.module"],"readme-metrics-inbound":["apiKey"],"require-origin-inbound":["origins"],"semantic-cache-inbound":["cacheByFunction.export","cacheByFunction.module"],"set-upstream-api-key-inbound":["value"],"stripe-webhook-verification-inbound":["signingSecret"],"supabase-jwt-auth-inbound":["secret"],"traffic-splitting-inbound":["customOutputProperty"],"upstream-aws-federated-auth-inbound":["roleArn","region"],"upstream-aws-service-auth-inbound":["accessKeyId","secretAccessKey","region"],"upstream-azure-ad-service-auth-inbound":["activeDirectoryTenantId","activeDirectoryClientId","activeDirectoryClientSecret"],"upstream-firebase-admin-auth-inbound":["serviceAccountJson"],"upstream-firebase-user-auth-inbound":["serviceAccountJson","webApiKey"],"upstream-gcp-federated-auth-inbound":["audience","serviceAccountEmail","workloadIdentityProvider"],"upstream-gcp-jwt-inbound":["audience","serviceAccountJson"],"upstream-gcp-service-auth-inbound":["serviceAccountJson"],"upstream-oauth-client-credentials-inbound":["tokenUrl","clientId","clientSecret"],"validate-json-schema-inbound":["validator"]};function Vf(t,e,n){if(!k.instance.build.COMPATIBILITY_FLAGS.treatBlankOptionalStringOptionsAsUnset)return;let o=t!==void 0&&Object.hasOwn(Ox,t)?Ox[t]:void 0;if(!o)return;let r=o.filter(a=>kV(PV(e,a)));if(r.length===0)return;let s=r.map(a=>`'${a}'`).join(", ");throw new T(r.length===1?`${n}: the required option ${s} is empty. Set it to a value, or check that the environment variable it reads is set.`:`${n}: the required options ${s} are empty. Set them to a value, or check that the environment variables they read are set.`)}i(Vf,"assertRequiredStringOptionsNotBlank");function PV(t,e){let n=t;for(let o of e.split(".")){if(typeof n!="object"||n===null)return;n=n[o]}return n}i(PV,"valueAt");function kV(t){return typeof t=="string"&&t.trim()===""}i(kV,"isBlank");var Mx,Jf=i(()=>(Mx??=_V.getTracer("pipeline"),Mx),"tracer"),Kf=class extends he{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,n,o){super(n,o),this.policyType=e.policyType,this.#e=e}handler(e,n){return this.#e(e,n,this.options,this.policyName)}},$w=class extends To{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,n,o){super(n,o),this.policyType=e.policyType,this.#e=e}handler(e,n,o){return this.#e(e,n,o,this.options,this.policyName)}},Uw=new Map,Lx="an inbound policy class or function",xV="an outbound policy class or function";function Dw(t,e,n){let o=t.handler?.module;if(!_w(o))throw xw(e,o);let r=o[t.handler.export];if(typeof r!="function")throw Ow(e,o,t.handler.export,n);return r}i(Dw,"resolvePolicyExport");function zw(t,e,n){return new T(`${t}: the policy created from export '${e.handler.export}' has no handler method (handler is ${sl(n)}).`)}i(zw,"noHandlerMethodError");function Wf(t,e,...n){if(n.length===1){let[r]=n,s=e?.find(f=>f.name===t);if(!s)throw Bf(t,e);let a=al(t),c=Dw(s,a,Lx);Vf(s.policyType,r,a);let u=c.prototype instanceof he,l=c.prototype instanceof To||Function.prototype.toString.call(c).startsWith("class ");if(c.policyDirection==="outbound"||!u&&l)throw new T(`${a}: export '${s.handler.export}' must be an inbound policy function or a class extending InboundPolicy.`);let p=u?new c(r,s.name):new Kf(c,r,s.name);if(typeof p.handler!="function")throw zw(a,s,p.handler);return p}let[o]=Va([t],e);if(!o)throw new Z("Internal error. Policy not found in cache.");return o}i(Wf,"getInboundPolicyInstance");function Va(t,e){let n,o;return Array.isArray(t)?n=t:(n=t.policies?.inbound??[],o=t.path),n.filter(s=>!Uw.has(s)).forEach(s=>{let a=e?.find(d=>d.name===s);if(!a)throw Bf(s,e,o);let c=al(s,o),u=Dw(a,c,Lx);Vf(a.policyType,a.handler.options,c);let l=u.prototype instanceof he?new u(a.handler.options,a.name):new Kf(u,a.handler.options,a.name);if(typeof l.handler!="function")throw zw(c,a,l.handler);Uw.set(a.name,l)}),n.map(s=>{let a=Uw.get(s);if(a===void 0)throw new Z("Internal error. Policy not found in cache.");return a})}i(Va,"getInboundPolicyInstances");var qw=new Map;function dl(t,e){let n,o;return Array.isArray(t)?n=t:(n=t.policies?.outbound??[],o=t.path),n.filter(s=>!qw.has(s)).forEach(s=>{let a=e?.find(d=>d.name===s);if(!a)throw Bf(s,e,o);let c=al(s,o),u=Dw(a,c,xV);Vf(a.policyType,a.handler.options,c);let l=u.prototype instanceof To?new u(a.handler.options??{},a.name):new $w(u,a.handler.options??{},a.name);if(typeof l.handler!="function")throw zw(c,a,l.handler);qw.set(a.name,l)}),n.map(s=>{let a=qw.get(s);if(a===void 0)throw new Z("Internal error. Policy not found in cache.");return a})}i(dl,"getOutboundPolicyInstances");var pl=i(t=>async(e,n)=>{let o=tt.getContextExtensions(n);return await Jf().startActiveSpan("policies:inbound",async r=>{try{let s=[...t],a=e;for(;s.length>0;){let c=s.shift();if(!c)return a;let u=o.currentPolicyName;o.currentPolicyName=c.policyName;let l;try{l=await Jf().startActiveSpan(`policy:${c.policyName}`,async d=>{try{Za(d,c);let p=await c.handler(a,n);if(p instanceof Request||p instanceof Ge||p instanceof Response){if(p instanceof Response||p instanceof Ge)return p;{let f=a.user;return new Ge(p,{user:f})}}else throw new T(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`)}catch(p){throw Wo(d,p),p}finally{d.end()}})}finally{o.currentPolicyName=u}if(l instanceof Ge)a=l;else if(l instanceof Request){let d=a.user;a=new Ge(l,{user:d})}else if(l instanceof Response)return $a(n,c.policyName,l),l;if(o.latestRequest=a,o.preRequestState!==void 0){let d=await _x(n,o);if(d.kind==="response")return $a(n,d.policyName,d.response),d.response;if(d.kind==="error")throw d.error}}return a}finally{r.end()}})},"toStackedInboundHandler"),jw=i(t=>async(e,n,o)=>await Jf().startActiveSpan("policies:outbound",async r=>{try{let s=[...t],a=e;for(;s.length>0;){let c=s.shift();if(!c)return a;a=await Jf().startActiveSpan(`policy:${c.policyName}`,async l=>{try{Za(l,c);let d=await c.handler(a,n,o);if(d instanceof Response)return d;throw new T(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}'. The result of an outbound policy must be a Response.`)}catch(d){throw Wo(l,d),d}finally{l.end()}})}return a}finally{r.end()}}),"toStackedOutboundHandler"),Yf=i(async(t,e,n)=>{let o=Va(e.route,nt.instance.routeData.policies),r=dl(e.route,nt.instance.routeData.policies);return OV({request:t,context:e,inboundPolicies:o,outboundPolicies:r,next:n})},"policyProcessor");async function OV({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r}){let s=pl(n),a=tt.getContextExtensions(e),c=a.preRequestPhase===void 0;c&&(a.preRequestPhase="active");let u=!1;try{let l=await s(t,e);if(l instanceof Response){c&&(a.preRequestPhase="closed");let h=await Nw(e,a,"chain-response");return h.kind==="response"?($a(e,h.policyName,h.response,{replacesEarlier:!0}),h.response):h.kind==="error"?Nn(t,e,"Error executing policies",h.error):l}if(c&&(a.preRequestPhase="closed"),a.preRequestState!==void 0){let h=await xx(e,a);if(h.kind==="response")return $a(e,h.policyName,h.response),h.response;if(h.kind==="error")return Nn(t,e,"Error executing policies",h.error)}u=!0;let d=await r(l),p=jw(o),f;return k.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?f=p(d,t,e):f=d.ok?p(d,t,e):d,f}catch(l){if(!u&&a.preRequestState!==void 0){c&&(a.preRequestPhase="closed");let d=await Nw(e,a,"pipeline-error");if(d.kind==="response")return $a(e,d.policyName,d.response,{replacesEarlier:!0}),d.response;if(d.kind==="error")return Nn(t,e,"Error executing policies",d.error)}return Nn(t,e,"Error executing policies",l)}finally{c&&a.preRequestPhase==="active"&&(a.preRequestPhase="closed")}}i(OV,"executePolicyProcessor");var $x=PB(qx(),1);function Dx(t,e){try{let n=/v\d+(-\d+)?/g,r=(0,$x.parse)(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&n.test(r)?`https://dev-portal-${r}.zuplo.com`:t}catch{}return t}i(Dx,"devPortalBaseURL");var zx="/__zuplo/dev-portal",GV="dev-portal-id",FV="dev-portal-host",BV="zp-account",ZV="zp-project",VV="dev-portal-build",JV=`
|
|
41
41
|
<!DOCTYPE html>
|
|
42
42
|
<html lang="en">
|
|
@@ -270,5 +270,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
270
270
|
`);let R=new v("!xml"),I=R,x="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let q=new A(this.options.processEntities);for(let _=0;_<y.length;_++)if(y[_]==="<")if(y[_+1]==="/"){let ee=bn(y,">",_,"Closing Tag is not closed."),B=y.substring(_+2,ee).trim();if(this.options.removeNSPrefix){let Ee=B.indexOf(":");Ee!==-1&&(B=B.substr(Ee+1))}B=Gn(this.options.transformTagName,B,"",this.options).tagName,I&&(x=this.saveTextToParentTag(x,I,this.matcher));let Se=this.matcher.getCurrentTag();if(B&&this.options.unpairedTags.indexOf(B)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${B}>`);Se&&this.options.unpairedTags.indexOf(Se)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,I=this.tagsNodeStack.pop(),x="",_=ee}else if(y[_+1]==="?"){let ee=kn(y,_,!1,"?>");if(!ee)throw new Error("Pi Tag is not closed.");if(x=this.saveTextToParentTag(x,I,this.matcher),!(this.options.ignoreDeclaration&&ee.tagName==="?xml"||this.options.ignorePiTags)){let B=new v(ee.tagName);B.add(this.options.textNodeName,""),ee.tagName!==ee.tagExp&&ee.attrExpPresent&&(B[":@"]=this.buildAttributesMap(ee.tagExp,this.matcher,ee.tagName)),this.addChild(I,B,this.matcher,_)}_=ee.closeIndex+1}else if(y.substr(_+1,3)==="!--"){let ee=bn(y,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let B=y.substring(_+4,ee-2);x=this.saveTextToParentTag(x,I,this.matcher),I.add(this.options.commentPropName,[{[this.options.textNodeName]:B}])}_=ee}else if(y.substr(_+1,2)==="!D"){let ee=q.readDocType(y,_);this.docTypeEntities=ee.entities,_=ee.i}else if(y.substr(_+1,2)==="!["){let ee=bn(y,"]]>",_,"CDATA is not closed.")-2,B=y.substring(_+9,ee);x=this.saveTextToParentTag(x,I,this.matcher);let Se=this.parseTextData(B,I.tagname,this.matcher,!0,!1,!0,!0);Se==null&&(Se=""),this.options.cdataPropName?I.add(this.options.cdataPropName,[{[this.options.textNodeName]:B}]):I.add(this.options.textNodeName,Se),_=ee+2}else{let ee=kn(y,_,this.options.removeNSPrefix);if(!ee){let tn=y.substring(Math.max(0,_-50),Math.min(y.length,_+50));throw new Error(`readTagExp returned undefined at position ${_}. Context: "${tn}"`)}let B=ee.tagName,Se=ee.rawTagName,Ee=ee.tagExp,je=ee.attrExpPresent,Rt=ee.closeIndex;if({tagName:B,tagExp:Ee}=Gn(this.options.transformTagName,B,Ee,this.options),this.options.strictReservedNames&&(B===this.options.commentPropName||B===this.options.cdataPropName||B===this.options.textNodeName||B===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${B}`);I&&x&&I.tagname!=="!xml"&&(x=this.saveTextToParentTag(x,I,this.matcher,!1));let pn=I;pn&&this.options.unpairedTags.indexOf(pn.tagname)!==-1&&(I=this.tagsNodeStack.pop(),this.matcher.pop());let ci=!1;Ee.length>0&&Ee.lastIndexOf("/")===Ee.length-1&&(ci=!0,B[B.length-1]==="/"?(B=B.substr(0,B.length-1),Ee=B):Ee=Ee.substr(0,Ee.length-1),je=B!==Ee);let wt=null,xn={},ui;ui=se(Se),B!==R.tagname&&this.matcher.push(B,{},ui),B!==Ee&&je&&(wt=this.buildAttributesMap(Ee,this.matcher,B),wt&&(xn=ce(wt,this.options))),B!==R.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let wn=_;if(this.isCurrentNodeStopNode){let tn="";if(ci)_=ee.closeIndex;else if(this.options.unpairedTags.indexOf(B)!==-1)_=ee.closeIndex;else{let di=this.readStopNodeData(y,Se,Rt+1);if(!di)throw new Error(`Unexpected end of ${Se}`);_=di.i,tn=di.tagContent}let li=new v(B);wt&&(li[":@"]=wt),li.add(this.options.textNodeName,tn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(I,li,this.matcher,wn)}else{if(ci){({tagName:B,tagExp:Ee}=Gn(this.options.transformTagName,B,Ee,this.options));let tn=new v(B);wt&&(tn[":@"]=wt),this.addChild(I,tn,this.matcher,wn),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(B)!==-1){let tn=new v(B);wt&&(tn[":@"]=wt),this.addChild(I,tn,this.matcher,wn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,_=ee.closeIndex;continue}else{let tn=new v(B);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(I),wt&&(tn[":@"]=wt),this.addChild(I,tn,this.matcher,wn),I=tn}x="",_=Rt}}else x+=y[_];return R.child},"parseXml");function de(y,R,I,x){this.options.captureMetaData||(x=void 0);let q=this.options.jPath?I.toString():I,_=this.options.updateTag(R.tagname,q,R[":@"]);_===!1||(typeof _=="string"&&(R.tagname=_),y.addChild(R,x))}i(de,"addChild"),n(de,"addChild");function pe(y,R,I){let x=this.options.processEntities;if(!x||!x.enabled)return y;if(x.allowedTags){let q=this.options.jPath?I.toString():I;if(!(Array.isArray(x.allowedTags)?x.allowedTags.includes(R):x.allowedTags(R,q)))return y}if(x.tagFilter){let q=this.options.jPath?I.toString():I;if(!x.tagFilter(R,q))return y}for(let q of Object.keys(this.docTypeEntities)){let _=this.docTypeEntities[q],re=y.match(_.regx);if(re){if(this.entityExpansionCount+=re.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);let ee=y.length;if(y=y.replace(_.regx,_.val),x.maxExpandedLength&&(this.currentExpandedLength+=y.length-ee,this.currentExpandedLength>x.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${x.maxExpandedLength}`)}}for(let q of Object.keys(this.lastEntities)){let _=this.lastEntities[q],re=y.match(_.regex);if(re&&(this.entityExpansionCount+=re.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);y=y.replace(_.regex,_.val)}if(y.indexOf("&")===-1)return y;if(this.options.htmlEntities)for(let q of Object.keys(this.htmlEntities)){let _=this.htmlEntities[q],re=y.match(_.regex);if(re&&(this.entityExpansionCount+=re.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);y=y.replace(_.regex,_.val)}return y=y.replace(this.ampEntity.regex,this.ampEntity.val),y}i(pe,"replaceEntitiesValue"),n(pe,"replaceEntitiesValue");function Pe(y,R,I,x){return y&&(x===void 0&&(x=R.child.length===0),y=this.parseTextData(y,R.tagname,I,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,x),y!==void 0&&y!==""&&R.add(this.options.textNodeName,y),y=""),y}i(Pe,"saveTextToParentTag"),n(Pe,"saveTextToParentTag");function xe(y,R){if(!y||y.length===0)return!1;for(let I=0;I<y.length;I++)if(R.matches(y[I]))return!0;return!1}i(xe,"isItStopNode"),n(xe,"isItStopNode");function j(y,R,I=">"){let x,q="";for(let _=R;_<y.length;_++){let re=y[_];if(x)re===x&&(x="");else if(re==='"'||re==="'")x=re;else if(re===I[0])if(I[1]){if(y[_+1]===I[1])return{data:q,index:_}}else return{data:q,index:_};else re===" "&&(re=" ");q+=re}}i(j,"tagExpWithClosingIndex"),n(j,"tagExpWithClosingIndex");function bn(y,R,I,x){let q=y.indexOf(R,I);if(q===-1)throw new Error(x);return q+R.length-1}i(bn,"findClosingIndex"),n(bn,"findClosingIndex");function kn(y,R,I,x=">"){let q=j(y,R+1,x);if(!q)return;let _=q.data,re=q.index,ee=_.search(/\s/),B=_,Se=!0;ee!==-1&&(B=_.substring(0,ee),_=_.substring(ee+1).trimStart());let Ee=B;if(I){let je=B.indexOf(":");je!==-1&&(B=B.substr(je+1),Se=B!==q.data.substr(je+1))}return{tagName:B,tagExp:_,closeIndex:re,attrExpPresent:Se,rawTagName:Ee}}i(kn,"readTagExp"),n(kn,"readTagExp");function jo(y,R,I){let x=I,q=1;for(;I<y.length;I++)if(y[I]==="<")if(y[I+1]==="/"){let _=bn(y,">",I,`${R} is not closed`);if(y.substring(I+2,_).trim()===R&&(q--,q===0))return{tagContent:y.substring(x,I),i:_};I=_}else if(y[I+1]==="?")I=bn(y,"?>",I+1,"StopNode is not closed.");else if(y.substr(I+1,3)==="!--")I=bn(y,"-->",I+3,"StopNode is not closed.");else if(y.substr(I+1,2)==="![")I=bn(y,"]]>",I,"StopNode is not closed.")-2;else{let _=kn(y,I,">");_&&((_&&_.tagName)===R&&_.tagExp[_.tagExp.length-1]!=="/"&&q++,I=_.closeIndex)}}i(jo,"readStopNodeData"),n(jo,"readStopNodeData");function ro(y,R,I){if(R&&typeof y=="string"){let x=y.trim();return x==="true"?!0:x==="false"?!1:Ct(y,I)}else return l(y)?y:""}i(ro,"parseValue"),n(ro,"parseValue");function yr(y,R,I){let x=Number.parseInt(y,R);return x>=0&&x<=1114111?String.fromCodePoint(x):I+y+";"}i(yr,"fromCodePoint"),n(yr,"fromCodePoint");function Gn(y,R,I,x){if(y){let q=y(R);I===R&&(I=q),R=q}return R=br(R,x),{tagName:R,tagExp:I}}i(Gn,"transformTagName"),n(Gn,"transformTagName");function br(y,R){if(p.includes(y))throw new Error(`[SECURITY] Invalid name: "${y}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(y)?R.onDangerousProperty(y):y}i(br,"sanitizeName"),n(br,"sanitizeName");var Rn=v.getMetaDataSymbol();function Rr(y,R){if(!y||typeof y!="object")return{};if(!R)return y;let I={};for(let x in y)if(x.startsWith(R)){let q=x.substring(R.length);I[q]=y[x]}else I[x]=y[x];return I}i(Rr,"stripAttributePrefix"),n(Rr,"stripAttributePrefix");function wr(y,R,I){return Co(y,R,I)}i(wr,"prettify"),n(wr,"prettify");function Co(y,R,I){let x,q={};for(let _=0;_<y.length;_++){let re=y[_],ee=ti(re);if(ee!==void 0&&ee!==R.textNodeName){let B=Rr(re[":@"]||{},R.attributeNamePrefix);I.push(ee,B)}if(ee===R.textNodeName)x===void 0?x=re[ee]:x+=""+re[ee];else{if(ee===void 0)continue;if(re[ee]){let B=Co(re[ee],R,I),Se=Ho(B,R);if(re[":@"]?Sr(B,re[":@"],I,R):Object.keys(B).length===1&&B[R.textNodeName]!==void 0&&!R.alwaysCreateTextNode?B=B[R.textNodeName]:Object.keys(B).length===0&&(R.alwaysCreateTextNode?B[R.textNodeName]="":B=""),re[Rn]!==void 0&&typeof B=="object"&&B!==null&&(B[Rn]=re[Rn]),q[ee]!==void 0&&Object.prototype.hasOwnProperty.call(q,ee))Array.isArray(q[ee])||(q[ee]=[q[ee]]),q[ee].push(B);else{let Ee=R.jPath?I.toString():I;R.isArray(ee,Ee,Se)?q[ee]=[B]:q[ee]=B}ee!==void 0&&ee!==R.textNodeName&&I.pop()}}}return typeof x=="string"?x.length>0&&(q[R.textNodeName]=x):x!==void 0&&(q[R.textNodeName]=x),q}i(Co,"compress"),n(Co,"compress");function ti(y){let R=Object.keys(y);for(let I=0;I<R.length;I++){let x=R[I];if(x!==":@")return x}}i(ti,"propName"),n(ti,"propName");function Sr(y,R,I,x){if(R){let q=Object.keys(R),_=q.length;for(let re=0;re<_;re++){let ee=q[re],B=ee.startsWith(x.attributeNamePrefix)?ee.substring(x.attributeNamePrefix.length):ee,Se=x.jPath?I.toString()+"."+B:I;x.isArray(ee,Se,!0,!0)?y[ee]=[R[ee]]:y[ee]=R[ee]}}}i(Sr,"assignAttributes"),n(Sr,"assignAttributes");function Ho(y,R){let{textNodeName:I}=R,x=Object.keys(y).length;return!!(x===0||x===1&&(y[I]||typeof y[I]=="boolean"||y[I]===0))}i(Ho,"isLeafTag"),n(Ho,"isLeafTag");var ni={allowBooleanAttributes:!1,unpairedTags:[]};function Cr(y,R){R=Object.assign({},ni,R);let I=[],x=!1,q=!1;y[0]==="\uFEFF"&&(y=y.substr(1));for(let _=0;_<y.length;_++)if(y[_]==="<"&&y[_+1]==="?"){if(_+=2,_=Jt(y,_),_.err)return _}else if(y[_]==="<"){let re=_;if(_++,y[_]==="!"){_=vr(y,_);continue}else{let ee=!1;y[_]==="/"&&(ee=!0,_++);let B="";for(;_<y.length&&y[_]!==">"&&y[_]!==" "&&y[_]!==" "&&y[_]!==`
|
|
271
271
|
`&&y[_]!=="\r";_++)B+=y[_];if(B=B.trim(),B[B.length-1]==="/"&&(B=B.substring(0,B.length-1),_--),!Wi(B)){let je;return B.trim().length===0?je="Invalid space after '<'.":je="Tag '"+B+"' is an invalid name.",at("InvalidTag",je,Ut(y,_))}let Se=ri(y,_);if(Se===!1)return at("InvalidAttr","Attributes for '"+B+"' have open quote.",Ut(y,_));let Ee=Se.value;if(_=Se.index,Ee[Ee.length-1]==="/"){let je=_-Ee.length;Ee=Ee.substring(0,Ee.length-1);let Rt=Tr(Ee,R);if(Rt===!0)x=!0;else return at(Rt.err.code,Rt.err.msg,Ut(y,je+Rt.err.line))}else if(ee)if(Se.tagClosed){if(Ee.trim().length>0)return at("InvalidTag","Closing tag '"+B+"' can't have attributes or invalid starting.",Ut(y,re));if(I.length===0)return at("InvalidTag","Closing tag '"+B+"' has not been opened.",Ut(y,re));{let je=I.pop();if(B!==je.tagName){let Rt=Ut(y,je.tagStartPos);return at("InvalidTag","Expected closing tag '"+je.tagName+"' (opened in line "+Rt.line+", col "+Rt.col+") instead of closing tag '"+B+"'.",Ut(y,re))}I.length==0&&(q=!0)}}else return at("InvalidTag","Closing tag '"+B+"' doesn't have proper closing.",Ut(y,_));else{let je=Tr(Ee,R);if(je!==!0)return at(je.err.code,je.err.msg,Ut(y,_-Ee.length+je.err.line));if(q===!0)return at("InvalidXml","Multiple possible root nodes found.",Ut(y,_));R.unpairedTags.indexOf(B)!==-1||I.push({tagName:B,tagStartPos:re}),x=!0}for(_++;_<y.length;_++)if(y[_]==="<")if(y[_+1]==="!"){_++,_=vr(y,_);continue}else if(y[_+1]==="?"){if(_=Jt(y,++_),_.err)return _}else break;else if(y[_]==="&"){let je=si(y,_);if(je==-1)return at("InvalidChar","char '&' is not expected.",Ut(y,_));_=je}else if(q===!0&&!Go(y[_]))return at("InvalidXml","Extra text at the end",Ut(y,_));y[_]==="<"&&_--}}else{if(Go(y[_]))continue;return at("InvalidChar","char '"+y[_]+"' is not expected.",Ut(y,_))}if(x){if(I.length==1)return at("InvalidTag","Unclosed tag '"+I[0].tagName+"'.",Ut(y,I[0].tagStartPos));if(I.length>0)return at("InvalidXml","Invalid '"+JSON.stringify(I.map(_=>_.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return at("InvalidXml","Start tag expected.",1);return!0}i(Cr,"validate"),n(Cr,"validate");function Go(y){return y===" "||y===" "||y===`
|
|
272
272
|
`||y==="\r"}i(Go,"isWhiteSpace"),n(Go,"isWhiteSpace");function Jt(y,R){let I=R;for(;R<y.length;R++)if(y[R]=="?"||y[R]==" "){let x=y.substr(I,R-I);if(R>5&&x==="xml")return at("InvalidXml","XML declaration allowed only at the start of the document.",Ut(y,R));if(y[R]=="?"&&y[R+1]==">"){R++;break}else continue}return R}i(Jt,"readPI"),n(Jt,"readPI");function vr(y,R){if(y.length>R+5&&y[R+1]==="-"&&y[R+2]==="-"){for(R+=3;R<y.length;R++)if(y[R]==="-"&&y[R+1]==="-"&&y[R+2]===">"){R+=2;break}}else if(y.length>R+8&&y[R+1]==="D"&&y[R+2]==="O"&&y[R+3]==="C"&&y[R+4]==="T"&&y[R+5]==="Y"&&y[R+6]==="P"&&y[R+7]==="E"){let I=1;for(R+=8;R<y.length;R++)if(y[R]==="<")I++;else if(y[R]===">"&&(I--,I===0))break}else if(y.length>R+9&&y[R+1]==="["&&y[R+2]==="C"&&y[R+3]==="D"&&y[R+4]==="A"&&y[R+5]==="T"&&y[R+6]==="A"&&y[R+7]==="["){for(R+=8;R<y.length;R++)if(y[R]==="]"&&y[R+1]==="]"&&y[R+2]===">"){R+=2;break}}return R}i(vr,"readCommentAndCDATA"),n(vr,"readCommentAndCDATA");var ha='"',oi="'";function ri(y,R){let I="",x="",q=!1;for(;R<y.length;R++){if(y[R]===ha||y[R]===oi)x===""?x=y[R]:x!==y[R]||(x="");else if(y[R]===">"&&x===""){q=!0;break}I+=y[R]}return x!==""?!1:{value:I,index:R,tagClosed:q}}i(ri,"readAttributeStr"),n(ri,"readAttributeStr");var Ki=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Tr(y,R){let I=c(y,Ki),x={};for(let q=0;q<I.length;q++){if(I[q][1].length===0)return at("InvalidAttr","Attribute '"+I[q][2]+"' has no space in starting.",_n(I[q]));if(I[q][3]!==void 0&&I[q][4]===void 0)return at("InvalidAttr","Attribute '"+I[q][2]+"' is without value.",_n(I[q]));if(I[q][3]===void 0&&!R.allowBooleanAttributes)return at("InvalidAttr","boolean attribute '"+I[q][2]+"' is not allowed.",_n(I[q]));let _=I[q][2];if(!ai(_))return at("InvalidAttr","Attribute '"+_+"' is an invalid name.",_n(I[q]));if(!Object.prototype.hasOwnProperty.call(x,_))x[_]=1;else return at("InvalidAttr","Attribute '"+_+"' is repeated.",_n(I[q]))}return!0}i(Tr,"validateAttributeString"),n(Tr,"validateAttributeString");function ii(y,R){let I=/\d/;for(y[R]==="x"&&(R++,I=/[\da-fA-F]/);R<y.length;R++){if(y[R]===";")return R;if(!y[R].match(I))break}return-1}i(ii,"validateNumberAmpersand"),n(ii,"validateNumberAmpersand");function si(y,R){if(R++,y[R]===";")return-1;if(y[R]==="#")return R++,ii(y,R);let I=0;for(;R<y.length;R++,I++)if(!(y[R].match(/\w/)&&I<20)){if(y[R]===";")break;return-1}return R}i(si,"validateAmpersand"),n(si,"validateAmpersand");function at(y,R,I){return{err:{code:y,msg:R,line:I.line||I,col:I.col}}}i(at,"getErrorObject"),n(at,"getErrorObject");function ai(y){return u(y)}i(ai,"validateAttrName"),n(ai,"validateAttrName");function Wi(y){return u(y)}i(Wi,"validateTagName"),n(Wi,"validateTagName");function Ut(y,R){let I=y.substring(0,R).split(/\r?\n/);return{line:I.length,col:I[I.length-1].length+1}}i(Ut,"getLineNumberForPosition"),n(Ut,"getLineNumberForPosition");function _n(y){return y.startIndex+y[1].length}i(_n,"getPositionFromMatch"),n(_n,"getPositionFromMatch");var Yi=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(y){this.externalEntities={},this.options=b(y)}parse(y,R){if(typeof y!="string"&&y.toString)y=y.toString();else if(typeof y!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(R){R===!0&&(R={});let q=Cr(y,R);if(q!==!0)throw Error(`${q.err.msg}:${q.err.line}:${q.err.col}`)}let I=new we(this.options);I.addExternalEntities(this.externalEntities);let x=I.parseXml(y);return this.options.preserveOrder||x===void 0?x:wr(x,this.options,I.matcher)}addEntity(y,R){if(R.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(y.indexOf("&")!==-1||y.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(R==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[y]=R}static getMetaDataSymbol(){return v.getMetaDataSymbol()}};return new Yi(t)},"getXmlParser");var QE=class extends To{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){let o=Ro(e,["textNodeName"]);super(o,n),Ke(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=o.parseOnStatusCodes?Yo(o.parseOnStatusCodes):void 0,this.parser=hB({removeNSPrefix:o?.removeNSPrefix??!0,ignorePiTags:o?.ignoreProcessingInstructions??!0,ignoreDeclaration:o?.ignoreDeclarations??!0,ignoreAttributes:o?.ignoreAttributes??!0,stopNodes:o?.stopNodes??[],attributeNamePrefix:o?.attributeNamePrefix??"@_",textNodeName:o?.textNodeName??"#text",trimValues:o?.trimValues??!0,processEntities:{enabled:!0,maxTotalExpansions:1/0,maxEntityCount:1e3}})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new Z(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var Wb=/(?:^|[?&;])([^=&#;?\s"'<>]+)=/g,gB=/[&#\s"'<>]/g;function eae(t,e,n){let o="",r=0;Wb.lastIndex=0;for(let s=Wb.exec(t);s!==null;s=Wb.exec(t)){if(!e.has(tae(s[1]).toLowerCase()))continue;let a=s.index+s[0].length;gB.lastIndex=a;let c=gB.exec(t)?.index??t.length;o+=t.slice(r,a)+n,r=c,Wb.lastIndex=c}return r===0?t:o+t.slice(r)}i(eae,"redactQueryParameters");function tae(t){let e=t.replaceAll("+"," ");try{return decodeURIComponent(e)}catch{return e}}i(tae,"decodeQueryName");var nae=.5;function oae(t){let e=t.replacement??"[REDACTED]";if(typeof e!="string")throw new T("createRedactor: 'replacement' must be a string.");let n=t.minConfidence??nae;if(typeof n!="number"||!(n>=0&&n<=1))throw new T("createRedactor: 'minConfidence' must be a number from 0 to 1.");let o=t.entities??[],{unknown:r}=dm(o);if(r.length>0)throw new T(`createRedactor: unknown entities ${JSON.stringify(r)}. Use a Data Loss Prevention recognizer id, group or id prefix.`);let s=[],a=Jy({entities:o,customPatterns:t.customPatterns},{warn:i(p=>{s.push(String(p?.name))},"warn")});if(s.length>0)throw new T(`createRedactor: custom patterns ${JSON.stringify(s)} are not valid regular expressions.`);let c=t.allowValues,u=new Set((t.fieldNames??[]).map(p=>p.toLowerCase())),l=new Set((t.queryParameters??[]).map(p=>p.toLowerCase())),d=encodeURIComponent(e);return(p,f)=>{if(u.size>0&&f.keys.some(g=>u.has(g.toLowerCase())))return e;let h=p;if(l.size>0&&h.includes("=")&&(h=eae(h,l,d)),a.length>0){let{matches:g}=ur(h,a,n,c);h=Ky(h,g,e)}return h}}i(oae,"createRedactor");var XE=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $e(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var eP=class{static{i(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Qe("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){me("utility.get-consumer");let n=bs(),o=this.bucketId??Xe.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new T("ApiKeyConsumerClient - no bucketId provided and no default bucket is configured for this environment. Pass `bucketId` explicitly (find it in the Zuplo portal under Settings > API Key Buckets).");if(!o.startsWith("bckt_"))throw new T(`ApiKeyConsumerClient - bucketId "${o}" is not a valid bucket id. Bucket ids start with "bckt_" (e.g. "bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL"); a bucket name (e.g. "zprj-...-working-copy") is not accepted here. Find the bucket id in the Zuplo portal under Settings > API Key Buckets.`);if(!e||e.trim()==="")throw new T("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let r=await this.getCacheName(o),s=new et(r,n);if(this.cacheDurationSeconds>0){let l=await s.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await qR(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&s.put(e,u,this.cacheDurationSeconds),u}};var yB=10,bB=3e4,tm=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i;#s={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#r=bB,this.#n=yB,this.#i=Number.POSITIVE_INFINITY}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:bB,this.#n=yB,this.#i=o.staleIfErrorSeconds===void 0?Number.POSITIVE_INFINITY:o.staleIfErrorSeconds*1e3}this.#t=e}#a(e){return e.expiry<=new Date}#c(e){let n=this.#s[e];return!(n===void 0||n===0)}#u(e){let n=this.#e.get(e);if(n&&!this.#a(n))return n.data}async get(e){let n=this.#u(e);if(n)return this.#d(e),n;if(this.#c(e))try{await rae(()=>this.#u(e)!==void 0||!this.#c(e),this.#r+this.#n+1,this.#n);let o=this.#u(e);if(o)return o}catch{}try{return await this.#l(e)}catch(o){let r=this.#e.get(e);if(r&&!this.#p(r))return r.data;throw o}}#p(e){return this.#i===Number.POSITIVE_INFINITY?!1:this.#i<=0?!0:Date.now()>e.expiry.getTime()+this.#i}#d(e){if(!this.#c(e)){let n=this.#l(e);fi().waitUntil(n)}}async#l(e){try{this.#s[e]===void 0&&(this.#s[e]=0),this.#s[e]++;let n=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(n===void 0)throw new T(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#s[e]--}}};async function rae(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new T(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(rae,"waitUntilTrue");import{trace as iae}from"@opentelemetry/api";var RB,wB=i(()=>(RB??=iae.getTracer("pipeline"),RB),"tracer"),SB=i(async(t,e,n)=>{let o=nt.instance.routeData.policies,r=Va([t],o);if(r.length===0)throw new Z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0],a;try{a=tt.getContextExtensions(n)}catch{a=void 0}let c=a?.currentPolicyName;a&&(a.currentPolicyName=s.policyName);try{return await wB().startActiveSpan(`policy:${s.policyName}`,async l=>{try{Za(l,s);let d=await s.handler(e,n);if(d instanceof Request||d instanceof Ge||d instanceof Response)return d instanceof Response||d instanceof Ge?d:new Ge(d);throw new T(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`)}catch(d){throw Wo(l,d),d}finally{l.end()}})}finally{a&&a.currentPolicyName===s.policyName&&(a.currentPolicyName=c)}},"invokeInboundPolicy"),CB=i(async(t,e,n,o)=>{let r=nt.instance.routeData.policies,s=dl([t],r);if(s.length===0)throw new Z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await wB().startActiveSpan(`policy:${a.policyName}`,async u=>{try{Za(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;throw new T(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`)}catch(l){throw Wo(u,l),l}finally{u.end()}})},"invokeOutboundPolicy");var gt=class{static{i(this,"BaseAnalyticsEvent")}eventId;requestId;timestamp;accountName;projectName;deploymentName;unit;value;constructor(e){this.eventId=e.eventId,this.requestId=e.requestId,this.timestamp=e.timestamp??new Date,this.accountName=e.accountName,this.projectName=e.projectName,this.deploymentName=e.deploymentName,this.unit=e.unit,this.value=e.value}};var Yb=class extends gt{static{i(this,"AiGatewayBlockedCountEvent")}eventType=$.AI_GATEWAY_BLOCKED_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Qb=class extends gt{static{i(this,"AiGatewayCostSumEvent")}eventType=$.AI_GATEWAY_COST_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown"),(!this.metadata.costSource||!this.metadata.costSource.trim())&&(this.metadata.costSource="unknown"),(!this.metadata.costAccuracy||!this.metadata.costAccuracy.trim())&&(this.metadata.costAccuracy="unknown")}};var Xb=class extends gt{static{i(this,"AiGatewayFallbackCountEvent")}eventType=$.AI_GATEWAY_FALLBACK_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var eR=class extends gt{static{i(this,"AiGatewayLatencyHistogramEvent")}eventType=$.AI_GATEWAY_LATENCY_HISTOGRAM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var tR=class extends gt{static{i(this,"AiGatewayRequestCountEvent")}eventType=$.AI_GATEWAY_REQUEST_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var nR=class extends gt{static{i(this,"AiGatewayTokenSumEvent")}eventType=$.AI_GATEWAY_TOKEN_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var oR=class extends gt{static{i(this,"AiGatewayWarningCountEvent")}eventType=$.AI_GATEWAY_WARNING_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var rR=class extends gt{static{i(this,"CacheOperationEvent")}eventType=$.CACHE_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var iR=class extends gt{static{i(this,"GraphqlOperationEvent")}eventType=$.GRAPHQL_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var sR=class extends gt{static{i(this,"HandlerExecutionEvent")}eventType=$.HANDLER_EXECUTION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var aR=class extends gt{static{i(this,"McpEvent")}eventType;metadata;constructor(e){super(e),this.eventType=e.eventType,this.metadata=e.metadata}};var cR=class extends gt{static{i(this,"RateLimitServiceCallEvent")}eventType=$.RATE_LIMIT_SERVICE_CALL;metadata;constructor(e){super(e),this.metadata=e.metadata}};var yt=i(t=>e=>new aR({...e,eventType:t}),"buildMcpEvent"),sae={[$.AI_GATEWAY_COST_SUM]:t=>new Qb(t),[$.AI_GATEWAY_REQUEST_COUNT]:t=>new tR(t),[$.AI_GATEWAY_TOKEN_SUM]:t=>new nR(t),[$.AI_GATEWAY_LATENCY_HISTOGRAM]:t=>new eR(t),[$.AI_GATEWAY_WARNING_COUNT]:t=>new oR(t),[$.AI_GATEWAY_BLOCKED_COUNT]:t=>new Yb(t),[$.AI_GATEWAY_FALLBACK_COUNT]:t=>new Xb(t),[$.MCP_REQUEST_RECEIVED]:yt($.MCP_REQUEST_RECEIVED),[$.MCP_REQUEST_COMPLETED]:yt($.MCP_REQUEST_COMPLETED),[$.MCP_REQUEST_REJECTED]:yt($.MCP_REQUEST_REJECTED),[$.MCP_INITIALIZE_NEGOTIATED]:yt($.MCP_INITIALIZE_NEGOTIATED),[$.MCP_CLIENT_UNSUPPORTED_BEHAVIOR]:yt($.MCP_CLIENT_UNSUPPORTED_BEHAVIOR),[$.MCP_CAPABILITY_LISTED]:yt($.MCP_CAPABILITY_LISTED),[$.MCP_CAPABILITY_INVOKED]:yt($.MCP_CAPABILITY_INVOKED),[$.MCP_CAPABILITY_COMPLETED]:yt($.MCP_CAPABILITY_COMPLETED),[$.MCP_CAPABILITY_FAILED]:yt($.MCP_CAPABILITY_FAILED),[$.MCP_CAPABILITY_CONNECT_REQUIRED]:yt($.MCP_CAPABILITY_CONNECT_REQUIRED),[$.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED]:yt($.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED),[$.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED]:yt($.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED),[$.MCP_OAUTH_CLIENT_REGISTERED]:yt($.MCP_OAUTH_CLIENT_REGISTERED),[$.MCP_OAUTH_AUTHORIZE_STARTED]:yt($.MCP_OAUTH_AUTHORIZE_STARTED),[$.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP]:yt($.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP),[$.MCP_OAUTH_TOKEN_ISSUED]:yt($.MCP_OAUTH_TOKEN_ISSUED),[$.MCP_OAUTH_TOKEN_REFRESH_ROTATED]:yt($.MCP_OAUTH_TOKEN_REFRESH_ROTATED),[$.MCP_OAUTH_TOKEN_REVOKED]:yt($.MCP_OAUTH_TOKEN_REVOKED),[$.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED]:yt($.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED),[$.MCP_AUTH_UPSTREAM_CONNECT_STARTED]:yt($.MCP_AUTH_UPSTREAM_CONNECT_STARTED),[$.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED]:yt($.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED),[$.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED]:yt($.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED),[$.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED]:yt($.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED),[$.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED]:yt($.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED),[$.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING]:yt($.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING),[$.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED]:yt($.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED),[$.GRAPHQL_OPERATION]:t=>new iR(t),[$.CACHE_OPERATION]:t=>new rR(t),[$.HANDLER_EXECUTION]:t=>new sR(t),[$.RATE_LIMIT_SERVICE_CALL]:t=>new cR(t)};function vB(t,e){let n=sae[t];return n(e)}i(vB,"createAnalyticsEvent");var uR=class{static{i(this,"ZuploGatewayAnalyticsContext")}#e;#t;constructor(e){this.#e=[],this.#t=e}addAnalyticsEvent(e,n,o,r,s){let a=this.createAnalyticsEvent(e,n,o,r,s);this.#e.push(a)}flushAnalyticsEvents(){let e=[...this.#e];return this.#e.length=0,e}getAnalyticsEvents(){return[...this.#e]}createAnalyticsEvent(e,n,o,r,s){return vB(n,{eventId:s??crypto.randomUUID(),requestId:this.#t,accountName:k.instance.accountName??"unknown",projectName:k.instance.projectName??"unknown",deploymentName:k.instance.deploymentName??"unknown",metadata:o,unit:r,value:e})}};var aae="127.0.0.1";function TB(t){let e=k.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?aae:void 0)}i(TB,"resolveClientIp");function cae(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[s,a]=r.split("=");s&&a&&(o[s.trim()]=a.trim())}),o.asnum&&(e[ef]=o.asnum),o.zip&&(e[tf]=o.zip.split("+")[0]),o.dma&&(e[nf]=o.dma),o.region_code&&(e[of]=o.region_code),o.timezone&&(e[rf]=o.timezone),o.city&&(e[Km]=o.city),o.continent&&(e[Wm]=o.continent),o.country_code&&(e[Ym]=o.country_code),o.long&&(e[Qm]=o.long),o.lat&&(e[Xm]=o.lat),e}catch{return{}}}i(cae,"parseEdgeScapeHeader");function AB(t,e){let n=cae(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(AB,"setZpHeadersFromAkamaiEdgeScapeHeader");var Ja=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(OP);if(n){let o=new Headers(e);AB(o,n),this.#e=o}}detachFromRequest(){this.#e=vi(this.#e)}get ip(){return TB(this.#e)}get asn(){try{let e=this.#e.get(ef);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(IP)??void 0}get city(){return this.#e.get(aP)??this.#e.get(Km)??void 0}get continent(){return this.#e.get(cP)??this.#e.get(Wm)??void 0}get country(){return this.#e.get(uP)??this.#e.get(Ym)??void 0}get latitude(){return this.#e.get(dP)??this.#e.get(Xm)??void 0}get longitude(){return this.#e.get(lP)??this.#e.get(Qm)??void 0}get colo(){return this.#e.get(EP)??void 0}get postalCode(){return this.#e.get(hP)??this.#e.get(tf)??void 0}get metroCode(){return this.#e.get(fP)??this.#e.get(nf)??void 0}get region(){return this.#e.get(pP)??this.#e.get(PP)??void 0}get regionCode(){return this.#e.get(mP)??this.#e.get(of)??void 0}get timezone(){return this.#e.get(gP)??this.#e.get(rf)??void 0}get httpProtocol(){return this.#e.get(kP)??void 0}get clientCert(){return this.#e.get(bP)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(RP)??void 0}get clientMtlsVerificationReason(){return this.#e.get(wP)??void 0}get clientCertFingerprintSha256(){return this.#e.get(SP)??void 0}get clientCertNotBefore(){return this.#e.get(CP)??void 0}get clientCertNotAfter(){return this.#e.get(vP)??void 0}get clientCertIssuerDn(){return this.#e.get(TP)??void 0}get clientCertSubjectDn(){return this.#e.get(AP)??void 0}toJSON(){return{ip:this.ip,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,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function iu(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(iu,"createRewriteContext");var tl=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},nl=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},uae=Object.freeze([]),tt=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n,o=n.url){if(!t.#e.has(e)){let r=new t(n,o);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static findContextExtensions(e){return t.#e.get(e)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new Z(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;originalRequest;receivedUrl;requestLogProperties=new Map;systemRequestLogProperties=new Map;#t;startDeferringMetrics(){return this.#t?!1:(this.#t=[],!0)}deferMetrics(e){return this.#t?(this.#t.push(e),!0):!1}flushDeferredMetrics(){let e=this.#t??[];this.#t=void 0;let n=[];for(let o of e)try{o()}catch(r){n.push(r)}return n}#o;#n=!1;addPipelineExitHook(e){if(this.#n){try{e(void 0)}catch(n){W.console.error("Error running a late pipeline exit hook",n)}return}this.#o??=[],this.#o.push(e)}runPipelineExitHooks(e){this.#n=!0;let n=this.#o;if(!n)return uae;this.#o=void 0;let o=[];for(let r of n)try{r(e)}catch(s){o.push(s)}return o}auditLogEventId="";preRequestState;currentPolicyName;preRequestPhase;#r;#i;#s;constructor(e,n){this.latestRequest=e,this.originalRequest=e.originalRequest,this.receivedUrl=n,this.preRequestState=void 0,this.currentPolicyName=void 0,this.preRequestPhase=void 0,this.#r=[],this.#i=[],this.#s=[]}addResponseSendingHook(e){this.#i.push(e)}addResponseSendingFinalHook(e){this.#r.push(e)}addHandlerResponseHook(e){this.#s.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#r)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=k.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#i)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#s)await r(e,n,o)},"onHandlerResponse")},lh=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:s,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,l)=>SB(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>CB(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new Ge(d,l);return nt.instance.handleRequest(p,this,{parentContext:this,routeBinding:mO(l)})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{tt.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{tt.getContextExtensions(this).addResponseSendingFinalHook(u)},this.addPreRequestHandler=(u,l)=>{Px(this,tt.getContextExtensions(this),u,l)},this.analyticsContext=new uR(o),Object.freeze(this)}#e;#t=new EventTarget;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addPreRequestHandler;addEventListener(e,n,o){me("context.addEventListener");let r=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");this.#t.addEventListener(e,r,o)}removeEventListener(e,n,o){me("context.removeEventListener"),this.#t.removeEventListener(e,n,o)}dispatchEvent(e){return this.#t.dispatchEvent(e)}};export{Xe as a,le as b,MR as c,Cn as d,Kt as e,Gu as f,uZ as g,NR as h,ut as i,xa as j,lZ as k,ds as l,UR as m,qR as n,DR as o,Pf as p,g_ as q,Jue as r,Kue as s,kf as t,Xue as u,ele as v,tle as w,KZ as x,nle as y,Ln as z,Er as A,Ma as B,ps as C,V as D,$t as E,ms as F,$ as G,zR as H,jR as I,Sf as J,Be as K,Dn as L,bi as M,he as N,To as O,Px as P,Fx as Q,BR as R,WR as S,NZ as T,wi as U,uR as V,iu as W,tl as X,nl as Y,tt as Z,Kw as _,Kn as $,xM as aa,g0 as ba,S0 as ca,xW as da,E0 as ea,US as fa,zW as ga,_s as ha,zn as ia,mo as ja,xs as ka,nr as la,or as ma,Ni as na,Ms as oa,Mr as pa,xt as qa,mg as ra,yc as sa,bc as ta,jl as ua,Hl as va,Rc as wa,ln as xa,Ui as ya,Ot as za,Tn as Aa,fn as Ba,wc as Ca,Mt as Da,Lr as Ea,Sc as Fa,Cc as Ga,Ls as Ha,Ns as Ia,qi as Ja,fg as Ka,vc as La,Gl as Ma,Tc as Na,Fl as Oa,Nr as Pa,tr as Qa,ko as Ra,hg as Sa,gg as Ta,Bl as Ua,Zl as Va,Ac as Wa,Ic as Xa,Vl as Ya,Jl as Za,Kl as _a,Wl as $a,Ec as ab,Yl as bb,Ql as cb,Pc as db,Xl as eb,Ur as fb,qr as gb,kc as hb,_c as ib,xc as jb,$r as kb,fo as lb,Oc as mb,ed as nb,td as ob,nd as pb,od as qb,rd as rb,Us as sb,id as tb,sd as ub,ad as vb,cd as wb,ud as xb,ld as yb,dd as zb,pd as Ab,Mc as Bb,md as Cb,fd as Db,hd as Eb,gd as Fb,yd as Gb,bd as Hb,Rd as Ib,wd as Jb,Sd as Kb,Cd as Lb,vd as Mb,Td as Nb,Ad as Ob,Id as Pb,_o as Qb,xo as Rb,Oo as Sb,Ed as Tb,Dr as Ub,zr as Vb,qs as Wb,Pd as Xb,kd as Yb,_d as Zb,xd as _b,Od as $b,Lc as ac,Md as bc,Ld as cc,Nc as dc,yg as ec,Nd as fc,Ud as gc,qd as hc,DS as ic,jr as jc,$d as kc,Dd as lc,zd as mc,jd as nc,Hd as oc,Gd as pc,Fd as qc,Bd as rc,Zd as sc,Li as tc,Vd as uc,Jd as vc,Kd as wc,Wd as xc,Yd as yc,Uc as zc,$s as Ac,Ds as Bc,qc as Cc,$c as Dc,Dc as Ec,Qd as Fc,zc as Gc,jc as Hc,Xd as Ic,ep as Jc,Hc as Kc,zs as Lc,tp as Mc,np as Nc,op as Oc,rp as Pc,ip as Qc,sp as Rc,ap as Sc,cp as Tc,up as Uc,lp as Vc,dp as Wc,pp as Xc,mp as Yc,fp as Zc,hp as _c,bg as $c,gp as ad,Hr as bd,Rg as cd,yp as dd,wg as ed,Sg as fd,Cg as gd,vg as hd,Tg as id,Ag as jd,Ig as kd,Eg as ld,Pg as md,kg as nd,_g as od,xg as pd,Og as qd,Mg as rd,Lg as sd,Ng as td,bp as ud,Rp as vd,Ug as wd,qg as xd,$g as yd,Dg as zd,wp as Ad,Sp as Bd,zg as Cd,jg as Dd,Hg as Ed,Yg as Fd,Mp as Gd,ty as Hd,zi as Id,bN as Jd,Vr as Kd,uy as Ld,CN as Md,Hp as Nd,h5 as Od,dU as Pd,T5 as Qd,E5 as Rd,FC as Sd,iEe as Td,yy as Ud,sEe as Vd,YC as Wd,G5 as Xd,QC as Yd,tv as Zd,AEe as _d,IEe as $d,KU as ae,Oq as be,Mq as ce,Lq as de,Nq as ee,Uq as fe,qq as ge,J8 as he,Sv as ie,r9 as je,Cv as ke,Tv as le,Iv as me,kv as ne,xv as oe,Mv as pe,Nv as qe,qv as re,zv as se,Gv as te,Zv as ue,Kv as ve,ea as we,At as xe,ar as ye,Yv as ze,Qv as Ae,Yp as Be,Qp as Ce,Xp as De,rT as Ee,nm as Fe,aT as Ge,cT as He,H9 as Ie,uT as Je,lT as Ke,vT as Le,IT as Me,Hy as Ne,Gy as Oe,TD as Pe,Xy as Qe,gA as Re,wA as Se,sb as Te,AA as Ue,PA as Ve,cz as We,UA as Xe,Mz as Ye,$z as Ze,Dz as _e,HA as $e,Hz as af,db as bf,fee as cf,GA as df,In as ef,Yz as ff,JA as gf,KA as hf,Xz as if,QA as jf,tj as kf,lj as lf,dj as mf,pj as nf,mj as of,fj as pf,hj as qf,iI as rf,bj as sf,Rj as tf,wj as uf,Sj as vf,Cj as wf,vj as xf,Tj as yf,Aj as zf,Ij as Af,Cb as Bf,Cte as Cf,_j as Df,Oj as Ef,pI as Ff,Ute as Gf,hI as Hf,Hj as If,Vi as Jf,wu as Kf,it as Lf,Pt as Mf,xZe as Nf,pr as Of,jZe as Pf,Am as Qf,BZe as Rf,ZZe as Sf,to as Tf,KZe as Uf,WZe as Vf,YZe as Wf,QZe as Xf,XZe as Yf,e2e as Zf,t2e as _f,n2e as $f,Im as ag,o2e as bg,ca as cg,c2e as dg,Eb as eg,ua as fg,Cu as gg,RI as hg,w2e as ig,wI as jg,SI as kg,CI as lg,vI as mg,TI as ng,AI as og,II as pg,EI as qg,PI as rg,kI as sg,xH as tg,So as ug,no as vg,zt as wg,NH as xg,Jne as yg,Kne as zg,_I as Ag,UJe as Bg,qJe as Cg,$Je as Dg,XH as Eg,e1 as Fg,cKe as Gg,uKe as Hg,xI as Ig,Pm as Jg,Lb as Kg,lKe as Lg,o1 as Mg,fKe as Ng,km as Og,r1 as Pg,i1 as Qg,wKe as Rg,SKe as Sg,CKe as Tg,vKe as Ug,s1 as Vg,a1 as Wg,u1 as Xg,mr as Yg,ei as Zg,voe as _g,Toe as $g,xKe as ah,OKe as bh,MKe as ch,LKe as dh,fr as eh,LI as fh,Poe as gh,VKe as hh,p1 as ih,o4e as jh,NI as kh,_oe as lh,$oe as mh,zoe as nh,h1 as oh,g4e as ph,y4e as qh,b4e as rh,R1 as sh,C4e as th,v4e as uh,T4e as vh,jI as wh,$b as xh,HI as yh,C1 as zh,M4e as Ah,L4e as Bh,N4e as Ch,U4e as Dh,bG as Eh,oo as Fh,lWe as Gh,rE as Hh,bWe as Ih,RG as Jh,RWe as Kh,lie as Lh,die as Mh,$We as Nh,DWe as Oh,pie as Ph,FWe as Qh,MG as Rh,VWe as Sh,dE as Th,pE as Uh,zG as Vh,Nie as Wh,FG as Xh,bE as Yh,eF as Zh,wE as _h,uF as $h,SE as ai,vE as bi,dF as ci,pF as di,mF as ei,IE as fi,PE as gi,wF as hi,SF as ii,CF as ji,vF as ki,TF as li,IF as mi,xE as ni,ase as oi,xF as pi,NE as qi,qF as ri,$F as si,DF as ti,wse as ui,zF as vi,jF as wi,HF as xi,GF as yi,FF as zi,DE as Ai,ZF as Bi,VF as Ci,zE as Di,jE as Ei,WF as Fi,QF as Gi,XF as Hi,FE as Ii,tB as Ji,aB as Ki,KE as Li,WE as Mi,cB as Ni,fB as Oi,QE as Pi,oae as Qi,XE as Ri,eP as Si,tm as Ti};
|
|
273
|
-
/*! For license information please see chunk-
|
|
274
|
-
//# sourceMappingURL=chunk-
|
|
273
|
+
/*! For license information please see chunk-C4ZTXG6P.js.LEGAL.txt */
|
|
274
|
+
//# sourceMappingURL=chunk-C4ZTXG6P.js.map
|