@zuplo/runtime 7.13.13 → 7.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as $E,b as zE,c as VE,d as Yr,e as He,f as WE,g as bm,h as YE,i as QE,j as XE,k as tb,m as nb,o as eP,q as ob,r as rb}from"./chunk-VP5Q3DEN.js";import{a as Fe}from"./chunk-QGAJTUPE.js";import{$ as _,A as cm,Aa as ZE,B as wE,Ba as m,C as SE,Ca as Di,D as CE,Da as Xe,E as vE,Ea as Xs,F as TE,G as IE,Ga as tt,H as EE,Ha as $t,I as PE,Ia as gm,J as AE,Ja as JE,K as um,Ka as ym,L as kE,La as KE,M as _E,Ma as tP,N as lm,Na as su,O as dm,Oa as nP,P as xE,Pa as oP,Q as pm,R as mm,S as OE,T as ME,U as LE,V as NE,W as UE,X as qE,Y as Ys,Z as DE,_ as fm,a as $e,aa as V,b as Xy,ba as jE,c as H,ca as eb,d as v,da as HE,e as ct,ea as w,f as iE,fa as FE,g as Li,ga as hm,h as sE,ha as oe,i as Ws,ia as Ce,j as aE,ja as Ni,k as cE,ka as GE,l as uE,la as Ue,m as lE,ma as U,n as dE,na as O,o as pE,oa as qe,p as mE,pa as ve,q as fE,qa as Qs,r as hE,ra as Wr,s as gE,sa as ye,t as yE,ta as Ve,u as bE,ua as D,v as RE,va as Me,w as rm,wa as iu,x as im,xa as Ui,y as sm,ya as BE,z as am,za as qi}from"./chunk-KA4STQE7.js";import{a as he}from"./chunk-UKQQD2JN.js";import{a as i,b as RH,d as wH}from"./chunk-TYV53J3B.js";var UA=RH(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.parse=zF;Km.serialize=jF;var LF=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,NF=/^[\u0021-\u003A\u003C-\u007E]*$/,UF=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qF=/^[\u0020-\u003A\u003D-\u007E]*$/,DF=Object.prototype.toString,$F=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function zF(t,e){let n=new $F,o=t.length;if(o<2)return n;let r=e?.decode||HF,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=LA(t,s,a),d=NA(t,a,l),p=t.slice(l,d);if(n[p]===void 0){let f=LA(t,a+1,u),h=NA(t,u,f),y=r(t.slice(f,h));n[p]=y}s=u+1}while(s<o);return n}i(zF,"parse");function LA(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(LA,"startIndex");function NA(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(NA,"endIndex");function jF(t,e,n){let o=n?.encode||encodeURIComponent;if(!LF.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!NF.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(!UF.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!qF.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!FF(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(jF,"serialize");function HF(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(HF,"decode");function FF(t){return DF.call(t)==="[object Date]"}i(FF,"isDate")});var et=new Proxy({},{get(t,e){let n=String(e);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return _.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return _.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return _.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return _.instance.accountName;case"ZUPLO_PROJECT_NAME":return _.instance.projectName;case"ZUPLO_BUILD_ID":return _.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return _.instance.build.COMPATIBILITY_DATE}if(!($E(n)&&!zE(n)))return _.instance.runtime[n]}});var rP=new Map([["input","input"],["cache-read-input","cache_read_input"],["cache-write-input","cache_write_input"],["output","output"]]),SH=new Set(["5m","1h"]);function iP(t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).filter(([,e])=>e!==null))}i(iP,"withoutNullFields");var sP=m.number().int().min(0).max(Number.MAX_SAFE_INTEGER),CH=m.object({category:m.enum(["input","cache_read_input","cache_write_input","output"]),costPerToken:m.number().nonnegative(),minInputTokens:sP.optional(),maxInputTokens:sP.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"})}),vH=m.object({revision:m.string().min(1),currency:m.literal("USD"),rates:m.array(CH)}).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 TH(t){let e=iP(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=iP(s);if(typeof a!="object"||a===null||Array.isArray(a)){r.push(a);continue}let{category:c,cacheTtl:u}=a;if(typeof c=="string"&&!rP.has(c)){o.push(`category ${JSON.stringify(c)}`);continue}if(typeof u=="string"&&!SH.has(u)){o.push(`cacheTtl ${JSON.stringify(u)}`);continue}r.push(typeof c=="string"?{...a,category:rP.get(c)}:a)}return{card:{...e,rates:r},ignoredRates:o}}i(TH,"fromWireCard");function uP(t){let e=vH.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(uP,"parseTokenRateCard");function aP(t){if(t==null)return{};let{card:e,ignoredRates:n}=TH(t),o=uP(e);return o.tokenRateCard===void 0||n.length===0?o:{...o,ignoredRates:n}}i(aP,"validateTokenRateCard");function Rm(t){return[t.category,t.cacheTtl??"",t.minInputTokens??"",t.maxInputTokens??""].join("\0")}i(Rm,"rateSelector");function IH(t,e){let n=new Map(e.rates.map(r=>[Rm(r),r])),o=new Set(t.rates.map(Rm));return{revision:e.revision,currency:e.currency,rates:[...t.rates.map(r=>n.get(Rm(r))??r),...e.rates.filter(r=>!o.has(Rm(r)))]}}i(IH,"mergeTokenRateCards");function lP(t,e){let n=aP(t);if(n.tokenRateCard===void 0)return n.error===void 0?{}:{error:n.error};let o=aP(e),r=[cP("list",n),cP("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=uP(IH(n.tokenRateCard,o.tokenRateCard));return a.tokenRateCard===void 0?{tokenRateCard:n.tokenRateCard,overrideError:`merged card: ${a.error}`,...s}:{tokenRateCard:a.tokenRateCard,...s}}i(lP,"resolveModelTokenRateCard");function cP(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(cP,"ignoredRatesOf");var de=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 V.console.error(o),new $e(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function pt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${_.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",_.instance.deploymentName??"unknown"),t.set("User-Agent",_.instance.systemUserAgent),t.set("zp-compat-date",_.instance.build.COMPATIBILITY_DATE??"none")}i(pt,"setZuploHeaders");var pP=["openai","anthropic","google","mistral","xai","bedrock-mantle","vertex-ai","openrouter","jev"];function dP(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(dP,"defineOwn");function EH(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};dP(a,u,p);let f=u.toLowerCase();f!==u&&!Object.hasOwn(a,f)&&dP(a,f,{...p,model:f})}}}i(EH,"applyDeploymentModelAliases");var PH="openrouter",AH=[":nitro",":floor",":online",":exacto"],kH="bedrock-runtime",_H=/^arn:aws(?:-[a-z]+)*:bedrock:[a-z0-9-]+:\d*:(?:foundation-model|inference-profile)\/([^/]+)$/;function xH(t){return _H.exec(t)?.[1]}i(xH,"bedrockArnModelId");function ur(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===kH){let u=xH(e);return u===void 0?void 0:r(u)}if(a!==PH)return;let c=AH.find(u=>e.endsWith(u));if(c!==void 0)return r(e.slice(0,-c.length))}i(ur,"resolveModelRow");var OH=60,mP="connections-v1";async function fP(t){let e=await Xe("supported-models",{});return new tt(e,t)}i(fP,"createSupportedModelsCache");async function au(t){return(await fP(t)).get(mP)}i(au,"getCachedSupportedModels");function ib(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(ib,"isRecord");function MH(t){return ib(t)&&Array.isArray(t.data)&&t.data.every(e=>ib(e)&&typeof e.label=="string"&&typeof e.providerType=="string"&&typeof e.isCustom=="boolean"&&Array.isArray(e.models)&&e.models.every(n=>ib(n)&&typeof n.model=="string"&&typeof n.kind=="string"&&typeof n.status=="string"))}i(MH,"isProviderAssignmentsResponse");function LH(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(LH,"fromProviderAssignments");function NH(t){let e=typeof t=="object"&&t!==null?t.revision:void 0;return typeof e=="string"?e:void 0}i(NH,"overrideRevision");function UH(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=lP(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:NH(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 EH(n,o,e),{modelsByProvider:n,providerMetadata:o}}i(UH,"buildSupportedModels");async function oo(t,e){let n=de.getLogger(t),o=await au(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"});pt(r,t.requestId);let s=et.ZUPLO_SERVICE_BUCKET_ID,a=new URL(`/v1/buckets/${s}/provider-assignments?includeDeprecated=true`,_.instance.zuploEdgeApiUrl).toString(),c=await $t({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(),y=JSON.parse(h);n.error(f,y),f=`${f}: ${y.message||c.statusText}`}catch{n.error(f,{status:c.status}),f=`${f}: ${c.status}`}throw new Error(f)}let u=await c.json();if(!MH(u)){let f="Gateway service returned an unexpected provider assignments body";throw n.error(f,{bucketId:s}),new Error(f)}let l=LH(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=UH(l,n),p=await fP(t);return e?.signal.throwIfAborted(),p.put(mP,d,OH),d}i(oo,"getSupportedModels");async function hP(t){let e=new AbortController,n;try{return await Promise.race([oo(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(hP,"getDiscoverySupportedModels");function sb(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(sb,"resolveProviderLabel");function gP(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(gP,"describeProviderAssignments");function yP(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(yP,"isModelSupported");function bP(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(bP,"getModelsByProviderAndKind");var RP=new he(Symbol("ai-gateway-provider-credential-passthrough"));function wP(t,e){RP.set(t,e)}i(wP,"setProviderCredentialPassthrough");function ab(t){return RP.get(t)}i(ab,"getProviderCredentialPassthrough");function wm(t){return ab(t)!==void 0}i(wm,"hasProviderCredentialPassthrough");function qH(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(qH,"publicTokenRateCard");var IP=Symbol("ai-gateway-model-selection"),DH="zuplodemo",$H="azure-ai",cu="https://demo.zuplo.ai";function zH(t){return t?.providerType?.toLowerCase()===DH&&t.isCustom!==!0}i(zH,"isZuploDemoAssignment");var SP=Symbol("ai-gateway-model-routing"),$i='Use "providerName/model", for example "openai/gpt-5".',cb=["completions","embeddings"],CP=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function _o(t,e,n){throw new v(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(_o,"invalid");function an(t,e,n,o){return o?o(t,e,n):_o(t,e,n)}i(an,"reject");function ub(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(ub,"isRecord");function ln(t,e,n){if(typeof t!="string")return an(e,"must be a string",$i,n);if(t.length===0)return an(e,"must not be empty",$i,n);if(t.trim()!==t||/\s/.test(t))return an(e,`contains whitespace in '${t}'`,$i,n);let o=t.indexOf("/");if(o===-1)return an(e,`'${t}' has no provider name separator`,$i,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?an(e,`'${t}' has an empty provider name`,$i,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?an(e,`'${t}' has an empty model`,$i,n):s.startsWith("/")?an(e,`'${t}' starts the model with an extra "/"`,$i,n):{provider:r,model:s,raw:t}:an(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(ln,"parseModelRef");function jH(t,e,n){let o=typeof t=="string"?{main:t}:ub(t)?t:{};if(typeof t!="string"&&!ub(t))return an(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=>!CP.includes(l));if(r.length>0)return an(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${CP.join(", ")}`,n);if(Object.keys(o).length===0)return an(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=ln(o.main,`${e}.main`,n);if(o.backup===null)return an(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return an(`${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:ln(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:ln(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return an(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return an(`${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 an(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return an(`${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 an(`${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 an(`${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(jH,"normalizeAIGatewayRouteTarget");async function zi(t){let{modelsByProvider:e,providerMetadata:n}=await oo(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:qH(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(zi,"loadProviders");function HH(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(HH,"conventionEnvironmentVariable");function vP(t){return t&&et[t]?.trim()||void 0}i(vP,"nonEmptyEnvironmentValue");function lb(t){let{provider:e,providerEnvironmentVariables:n,metadata:o,path:r,allowMissingApiKey:s,log:a}=t;if(zH(o)){let p;try{p=new URL(o.baseUrl).origin}catch{}return p!==cu?_o(r,`ZuploDemo provider URL '${o.baseUrl}' is not the trusted demo provider origin '${cu}'`,`Set the ZuploDemo catalog base URL to '${cu}', or choose a keyed provider`):_.instance.authApiJWT?.trim()?{apiKeySource:"zuplodemo"}:_o(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=HH(e),l,d;if(c!==void 0){let p=vP(c);p!==void 0&&(l=p,d=c)}if(l===void 0){let p=vP(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 v(`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 _o(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(lb,"resolveApiKey");function FH(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(", ");_o(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(FH,"resolveCatalogEntryLabel");function GH(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===$H)return;let d=ur(r[c],n,l);d?.kind===o&&d.status==="active"||(d?.kind===o&&_o(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`),_o(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(GH,"assertAssignmentOffersModel");function TP(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(TP,"cloneRouting");function BH(t,e){he.set(t,IP,e)}i(BH,"setModelSelection");function Un(t){return he.get(t,IP)}i(Un,"getModelSelection");var db={async load(t){let{providers:e}=await zi(t);return e}},In={async set(t,e){if(!ub(e))return _o("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!cb.includes(d));if(n.length>0)return _o(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=cb.filter(d=>e[d]!==void 0);if(o.length===0)return _o("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=jH(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await zi(t),l={};for(let d of cb){let p=r[d];if(typeof p!="object")continue;let f=ln(p.main,`routing.${d}.main`),h=p.backup?ln(p.backup,`routing.${d}.backup`):void 0,y=p.quotaFallback?ln(p.quotaFallback,`routing.${d}.quotaFallback`):void 0,S=new Map;for(let[C,T]of[["main",f],["backup",h],["quotaFallback",y]])if(T){let I=FH({provider:T.provider,providers:s,path:`routing.${d}.${C}`});GH({provider:I,model:T.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${C}`});let P={...T,provider:I};S.set(C,P)}let R=i(C=>{let T=S.get(C);if(T===void 0)throw new Error(`Missing resolved AI Gateway routing field '${C}'`);let I=u[T.provider.toLowerCase()];return{provider:T.provider,model:T.model,...lb({provider:T.provider,providerEnvironmentVariables:a,metadata:I,path:`routing.${d}.${C}`,allowMissingApiKey:C==="main"&&wm(t),log:t.log})}},"toCandidate");l[d]={candidates:[R("main"),...h?[R("backup")]:[]],...h?{fallbackTimeoutSeconds:p.fallbackTimeoutSeconds??60}:{},...y?{quotaFallback:R("quotaFallback")}:{}}}BH(t,{byCapability:l}),he.set(t,SP,TP(r))},get(t){let e=he.get(t,SP);return e===void 0?void 0:TP(e)}};var ZH=new Set(["converse","converse-stream","invoke","invoke-with-response-stream"]),VH=new Set(["count-tokens","invoke-with-bidirectional-stream"]),JH=/\/model\/(.+)\/([a-z-]+)$/;function ji(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=JH.exec(e);if(!r)return null;let[,s,a]=r;return!s||!a?null:ZH.has(a)?{operation:a,requested:a,encodedModelId:s}:VH.has(a)?{operation:"unsupported",requested:a,encodedModelId:s}:null}i(ji,"matchBedrockRuntimeRoute");function Zt(t){return ji(t)!==null}i(Zt,"isBedrockRuntimeRoute");function EP(t){try{return decodeURIComponent(t)}catch{return t}}i(EP,"decodeBedrockModelId");function ro(t,e,n,o){if(Zt(t))return cn(e,KH(e),n,o)}i(ro,"bedrockPolicyErrorResponse");function KH(t){return t===401||t===403?"AccessDeniedException":t===404?"ResourceNotFoundException":t===429?"ThrottlingException":t>=500?t===503?"ServiceUnavailableException":"InternalServerException":"ValidationException"}i(KH,"bedrockExceptionForStatus");function cn(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(cn,"createBedrockErrorResponse");function pb(t,e,n){if(Zt(t))return cn(400,"ServiceQuotaExceededException",e,n)}i(pb,"bedrockQuotaExceededResponse");function uu(t){if(Zt(t))return null;let e=/\/v1\/models(?:\/|$)/.exec(t);return e?.index===void 0?null:t.slice(e.index)}i(uu,"resolveModelsBasePath");function Tt(t){return uu(new URL(t.url).pathname)!==null}i(Tt,"isModelsDiscoveryRoute");function ea(t,e){return t.provider.toLowerCase()===e.provider.toLowerCase()&&t.model.toLowerCase()===e.model.toLowerCase()}i(ea,"refsEqual");function xo(t){let e=new URL(t.url).pathname;return Zt(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(xo,"resolveAIGatewayRequestRoute");function PP(t){let e;try{e=new URL(t.url).pathname}catch{return}let n=i(o=>e===o||e.endsWith(o),"matchesBase");if(!Zt(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(PP,"resolveMeteredCapability");function ta(t,e,n,o){return ur(n?.[t.toLowerCase()],e,o)?.dialect?.toLowerCase()}i(ta,"catalogModelDialect");var WH={openai:new Set(["xai"])};function na(t){let e=t.nativeProvider.toLowerCase(),n=t.providerType?.toLowerCase();return n===e||n!==void 0&&WH[e]?.has(n)===!0||t.dialect?.toLowerCase()===e}i(na,"selectionSatisfiesNativeProvider");function YH(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(YH,"isRecord");async function QH(t){try{let e=await t.clone().json();if(YH(e)&&Object.hasOwn(e,"model"))return{present:!0,value:e.model}}catch{}return{present:!1,value:void 0}}i(QH,"readAIGatewayRequestModel");async function Qr(t){let e=ji(new URL(t.url).pathname);return e!==null?{present:!0,value:EP(e.encodedModelId)}:QH(t)}i(Qr,"readAIGatewayRequestedModel");function Sm(t){if(Zt(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(Sm,"describeRequestModelSource");function oa(t,e="request.body.model"){let n=ln(t,e);return{ref:n,raw:n.raw}}i(oa,"parseAIGatewayRequestModel");var XH=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),e1=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Qt(t){if(Tt(t))return null;let e=new URL(t.url).pathname;if(Zt(e))return null;for(let[n,o]of e1)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Qt,"getFormat");async function lu(t){let e=Qt(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(lu,"getRequestBody");async function t1(t,e){let n=Qt(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(t1,"getResponseBody");function mb(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(mb,"getUsage");function lt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>lt(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 lt(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(lt,"flattenMessageContent");function ra(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(lt(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(lt(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(lt(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(lt(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(lt(o.content));return Array.isArray(e.content)&&n.push(lt(e.content)),n.filter(Boolean).join(`
25
+ import{a as $E,b as zE,c as VE,d as Yr,e as He,f as WE,g as bm,h as YE,i as QE,j as XE,k as tb,m as nb,o as eP,q as ob,r as rb}from"./chunk-VP5Q3DEN.js";import{a as Fe}from"./chunk-QGAJTUPE.js";import{$ as _,A as cm,Aa as ZE,B as wE,Ba as m,C as SE,Ca as Di,D as CE,Da as Xe,E as vE,Ea as Xs,F as TE,G as IE,Ga as tt,H as EE,Ha as $t,I as PE,Ia as gm,J as AE,Ja as JE,K as um,Ka as ym,L as kE,La as KE,M as _E,Ma as tP,N as lm,Na as su,O as dm,Oa as nP,P as xE,Pa as oP,Q as pm,R as mm,S as OE,T as ME,U as LE,V as NE,W as UE,X as qE,Y as Ys,Z as DE,_ as fm,a as $e,aa as V,b as Xy,ba as jE,c as H,ca as eb,d as v,da as HE,e as ct,ea as w,f as iE,fa as FE,g as Li,ga as hm,h as sE,ha as oe,i as Ws,ia as Ce,j as aE,ja as Ni,k as cE,ka as GE,l as uE,la as Ue,m as lE,ma as U,n as dE,na as O,o as pE,oa as qe,p as mE,pa as ve,q as fE,qa as Qs,r as hE,ra as Wr,s as gE,sa as ye,t as yE,ta as Ve,u as bE,ua as D,v as RE,va as Me,w as rm,wa as iu,x as im,xa as Ui,y as sm,ya as BE,z as am,za as qi}from"./chunk-WUZE2HKB.js";import{a as he}from"./chunk-UKQQD2JN.js";import{a as i,b as RH,d as wH}from"./chunk-TYV53J3B.js";var UA=RH(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.parse=zF;Km.serialize=jF;var LF=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,NF=/^[\u0021-\u003A\u003C-\u007E]*$/,UF=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qF=/^[\u0020-\u003A\u003D-\u007E]*$/,DF=Object.prototype.toString,$F=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function zF(t,e){let n=new $F,o=t.length;if(o<2)return n;let r=e?.decode||HF,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=LA(t,s,a),d=NA(t,a,l),p=t.slice(l,d);if(n[p]===void 0){let f=LA(t,a+1,u),h=NA(t,u,f),y=r(t.slice(f,h));n[p]=y}s=u+1}while(s<o);return n}i(zF,"parse");function LA(t,e,n){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<n);return n}i(LA,"startIndex");function NA(t,e,n){for(;e>n;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return n}i(NA,"endIndex");function jF(t,e,n){let o=n?.encode||encodeURIComponent;if(!LF.test(t))throw new TypeError(`argument name is invalid: ${t}`);let r=o(e);if(!NF.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(!UF.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);s+="; Domain="+n.domain}if(n.path){if(!qF.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);s+="; Path="+n.path}if(n.expires){if(!FF(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(jF,"serialize");function HF(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(HF,"decode");function FF(t){return DF.call(t)==="[object Date]"}i(FF,"isDate")});var et=new Proxy({},{get(t,e){let n=String(e);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return _.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return _.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return _.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return _.instance.accountName;case"ZUPLO_PROJECT_NAME":return _.instance.projectName;case"ZUPLO_BUILD_ID":return _.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return _.instance.build.COMPATIBILITY_DATE}if(!($E(n)&&!zE(n)))return _.instance.runtime[n]}});var rP=new Map([["input","input"],["cache-read-input","cache_read_input"],["cache-write-input","cache_write_input"],["output","output"]]),SH=new Set(["5m","1h"]);function iP(t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).filter(([,e])=>e!==null))}i(iP,"withoutNullFields");var sP=m.number().int().min(0).max(Number.MAX_SAFE_INTEGER),CH=m.object({category:m.enum(["input","cache_read_input","cache_write_input","output"]),costPerToken:m.number().nonnegative(),minInputTokens:sP.optional(),maxInputTokens:sP.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"})}),vH=m.object({revision:m.string().min(1),currency:m.literal("USD"),rates:m.array(CH)}).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 TH(t){let e=iP(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=iP(s);if(typeof a!="object"||a===null||Array.isArray(a)){r.push(a);continue}let{category:c,cacheTtl:u}=a;if(typeof c=="string"&&!rP.has(c)){o.push(`category ${JSON.stringify(c)}`);continue}if(typeof u=="string"&&!SH.has(u)){o.push(`cacheTtl ${JSON.stringify(u)}`);continue}r.push(typeof c=="string"?{...a,category:rP.get(c)}:a)}return{card:{...e,rates:r},ignoredRates:o}}i(TH,"fromWireCard");function uP(t){let e=vH.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(uP,"parseTokenRateCard");function aP(t){if(t==null)return{};let{card:e,ignoredRates:n}=TH(t),o=uP(e);return o.tokenRateCard===void 0||n.length===0?o:{...o,ignoredRates:n}}i(aP,"validateTokenRateCard");function Rm(t){return[t.category,t.cacheTtl??"",t.minInputTokens??"",t.maxInputTokens??""].join("\0")}i(Rm,"rateSelector");function IH(t,e){let n=new Map(e.rates.map(r=>[Rm(r),r])),o=new Set(t.rates.map(Rm));return{revision:e.revision,currency:e.currency,rates:[...t.rates.map(r=>n.get(Rm(r))??r),...e.rates.filter(r=>!o.has(Rm(r)))]}}i(IH,"mergeTokenRateCards");function lP(t,e){let n=aP(t);if(n.tokenRateCard===void 0)return n.error===void 0?{}:{error:n.error};let o=aP(e),r=[cP("list",n),cP("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=uP(IH(n.tokenRateCard,o.tokenRateCard));return a.tokenRateCard===void 0?{tokenRateCard:n.tokenRateCard,overrideError:`merged card: ${a.error}`,...s}:{tokenRateCard:a.tokenRateCard,...s}}i(lP,"resolveModelTokenRateCard");function cP(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(cP,"ignoredRatesOf");var de=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 V.console.error(o),new $e(o)}return n}static addLogger(e,n){t.#e.set(e,n)}};function pt(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${_.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",_.instance.deploymentName??"unknown"),t.set("User-Agent",_.instance.systemUserAgent),t.set("zp-compat-date",_.instance.build.COMPATIBILITY_DATE??"none")}i(pt,"setZuploHeaders");var pP=["openai","anthropic","google","mistral","xai","bedrock-mantle","vertex-ai","openrouter","jev"];function dP(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(dP,"defineOwn");function EH(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};dP(a,u,p);let f=u.toLowerCase();f!==u&&!Object.hasOwn(a,f)&&dP(a,f,{...p,model:f})}}}i(EH,"applyDeploymentModelAliases");var PH="openrouter",AH=[":nitro",":floor",":online",":exacto"],kH="bedrock-runtime",_H=/^arn:aws(?:-[a-z]+)*:bedrock:[a-z0-9-]+:\d*:(?:foundation-model|inference-profile)\/([^/]+)$/;function xH(t){return _H.exec(t)?.[1]}i(xH,"bedrockArnModelId");function ur(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===kH){let u=xH(e);return u===void 0?void 0:r(u)}if(a!==PH)return;let c=AH.find(u=>e.endsWith(u));if(c!==void 0)return r(e.slice(0,-c.length))}i(ur,"resolveModelRow");var OH=60,mP="connections-v1";async function fP(t){let e=await Xe("supported-models",{});return new tt(e,t)}i(fP,"createSupportedModelsCache");async function au(t){return(await fP(t)).get(mP)}i(au,"getCachedSupportedModels");function ib(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(ib,"isRecord");function MH(t){return ib(t)&&Array.isArray(t.data)&&t.data.every(e=>ib(e)&&typeof e.label=="string"&&typeof e.providerType=="string"&&typeof e.isCustom=="boolean"&&Array.isArray(e.models)&&e.models.every(n=>ib(n)&&typeof n.model=="string"&&typeof n.kind=="string"&&typeof n.status=="string"))}i(MH,"isProviderAssignmentsResponse");function LH(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(LH,"fromProviderAssignments");function NH(t){let e=typeof t=="object"&&t!==null?t.revision:void 0;return typeof e=="string"?e:void 0}i(NH,"overrideRevision");function UH(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=lP(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:NH(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 EH(n,o,e),{modelsByProvider:n,providerMetadata:o}}i(UH,"buildSupportedModels");async function oo(t,e){let n=de.getLogger(t),o=await au(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"});pt(r,t.requestId);let s=et.ZUPLO_SERVICE_BUCKET_ID,a=new URL(`/v1/buckets/${s}/provider-assignments?includeDeprecated=true`,_.instance.zuploEdgeApiUrl).toString(),c=await $t({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(),y=JSON.parse(h);n.error(f,y),f=`${f}: ${y.message||c.statusText}`}catch{n.error(f,{status:c.status}),f=`${f}: ${c.status}`}throw new Error(f)}let u=await c.json();if(!MH(u)){let f="Gateway service returned an unexpected provider assignments body";throw n.error(f,{bucketId:s}),new Error(f)}let l=LH(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=UH(l,n),p=await fP(t);return e?.signal.throwIfAborted(),p.put(mP,d,OH),d}i(oo,"getSupportedModels");async function hP(t){let e=new AbortController,n;try{return await Promise.race([oo(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(hP,"getDiscoverySupportedModels");function sb(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(sb,"resolveProviderLabel");function gP(t){let e=Object.entries(t).map(([n,o])=>o.envVarName?`'${n}' (envVarName: ${o.envVarName})`:`'${n}'`);return e.length>0?e.join(", "):"none"}i(gP,"describeProviderAssignments");function yP(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(yP,"isModelSupported");function bP(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(bP,"getModelsByProviderAndKind");var RP=new he(Symbol("ai-gateway-provider-credential-passthrough"));function wP(t,e){RP.set(t,e)}i(wP,"setProviderCredentialPassthrough");function ab(t){return RP.get(t)}i(ab,"getProviderCredentialPassthrough");function wm(t){return ab(t)!==void 0}i(wm,"hasProviderCredentialPassthrough");function qH(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(qH,"publicTokenRateCard");var IP=Symbol("ai-gateway-model-selection"),DH="zuplodemo",$H="azure-ai",cu="https://demo.zuplo.ai";function zH(t){return t?.providerType?.toLowerCase()===DH&&t.isCustom!==!0}i(zH,"isZuploDemoAssignment");var SP=Symbol("ai-gateway-model-routing"),$i='Use "providerName/model", for example "openai/gpt-5".',cb=["completions","embeddings"],CP=["main","backup","fallbackTimeoutSeconds","quotaFallback"];function _o(t,e,n){throw new v(`Invalid AI Gateway model routing field '${t}': ${e}. ${n}`)}i(_o,"invalid");function an(t,e,n,o){return o?o(t,e,n):_o(t,e,n)}i(an,"reject");function ub(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(ub,"isRecord");function ln(t,e,n){if(typeof t!="string")return an(e,"must be a string",$i,n);if(t.length===0)return an(e,"must not be empty",$i,n);if(t.trim()!==t||/\s/.test(t))return an(e,`contains whitespace in '${t}'`,$i,n);let o=t.indexOf("/");if(o===-1)return an(e,`'${t}' has no provider name separator`,$i,n);let r=t.slice(0,o),s=t.slice(o+1);return r.length===0?an(e,`'${t}' has an empty provider name`,$i,n):/^[A-Za-z0-9._-]+$/.test(r)?s.length===0?an(e,`'${t}' has an empty model`,$i,n):s.startsWith("/")?an(e,`'${t}' starts the model with an extra "/"`,$i,n):{provider:r,model:s,raw:t}:an(e,`provider name '${r}' contains unsupported characters`,'Use only letters, numbers, ".", "_", or "-" in the provider name',n)}i(ln,"parseModelRef");function jH(t,e,n){let o=typeof t=="string"?{main:t}:ub(t)?t:{};if(typeof t!="string"&&!ub(t))return an(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=>!CP.includes(l));if(r.length>0)return an(`${e}.${r[0]}`,`unknown property '${r[0]}'`,`Remove it; supported properties are ${CP.join(", ")}`,n);if(Object.keys(o).length===0)return an(e,"must not be an empty object",`Set 'main' to a "providerName/model" reference`,n);let s=ln(o.main,`${e}.main`,n);if(o.backup===null)return an(`${e}.backup`,"is null",'Set it to a "providerName/model" reference, or omit the field instead',n);if(o.quotaFallback===null)return an(`${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:ln(o.backup,`${e}.backup`,n),c=o.quotaFallback===void 0?void 0:ln(o.quotaFallback,`${e}.quotaFallback`,n);if(a?.raw.toLowerCase()===s.raw.toLowerCase())return an(`${e}.backup`,`must differ from '${e}.main'`,"Choose a different backup model or omit 'backup'",n);if(c?.raw.toLowerCase()===s.raw.toLowerCase())return an(`${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 an(`${e}.fallbackTimeoutSeconds`,"requires a backup model","Set 'backup' or omit 'fallbackTimeoutSeconds'",n);if(typeof u=="string")return an(`${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 an(`${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 an(`${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(jH,"normalizeAIGatewayRouteTarget");async function zi(t){let{modelsByProvider:e,providerMetadata:n}=await oo(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:qH(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(zi,"loadProviders");function HH(t){return`${t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}_API_KEY`}i(HH,"conventionEnvironmentVariable");function vP(t){return t&&et[t]?.trim()||void 0}i(vP,"nonEmptyEnvironmentValue");function lb(t){let{provider:e,providerEnvironmentVariables:n,metadata:o,path:r,allowMissingApiKey:s,log:a}=t;if(zH(o)){let p;try{p=new URL(o.baseUrl).origin}catch{}return p!==cu?_o(r,`ZuploDemo provider URL '${o.baseUrl}' is not the trusted demo provider origin '${cu}'`,`Set the ZuploDemo catalog base URL to '${cu}', or choose a keyed provider`):_.instance.authApiJWT?.trim()?{apiKeySource:"zuplodemo"}:_o(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=HH(e),l,d;if(c!==void 0){let p=vP(c);p!==void 0&&(l=p,d=c)}if(l===void 0){let p=vP(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 v(`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 _o(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(lb,"resolveApiKey");function FH(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(", ");_o(o,`references unknown provider name '${e}'`,`Use 'providerName/model' to select a configured provider; configured provider names: ${s||"none"}`)}i(FH,"resolveCatalogEntryLabel");function GH(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===$H)return;let d=ur(r[c],n,l);d?.kind===o&&d.status==="active"||(d?.kind===o&&_o(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`),_o(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(GH,"assertAssignmentOffersModel");function TP(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,{...n}]))}i(TP,"cloneRouting");function BH(t,e){he.set(t,IP,e)}i(BH,"setModelSelection");function Un(t){return he.get(t,IP)}i(Un,"getModelSelection");var db={async load(t){let{providers:e}=await zi(t);return e}},In={async set(t,e){if(!ub(e))return _o("routing","must be an object","Set at least one of 'completions' or 'embeddings'");let n=Object.keys(e).filter(d=>!cb.includes(d));if(n.length>0)return _o(`routing.${n[0]}`,`unknown capability '${n[0]}'`,"Use 'completions' or 'embeddings', or remove this property");let o=cb.filter(d=>e[d]!==void 0);if(o.length===0)return _o("routing","must not be empty","Set at least one of 'completions' or 'embeddings'");let r={};for(let d of o)r[d]=jH(e[d],`routing.${d}`);let{providers:s,providerEnvironmentVariables:a,modelsByProvider:c,providerMetadata:u}=await zi(t),l={};for(let d of cb){let p=r[d];if(typeof p!="object")continue;let f=ln(p.main,`routing.${d}.main`),h=p.backup?ln(p.backup,`routing.${d}.backup`):void 0,y=p.quotaFallback?ln(p.quotaFallback,`routing.${d}.quotaFallback`):void 0,S=new Map;for(let[C,T]of[["main",f],["backup",h],["quotaFallback",y]])if(T){let I=FH({provider:T.provider,providers:s,path:`routing.${d}.${C}`});GH({provider:I,model:T.model,capability:d,modelsByProvider:c,providerMetadata:u,path:`routing.${d}.${C}`});let P={...T,provider:I};S.set(C,P)}let R=i(C=>{let T=S.get(C);if(T===void 0)throw new Error(`Missing resolved AI Gateway routing field '${C}'`);let I=u[T.provider.toLowerCase()];return{provider:T.provider,model:T.model,...lb({provider:T.provider,providerEnvironmentVariables:a,metadata:I,path:`routing.${d}.${C}`,allowMissingApiKey:C==="main"&&wm(t),log:t.log})}},"toCandidate");l[d]={candidates:[R("main"),...h?[R("backup")]:[]],...h?{fallbackTimeoutSeconds:p.fallbackTimeoutSeconds??60}:{},...y?{quotaFallback:R("quotaFallback")}:{}}}BH(t,{byCapability:l}),he.set(t,SP,TP(r))},get(t){let e=he.get(t,SP);return e===void 0?void 0:TP(e)}};var ZH=new Set(["converse","converse-stream","invoke","invoke-with-response-stream"]),VH=new Set(["count-tokens","invoke-with-bidirectional-stream"]),JH=/\/model\/(.+)\/([a-z-]+)$/;function ji(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=JH.exec(e);if(!r)return null;let[,s,a]=r;return!s||!a?null:ZH.has(a)?{operation:a,requested:a,encodedModelId:s}:VH.has(a)?{operation:"unsupported",requested:a,encodedModelId:s}:null}i(ji,"matchBedrockRuntimeRoute");function Zt(t){return ji(t)!==null}i(Zt,"isBedrockRuntimeRoute");function EP(t){try{return decodeURIComponent(t)}catch{return t}}i(EP,"decodeBedrockModelId");function ro(t,e,n,o){if(Zt(t))return cn(e,KH(e),n,o)}i(ro,"bedrockPolicyErrorResponse");function KH(t){return t===401||t===403?"AccessDeniedException":t===404?"ResourceNotFoundException":t===429?"ThrottlingException":t>=500?t===503?"ServiceUnavailableException":"InternalServerException":"ValidationException"}i(KH,"bedrockExceptionForStatus");function cn(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(cn,"createBedrockErrorResponse");function pb(t,e,n){if(Zt(t))return cn(400,"ServiceQuotaExceededException",e,n)}i(pb,"bedrockQuotaExceededResponse");function uu(t){if(Zt(t))return null;let e=/\/v1\/models(?:\/|$)/.exec(t);return e?.index===void 0?null:t.slice(e.index)}i(uu,"resolveModelsBasePath");function Tt(t){return uu(new URL(t.url).pathname)!==null}i(Tt,"isModelsDiscoveryRoute");function ea(t,e){return t.provider.toLowerCase()===e.provider.toLowerCase()&&t.model.toLowerCase()===e.model.toLowerCase()}i(ea,"refsEqual");function xo(t){let e=new URL(t.url).pathname;return Zt(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(xo,"resolveAIGatewayRequestRoute");function PP(t){let e;try{e=new URL(t.url).pathname}catch{return}let n=i(o=>e===o||e.endsWith(o),"matchesBase");if(!Zt(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(PP,"resolveMeteredCapability");function ta(t,e,n,o){return ur(n?.[t.toLowerCase()],e,o)?.dialect?.toLowerCase()}i(ta,"catalogModelDialect");var WH={openai:new Set(["xai"])};function na(t){let e=t.nativeProvider.toLowerCase(),n=t.providerType?.toLowerCase();return n===e||n!==void 0&&WH[e]?.has(n)===!0||t.dialect?.toLowerCase()===e}i(na,"selectionSatisfiesNativeProvider");function YH(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(YH,"isRecord");async function QH(t){try{let e=await t.clone().json();if(YH(e)&&Object.hasOwn(e,"model"))return{present:!0,value:e.model}}catch{}return{present:!1,value:void 0}}i(QH,"readAIGatewayRequestModel");async function Qr(t){let e=ji(new URL(t.url).pathname);return e!==null?{present:!0,value:EP(e.encodedModelId)}:QH(t)}i(Qr,"readAIGatewayRequestedModel");function Sm(t){if(Zt(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(Sm,"describeRequestModelSource");function oa(t,e="request.body.model"){let n=ln(t,e);return{ref:n,raw:n.raw}}i(oa,"parseAIGatewayRequestModel");var XH=new Set(["response.completed","response.failed","response.incomplete","response.cancelled","response.expired"]),e1=[["/v1/responses","openai-responses"],["/v1/messages","anthropic-messages"],["/v1/chat/completions","openai-chat"]];function Qt(t){if(Tt(t))return null;let e=new URL(t.url).pathname;if(Zt(e))return null;for(let[n,o]of e1)if(e===n||e.endsWith(n)||e.includes(`${n}/`))return o;return null}i(Qt,"getFormat");async function lu(t){let e=Qt(t);if(!e)return null;let n;try{n=await t.clone().json()}catch{return null}return{format:e,body:n}}i(lu,"getRequestBody");async function t1(t,e){let n=Qt(t);if(!n)return null;let o;try{o=await e.clone().json()}catch{return null}return{format:n,body:o}}i(t1,"getResponseBody");function mb(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(mb,"getUsage");function lt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>lt(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 lt(e.content);let n=e.source;if(n&&n.type==="text"&&typeof n.data=="string")return n.data}return""}i(lt,"flattenMessageContent");function ra(t){if(!t||typeof t!="object")return"";let e=t,n=[];if(Array.isArray(e.messages))for(let o of e.messages)n.push(lt(o.content));if(typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&n.push(lt(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(lt(o.content));if(Array.isArray(e.choices))for(let o of e.choices)n.push(lt(o.message?.content));if(Array.isArray(e.output))for(let o of e.output)n.push(lt(o.content));return Array.isArray(e.content)&&n.push(lt(e.content)),n.filter(Boolean).join(`
26
26
  `)}i(ra,"extractAllText");async function*n1(t,e){let n=Qt(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(`
27
27
 
28
28
  `))!==-1;){let d=a.slice(0,l);a=a.slice(l+2);let p=o1(d,n);p&&(yield p)}}}finally{r.releaseLock()}}i(n1,"getStreamEvents");function o1(t,e){let n=t.split(`
@@ -410,5 +410,5 @@ Signature verification is impossible without access to the original signed mater
410
410
  `);let b=new T("!xml"),E=b,x="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let L=new I(this.options.processEntities);for(let k=0;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="/"){let W=Sn(g,">",k,"Closing Tag is not closed."),j=g.substring(k+2,W).trim();if(this.options.removeNSPrefix){let Ee=j.indexOf(":");Ee!==-1&&(j=j.substr(Ee+1))}j=Zn(this.options.transformTagName,j,"",this.options).tagName,E&&(x=this.saveTextToParentTag(x,E,this.matcher));let Re=this.matcher.getCurrentTag();if(j&&this.options.unpairedTags.indexOf(j)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${j}>`);Re&&this.options.unpairedTags.indexOf(Re)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,E=this.tagsNodeStack.pop(),x="",k=W}else if(g[k+1]==="?"){let W=On(g,k,!1,"?>");if(!W)throw new Error("Pi Tag is not closed.");if(x=this.saveTextToParentTag(x,E,this.matcher),!(this.options.ignoreDeclaration&&W.tagName==="?xml"||this.options.ignorePiTags)){let j=new T(W.tagName);j.add(this.options.textNodeName,""),W.tagName!==W.tagExp&&W.attrExpPresent&&(j[":@"]=this.buildAttributesMap(W.tagExp,this.matcher,W.tagName)),this.addChild(E,j,this.matcher,k)}k=W.closeIndex+1}else if(g.substr(k+1,3)==="!--"){let W=Sn(g,"-->",k+4,"Comment is not closed.");if(this.options.commentPropName){let j=g.substring(k+4,W-2);x=this.saveTextToParentTag(x,E,this.matcher),E.add(this.options.commentPropName,[{[this.options.textNodeName]:j}])}k=W}else if(g.substr(k+1,2)==="!D"){let W=L.readDocType(g,k);this.docTypeEntities=W.entities,k=W.i}else if(g.substr(k+1,2)==="!["){let W=Sn(g,"]]>",k,"CDATA is not closed.")-2,j=g.substring(k+9,W);x=this.saveTextToParentTag(x,E,this.matcher);let Re=this.parseTextData(j,E.tagname,this.matcher,!0,!1,!0,!0);Re==null&&(Re=""),this.options.cdataPropName?E.add(this.options.cdataPropName,[{[this.options.textNodeName]:j}]):E.add(this.options.textNodeName,Re),k=W+2}else{let W=On(g,k,this.options.removeNSPrefix);if(!W){let sn=g.substring(Math.max(0,k-50),Math.min(g.length,k+50));throw new Error(`readTagExp returned undefined at position ${k}. Context: "${sn}"`)}let j=W.tagName,Re=W.rawTagName,Ee=W.tagExp,je=W.attrExpPresent,Rt=W.closeIndex;if({tagName:j,tagExp:Ee}=Zn(this.options.transformTagName,j,Ee,this.options),this.options.strictReservedNames&&(j===this.options.commentPropName||j===this.options.cdataPropName||j===this.options.textNodeName||j===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${j}`);E&&x&&E.tagname!=="!xml"&&(x=this.saveTextToParentTag(x,E,this.matcher,!1));let gn=E;gn&&this.options.unpairedTags.indexOf(gn.tagname)!==-1&&(E=this.tagsNodeStack.pop(),this.matcher.pop());let Br=!1;Ee.length>0&&Ee.lastIndexOf("/")===Ee.length-1&&(Br=!0,j[j.length-1]==="/"?(j=j.substr(0,j.length-1),Ee=j):Ee=Ee.substr(0,Ee.length-1),je=j!==Ee);let wt=null,Ln={},Zr;Zr=ne(Re),j!==b.tagname&&this.matcher.push(j,{},Zr),j!==Ee&&je&&(wt=this.buildAttributesMap(Ee,this.matcher,j),wt&&(Ln=ie(wt,this.options))),j!==b.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let vn=k;if(this.isCurrentNodeStopNode){let sn="";if(Br)k=W.closeIndex;else if(this.options.unpairedTags.indexOf(j)!==-1)k=W.closeIndex;else{let Jr=this.readStopNodeData(g,Re,Rt+1);if(!Jr)throw new Error(`Unexpected end of ${Re}`);k=Jr.i,sn=Jr.tagContent}let Vr=new T(j);wt&&(Vr[":@"]=wt),Vr.add(this.options.textNodeName,sn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(E,Vr,this.matcher,vn)}else{if(Br){({tagName:j,tagExp:Ee}=Zn(this.options.transformTagName,j,Ee,this.options));let sn=new T(j);wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(j)!==-1){let sn=new T(j);wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,k=W.closeIndex;continue}else{let sn=new T(j);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(E),wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),E=sn}x="",k=Rt}}else x+=g[k];return b.child},"parseXml");function ue(g,b,E,x){this.options.captureMetaData||(x=void 0);let L=this.options.jPath?E.toString():E,k=this.options.updateTag(b.tagname,L,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),g.addChild(b,x))}i(ue,"addChild"),n(ue,"addChild");function le(g,b,E){let x=this.options.processEntities;if(!x||!x.enabled)return g;if(x.allowedTags){let L=this.options.jPath?E.toString():E;if(!(Array.isArray(x.allowedTags)?x.allowedTags.includes(b):x.allowedTags(b,L)))return g}if(x.tagFilter){let L=this.options.jPath?E.toString():E;if(!x.tagFilter(b,L))return g}for(let L of Object.keys(this.docTypeEntities)){let k=this.docTypeEntities[L],ee=g.match(k.regx);if(ee){if(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);let W=g.length;if(g=g.replace(k.regx,k.val),x.maxExpandedLength&&(this.currentExpandedLength+=g.length-W,this.currentExpandedLength>x.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${x.maxExpandedLength}`)}}for(let L of Object.keys(this.lastEntities)){let k=this.lastEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}if(g.indexOf("&")===-1)return g;if(this.options.htmlEntities)for(let L of Object.keys(this.htmlEntities)){let k=this.htmlEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}return g=g.replace(this.ampEntity.regex,this.ampEntity.val),g}i(le,"replaceEntitiesValue"),n(le,"replaceEntitiesValue");function ke(g,b,E,x){return g&&(x===void 0&&(x=b.child.length===0),g=this.parseTextData(g,b.tagname,E,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,x),g!==void 0&&g!==""&&b.add(this.options.textNodeName,g),g=""),g}i(ke,"saveTextToParentTag"),n(ke,"saveTextToParentTag");function xe(g,b){if(!g||g.length===0)return!1;for(let E=0;E<g.length;E++)if(b.matches(g[E]))return!0;return!1}i(xe,"isItStopNode"),n(xe,"isItStopNode");function q(g,b,E=">"){let x,L="";for(let k=b;k<g.length;k++){let ee=g[k];if(x)ee===x&&(x="");else if(ee==='"'||ee==="'")x=ee;else if(ee===E[0])if(E[1]){if(g[k+1]===E[1])return{data:L,index:k}}else return{data:L,index:k};else ee===" "&&(ee=" ");L+=ee}}i(q,"tagExpWithClosingIndex"),n(q,"tagExpWithClosingIndex");function Sn(g,b,E,x){let L=g.indexOf(b,E);if(L===-1)throw new Error(x);return L+b.length-1}i(Sn,"findClosingIndex"),n(Sn,"findClosingIndex");function On(g,b,E,x=">"){let L=q(g,b+1,x);if(!L)return;let k=L.data,ee=L.index,W=k.search(/\s/),j=k,Re=!0;W!==-1&&(j=k.substring(0,W),k=k.substring(W+1).trimStart());let Ee=j;if(E){let je=j.indexOf(":");je!==-1&&(j=j.substr(je+1),Re=j!==L.data.substr(je+1))}return{tagName:j,tagExp:k,closeIndex:ee,attrExpPresent:Re,rawTagName:Ee}}i(On,"readTagExp"),n(On,"readTagExp");function Po(g,b,E){let x=E,L=1;for(;E<g.length;E++)if(g[E]==="<")if(g[E+1]==="/"){let k=Sn(g,">",E,`${b} is not closed`);if(g.substring(E+2,k).trim()===b&&(L--,L===0))return{tagContent:g.substring(x,E),i:k};E=k}else if(g[E+1]==="?")E=Sn(g,"?>",E+1,"StopNode is not closed.");else if(g.substr(E+1,3)==="!--")E=Sn(g,"-->",E+3,"StopNode is not closed.");else if(g.substr(E+1,2)==="![")E=Sn(g,"]]>",E,"StopNode is not closed.")-2;else{let k=On(g,E,">");k&&((k&&k.tagName)===b&&k.tagExp[k.tagExp.length-1]!=="/"&&L++,E=k.closeIndex)}}i(Po,"readStopNodeData"),n(Po,"readStopNodeData");function no(g,b,E){if(b&&typeof g=="string"){let x=g.trim();return x==="true"?!0:x==="false"?!1:vt(g,E)}else return l(g)?g:""}i(no,"parseValue"),n(no,"parseValue");function tr(g,b,E){let x=Number.parseInt(g,b);return x>=0&&x<=1114111?String.fromCodePoint(x):E+g+";"}i(tr,"fromCodePoint"),n(tr,"fromCodePoint");function Zn(g,b,E,x){if(g){let L=g(b);E===b&&(E=L),b=L}return b=nr(b,x),{tagName:b,tagExp:E}}i(Zn,"transformTagName"),n(Zn,"transformTagName");function nr(g,b){if(p.includes(g))throw new Error(`[SECURITY] Invalid name: "${g}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(g)?b.onDangerousProperty(g):g}i(nr,"sanitizeName"),n(nr,"sanitizeName");var Cn=T.getMetaDataSymbol();function or(g,b){if(!g||typeof g!="object")return{};if(!b)return g;let E={};for(let x in g)if(x.startsWith(b)){let L=x.substring(b.length);E[L]=g[x]}else E[x]=g[x];return E}i(or,"stripAttributePrefix"),n(or,"stripAttributePrefix");function rr(g,b,E){return fo(g,b,E)}i(rr,"prettify"),n(rr,"prettify");function fo(g,b,E){let x,L={};for(let k=0;k<g.length;k++){let ee=g[k],W=Dr(ee);if(W!==void 0&&W!==b.textNodeName){let j=or(ee[":@"]||{},b.attributeNamePrefix);E.push(W,j)}if(W===b.textNodeName)x===void 0?x=ee[W]:x+=""+ee[W];else{if(W===void 0)continue;if(ee[W]){let j=fo(ee[W],b,E),Re=Ao(j,b);if(ee[":@"]?ir(j,ee[":@"],E,b):Object.keys(j).length===1&&j[b.textNodeName]!==void 0&&!b.alwaysCreateTextNode?j=j[b.textNodeName]:Object.keys(j).length===0&&(b.alwaysCreateTextNode?j[b.textNodeName]="":j=""),ee[Cn]!==void 0&&typeof j=="object"&&j!==null&&(j[Cn]=ee[Cn]),L[W]!==void 0&&Object.prototype.hasOwnProperty.call(L,W))Array.isArray(L[W])||(L[W]=[L[W]]),L[W].push(j);else{let Ee=b.jPath?E.toString():E;b.isArray(W,Ee,Re)?L[W]=[j]:L[W]=j}W!==void 0&&W!==b.textNodeName&&E.pop()}}}return typeof x=="string"?x.length>0&&(L[b.textNodeName]=x):x!==void 0&&(L[b.textNodeName]=x),L}i(fo,"compress"),n(fo,"compress");function Dr(g){let b=Object.keys(g);for(let E=0;E<b.length;E++){let x=b[E];if(x!==":@")return x}}i(Dr,"propName"),n(Dr,"propName");function ir(g,b,E,x){if(b){let L=Object.keys(b),k=L.length;for(let ee=0;ee<k;ee++){let W=L[ee],j=W.startsWith(x.attributeNamePrefix)?W.substring(x.attributeNamePrefix.length):W,Re=x.jPath?E.toString()+"."+j:E;x.isArray(W,Re,!0,!0)?g[W]=[b[W]]:g[W]=b[W]}}}i(ir,"assignAttributes"),n(ir,"assignAttributes");function Ao(g,b){let{textNodeName:E}=b,x=Object.keys(g).length;return!!(x===0||x===1&&(g[E]||typeof g[E]=="boolean"||g[E]===0))}i(Ao,"isLeafTag"),n(Ao,"isLeafTag");var $r={allowBooleanAttributes:!1,unpairedTags:[]};function sr(g,b){b=Object.assign({},$r,b);let E=[],x=!1,L=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let k=0;k<g.length;k++)if(g[k]==="<"&&g[k+1]==="?"){if(k+=2,k=Yt(g,k),k.err)return k}else if(g[k]==="<"){let ee=k;if(k++,g[k]==="!"){k=ar(g,k);continue}else{let W=!1;g[k]==="/"&&(W=!0,k++);let j="";for(;k<g.length&&g[k]!==">"&&g[k]!==" "&&g[k]!==" "&&g[k]!==`
411
411
  `&&g[k]!=="\r";k++)j+=g[k];if(j=j.trim(),j[j.length-1]==="/"&&(j=j.substring(0,j.length-1),k--),!_i(j)){let je;return j.trim().length===0?je="Invalid space after '<'.":je="Tag '"+j+"' is an invalid name.",ut("InvalidTag",je,Dt(g,k))}let Re=jr(g,k);if(Re===!1)return ut("InvalidAttr","Attributes for '"+j+"' have open quote.",Dt(g,k));let Ee=Re.value;if(k=Re.index,Ee[Ee.length-1]==="/"){let je=k-Ee.length;Ee=Ee.substring(0,Ee.length-1);let Rt=cr(Ee,b);if(Rt===!0)x=!0;else return ut(Rt.err.code,Rt.err.msg,Dt(g,je+Rt.err.line))}else if(W)if(Re.tagClosed){if(Ee.trim().length>0)return ut("InvalidTag","Closing tag '"+j+"' can't have attributes or invalid starting.",Dt(g,ee));if(E.length===0)return ut("InvalidTag","Closing tag '"+j+"' has not been opened.",Dt(g,ee));{let je=E.pop();if(j!==je.tagName){let Rt=Dt(g,je.tagStartPos);return ut("InvalidTag","Expected closing tag '"+je.tagName+"' (opened in line "+Rt.line+", col "+Rt.col+") instead of closing tag '"+j+"'.",Dt(g,ee))}E.length==0&&(L=!0)}}else return ut("InvalidTag","Closing tag '"+j+"' doesn't have proper closing.",Dt(g,k));else{let je=cr(Ee,b);if(je!==!0)return ut(je.err.code,je.err.msg,Dt(g,k-Ee.length+je.err.line));if(L===!0)return ut("InvalidXml","Multiple possible root nodes found.",Dt(g,k));b.unpairedTags.indexOf(j)!==-1||E.push({tagName:j,tagStartPos:ee}),x=!0}for(k++;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="!"){k++,k=ar(g,k);continue}else if(g[k+1]==="?"){if(k=Yt(g,++k),k.err)return k}else break;else if(g[k]==="&"){let je=Fr(g,k);if(je==-1)return ut("InvalidChar","char '&' is not expected.",Dt(g,k));k=je}else if(L===!0&&!ko(g[k]))return ut("InvalidXml","Extra text at the end",Dt(g,k));g[k]==="<"&&k--}}else{if(ko(g[k]))continue;return ut("InvalidChar","char '"+g[k]+"' is not expected.",Dt(g,k))}if(x){if(E.length==1)return ut("InvalidTag","Unclosed tag '"+E[0].tagName+"'.",Dt(g,E[0].tagStartPos));if(E.length>0)return ut("InvalidXml","Invalid '"+JSON.stringify(E.map(k=>k.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return ut("InvalidXml","Start tag expected.",1);return!0}i(sr,"validate"),n(sr,"validate");function ko(g){return g===" "||g===" "||g===`
412
412
  `||g==="\r"}i(ko,"isWhiteSpace"),n(ko,"isWhiteSpace");function Yt(g,b){let E=b;for(;b<g.length;b++)if(g[b]=="?"||g[b]==" "){let x=g.substr(E,b-E);if(b>5&&x==="xml")return ut("InvalidXml","XML declaration allowed only at the start of the document.",Dt(g,b));if(g[b]=="?"&&g[b+1]==">"){b++;break}else continue}return b}i(Yt,"readPI"),n(Yt,"readPI");function ar(g,b){if(g.length>b+5&&g[b+1]==="-"&&g[b+2]==="-"){for(b+=3;b<g.length;b++)if(g[b]==="-"&&g[b+1]==="-"&&g[b+2]===">"){b+=2;break}}else if(g.length>b+8&&g[b+1]==="D"&&g[b+2]==="O"&&g[b+3]==="C"&&g[b+4]==="T"&&g[b+5]==="Y"&&g[b+6]==="P"&&g[b+7]==="E"){let E=1;for(b+=8;b<g.length;b++)if(g[b]==="<")E++;else if(g[b]===">"&&(E--,E===0))break}else if(g.length>b+9&&g[b+1]==="["&&g[b+2]==="C"&&g[b+3]==="D"&&g[b+4]==="A"&&g[b+5]==="T"&&g[b+6]==="A"&&g[b+7]==="["){for(b+=8;b<g.length;b++)if(g[b]==="]"&&g[b+1]==="]"&&g[b+2]===">"){b+=2;break}}return b}i(ar,"readCommentAndCDATA"),n(ar,"readCommentAndCDATA");var Bs='"',zr="'";function jr(g,b){let E="",x="",L=!1;for(;b<g.length;b++){if(g[b]===Bs||g[b]===zr)x===""?x=g[b]:x!==g[b]||(x="");else if(g[b]===">"&&x===""){L=!0;break}E+=g[b]}return x!==""?!1:{value:E,index:b,tagClosed:L}}i(jr,"readAttributeStr"),n(jr,"readAttributeStr");var ki=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function cr(g,b){let E=c(g,ki),x={};for(let L=0;L<E.length;L++){if(E[L][1].length===0)return ut("InvalidAttr","Attribute '"+E[L][2]+"' has no space in starting.",Mn(E[L]));if(E[L][3]!==void 0&&E[L][4]===void 0)return ut("InvalidAttr","Attribute '"+E[L][2]+"' is without value.",Mn(E[L]));if(E[L][3]===void 0&&!b.allowBooleanAttributes)return ut("InvalidAttr","boolean attribute '"+E[L][2]+"' is not allowed.",Mn(E[L]));let k=E[L][2];if(!Gr(k))return ut("InvalidAttr","Attribute '"+k+"' is an invalid name.",Mn(E[L]));if(!Object.prototype.hasOwnProperty.call(x,k))x[k]=1;else return ut("InvalidAttr","Attribute '"+k+"' is repeated.",Mn(E[L]))}return!0}i(cr,"validateAttributeString"),n(cr,"validateAttributeString");function Hr(g,b){let E=/\d/;for(g[b]==="x"&&(b++,E=/[\da-fA-F]/);b<g.length;b++){if(g[b]===";")return b;if(!g[b].match(E))break}return-1}i(Hr,"validateNumberAmpersand"),n(Hr,"validateNumberAmpersand");function Fr(g,b){if(b++,g[b]===";")return-1;if(g[b]==="#")return b++,Hr(g,b);let E=0;for(;b<g.length;b++,E++)if(!(g[b].match(/\w/)&&E<20)){if(g[b]===";")break;return-1}return b}i(Fr,"validateAmpersand"),n(Fr,"validateAmpersand");function ut(g,b,E){return{err:{code:g,msg:b,line:E.line||E,col:E.col}}}i(ut,"getErrorObject"),n(ut,"getErrorObject");function Gr(g){return u(g)}i(Gr,"validateAttrName"),n(Gr,"validateAttrName");function _i(g){return u(g)}i(_i,"validateTagName"),n(_i,"validateTagName");function Dt(g,b){let E=g.substring(0,b).split(/\r?\n/);return{line:E.length,col:E[E.length-1].length+1}}i(Dt,"getLineNumberForPosition"),n(Dt,"getLineNumberForPosition");function Mn(g){return g.startIndex+g[1].length}i(Mn,"getPositionFromMatch"),n(Mn,"getPositionFromMatch");var xi=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(g){this.externalEntities={},this.options=R(g)}parse(g,b){if(typeof g!="string"&&g.toString)g=g.toString();else if(typeof g!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(b){b===!0&&(b={});let L=sr(g,b);if(L!==!0)throw Error(`${L.err.msg}:${L.err.line}:${L.err.col}`)}let E=new be(this.options);E.addExternalEntities(this.externalEntities);let x=E.parseXml(g);return this.options.preserveOrder||x===void 0?x:rr(x,this.options,E.matcher)}addEntity(g,b){if(b.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(g.indexOf("&")!==-1||g.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(b==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[g]=b}static getMetaDataSymbol(){return T.getMetaDataSymbol()}};return new xi(t)},"getXmlParser");var tE=class extends ho{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){let o=lo(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?Uo(o.parseOnStatusCodes):void 0,this.parser=cH({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 H(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 nE=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 oE=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=Xe("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){pe("utility.get-consumer");let n=Qi(),o=this.bucketId??et.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new v("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 v(`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 v("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let r=await this.getCacheName(o),s=new tt(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 gb(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 uH=10,lH=3e4,fp=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#i;#r;#s={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#i=lH,this.#n=uH,this.#r=Number.POSITIVE_INFINITY}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#i=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:lH,this.#n=uH,this.#r=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)}#l(e){let n=this.#e.get(e);if(n&&!this.#a(n))return n.data}async get(e){let n=this.#l(e);if(n)return this.#d(e),n;if(this.#c(e))try{await Xee(()=>this.#l(e)!==void 0||!this.#c(e),this.#i+this.#n+1,this.#n);let o=this.#l(e);if(o)return o}catch{}try{return await this.#u(e)}catch(o){let r=this.#e.get(e);if(r&&!this.#p(r))return r.data;throw o}}#p(e){return this.#r===Number.POSITIVE_INFINITY?!1:this.#r<=0?!0:Date.now()>e.expiry.getTime()+this.#r}#d(e){if(!this.#c(e)){let n=this.#u(e);Yr().waitUntil(n)}}async#u(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.#i)]);if(n===void 0)throw new v(`BackgroundLoader: Loader timed out after ${this.#i} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#s[e]--}}};async function Xee(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new v(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(Xee,"waitUntilTrue");import{trace as ete}from"@opentelemetry/api";var dH,pH=i(()=>(dH??=ete.getTracer("pipeline"),dH),"tracer"),mH=i(async(t,e,n)=>{let o=ot.instance.routeData.policies,r=fa([t],o);if(r.length===0)throw new H(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0],a;try{a=it.getContextExtensions(n)}catch{a=void 0}let c=a?.currentPolicyName;a&&(a.currentPolicyName=s.policyName);try{return await pH().startActiveSpan(`policy:${s.policyName}`,async l=>{try{ma(l,s);let d=await s.handler(e,n);if(d instanceof Request||d instanceof Fe||d instanceof Response)return d instanceof Response||d instanceof Fe?d:new Fe(d);throw new v(`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 Lo(l,d),d}finally{l.end()}})}finally{a&&a.currentPolicyName===s.policyName&&(a.currentPolicyName=c)}},"invokeInboundPolicy"),fH=i(async(t,e,n,o)=>{let r=ot.instance.routeData.policies,s=Pu([t],r);if(s.length===0)throw new H(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await pH().startActiveSpan(`policy:${a.policyName}`,async u=>{try{ma(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;throw new v(`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 Lo(u,l),l}finally{u.end()}})},"invokeOutboundPolicy");var _t=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 zy=class extends _t{static{i(this,"AiGatewayBlockedCountEvent")}eventType=N.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 jy=class extends _t{static{i(this,"AiGatewayCostSumEvent")}eventType=N.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 Hy=class extends _t{static{i(this,"AiGatewayFallbackCountEvent")}eventType=N.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 Fy=class extends _t{static{i(this,"AiGatewayLatencyHistogramEvent")}eventType=N.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 Gy=class extends _t{static{i(this,"AiGatewayRequestCountEvent")}eventType=N.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 By=class extends _t{static{i(this,"AiGatewayTokenSumEvent")}eventType=N.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 Zy=class extends _t{static{i(this,"AiGatewayWarningCountEvent")}eventType=N.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 Vy=class extends _t{static{i(this,"CacheOperationEvent")}eventType=N.CACHE_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Jy=class extends _t{static{i(this,"GraphqlOperationEvent")}eventType=N.GRAPHQL_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Ky=class extends _t{static{i(this,"HandlerExecutionEvent")}eventType=N.HANDLER_EXECUTION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Wy=class extends _t{static{i(this,"McpEvent")}eventType;metadata;constructor(e){super(e),this.eventType=e.eventType,this.metadata=e.metadata}};var yt=i(t=>e=>new Wy({...e,eventType:t}),"buildMcpEvent"),tte={[N.AI_GATEWAY_COST_SUM]:t=>new jy(t),[N.AI_GATEWAY_REQUEST_COUNT]:t=>new Gy(t),[N.AI_GATEWAY_TOKEN_SUM]:t=>new By(t),[N.AI_GATEWAY_LATENCY_HISTOGRAM]:t=>new Fy(t),[N.AI_GATEWAY_WARNING_COUNT]:t=>new Zy(t),[N.AI_GATEWAY_BLOCKED_COUNT]:t=>new zy(t),[N.AI_GATEWAY_FALLBACK_COUNT]:t=>new Hy(t),[N.MCP_REQUEST_RECEIVED]:yt(N.MCP_REQUEST_RECEIVED),[N.MCP_REQUEST_COMPLETED]:yt(N.MCP_REQUEST_COMPLETED),[N.MCP_REQUEST_REJECTED]:yt(N.MCP_REQUEST_REJECTED),[N.MCP_INITIALIZE_NEGOTIATED]:yt(N.MCP_INITIALIZE_NEGOTIATED),[N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR]:yt(N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR),[N.MCP_CAPABILITY_LISTED]:yt(N.MCP_CAPABILITY_LISTED),[N.MCP_CAPABILITY_INVOKED]:yt(N.MCP_CAPABILITY_INVOKED),[N.MCP_CAPABILITY_COMPLETED]:yt(N.MCP_CAPABILITY_COMPLETED),[N.MCP_CAPABILITY_FAILED]:yt(N.MCP_CAPABILITY_FAILED),[N.MCP_CAPABILITY_CONNECT_REQUIRED]:yt(N.MCP_CAPABILITY_CONNECT_REQUIRED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED]:yt(N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED]:yt(N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED),[N.MCP_OAUTH_CLIENT_REGISTERED]:yt(N.MCP_OAUTH_CLIENT_REGISTERED),[N.MCP_OAUTH_AUTHORIZE_STARTED]:yt(N.MCP_OAUTH_AUTHORIZE_STARTED),[N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP]:yt(N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP),[N.MCP_OAUTH_TOKEN_ISSUED]:yt(N.MCP_OAUTH_TOKEN_ISSUED),[N.MCP_OAUTH_TOKEN_REFRESH_ROTATED]:yt(N.MCP_OAUTH_TOKEN_REFRESH_ROTATED),[N.MCP_OAUTH_TOKEN_REVOKED]:yt(N.MCP_OAUTH_TOKEN_REVOKED),[N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED]:yt(N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED),[N.MCP_AUTH_UPSTREAM_CONNECT_STARTED]:yt(N.MCP_AUTH_UPSTREAM_CONNECT_STARTED),[N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED]:yt(N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED]:yt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED]:yt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED]:yt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING]:yt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING),[N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED]:yt(N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED),[N.GRAPHQL_OPERATION]:t=>new Jy(t),[N.CACHE_OPERATION]:t=>new Vy(t),[N.HANDLER_EXECUTION]:t=>new Ky(t)};function hH(t,e){let n=tte[t];return n(e)}i(hH,"createAnalyticsEvent");var Yy=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 hH(n,{eventId:s??crypto.randomUUID(),requestId:this.#t,accountName:_.instance.accountName??"unknown",projectName:_.instance.projectName??"unknown",deploymentName:_.instance.deploymentName??"unknown",metadata:o,unit:r,value:e})}};var nte="127.0.0.1";function gH(t){let e=_.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?nte:void 0)}i(gH,"resolveClientIp");function ote(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[um]=o.asnum),o.zip&&(e[lm]=o.zip.split("+")[0]),o.dma&&(e[dm]=o.dma),o.region_code&&(e[pm]=o.region_code),o.timezone&&(e[mm]=o.timezone),o.city&&(e[rm]=o.city),o.continent&&(e[im]=o.continent),o.country_code&&(e[sm]=o.country_code),o.long&&(e[am]=o.long),o.lat&&(e[cm]=o.lat),e}catch{return{}}}i(ote,"parseEdgeScapeHeader");function yH(t,e){let n=ote(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(yH,"setZpHeadersFromAkamaiEdgeScapeHeader");var Ca=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(NE);if(n){let o=new Headers(e);yH(o,n),this.#e=o}}detachFromRequest(){this.#e=ii(this.#e)}get ip(){return gH(this.#e)}get asn(){try{let e=this.#e.get(um);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(kE)??void 0}get city(){return this.#e.get(lE)??this.#e.get(rm)??void 0}get continent(){return this.#e.get(dE)??this.#e.get(im)??void 0}get country(){return this.#e.get(pE)??this.#e.get(sm)??void 0}get latitude(){return this.#e.get(fE)??this.#e.get(cm)??void 0}get longitude(){return this.#e.get(mE)??this.#e.get(am)??void 0}get colo(){return this.#e.get(_E)??void 0}get postalCode(){return this.#e.get(bE)??this.#e.get(lm)??void 0}get metroCode(){return this.#e.get(yE)??this.#e.get(dm)??void 0}get region(){return this.#e.get(hE)??this.#e.get(xE)??void 0}get regionCode(){return this.#e.get(gE)??this.#e.get(pm)??void 0}get timezone(){return this.#e.get(RE)??this.#e.get(mm)??void 0}get httpProtocol(){return this.#e.get(OE)??void 0}get clientCert(){return this.#e.get(SE)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(CE)??void 0}get clientMtlsVerificationReason(){return this.#e.get(vE)??void 0}get clientCertFingerprintSha256(){return this.#e.get(TE)??void 0}get clientCertNotBefore(){return this.#e.get(IE)??void 0}get clientCertNotAfter(){return this.#e.get(EE)??void 0}get clientCertIssuerDn(){return this.#e.get(PE)??void 0}get clientCertSubjectDn(){return this.#e.get(AE)??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 _c(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(_c,"createRewriteContext");var yu=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},bu=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},rte=Object.freeze([]),it=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 H(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;originalRequest;receivedUrl;requestLogProperties=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){V.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 rte;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;#i;#r;#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.#i=[],this.#r=[],this.#s=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#i.push(e)}addHandlerResponseHook(e){this.#s.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#i)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=_.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#r)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")},yf=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)=>mH(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>fH(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 Fe(d,l);return ot.instance.handleRequest(p,this,{parentContext:this,routeBinding:Ik(l)})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{it.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{it.getContextExtensions(this).addResponseSendingFinalHook(u)},this.addPreRequestHandler=(u,l)=>{AA(this,it.getContextExtensions(this),u,l)},this.analyticsContext=new Yy(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){pe("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){pe("context.removeEventListener"),this.#t.removeEventListener(e,n,o)}dispatchEvent(e){return this.#t.dispatchEvent(e)}};export{et as a,de as b,db as c,In as d,Qt as e,lu as f,t1 as g,mb as h,lt as i,ra as j,n1 as k,Hi as l,fb as m,pe as n,gb as o,bb as p,qn as q,lr as r,sa as s,Fi as t,G as u,zt as v,Gi as w,N as x,Rb as y,wb as z,Em as A,Be as B,Fn as C,ei as D,fe as E,ho as F,AA as G,Pb as H,Ob as I,P1 as J,ni as K,Yy as L,yu as M,bu as N,it as O,AR as P,Jn as Q,B_ as R,_x as S,Nx as T,cV as U,jx as V,hw as W,yV as X,us as Y,jo as Z,ls as _,Fa as $,yr as aa,br as ba,bi as ca,ds as da,gr as ea,Mt as fa,wh as ga,Ga as ha,Ba as ia,cl as ja,ul as ka,Za as la,fn as ma,Ri as na,Lt as oa,Pn as pa,bn as qa,Va as ra,Nt as sa,Rr as ta,Ja as ua,Ka as va,ps as wa,ms as xa,wi as ya,Sh as za,Wa as Aa,ll as Ba,Ya as Ca,dl as Da,wr as Ea,zo as Fa,wo as Ga,Ch as Ha,vh as Ia,pl as Ja,ml as Ka,Qa as La,Xa as Ma,fl as Na,hl as Oa,gl as Pa,yl as Qa,ec as Ra,bl as Sa,Rl as Ta,tc as Ua,wl as Va,Sr as Wa,Cr as Xa,nc as Ya,oc as Za,rc as _a,vr as $a,Ho as ab,ic as bb,Sl as cb,Cl as db,vl as eb,Tl as fb,Il as gb,fs as hb,El as ib,Pl as jb,Al as kb,kl as lb,_l as mb,xl as nb,Ol as ob,Ml as pb,sc as qb,Ll as rb,Nl as sb,Ul as tb,ql as ub,Dl as vb,$l as wb,zl as xb,jl as yb,Hl as zb,Fl as Ab,Gl as Bb,Bl as Cb,Zl as Db,Vl as Eb,Tr as Fb,Ir as Gb,Er as Hb,Jl as Ib,hs as Jb,gs as Kb,ys as Lb,Kl as Mb,Wl as Nb,Yl as Ob,Ql as Pb,Xl as Qb,ac as Rb,ed as Sb,td as Tb,cc as Ub,Th as Vb,nd as Wb,od as Xb,rd as Yb,bw as Zb,Pr as _b,id as $b,sd as ac,ad as bc,cd as cc,ud as dc,ld as ec,dd as fc,pd as gc,md as hc,yi as ic,fd as jc,hd as kc,gd as lc,yd as mc,bd as nc,uc as oc,bs as pc,Rs as qc,lc as rc,dc as sc,pc as tc,Rd as uc,mc as vc,fc as wc,wd as xc,Sd as yc,hc as zc,ws as Ac,Cd as Bc,vd as Cc,Td as Dc,Id as Ec,Ed as Fc,Pd as Gc,Ad as Hc,kd as Ic,_d as Jc,xd as Kc,Od as Lc,Md as Mc,Ld as Nc,Nd as Oc,Ud as Pc,Ih as Qc,qd as Rc,Ar as Sc,Eh as Tc,Dd as Uc,Ph as Vc,Ah as Wc,kh as Xc,_h as Yc,xh as Zc,Oh as _c,Mh as $c,Lh as ad,Nh as bd,Uh as cd,qh as dd,Dh as ed,$h as fd,zh as gd,jh as hd,Hh as id,$d as jd,zd as kd,Fh as ld,Gh as md,Bh as nd,Zh as od,jd as pd,Hd as qd,Vh as rd,Jh as sd,Kh as td,Is as ud,tS as vd,dg as wd,Sc as xd,mg as yd,D0 as zd,$0 as Ad,z0 as Bd,j0 as Cd,H0 as Dd,F0 as Ed,gW as Fd,TS as Gd,EW as Hd,IS as Id,PS as Jd,kS as Kd,OS as Ld,LS as Md,US as Nd,DS as Od,zS as Pd,FS as Qd,ZS as Rd,KS as Sd,QS as Td,_s as Ud,Et as Vd,Zo as Wd,eC as Xd,tC as Yd,lp as Zd,dp as _d,pp as $d,aC as ae,hp as be,lC as ce,dC as de,l3 as ee,pC as fe,mC as ge,EC as he,kC as ie,qg as je,Dg as ke,_N as le,Zg as me,wv as ne,Tv as oe,Xg as pe,kv as qe,Ov as re,fU as se,zv as te,$U as ue,GU as ve,BU as we,Zv as xe,JU as ye,ry as ze,xY as Ae,Vv as Be,kn as Ce,oq as De,Qv as Ee,Xv as Fe,iq as Ge,nT as He,aq as Ie,gq as Je,yq as Ke,bq as Le,Rq as Me,wq as Ne,Sq as Oe,uT as Pe,Tq as Qe,Iq as Re,Eq as Se,Pq as Te,Aq as Ue,kq as Ve,_q as We,xq as Xe,Oq as Ye,hy as Ze,U9 as _e,Uq as $e,Dq as af,gT as bf,W9 as cf,RT as df,Jq as ef,Pi as ff,Bc as gf,at as hf,kt as if,gHe as jf,Wo as kf,EHe as lf,qp as mf,_He as nf,xHe as of,Xn as pf,LHe as qf,NHe as rf,UHe as sf,qHe as tf,DHe as uf,$He as vf,zHe as wf,jHe as xf,Dp as yf,HHe as zf,Ds as Af,VHe as Bf,wy as Cf,$s as Df,Vc as Ef,vT as Ff,i1e as Gf,TT as Hf,IT as If,ET as Jf,PT as Kf,AT as Lf,kT as Mf,_T as Nf,xT as Of,OT as Pf,MT as Qf,qD as Rf,mo as Sf,eo as Tf,Ht as Uf,jD as Vf,cQ as Wf,uQ as Xf,LT as Yf,SGe as Zf,CGe as _f,vGe as $f,o$ as ag,r$ as bg,VGe as cg,JGe as dg,NT as eg,zp as fg,Ey as gg,KGe as hg,a$ as ig,XGe as jg,jp as kg,xQ as lg,OQ as mg,qT as ng,cBe as og,d$ as pg,p$ as qg,pBe as rg,mBe as sg,fBe as tg,hBe as ug,m$ as vg,f$ as wg,g$ as xg,Yo as yg,qr as zg,NQ as Ag,UQ as Bg,vBe as Cg,TBe as Dg,IBe as Eg,EBe as Fg,Qo as Gg,zQ as Hg,DBe as Ig,R$ as Jg,JBe as Kg,jT as Lg,HQ as Mg,WQ as Ng,QQ as Og,C$ as Pg,uZe as Qg,lZe as Rg,dZe as Sg,E$ as Tg,hZe as Ug,gZe as Vg,yZe as Wg,VT as Xg,_y as Yg,JT as Zg,k$ as _g,EZe as $g,PZe as ah,AZe as bh,kZe as ch,Iz as dh,to as eh,o2e as fh,lI as gh,d2e as hh,Ez as ih,p2e as jh,k2e as kh,fI as lh,hI as mh,Mz as nh,U7 as oh,qz as ph,SI as qh,Vz as rh,vI as sh,nj as th,TI as uh,EI as vh,rj as wh,ij as xh,sj as yh,kI as zh,xI as Ah,mj as Bh,fj as Ch,hj as Dh,gj as Eh,yj as Fh,Rj as Gh,LI as Hh,see as Ih,Tj as Jh,DI as Kh,_j as Lh,xj as Mh,Oj as Nh,Ree as Oh,Mj as Ph,Lj as Qh,Nj as Rh,Uj as Sh,qj as Th,HI as Uh,$j as Vh,zj as Wh,FI as Xh,GI as Yh,Fj as Zh,Bj as _h,Zj as $h,VI as ai,Jj as bi,eH as ci,QI as di,XI as ei,tH as fi,aH as gi,tE as hi,nE as ii,oE as ji,fp as ki};
413
- /*! For license information please see chunk-3DWWKPBI.js.LEGAL.txt */
414
- //# sourceMappingURL=chunk-3DWWKPBI.js.map
413
+ /*! For license information please see chunk-4SVXBKXH.js.LEGAL.txt */
414
+ //# sourceMappingURL=chunk-4SVXBKXH.js.map