@zuplo/runtime 7.6.6 → 7.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/{chunk-VXNLSYUR.js → chunk-ZZCZZHOD.js} +3 -3
- package/out/esm/{chunk-VXNLSYUR.js.map → chunk-ZZCZZHOD.js.map} +1 -1
- package/out/esm/index.js +1 -1
- package/out/esm/mcp-gateway/index.js +1 -1
- package/out/types/index.d.ts +14 -14
- package/package.json +1 -1
- /package/out/esm/{chunk-VXNLSYUR.js.LEGAL.txt → chunk-ZZCZZHOD.js.LEGAL.txt} +0 -0
|
@@ -327,7 +327,7 @@ data: [DONE]
|
|
|
327
327
|
`).trim():typeof t=="string"?t.trim():"";if(!n)throw new Error("Missing smart-router options.classifierPrompt.");return n.includes(Ih)?n.replaceAll(Ih,XF(e)):n}i(eG,"buildClassifierSystemPrompt");function tG(t){return{type:"object",additionalProperties:!1,properties:{intent:{type:"string",enum:t},complexity:{type:"string",enum:[...Tk]},confidence:{type:"number"},reasons:{type:"array",items:{type:"string"}}},required:["intent","complexity","confidence","reasons"]}}i(tG,"buildExecutionProfileJsonSchema");function Ak(t,e,n,o){let r=tG(n.map(s=>s.id));return{model:e,max_completion_tokens:256,messages:[{role:"system",content:eG(o,n)},{role:"user",content:t}],response_format:{type:"json_schema",json_schema:{name:"execution_profile",strict:!0,schema:r}}}}i(Ak,"buildClassifierRequestBody");function Ek(t,e,n=.5){if(!t||typeof t!="object")throw new Error("Classifier returned a non-object profile");let o=t,r=typeof o.intent=="string"?o.intent:"",s=!e.has(r),a=!IR(o.complexity),c=IR(o.complexity)?o.complexity:"medium",u=Array.isArray(o.reasons)?o.reasons.filter(d=>typeof d=="string"):[],l=typeof o.confidence=="number"&&Number.isFinite(o.confidence)?Math.min(1,Math.max(0,o.confidence)):.5;return s&&(l=Math.min(l,YF(n)),u=["unknown intent",...u]),{profile:{intent:r,complexity:c,confidence:l,reasons:u.slice(0,3)},unknownIntent:s,complexityDefaulted:a}}i(Ek,"parseAndRepairProfile");function kk(t,e={}){return IR(t.complexity)?{model:e.modelsByComplexity?.[t.complexity]}:{}}i(kk,"resolveRoutingDecision");function Ok(t){return!!t&&typeof t=="object"&&t.type==="tool_result"}i(Ok,"isToolResultPart");function Mk(t){let e=t?.content;return!Array.isArray(e)||e.length===0?!1:e.every(n=>Ok(n))}i(Mk,"isToolResultOnlyMessage");function xk(t){if(!t)return!1;let e=t.role?.toLowerCase();if(e==="tool"||e==="function")return!0;let n=t.type?.toLowerCase();return n==="function_call_output"||n==="tool_result"?!0:Mk(t)}i(xk,"isToolFollowUpItem");function nG(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>!Ok(e)).map(e=>pt(e)).filter(Boolean).join(`
|
|
328
328
|
`):pt(t)}i(nG,"messageContentToText");function TR(t){let e=t[t.length-1],n=xk(e),o=t.filter(s=>s.role==="user"),r=o.length>0?o:[e];for(let s=r.length-1;s>=0;s--){let a=r[s];if(xk(a)){n=!0;continue}let c=nG(a?.content).trim();if(c)return{text:c,source:n?"prior-user":"user"}}}i(TR,"extractFromMessages");function Lk(t){switch(t.format){case"openai-chat":return TR(t.body.messages??[]);case"anthropic-messages":return TR(t.body.messages??[]);case"openai-responses":return oG(t.body.input)}}i(Lk,"extractPromptFromRequestBody");function oG(t){if(typeof t=="string"&&t.trim())return{text:t.trim(),source:"user"};if(!Array.isArray(t))return;let e=t.filter(o=>!!o&&typeof o=="object"&&!Array.isArray(o));if(e.length>0){let o=TR(e);if(o)return o}let n=t.map(o=>typeof o=="string"?o:"").filter(Boolean).join(`
|
|
329
329
|
`).trim();return n?{text:n,source:"user"}:void 0}i(oG,"extractFromResponsesInput");function rG(t){return t===void 0?{contentKind:"undefined"}:typeof t=="string"?{contentKind:"string",length:t.length,trimmedLength:t.trim().length}:Array.isArray(t)?{contentKind:"array",partCount:t.length,partTypes:t.map(e=>{if(e&&typeof e=="object"){let n=e.type;if(typeof n=="string")return n}return typeof e}),partsWithText:t.filter(e=>{let n=e?.text;return typeof n=="string"&&n.trim().length>0}).length}:{contentKind:typeof t}}i(rG,"describeContent");function Nk(t){let e={format:t.format};if(t.format==="openai-chat")return{...e,..._k(t.body.messages)};if(t.format==="anthropic-messages")return{...e,..._k(t.body.messages)};let n=t.body.input;return typeof n=="string"?{...e,inputKind:"string",inputLength:n.length,inputTrimmedLength:n.trim().length}:Array.isArray(n)?{...e,inputKind:"array",inputLength:n.length,inputItemKinds:n.map(o=>typeof o=="string"?"string":o&&typeof o=="object"?"object":typeof o)}:{...e,inputKind:n===void 0?"undefined":typeof n}}i(Nk,"describeUnextractablePrompt");function _k(t){if(!Array.isArray(t))return{hasMessages:!1};let e=t.filter(o=>o.role==="user"),n=e.length>0?e[e.length-1]:t[t.length-1];return{hasMessages:!0,messageCount:t.length,userMessageCount:e.length,messageRoles:t.map(o=>o.role??"unset").slice(-8),sourceRole:n?.role??"unset",lastUserIsToolResultOnly:Mk(e[e.length-1]),...rG(n?.content)}}i(_k,"describeMessageList");function qk(t,e){return e<=0||t.length<=e?{text:t,truncated:!1}:{text:t.slice(0,e),truncated:!0}}i(qk,"truncatePrompt");var $k=8e3,Dk=8e3,iG=512;async function sG(t,e,n){let o;try{return await Promise.race([t,new Promise((r,s)=>{o=setTimeout(()=>s(new Error(n)),e)})])}finally{o!==void 0&&clearTimeout(o)}}i(sG,"withTimeout");async function zk(t,e,{classifierAppApiKey:n,classifierAppID:o,classifierModel:r,intents:s,classifierPrompt:a,minConfidenceForRouting:c,timeoutMs:u,maxPromptChars:l}){let d=Pk(s),p=new Set(d.map(H=>H.id)),h=Array.isArray(a)?a.join(`
|
|
330
|
-
`):a,g=typeof h=="string"&&h.includes(Ih),{text:y,truncated:S}=qk(e,l);t.log.info({classifierAppID:o,classifierModel:r,intentCount:d.length,intentIds:d.map(H=>H.id),intentsInjected:g,promptLength:e.length,promptTruncated:S,timeoutMs:u},"Classifying prompt");let R=await sG(t.invokeRoute(`/${o}/v1/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(Ak(y,r,d,a))}),u,`Classifier request timed out after ${u}ms`);if(!R.ok){let H=(await R.text()).slice(0,iG);throw new Error(`Classifier error (${R.status}): ${H}`)}let C=await R.json();if(!C||typeof C!="object")throw new Error("Classifier returned a non-object response");let v=C,P=v.choices?.[0]?.message?.content;if(typeof P!="string"||P.length===0)throw new Error("Classifier returned an empty response");let A;try{A=JSON.parse(P)}catch{throw new Error("Classifier returned invalid JSON")}let{profile:E,unknownIntent:L,complexityDefaulted:z}=Ek(A,p,c);L&&t.log.info({intent:E.intent,confidence:E.confidence,minConfidenceForRouting:c},"Unknown intent kept; confidence capped for routing"),z&&t.log.info({received:typeof A=="object"&&A&&"complexity"in A?A.complexity:void 0,complexity:E.complexity},"Invalid complexity defaulted to medium");let B=i(H=>typeof H=="number"&&Number.isFinite(H)?H:0,"num");return{profile:E,usage:{promptTokens:B(v.usage?.prompt_tokens),completionTokens:B(v.usage?.completion_tokens),totalTokens:B(v.usage?.total_tokens)},model:typeof v.model=="string"&&v.model.length>0?v.model:r,unknownIntent:L,promptTruncated:S}}i(zk,"classifyPrompt");var Uk=["You are an intent classifier.","","Never answer the user's question.","Return JSON only that matches the schema.","","Pick the single most specific intent. Classify complexity independently of intent.","Do not choose an intent based on which model would be better.","","Intent (pick the single most specific match):","{{intents}}","","When intents overlap:","- code vs agentic: pick agentic only when tools must be invoked (function calling, browsing, file operations). Otherwise pick code.","- qa vs document_qa vs summarization: summarization condenses or extracts from given text; document_qa asks a question over large provided or retrieved documents; qa is a short factual question with no large attached context.","- classification vs summarization: classification assigns labels (sentiment, tags, routing). summarization pulls content or fields from unstructured text.","- other is last. Never use other when a listed intent fits. If two listed intents fit, pick the more specific one and lower confidence (typically 0.4\u20130.7) instead of other.","","If two intents fit, pick the more specific one and lower confidence (typically 0.4\u20130.7).","","complexity (from the prompt alone):","- low: single-step, no synthesis \u2014 greetings, one-fact lookups.","- medium: combines knowledge or a few steps.","- high: architecture, multi-system, security-sensitive, or a large change.","","confidence: 0 to 1. Use low confidence when assigning other or when the match is weak.","reasons: 1-3 short phrases."],jk=[{id:"code",description:"Write, edit, refactor, debug, or review source code. Produce or change code text. Not agentic unless tools must be invoked."},{id:"summarization",description:"Condense given text, or extract fields and entities from unstructured text. Not a question over a large document (that is document_qa)."},{id:"translation",description:"Convert text from one language to another."},{id:"qa",description:'Short factual questions, definitions, or "what is X". No large attached or retrieved document.'},{id:"conversation",description:"Greetings, small talk, or low-stakes back-and-forth."},{id:"classification",description:"Assign labels: sentiment, tagging, routing decisions, or form-filling / JSON label assignment. Not pulling facts from a document (that is summarization)."},{id:"creative_writing",description:"Stories, poetry, scripts, or marketing prose. Prose, not source code."},{id:"agentic",description:"Multi-step tasks that require calling tools \u2014 function calling, browsing, or file operations. If both code and agentic fit, pick agentic only when tools must be invoked."},{id:"document_qa",description:"Questions over large provided or retrieved documents (RAG-style). Prefer this over qa or summarization when the user is asking about attached or retrieved document content."},{id:"other",description:"ONLY when none of the other intents fit. Never use other for code, qa, conversation, or any listed intent. If two listed intents fit, pick the more specific one and lower confidence instead of other."}];var Th=m.string().regex(/^[^/\s]+\/.+$/,{message:'must be a providerName/model reference such as "openai/gpt-4o-mini"'}),cG=m.object({id:m.string().min(1),description:m.string()}).strict(),uG=m.object({classifierAppApiKey:m.string().min(1),classifierAppID:m.string().min(1),classifierModel:Th,intents:m.array(cG).min(1).optional(),classifierPrompt:m.union([m.string().min(1),m.array(m.string()).min(1)]).optional(),smartRoutingEnabled:m.boolean().optional(),modelsByComplexity:m.object({low:Th.optional(),medium:Th.optional(),high:Th.optional()}).strict().optional(),minConfidenceForRouting:m.number().min(0).max(1).optional(),classifierTimeoutMs:m.number().int().min(1).max(12e4).optional(),maxPromptChars:m.number().int().min(1).optional()}).strict();function Hk(t,e){let n=t;for(let o of e){if(n===null||typeof n!="object")return;n=n[o]}return n}i(Hk,"valueAtIssuePath");function lG(t,e){if(!t)return"is invalid";switch(t.code){case"invalid_type":return Hk(e,t.path)===void 0?"is required":`must be ${t.expected??"a different type"}`;case"too_small":return"must not be empty or below the minimum";case"too_big":return"is above the maximum";case"unrecognized_keys":return`contains unsupported field(s): ${(t.keys??[]).join(", ")}`;case"invalid_value":return Hk(e,t.path)===void 0?"is required":"is not one of the allowed values";case"custom":return t.message??"is invalid";default:return t.message||"is invalid"}}i(lG,"describeIssue");function Fk(t,e){let n=uG.safeParse(t??{});if(!n.success){let r=n.error.issues[0],s=r?.path.length?`options.${r.path.join(".")}`:"options";return{ok:!1,failure:{policyName:e,message:`Invalid AIGatewaySmartRouterInboundPolicy '${e}': ${s} ${lG(r,t)}. Set the required classifierAppID, classifierAppApiKey, and classifierModel options, or omit this policy from the chain. A configuration.inboundPolicyChain entry's options replace the declared options completely.`}}}let o=n.data;return{ok:!0,value:{classifierAppApiKey:o.classifierAppApiKey,classifierAppID:o.classifierAppID,classifierModel:o.classifierModel,intents:o.intents??jk,classifierPrompt:o.classifierPrompt??Uk,smartRoutingEnabled:o.smartRoutingEnabled??!1,modelsByComplexity:o.modelsByComplexity,minConfidenceForRouting:o.minConfidenceForRouting??.5,classifierTimeoutMs:o.classifierTimeoutMs??$k,maxPromptChars:o.maxPromptChars??Dk}}}i(Fk,"parseSmartRouterOptions");var dG=nt("zuplo:policies:AIGatewaySmartRouterPolicy");function pG(t,e,n,o,r){return t?r?"unknown-intent":e?n<o?"low-confidence":"applied":"no-model":"disabled"}i(pG,"resolveSmartRoutingReason");async function Gk(t,e,n,o){try{if(e.parentContext)return t;let r=Fk(n,o);if(!r.ok)return e.log.error({policyName:o},r.failure.message),t;let s=r.value;if(Rt(t)===null)return dG("Smart router skipping a non-AI request shape"),t;let c=await Rf(t);if(!c)return e.log.info({policyName:o,reason:"non-json-body",contentType:t.headers.get("content-type")??"unset",method:t.method},"Prompt classification skipped"),t;let u=Lk(c);if(!u){let A=Nk(c),E=A.lastUserIsToolResultOnly===!0?"tool-follow-up":"no-extractable-prompt";return e.log.info({policyName:o,reason:E,...A},"Prompt classification skipped"),t}let l=Date.now(),{profile:d,usage:p,model:h,unknownIntent:g,promptTruncated:y}=await zk(e,u.text,{classifierAppApiKey:s.classifierAppApiKey,classifierAppID:s.classifierAppID,classifierModel:s.classifierModel,intents:s.intents,classifierPrompt:s.classifierPrompt,minConfidenceForRouting:s.minConfidenceForRouting,timeoutMs:s.classifierTimeoutMs,maxPromptChars:s.maxPromptChars}),S=Date.now()-l,R=kk(d,{modelsByComplexity:s.modelsByComplexity}),C=R.model,v=pG(s.smartRoutingEnabled,C,d.confidence,s.minConfidenceForRouting,g),P=!1;if(s.smartRoutingEnabled&&!g&&C&&d.confidence>=s.minConfidenceForRouting)try{await Fn.set(e,{completions:C}),P=!0,v="applied",e.log.info({policyName:o,complexity:d.complexity,confidence:d.confidence,minConfidence:s.minConfidenceForRouting,model:C},"Model routed from classification")}catch(A){v="internal-error",e.log.error(A,"Smart routing failed")}else e.log.info({policyName:o,reason:v,smartRoutingEnabled:s.smartRoutingEnabled,unknownIntent:g,complexity:d.complexity,confidence:d.confidence,minConfidence:s.minConfidenceForRouting,mappedModel:C??"none"},"Smart routing skipped");Sf.set(e,{profile:d,usage:p,classifierModel:h,routing:R,durationMs:S,promptSource:u.source,promptLength:u.text.length,promptTruncated:y,unknownIntent:g,smartRouting:{enabled:s.smartRoutingEnabled,applied:P,reason:v,minConfidence:s.minConfidenceForRouting}}),e.log.info({policyName:o,intent:d.intent,complexity:d.complexity,confidence:d.confidence,durationMs:S,promptSource:u.source,unknownIntent:g,smartRoutingApplied:P,smartRoutingReason:v},"Prompt classified")}catch(r){e.log.error(r,"Smart router failed")}return t}i(Gk,"AIGatewaySmartRouterInboundPolicy");J("ai-gateway-smart-router",Gk);async function Bk(t,e,n,o,r){let s=ne.getLogger(n);if(n.custom.streamingUsageHandled===!0)return s.debug("Streaming usage will be handled in streaming transform, skipping sync usage tracker"),t;let c=pn(n);if(c?.servedFromCache)return s.debug("Response served from cache; cache policy emitted analytics, skipping usage tracker"),t;let u={requests:1},l=0,d=0,p=0,h="",g="";try{let Se=await t.clone().json();if(Se.usage){d=Se.usage.input_tokens??Se.usage.prompt_tokens??0,p=Se.usage.output_tokens??Se.usage.completion_tokens??0;let K=Se.usage.total_tokens||0;h=Se.model||"",g=Se.provider||"";let de=n.custom.label??g,{modelsByProvider:Q}=await Wn(n);l=ds(h,de,d,p,Q,s),s.info("Usage tracked",{userId:e.user?.sub,requestsIncrement:1,tokensUsed:K,promptTokens:d,completionTokens:p,model:h,provider:g,cost:l})}}catch(pe){s.debug("Could not track token usage, tracking request only",{error:pe})}u.tokens=d+p,u.costs=l,Zt.setIncrements(n,u);let y=new Headers(t.headers);u.tokens&&y.set("X-Tokens-Used",u.tokens.toString()),l>0&&(y.set("X-Cost-USD",l.toFixed(10)),y.set("X-Model",h)),y.set("X-Requests-Increment","1");let S=e.user,R=S?.configuration?.id??null,C=S?.sub??null,v=Fo(S?.configuration),P=v.teamId??c?.teamId??null,A=v.appId??c?.appId??null,E=null,L=null,z=c?.cacheState??null,B=null,H=n.custom.label??g;switch(n.analyticsContext.addAnalyticsEvent(1,ee.AI_GATEWAY_REQUEST_COUNT,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,routingTarget:B,...In(n)}),n.analyticsContext.addAnalyticsEvent(parseFloat(l.toFixed(10)),ee.AI_GATEWAY_COST_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,...In(n)}),new URL(e.url).pathname){case"/v1/responses":case"/v1/chat/completions":case"/v1/messages":n.analyticsContext.addAnalyticsEvent(d,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"prompt",...In(n)}),n.analyticsContext.addAnalyticsEvent(p,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"completion",...In(n)});break;case"/v1/embeddings":n.analyticsContext.addAnalyticsEvent(d,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"embedding",...In(n)});break;default:break}return new Response(t.body,{status:t.status,statusText:t.statusText,headers:y})}i(Bk,"AIGatewayUsageTrackerPolicy");at("ai-gateway-usage-tracker",Bk);function Ql(t,e,n){let o=n==="block"?"The request was blocked because the firewall is configured to fail closed (onError=block).":"The content was allowed through WITHOUT inspection because the firewall is configured to fail open (onError=allow).",r;e?.status===401?r="Akamai AI Firewall API key is invalid. Please check the Application ID and API key in your policy configuration.":e?.status===429?r="Akamai AI Firewall rate limit exceeded. Please contact Akamai support.":e?r=`Request to Akamai AI Firewall failed with ${e.status} ${e.statusText}.`:r="Request to Akamai AI Firewall failed before a valid response was received.";let s=`${r} ${o}`;n==="block"?t.log.error(s):t.log.warn(s)}i(Ql,"logDetectFailure");async function Gi(t,e,n,o,r){if(!t)return r.debug(`No text content to analyze for ${e}`),{kind:"ok"};let s=o.onError??"block";try{let a=`https://aisec.akamai.com/fai/v1/fai-configurations/${o.configurationId}/detect`,c={clientRequestId:n.requestId};o.applicationId&&(c.userApplicationId=o.applicationId),e==="input"?c.llmInput=t:c.llmOutput=t,r.debug(`Calling Akamai API for ${e}`,{contentLength:t.length});let u=await V.fetch(a,{method:"POST",headers:{"Content-Type":"application/json","Fai-Api-Key":o["api-key"]},body:JSON.stringify(c)});if(!u.ok){Ql(n,u,s);let p=new Error(`Akamai API call failed: ${u.status} ${u.statusText}`);return r.error(p,`Failed to check with Akamai for ${e}`),{kind:"error",error:p}}let l=await u.json();r.debug(`Akamai response for ${e}`,{overallRiskScore:l.overallRiskScore,rulesTriggered:l.rulesTriggered.length});let d=l.rulesTriggered.find(p=>p.action==="deny");return d?{kind:"deny",rule:d}:{kind:"ok"}}catch(a){return Ql(n,null,s),r.error(a,`Failed to check with Akamai for ${e}`),{kind:"error",error:a}}}i(Gi,"checkWithAkamai");function Bi(t,e,n){let o=`Request blocked by AI Firewall during ${e}. ${t.message} (Rule: ${t.ruleId})`,r=n==="anthropic-messages"?{type:"error",error:{type:"invalid_request_error",message:o}}:{error:{message:o,code:t.ruleId}};return new Response(JSON.stringify(r),{status:400,headers:{"Content-Type":"application/json"}})}i(Bi,"createBlockedResponse");function Zi(t,e){let n=`Request blocked during ${t}: the AI Firewall could not verify this content and the gateway is configured to fail closed. Contact your API administrator.`,o=e==="anthropic-messages"?{type:"error",error:{type:"api_error",message:n}}:{error:{message:n,code:"guardrail_unavailable"}};return new Response(JSON.stringify(o),{status:502,headers:{"Content-Type":"application/json"}})}i(Zi,"createFirewallUnavailableResponse");function Ph(t,e,n,o="unknown",r){let s=ne.getLogger(t),a=new TextDecoder,c=new TextEncoder,u=e.eventsInterval??5,l=e.checkIntervalMs,d=e.onError??"block";s.info("Akamai streaming accumulator initialized",{provider:o,requestId:t.requestId,configurationId:e.configurationId,applicationId:e.applicationId,eventsInterval:u,checkIntervalMs:l});let p={accumulatedText:"",chunkCount:0,lastCheckTime:Date.now(),sentEvents:[],pendingEvents:[],isBlocked:!1,sseBuffer:"",anthropicMessageStarted:!1,anthropicOpenContentBlocks:new Set};function h(A,E){return`event: ${A}
|
|
330
|
+
`):a,g=typeof h=="string"&&h.includes(Ih),{text:y,truncated:S}=qk(e,l);t.log.info({classifierAppID:o,classifierModel:r,intentCount:d.length,intentIds:d.map(H=>H.id),intentsInjected:g,promptLength:e.length,promptTruncated:S,timeoutMs:u},"Classifying prompt");let R=await sG(t.invokeRoute(`/${o}/v1/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(Ak(y,r,d,a))}),u,`Classifier request timed out after ${u}ms`);if(!R.ok){let H=(await R.text()).slice(0,iG);throw new Error(`Classifier error (${R.status}): ${H}`)}let C=await R.json();if(!C||typeof C!="object")throw new Error("Classifier returned a non-object response");let v=C,P=v.choices?.[0]?.message?.content;if(typeof P!="string"||P.length===0)throw new Error("Classifier returned an empty response");let A;try{A=JSON.parse(P)}catch{throw new Error("Classifier returned invalid JSON")}let{profile:E,unknownIntent:L,complexityDefaulted:z}=Ek(A,p,c);L&&t.log.info({intent:E.intent,confidence:E.confidence,minConfidenceForRouting:c},"Unknown intent kept; confidence capped for routing"),z&&t.log.info({received:typeof A=="object"&&A&&"complexity"in A?A.complexity:void 0,complexity:E.complexity},"Invalid complexity defaulted to medium");let B=i(H=>typeof H=="number"&&Number.isFinite(H)?H:0,"num");return{profile:E,usage:{promptTokens:B(v.usage?.prompt_tokens),completionTokens:B(v.usage?.completion_tokens),totalTokens:B(v.usage?.total_tokens)},model:typeof v.model=="string"&&v.model.length>0?v.model:r,unknownIntent:L,promptTruncated:S}}i(zk,"classifyPrompt");var Uk=["You are an intent classifier.","","Never answer the user's question.","Return JSON only that matches the schema.","","Pick the single most specific intent. Classify complexity independently of intent.","Do not choose an intent based on which model would be better.","","Intent (pick the single most specific match):","{{intents}}","","When intents overlap:","- code vs agentic: pick agentic only when tools must be invoked (function calling, browsing, file operations). Otherwise pick code.","- qa vs document_qa vs summarization: summarization condenses or extracts from given text; document_qa asks a question over large provided or retrieved documents; qa is a short factual question with no large attached context.","- classification vs summarization: classification assigns labels (sentiment, tags, routing). summarization pulls content or fields from unstructured text.","- other is last. Never use other when a listed intent fits. If two listed intents fit, pick the more specific one and lower confidence (typically 0.4\u20130.7) instead of other.","","If two intents fit, pick the more specific one and lower confidence (typically 0.4\u20130.7).","","complexity (from the prompt alone):","- low: single-step, no synthesis \u2014 greetings, one-fact lookups.","- medium: combines knowledge or a few steps.","- high: architecture, multi-system, security-sensitive, or a large change.","","confidence: 0 to 1. Use low confidence when assigning other or when the match is weak.","reasons: 1-3 short phrases."],jk=[{id:"code",description:"Write, edit, refactor, debug, or review source code. Produce or change code text. Not agentic unless tools must be invoked."},{id:"summarization",description:"Condense given text, or extract fields and entities from unstructured text. Not a question over a large document (that is document_qa)."},{id:"translation",description:"Convert text from one language to another."},{id:"qa",description:'Short factual questions, definitions, or "what is X". No large attached or retrieved document.'},{id:"conversation",description:"Greetings, small talk, or low-stakes back-and-forth."},{id:"classification",description:"Assign labels: sentiment, tagging, routing decisions, or form-filling / JSON label assignment. Not pulling facts from a document (that is summarization)."},{id:"creative_writing",description:"Stories, poetry, scripts, or marketing prose. Prose, not source code."},{id:"agentic",description:"Multi-step tasks that require calling tools \u2014 function calling, browsing, or file operations. If both code and agentic fit, pick agentic only when tools must be invoked."},{id:"document_qa",description:"Questions over large provided or retrieved documents (RAG-style). Prefer this over qa or summarization when the user is asking about attached or retrieved document content."},{id:"other",description:"ONLY when none of the other intents fit. Never use other for code, qa, conversation, or any listed intent. If two listed intents fit, pick the more specific one and lower confidence instead of other."}];var Th=m.string().regex(/^[^/\s]+\/.+$/,{message:'must be a providerName/model reference such as "openai/gpt-4o-mini"'}),cG=m.object({id:m.string().min(1),description:m.string()}).strict(),uG=m.object({classifierAppApiKey:m.string().min(1),classifierAppID:m.string().min(1),classifierModel:Th,intents:m.array(cG).min(1).optional(),classifierPrompt:m.union([m.string().min(1),m.array(m.string()).min(1)]).optional(),smartRoutingEnabled:m.boolean().optional(),modelsByComplexity:m.object({low:Th,medium:Th,high:Th}).strict(),minConfidenceForRouting:m.number().min(0).max(1).optional(),classifierTimeoutMs:m.number().int().min(1).max(12e4).optional(),maxPromptChars:m.number().int().min(1).optional()}).strict();function Hk(t,e){let n=t;for(let o of e){if(n===null||typeof n!="object")return;n=n[o]}return n}i(Hk,"valueAtIssuePath");function lG(t,e){if(!t)return"is invalid";switch(t.code){case"invalid_type":return Hk(e,t.path)===void 0?"is required":`must be ${t.expected??"a different type"}`;case"too_small":return"must not be empty or below the minimum";case"too_big":return"is above the maximum";case"unrecognized_keys":return`contains unsupported field(s): ${(t.keys??[]).join(", ")}`;case"invalid_value":return Hk(e,t.path)===void 0?"is required":"is not one of the allowed values";case"custom":return t.message??"is invalid";default:return t.message||"is invalid"}}i(lG,"describeIssue");function Fk(t,e){let n=uG.safeParse(t??{});if(!n.success){let r=n.error.issues[0],s=r?.path.length?`options.${r.path.join(".")}`:"options";return{ok:!1,failure:{policyName:e,message:`Invalid AIGatewaySmartRouterInboundPolicy '${e}': ${s} ${lG(r,t)}. Set the required classifierAppID, classifierAppApiKey, classifierModel, and modelsByComplexity (low, medium, high) options, or omit this policy from the chain. A configuration.inboundPolicyChain entry's options replace the declared options completely.`}}}let o=n.data;return{ok:!0,value:{classifierAppApiKey:o.classifierAppApiKey,classifierAppID:o.classifierAppID,classifierModel:o.classifierModel,intents:o.intents??jk,classifierPrompt:o.classifierPrompt??Uk,smartRoutingEnabled:o.smartRoutingEnabled??!1,modelsByComplexity:o.modelsByComplexity,minConfidenceForRouting:o.minConfidenceForRouting??.5,classifierTimeoutMs:o.classifierTimeoutMs??$k,maxPromptChars:o.maxPromptChars??Dk}}}i(Fk,"parseSmartRouterOptions");var dG=nt("zuplo:policies:AIGatewaySmartRouterPolicy");function pG(t,e,n,o,r){return t?r?"unknown-intent":e?n<o?"low-confidence":"applied":"no-model":"disabled"}i(pG,"resolveSmartRoutingReason");async function Gk(t,e,n,o){try{if(e.parentContext)return t;let r=Fk(n,o);if(!r.ok)return e.log.error({policyName:o},r.failure.message),t;let s=r.value;if(Rt(t)===null)return dG("Smart router skipping a non-AI request shape"),t;let c=await Rf(t);if(!c)return e.log.info({policyName:o,reason:"non-json-body",contentType:t.headers.get("content-type")??"unset",method:t.method},"Prompt classification skipped"),t;let u=Lk(c);if(!u){let A=Nk(c),E=A.lastUserIsToolResultOnly===!0?"tool-follow-up":"no-extractable-prompt";return e.log.info({policyName:o,reason:E,...A},"Prompt classification skipped"),t}let l=Date.now(),{profile:d,usage:p,model:h,unknownIntent:g,promptTruncated:y}=await zk(e,u.text,{classifierAppApiKey:s.classifierAppApiKey,classifierAppID:s.classifierAppID,classifierModel:s.classifierModel,intents:s.intents,classifierPrompt:s.classifierPrompt,minConfidenceForRouting:s.minConfidenceForRouting,timeoutMs:s.classifierTimeoutMs,maxPromptChars:s.maxPromptChars}),S=Date.now()-l,R=kk(d,{modelsByComplexity:s.modelsByComplexity}),C=R.model,v=pG(s.smartRoutingEnabled,C,d.confidence,s.minConfidenceForRouting,g),P=!1;if(s.smartRoutingEnabled&&!g&&C&&d.confidence>=s.minConfidenceForRouting)try{await Fn.set(e,{completions:C}),P=!0,v="applied",e.log.info({policyName:o,complexity:d.complexity,confidence:d.confidence,minConfidence:s.minConfidenceForRouting,model:C},"Model routed from classification")}catch(A){v="internal-error",e.log.error(A,"Smart routing failed")}else e.log.info({policyName:o,reason:v,smartRoutingEnabled:s.smartRoutingEnabled,unknownIntent:g,complexity:d.complexity,confidence:d.confidence,minConfidence:s.minConfidenceForRouting,mappedModel:C??"none"},"Smart routing skipped");Sf.set(e,{profile:d,usage:p,classifierModel:h,routing:R,durationMs:S,promptSource:u.source,promptLength:u.text.length,promptTruncated:y,unknownIntent:g,smartRouting:{enabled:s.smartRoutingEnabled,applied:P,reason:v,minConfidence:s.minConfidenceForRouting}}),e.log.info({policyName:o,intent:d.intent,complexity:d.complexity,confidence:d.confidence,durationMs:S,promptSource:u.source,unknownIntent:g,smartRoutingApplied:P,smartRoutingReason:v},"Prompt classified")}catch(r){e.log.error(r,"Smart router failed")}return t}i(Gk,"AIGatewaySmartRouterInboundPolicy");J("ai-gateway-smart-router",Gk);async function Bk(t,e,n,o,r){let s=ne.getLogger(n);if(n.custom.streamingUsageHandled===!0)return s.debug("Streaming usage will be handled in streaming transform, skipping sync usage tracker"),t;let c=pn(n);if(c?.servedFromCache)return s.debug("Response served from cache; cache policy emitted analytics, skipping usage tracker"),t;let u={requests:1},l=0,d=0,p=0,h="",g="";try{let Se=await t.clone().json();if(Se.usage){d=Se.usage.input_tokens??Se.usage.prompt_tokens??0,p=Se.usage.output_tokens??Se.usage.completion_tokens??0;let K=Se.usage.total_tokens||0;h=Se.model||"",g=Se.provider||"";let de=n.custom.label??g,{modelsByProvider:Q}=await Wn(n);l=ds(h,de,d,p,Q,s),s.info("Usage tracked",{userId:e.user?.sub,requestsIncrement:1,tokensUsed:K,promptTokens:d,completionTokens:p,model:h,provider:g,cost:l})}}catch(pe){s.debug("Could not track token usage, tracking request only",{error:pe})}u.tokens=d+p,u.costs=l,Zt.setIncrements(n,u);let y=new Headers(t.headers);u.tokens&&y.set("X-Tokens-Used",u.tokens.toString()),l>0&&(y.set("X-Cost-USD",l.toFixed(10)),y.set("X-Model",h)),y.set("X-Requests-Increment","1");let S=e.user,R=S?.configuration?.id??null,C=S?.sub??null,v=Fo(S?.configuration),P=v.teamId??c?.teamId??null,A=v.appId??c?.appId??null,E=null,L=null,z=c?.cacheState??null,B=null,H=n.custom.label??g;switch(n.analyticsContext.addAnalyticsEvent(1,ee.AI_GATEWAY_REQUEST_COUNT,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,routingTarget:B,...In(n)}),n.analyticsContext.addAnalyticsEvent(parseFloat(l.toFixed(10)),ee.AI_GATEWAY_COST_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,...In(n)}),new URL(e.url).pathname){case"/v1/responses":case"/v1/chat/completions":case"/v1/messages":n.analyticsContext.addAnalyticsEvent(d,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"prompt",...In(n)}),n.analyticsContext.addAnalyticsEvent(p,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"completion",...In(n)});break;case"/v1/embeddings":n.analyticsContext.addAnalyticsEvent(d,ee.AI_GATEWAY_TOKEN_SUM,{model:h,provider:g,label:H,configId:R,teamId:P,appId:A,consumerSub:C,environment:E,region:L,cacheState:z,tokenType:"embedding",...In(n)});break;default:break}return new Response(t.body,{status:t.status,statusText:t.statusText,headers:y})}i(Bk,"AIGatewayUsageTrackerPolicy");at("ai-gateway-usage-tracker",Bk);function Ql(t,e,n){let o=n==="block"?"The request was blocked because the firewall is configured to fail closed (onError=block).":"The content was allowed through WITHOUT inspection because the firewall is configured to fail open (onError=allow).",r;e?.status===401?r="Akamai AI Firewall API key is invalid. Please check the Application ID and API key in your policy configuration.":e?.status===429?r="Akamai AI Firewall rate limit exceeded. Please contact Akamai support.":e?r=`Request to Akamai AI Firewall failed with ${e.status} ${e.statusText}.`:r="Request to Akamai AI Firewall failed before a valid response was received.";let s=`${r} ${o}`;n==="block"?t.log.error(s):t.log.warn(s)}i(Ql,"logDetectFailure");async function Gi(t,e,n,o,r){if(!t)return r.debug(`No text content to analyze for ${e}`),{kind:"ok"};let s=o.onError??"block";try{let a=`https://aisec.akamai.com/fai/v1/fai-configurations/${o.configurationId}/detect`,c={clientRequestId:n.requestId};o.applicationId&&(c.userApplicationId=o.applicationId),e==="input"?c.llmInput=t:c.llmOutput=t,r.debug(`Calling Akamai API for ${e}`,{contentLength:t.length});let u=await V.fetch(a,{method:"POST",headers:{"Content-Type":"application/json","Fai-Api-Key":o["api-key"]},body:JSON.stringify(c)});if(!u.ok){Ql(n,u,s);let p=new Error(`Akamai API call failed: ${u.status} ${u.statusText}`);return r.error(p,`Failed to check with Akamai for ${e}`),{kind:"error",error:p}}let l=await u.json();r.debug(`Akamai response for ${e}`,{overallRiskScore:l.overallRiskScore,rulesTriggered:l.rulesTriggered.length});let d=l.rulesTriggered.find(p=>p.action==="deny");return d?{kind:"deny",rule:d}:{kind:"ok"}}catch(a){return Ql(n,null,s),r.error(a,`Failed to check with Akamai for ${e}`),{kind:"error",error:a}}}i(Gi,"checkWithAkamai");function Bi(t,e,n){let o=`Request blocked by AI Firewall during ${e}. ${t.message} (Rule: ${t.ruleId})`,r=n==="anthropic-messages"?{type:"error",error:{type:"invalid_request_error",message:o}}:{error:{message:o,code:t.ruleId}};return new Response(JSON.stringify(r),{status:400,headers:{"Content-Type":"application/json"}})}i(Bi,"createBlockedResponse");function Zi(t,e){let n=`Request blocked during ${t}: the AI Firewall could not verify this content and the gateway is configured to fail closed. Contact your API administrator.`,o=e==="anthropic-messages"?{type:"error",error:{type:"api_error",message:n}}:{error:{message:n,code:"guardrail_unavailable"}};return new Response(JSON.stringify(o),{status:502,headers:{"Content-Type":"application/json"}})}i(Zi,"createFirewallUnavailableResponse");function Ph(t,e,n,o="unknown",r){let s=ne.getLogger(t),a=new TextDecoder,c=new TextEncoder,u=e.eventsInterval??5,l=e.checkIntervalMs,d=e.onError??"block";s.info("Akamai streaming accumulator initialized",{provider:o,requestId:t.requestId,configurationId:e.configurationId,applicationId:e.applicationId,eventsInterval:u,checkIntervalMs:l});let p={accumulatedText:"",chunkCount:0,lastCheckTime:Date.now(),sentEvents:[],pendingEvents:[],isBlocked:!1,sseBuffer:"",anthropicMessageStarted:!1,anthropicOpenContentBlocks:new Set};function h(A,E){return`event: ${A}
|
|
331
331
|
data: ${JSON.stringify(E)}
|
|
332
332
|
|
|
333
333
|
`}i(h,"anthropicSseEvent");function g(A){if(n==="anthropic-messages"){for(let E of A.split(`
|
|
@@ -406,5 +406,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
406
406
|
`);let b=new v("!xml"),T=b,x="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let M=new P(this.options.processEntities);for(let k=0;k<f.length;k++)if(f[k]==="<")if(f[k+1]==="/"){let Z=cn(f,">",k,"Closing Tag is not closed."),U=f.substring(k+2,Z).trim();if(this.options.removeNSPrefix){let Pe=U.indexOf(":");Pe!==-1&&(U=U.substr(Pe+1))}U=On(this.options.transformTagName,U,"",this.options).tagName,T&&(x=this.saveTextToParentTag(x,T,this.matcher));let Re=this.matcher.getCurrentTag();if(U&&this.options.unpairedTags.indexOf(U)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${U}>`);Re&&this.options.unpairedTags.indexOf(Re)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,T=this.tagsNodeStack.pop(),x="",k=Z}else if(f[k+1]==="?"){let Z=Sn(f,k,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(x=this.saveTextToParentTag(x,T,this.matcher),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let U=new v(Z.tagName);U.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(U[":@"]=this.buildAttributesMap(Z.tagExp,this.matcher,Z.tagName)),this.addChild(T,U,this.matcher,k)}k=Z.closeIndex+1}else if(f.substr(k+1,3)==="!--"){let Z=cn(f,"-->",k+4,"Comment is not closed.");if(this.options.commentPropName){let U=f.substring(k+4,Z-2);x=this.saveTextToParentTag(x,T,this.matcher),T.add(this.options.commentPropName,[{[this.options.textNodeName]:U}])}k=Z}else if(f.substr(k+1,2)==="!D"){let Z=M.readDocType(f,k);this.docTypeEntities=Z.entities,k=Z.i}else if(f.substr(k+1,2)==="!["){let Z=cn(f,"]]>",k,"CDATA is not closed.")-2,U=f.substring(k+9,Z);x=this.saveTextToParentTag(x,T,this.matcher);let Re=this.parseTextData(U,T.tagname,this.matcher,!0,!1,!0,!0);Re==null&&(Re=""),this.options.cdataPropName?T.add(this.options.cdataPropName,[{[this.options.textNodeName]:U}]):T.add(this.options.textNodeName,Re),k=Z+2}else{let Z=Sn(f,k,this.options.removeNSPrefix);if(!Z){let Wt=f.substring(Math.max(0,k-50),Math.min(f.length,k+50));throw new Error(`readTagExp returned undefined at position ${k}. Context: "${Wt}"`)}let U=Z.tagName,Re=Z.rawTagName,Pe=Z.tagExp,Ue=Z.attrExpPresent,ht=Z.closeIndex;if({tagName:U,tagExp:Pe}=On(this.options.transformTagName,U,Pe,this.options),this.options.strictReservedNames&&(U===this.options.commentPropName||U===this.options.cdataPropName||U===this.options.textNodeName||U===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${U}`);T&&x&&T.tagname!=="!xml"&&(x=this.saveTextToParentTag(x,T,this.matcher,!1));let nn=T;nn&&this.options.unpairedTags.indexOf(nn.tagname)!==-1&&(T=this.tagsNodeStack.pop(),this.matcher.pop());let wr=!1;Pe.length>0&&Pe.lastIndexOf("/")===Pe.length-1&&(wr=!0,U[U.length-1]==="/"?(U=U.substr(0,U.length-1),Pe=U):Pe=Pe.substr(0,Pe.length-1),Ue=U!==Pe);let ft=null,Cn={},Cr;Cr=X(Re),U!==b.tagname&&this.matcher.push(U,{},Cr),U!==Pe&&Ue&&(ft=this.buildAttributesMap(Pe,this.matcher,U),ft&&(Cn=oe(ft,this.options))),U!==b.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let ln=k;if(this.isCurrentNodeStopNode){let Wt="";if(wr)k=Z.closeIndex;else if(this.options.unpairedTags.indexOf(U)!==-1)k=Z.closeIndex;else{let Ir=this.readStopNodeData(f,Re,ht+1);if(!Ir)throw new Error(`Unexpected end of ${Re}`);k=Ir.i,Wt=Ir.tagContent}let vr=new v(U);ft&&(vr[":@"]=ft),vr.add(this.options.textNodeName,Wt),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(T,vr,this.matcher,ln)}else{if(wr){({tagName:U,tagExp:Pe}=On(this.options.transformTagName,U,Pe,this.options));let Wt=new v(U);ft&&(Wt[":@"]=ft),this.addChild(T,Wt,this.matcher,ln),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(U)!==-1){let Wt=new v(U);ft&&(Wt[":@"]=ft),this.addChild(T,Wt,this.matcher,ln),this.matcher.pop(),this.isCurrentNodeStopNode=!1,k=Z.closeIndex;continue}else{let Wt=new v(U);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(T),ft&&(Wt[":@"]=ft),this.addChild(T,Wt,this.matcher,ln),T=Wt}x="",k=ht}}else x+=f[k];return b.child},"parseXml");function ae(f,b,T,x){this.options.captureMetaData||(x=void 0);let M=this.options.jPath?T.toString():T,k=this.options.updateTag(b.tagname,M,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),f.addChild(b,x))}i(ae,"addChild"),n(ae,"addChild");function ce(f,b,T){let x=this.options.processEntities;if(!x||!x.enabled)return f;if(x.allowedTags){let M=this.options.jPath?T.toString():T;if(!(Array.isArray(x.allowedTags)?x.allowedTags.includes(b):x.allowedTags(b,M)))return f}if(x.tagFilter){let M=this.options.jPath?T.toString():T;if(!x.tagFilter(b,M))return f}for(let M of Object.keys(this.docTypeEntities)){let k=this.docTypeEntities[M],Y=f.match(k.regx);if(Y){if(this.entityExpansionCount+=Y.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);let Z=f.length;if(f=f.replace(k.regx,k.val),x.maxExpandedLength&&(this.currentExpandedLength+=f.length-Z,this.currentExpandedLength>x.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${x.maxExpandedLength}`)}}for(let M of Object.keys(this.lastEntities)){let k=this.lastEntities[M],Y=f.match(k.regex);if(Y&&(this.entityExpansionCount+=Y.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);f=f.replace(k.regex,k.val)}if(f.indexOf("&")===-1)return f;if(this.options.htmlEntities)for(let M of Object.keys(this.htmlEntities)){let k=this.htmlEntities[M],Y=f.match(k.regex);if(Y&&(this.entityExpansionCount+=Y.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);f=f.replace(k.regex,k.val)}return f=f.replace(this.ampEntity.regex,this.ampEntity.val),f}i(ce,"replaceEntitiesValue"),n(ce,"replaceEntitiesValue");function ke(f,b,T,x){return f&&(x===void 0&&(x=b.child.length===0),f=this.parseTextData(f,b.tagname,T,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,x),f!==void 0&&f!==""&&b.add(this.options.textNodeName,f),f=""),f}i(ke,"saveTextToParentTag"),n(ke,"saveTextToParentTag");function _e(f,b){if(!f||f.length===0)return!1;for(let T=0;T<f.length;T++)if(b.matches(f[T]))return!0;return!1}i(_e,"isItStopNode"),n(_e,"isItStopNode");function $(f,b,T=">"){let x,M="";for(let k=b;k<f.length;k++){let Y=f[k];if(x)Y===x&&(x="");else if(Y==='"'||Y==="'")x=Y;else if(Y===T[0])if(T[1]){if(f[k+1]===T[1])return{data:M,index:k}}else return{data:M,index:k};else Y===" "&&(Y=" ");M+=Y}}i($,"tagExpWithClosingIndex"),n($,"tagExpWithClosingIndex");function cn(f,b,T,x){let M=f.indexOf(b,T);if(M===-1)throw new Error(x);return M+b.length-1}i(cn,"findClosingIndex"),n(cn,"findClosingIndex");function Sn(f,b,T,x=">"){let M=$(f,b+1,x);if(!M)return;let k=M.data,Y=M.index,Z=k.search(/\s/),U=k,Re=!0;Z!==-1&&(U=k.substring(0,Z),k=k.substring(Z+1).trimStart());let Pe=U;if(T){let Ue=U.indexOf(":");Ue!==-1&&(U=U.substr(Ue+1),Re=U!==M.data.substr(Ue+1))}return{tagName:U,tagExp:k,closeIndex:Y,attrExpPresent:Re,rawTagName:Pe}}i(Sn,"readTagExp"),n(Sn,"readTagExp");function co(f,b,T){let x=T,M=1;for(;T<f.length;T++)if(f[T]==="<")if(f[T+1]==="/"){let k=cn(f,">",T,`${b} is not closed`);if(f.substring(T+2,k).trim()===b&&(M--,M===0))return{tagContent:f.substring(x,T),i:k};T=k}else if(f[T+1]==="?")T=cn(f,"?>",T+1,"StopNode is not closed.");else if(f.substr(T+1,3)==="!--")T=cn(f,"-->",T+3,"StopNode is not closed.");else if(f.substr(T+1,2)==="![")T=cn(f,"]]>",T,"StopNode is not closed.")-2;else{let k=Sn(f,T,">");k&&((k&&k.tagName)===b&&k.tagExp[k.tagExp.length-1]!=="/"&&M++,T=k.closeIndex)}}i(co,"readStopNodeData"),n(co,"readStopNodeData");function Hn(f,b,T){if(b&&typeof f=="string"){let x=f.trim();return x==="true"?!0:x==="false"?!1:bt(f,T)}else return l(f)?f:""}i(Hn,"parseValue"),n(Hn,"parseValue");function xo(f,b,T){let x=Number.parseInt(f,b);return x>=0&&x<=1114111?String.fromCodePoint(x):T+f+";"}i(xo,"fromCodePoint"),n(xo,"fromCodePoint");function On(f,b,T,x){if(f){let M=f(b);T===b&&(T=M),b=M}return b=_o(b,x),{tagName:b,tagExp:T}}i(On,"transformTagName"),n(On,"transformTagName");function _o(f,b){if(p.includes(f))throw new Error(`[SECURITY] Invalid name: "${f}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(f)?b.onDangerousProperty(f):f}i(_o,"sanitizeName"),n(_o,"sanitizeName");var un=v.getMetaDataSymbol();function Oo(f,b){if(!f||typeof f!="object")return{};if(!b)return f;let T={};for(let x in f)if(x.startsWith(b)){let M=x.substring(b.length);T[M]=f[x]}else T[x]=f[x];return T}i(Oo,"stripAttributePrefix"),n(Oo,"stripAttributePrefix");function Mo(f,b,T){return Kn(f,b,T)}i(Mo,"prettify"),n(Mo,"prettify");function Kn(f,b,T){let x,M={};for(let k=0;k<f.length;k++){let Y=f[k],Z=hr(Y);if(Z!==void 0&&Z!==b.textNodeName){let U=Oo(Y[":@"]||{},b.attributeNamePrefix);T.push(Z,U)}if(Z===b.textNodeName)x===void 0?x=Y[Z]:x+=""+Y[Z];else{if(Z===void 0)continue;if(Y[Z]){let U=Kn(Y[Z],b,T),Re=uo(U,b);if(Y[":@"]?Lo(U,Y[":@"],T,b):Object.keys(U).length===1&&U[b.textNodeName]!==void 0&&!b.alwaysCreateTextNode?U=U[b.textNodeName]:Object.keys(U).length===0&&(b.alwaysCreateTextNode?U[b.textNodeName]="":U=""),Y[un]!==void 0&&typeof U=="object"&&U!==null&&(U[un]=Y[un]),M[Z]!==void 0&&Object.prototype.hasOwnProperty.call(M,Z))Array.isArray(M[Z])||(M[Z]=[M[Z]]),M[Z].push(U);else{let Pe=b.jPath?T.toString():T;b.isArray(Z,Pe,Re)?M[Z]=[U]:M[Z]=U}Z!==void 0&&Z!==b.textNodeName&&T.pop()}}}return typeof x=="string"?x.length>0&&(M[b.textNodeName]=x):x!==void 0&&(M[b.textNodeName]=x),M}i(Kn,"compress"),n(Kn,"compress");function hr(f){let b=Object.keys(f);for(let T=0;T<b.length;T++){let x=b[T];if(x!==":@")return x}}i(hr,"propName"),n(hr,"propName");function Lo(f,b,T,x){if(b){let M=Object.keys(b),k=M.length;for(let Y=0;Y<k;Y++){let Z=M[Y],U=Z.startsWith(x.attributeNamePrefix)?Z.substring(x.attributeNamePrefix.length):Z,Re=x.jPath?T.toString()+"."+U:T;x.isArray(Z,Re,!0,!0)?f[Z]=[b[Z]]:f[Z]=b[Z]}}}i(Lo,"assignAttributes"),n(Lo,"assignAttributes");function uo(f,b){let{textNodeName:T}=b,x=Object.keys(f).length;return!!(x===0||x===1&&(f[T]||typeof f[T]=="boolean"||f[T]===0))}i(uo,"isLeafTag"),n(uo,"isLeafTag");var fr={allowBooleanAttributes:!1,unpairedTags:[]};function No(f,b){b=Object.assign({},fr,b);let T=[],x=!1,M=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let k=0;k<f.length;k++)if(f[k]==="<"&&f[k+1]==="?"){if(k+=2,k=Ft(f,k),k.err)return k}else if(f[k]==="<"){let Y=k;if(k++,f[k]==="!"){k=qo(f,k);continue}else{let Z=!1;f[k]==="/"&&(Z=!0,k++);let U="";for(;k<f.length&&f[k]!==">"&&f[k]!==" "&&f[k]!==" "&&f[k]!==`
|
|
407
407
|
`&&f[k]!=="\r";k++)U+=f[k];if(U=U.trim(),U[U.length-1]==="/"&&(U=U.substring(0,U.length-1),k--),!Wr(U)){let Ue;return U.trim().length===0?Ue="Invalid space after '<'.":Ue="Tag '"+U+"' is an invalid name.",lt("InvalidTag",Ue,_t(f,k))}let Re=yr(f,k);if(Re===!1)return lt("InvalidAttr","Attributes for '"+U+"' have open quote.",_t(f,k));let Pe=Re.value;if(k=Re.index,Pe[Pe.length-1]==="/"){let Ue=k-Pe.length;Pe=Pe.substring(0,Pe.length-1);let ht=$o(Pe,b);if(ht===!0)x=!0;else return lt(ht.err.code,ht.err.msg,_t(f,Ue+ht.err.line))}else if(Z)if(Re.tagClosed){if(Pe.trim().length>0)return lt("InvalidTag","Closing tag '"+U+"' can't have attributes or invalid starting.",_t(f,Y));if(T.length===0)return lt("InvalidTag","Closing tag '"+U+"' has not been opened.",_t(f,Y));{let Ue=T.pop();if(U!==Ue.tagName){let ht=_t(f,Ue.tagStartPos);return lt("InvalidTag","Expected closing tag '"+Ue.tagName+"' (opened in line "+ht.line+", col "+ht.col+") instead of closing tag '"+U+"'.",_t(f,Y))}T.length==0&&(M=!0)}}else return lt("InvalidTag","Closing tag '"+U+"' doesn't have proper closing.",_t(f,k));else{let Ue=$o(Pe,b);if(Ue!==!0)return lt(Ue.err.code,Ue.err.msg,_t(f,k-Pe.length+Ue.err.line));if(M===!0)return lt("InvalidXml","Multiple possible root nodes found.",_t(f,k));b.unpairedTags.indexOf(U)!==-1||T.push({tagName:U,tagStartPos:Y}),x=!0}for(k++;k<f.length;k++)if(f[k]==="<")if(f[k+1]==="!"){k++,k=qo(f,k);continue}else if(f[k+1]==="?"){if(k=Ft(f,++k),k.err)return k}else break;else if(f[k]==="&"){let Ue=Rr(f,k);if(Ue==-1)return lt("InvalidChar","char '&' is not expected.",_t(f,k));k=Ue}else if(M===!0&&!lo(f[k]))return lt("InvalidXml","Extra text at the end",_t(f,k));f[k]==="<"&&k--}}else{if(lo(f[k]))continue;return lt("InvalidChar","char '"+f[k]+"' is not expected.",_t(f,k))}if(x){if(T.length==1)return lt("InvalidTag","Unclosed tag '"+T[0].tagName+"'.",_t(f,T[0].tagStartPos));if(T.length>0)return lt("InvalidXml","Invalid '"+JSON.stringify(T.map(k=>k.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return lt("InvalidXml","Start tag expected.",1);return!0}i(No,"validate"),n(No,"validate");function lo(f){return f===" "||f===" "||f===`
|
|
408
408
|
`||f==="\r"}i(lo,"isWhiteSpace"),n(lo,"isWhiteSpace");function Ft(f,b){let T=b;for(;b<f.length;b++)if(f[b]=="?"||f[b]==" "){let x=f.substr(T,b-T);if(b>5&&x==="xml")return lt("InvalidXml","XML declaration allowed only at the start of the document.",_t(f,b));if(f[b]=="?"&&f[b+1]==">"){b++;break}else continue}return b}i(Ft,"readPI"),n(Ft,"readPI");function qo(f,b){if(f.length>b+5&&f[b+1]==="-"&&f[b+2]==="-"){for(b+=3;b<f.length;b++)if(f[b]==="-"&&f[b+1]==="-"&&f[b+2]===">"){b+=2;break}}else if(f.length>b+8&&f[b+1]==="D"&&f[b+2]==="O"&&f[b+3]==="C"&&f[b+4]==="T"&&f[b+5]==="Y"&&f[b+6]==="P"&&f[b+7]==="E"){let T=1;for(b+=8;b<f.length;b++)if(f[b]==="<")T++;else if(f[b]===">"&&(T--,T===0))break}else if(f.length>b+9&&f[b+1]==="["&&f[b+2]==="C"&&f[b+3]==="D"&&f[b+4]==="A"&&f[b+5]==="T"&&f[b+6]==="A"&&f[b+7]==="["){for(b+=8;b<f.length;b++)if(f[b]==="]"&&f[b+1]==="]"&&f[b+2]===">"){b+=2;break}}return b}i(qo,"readCommentAndCDATA"),n(qo,"readCommentAndCDATA");var ns='"',gr="'";function yr(f,b){let T="",x="",M=!1;for(;b<f.length;b++){if(f[b]===ns||f[b]===gr)x===""?x=f[b]:x!==f[b]||(x="");else if(f[b]===">"&&x===""){M=!0;break}T+=f[b]}return x!==""?!1:{value:T,index:b,tagClosed:M}}i(yr,"readAttributeStr"),n(yr,"readAttributeStr");var Kr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function $o(f,b){let T=c(f,Kr),x={};for(let M=0;M<T.length;M++){if(T[M][1].length===0)return lt("InvalidAttr","Attribute '"+T[M][2]+"' has no space in starting.",wn(T[M]));if(T[M][3]!==void 0&&T[M][4]===void 0)return lt("InvalidAttr","Attribute '"+T[M][2]+"' is without value.",wn(T[M]));if(T[M][3]===void 0&&!b.allowBooleanAttributes)return lt("InvalidAttr","boolean attribute '"+T[M][2]+"' is not allowed.",wn(T[M]));let k=T[M][2];if(!Sr(k))return lt("InvalidAttr","Attribute '"+k+"' is an invalid name.",wn(T[M]));if(!Object.prototype.hasOwnProperty.call(x,k))x[k]=1;else return lt("InvalidAttr","Attribute '"+k+"' is repeated.",wn(T[M]))}return!0}i($o,"validateAttributeString"),n($o,"validateAttributeString");function br(f,b){let T=/\d/;for(f[b]==="x"&&(b++,T=/[\da-fA-F]/);b<f.length;b++){if(f[b]===";")return b;if(!f[b].match(T))break}return-1}i(br,"validateNumberAmpersand"),n(br,"validateNumberAmpersand");function Rr(f,b){if(b++,f[b]===";")return-1;if(f[b]==="#")return b++,br(f,b);let T=0;for(;b<f.length;b++,T++)if(!(f[b].match(/\w/)&&T<20)){if(f[b]===";")break;return-1}return b}i(Rr,"validateAmpersand"),n(Rr,"validateAmpersand");function lt(f,b,T){return{err:{code:f,msg:b,line:T.line||T,col:T.col}}}i(lt,"getErrorObject"),n(lt,"getErrorObject");function Sr(f){return u(f)}i(Sr,"validateAttrName"),n(Sr,"validateAttrName");function Wr(f){return u(f)}i(Wr,"validateTagName"),n(Wr,"validateTagName");function _t(f,b){let T=f.substring(0,b).split(/\r?\n/);return{line:T.length,col:T[T.length-1].length+1}}i(_t,"getLineNumberForPosition"),n(_t,"getLineNumberForPosition");function wn(f){return f.startIndex+f[1].length}i(wn,"getPositionFromMatch"),n(wn,"getPositionFromMatch");var Yr=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(f){this.externalEntities={},this.options=R(f)}parse(f,b){if(typeof f!="string"&&f.toString)f=f.toString();else if(typeof f!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(b){b===!0&&(b={});let M=No(f,b);if(M!==!0)throw Error(`${M.err.msg}:${M.err.line}:${M.err.col}`)}let T=new be(this.options);T.addExternalEntities(this.externalEntities);let x=T.parseXml(f);return this.options.preserveOrder||x===void 0?x:Mo(x,this.options,T.matcher)}addEntity(f,b){if(b.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(f.indexOf("&")!==-1||f.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(b==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[f]=b}static getMetaDataSymbol(){return v.getMetaDataSymbol()}};return new Yr(t)},"getXmlParser");var Hw=class extends zo{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){super(e,n),Ze(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?fo(e.parseOnStatusCodes):void 0,this.parser=_L({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0,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 j(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 Fw=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new je(`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 Gw=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){ue("utility.get-consumer");let n=hi(),o=this.bucketId??Qe.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new I("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 I(`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 I("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 Cf(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 OL=10,ML=3e4,Dl=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#r=ML,this.#n=OL}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:ML,this.#n=OL}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let n=this.#i[e];return!(n===void 0||n===0)}#c(e){let n=this.#e.get(e);if(n&&!this.#s(n))return n.data}async get(e){let n=this.#c(e);if(n)return this.#u(e),n;if(this.#a(e))try{await J4(()=>this.#c(e)!==void 0||!this.#a(e),this.#r+this.#n+1,this.#n);let o=this.#c(e);if(o)return o}catch{}return this.#l(e)}#u(e){if(!this.#a(e)){let n=this.#l(e);Pr().waitUntil(n)}}async#l(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let n=await Promise.race([this.#t(e),scheduler.wait(this.#r)]);if(n===void 0)throw new I(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#i[e]--}}};async function J4(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new I(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(J4,"waitUntilTrue");import{SpanStatusCode as NL,trace as K4}from"@opentelemetry/api";var LL,qL=i(()=>(LL??=K4.getTracer("pipeline"),LL),"tracer"),$L=i(async(t,e,n)=>{let o=it.instance.routeData.policies,r=Ss([t],o);if(r.length===0)throw new j(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0];return await qL().startActiveSpan(`policy:${s.policyName}`,async c=>{try{Rs(c,s);let u=await s.handler(e,n);if(u instanceof Request||u instanceof He||u instanceof Response)return u instanceof Response||u instanceof He?u:new He(u);{let l=new I(`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.`);throw c.setStatus({code:NL.ERROR}),c.recordException(l),l}}finally{c.end()}})},"invokeInboundPolicy"),DL=i(async(t,e,n,o)=>{let r=it.instance.routeData.policies,s=Rc([t],r);if(s.length===0)throw new j(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await qL().startActiveSpan(`policy:${a.policyName}`,async u=>{try{Rs(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;{let d=new I(`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.`);throw u.setStatus({code:NL.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeOutboundPolicy");var W4="127.0.0.1";function zL(t){let e=O.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?W4:void 0)}i(zL,"resolveClientIp");function Y4(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[_d]=o.asnum),o.zip&&(e[Od]=o.zip.split("+")[0]),o.dma&&(e[Md]=o.dma),o.region_code&&(e[Ld]=o.region_code),o.timezone&&(e[Nd]=o.timezone),o.city&&(e[Pd]=o.city),o.continent&&(e[Ad]=o.continent),o.country_code&&(e[Ed]=o.country_code),o.long&&(e[kd]=o.long),o.lat&&(e[xd]=o.lat),e}catch{return{}}}i(Y4,"parseEdgeScapeHeader");function UL(t,e){let n=Y4(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(UL,"setZpHeadersFromAkamaiEdgeScapeHeader");var Ap=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(wC);if(n){let o=new Headers(e);UL(o,n),this.#e=o}}get ip(){return zL(this.#e)}get asn(){try{let e=this.#e.get(_d);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(gC)??void 0}get city(){return this.#e.get(Yw)??this.#e.get(Pd)??void 0}get continent(){return this.#e.get(Qw)??this.#e.get(Ad)??void 0}get country(){return this.#e.get(Xw)??this.#e.get(Ed)??void 0}get latitude(){return this.#e.get(tC)??this.#e.get(xd)??void 0}get longitude(){return this.#e.get(eC)??this.#e.get(kd)??void 0}get colo(){return this.#e.get(yC)??void 0}get postalCode(){return this.#e.get(iC)??this.#e.get(Od)??void 0}get metroCode(){return this.#e.get(rC)??this.#e.get(Md)??void 0}get region(){return this.#e.get(nC)??this.#e.get(bC)??void 0}get regionCode(){return this.#e.get(oC)??this.#e.get(Ld)??void 0}get timezone(){return this.#e.get(sC)??this.#e.get(Nd)??void 0}get httpProtocol(){return this.#e.get(RC)??void 0}get clientCert(){return this.#e.get(cC)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(uC)??void 0}get clientMtlsVerificationReason(){return this.#e.get(lC)??void 0}get clientCertFingerprintSha256(){return this.#e.get(dC)??void 0}get clientCertNotBefore(){return this.#e.get(pC)??void 0}get clientCertNotAfter(){return this.#e.get(mC)??void 0}get clientCertIssuerDn(){return this.#e.get(hC)??void 0}get clientCertSubjectDn(){return this.#e.get(fC)??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 Ea(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(Ea,"createRewriteContext");var fc=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},gc=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},St=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let o=new t(n);return t.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new j(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;auditLogEventId="";#t;#o;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#o=[],this.#n=[]}addResponseSendingHook(e){this.#o.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#n.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#t)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=O.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#o)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#n)await r(e,n,o)},"onHandlerResponse")},Ep=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)=>$L(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>DL(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 He(d,l);return it.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{St.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{St.getContextExtensions(this).addResponseSendingFinalHook(u)},this.analyticsContext=new AC(o),Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,o){ue("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");super.addEventListener(e,r,o)}removeEventListener(e,n,o){ue("context.removeEventListener"),super.removeEventListener(e,n,o)}};export{yf as a,Fn as b,Rt as c,Rf as d,eN as e,bf as f,pt as g,Do as h,tN as i,ri as j,Sf as k,ue as l,Cf as m,If as n,Mn as o,Er as p,uc as q,ii as r,q as s,Ot as t,si as u,Pf as v,Af as w,Hd as x,Ge as y,kn as z,xr as A,me as B,zo as C,Lf as D,zf as E,PN as F,hs as G,fc as H,gc as I,wg as J,Zt as K,UT as L,FT as M,fz as N,KT as O,Zg as P,Iz as Q,vi as R,zc as S,Ii as T,Gs as U,Jo as V,Ko as W,zr as X,Ti as Y,Vo as Z,Pt as _,pm as $,Bs as aa,Zs as ba,jc as ca,Hc as da,Vs as ea,en as fa,Ur as ga,At as ha,fn as ia,rn as ja,Js as ka,Et as la,Wo as ma,Ks as na,Ws as oa,Pi as pa,Ai as qa,Ei as ra,mm as sa,Ys as ta,Fc as ua,Qs as va,Gc as wa,Yo as xa,Ro as ya,to as za,hm as Aa,fm as Ba,Bc as Ca,Zc as Da,Xs as Ea,ea as Fa,Vc as Ga,Jc as Ha,Kc as Ia,Wc as Ja,ta as Ka,Yc as La,Qc as Ma,na as Na,Xc as Oa,Qo as Pa,Xo as Qa,oa as Ra,ra as Sa,ia as Ta,er as Ua,So as Va,sa as Wa,eu as Xa,tu as Ya,nu as Za,ou as _a,ru as $a,ki as ab,iu as bb,su as cb,au as db,cu as eb,uu as fb,lu as gb,du as hb,pu as ib,aa as jb,mu as kb,hu as lb,fu as mb,gu as nb,yu as ob,bu as pb,Ru as qb,Su as rb,wu as sb,Cu as tb,vu as ub,Iu as vb,Tu as wb,Pu as xb,tr as yb,nr as zb,or as Ab,Au as Bb,xi as Cb,_i as Db,Oi as Eb,Eu as Fb,ku as Gb,xu as Hb,_u as Ib,Ou as Jb,ca as Kb,Mu as Lb,Lu as Mb,ua as Nb,gm as Ob,Nu as Pb,qu as Qb,$u as Rb,Kg as Sb,rr as Tb,Du as Ub,zu as Vb,Uu as Wb,ju as Xb,Hu as Yb,Fu as Zb,Gu as _b,Bu as $b,Zu as ac,Dr as bc,Vu as cc,Ju as dc,Ku as ec,Wu as fc,Yu as gc,la as hc,Mi as ic,Li as jc,da as kc,pa as lc,ma as mc,Qu as nc,ha as oc,fa as pc,Xu as qc,el as rc,ga as sc,Ni as tc,tl as uc,nl as vc,ol as wc,rl as xc,il as yc,sl as zc,al as Ac,cl as Bc,ul as Cc,ll as Dc,dl as Ec,pl as Fc,ml as Gc,hl as Hc,fl as Ic,ym as Jc,gl as Kc,ir as Lc,bm as Mc,yl as Nc,Rm as Oc,Sm as Pc,wm as Qc,Cm as Rc,vm as Sc,Im as Tc,Tm as Uc,Pm as Vc,Am as Wc,Em as Xc,km as Yc,xm as Zc,_m as _c,Om as $c,Mm as ad,Lm as bd,bl as cd,Rl as dd,Nm as ed,qm as fd,$m as gd,Dm as hd,Sl as id,wl as jd,zm as kd,Um as ld,jm as md,kA as nd,xA as od,_A as pd,OA as qd,MA as rd,LA as sd,Ly as td,E1 as ud,Ny as vd,$y as wd,zy as xd,Hy as yd,Gy as zd,Zy as Ad,Jy as Bd,Wy as Cd,Xy as Dd,nb as Ed,ib as Fd,cb as Gd,lb as Hd,db as Id,Ll as Jd,Nl as Kd,ql as Ld,gb as Md,zl as Nd,Rb as Od,Sb as Pd,uH as Qd,wb as Rd,Cb as Sd,YA as Td,QA as Ud,eE as Vd,xb as Wd,_b as Xd,HE as Yd,mR as Zd,fR as _d,yR as $d,rk as ae,ak as be,ck as ce,Ik as de,Gk as ee,Bk as fe,Zk as ge,Vk as he,Qk as ie,Xk as je,xR as ke,nx as le,Ah as me,OG as ne,_R as oe,yn as pe,dx as qe,qR as re,$R as se,mx as te,UR as ue,fx as ve,Ix as we,Tx as xe,Px as ye,Ax as ze,Ex as Ae,kx as Be,Nx as Ce,Dx as De,KR as Ee,jx as Fe,Hx as Ge,Fx as He,Gx as Ie,Bx as Je,Zx as Ke,Vx as Le,Qx as Me,n_ as Ne,o_ as Oe,Dh as Pe,GB as Qe,a_ as Re,u_ as Se,sS as Te,R_ as Ue,Vr as Ve,Ga as We,ct as Xe,Ct as Ye,To as Ze,HTe as _e,rd as $e,ZTe as af,VTe as bf,Un as cf,WTe as df,YTe as ef,QTe as ff,XTe as gf,id as hf,ePe as if,Wi as jf,iPe as kf,Fh as lf,Yi as mf,Za as nf,uS as of,yPe as pf,lS as qf,dS as rf,pS as sf,mS as tf,hS as uf,fS as vf,gS as wf,yS as xf,bS as yf,RS as zf,SS as Af,yEe as Bf,Vn as Cf,jn as Df,Lt as Ef,mO as Ff,s2 as Gf,a2 as Hf,wS as If,LEe as Jf,NEe as Kf,qEe as Lf,AO as Mf,EO as Nf,ske as Of,ake as Pf,CS as Qf,ad as Rf,Kh as Sf,cke as Tf,_O as Uf,pke as Vf,cd as Wf,k2 as Xf,x2 as Yf,IS as Zf,wke as _f,NO as $f,qO as ag,Tke as bg,Pke as cg,Ake as dg,Eke as eg,$O as fg,DO as gg,UO as hg,Po as ig,mr as jg,M2 as kg,L2 as lg,qke as mg,$ke as ng,Dke as og,zke as pg,Ao as qg,D2 as rg,Yke as sg,FO as tg,axe as ug,ES as vg,U2 as wg,J2 as xg,W2 as yg,ZO as zg,Cxe as Ag,vxe as Bg,Ixe as Cg,WO as Dg,Exe as Eg,kxe as Fg,xxe as Gg,LS as Hg,Xh as Ig,NS as Jg,XO as Kg,zxe as Lg,Uxe as Mg,jxe as Ng,Hxe as Og,K0 as Pg,Jn as Qg,YS as Rg,S_e as Sg,W0 as Tg,w_e as Ug,tw as Vg,nw as Wg,tM as Xg,LJ as Yg,sM as Zg,cw as _g,gM as $g,lw as ah,TM as bh,dw as ch,mw as dh,AM as eh,EM as fh,kM as gh,gw as hh,bw as ih,qM as jh,$M as kh,DM as lh,zM as mh,UM as nh,HM as oh,ww as ph,t4 as qh,VM as rh,Tw as sh,XM as th,eL as uh,tL as vh,h4 as wh,nL as xh,oL as yh,rL as zh,iL as Ah,sL as Bh,kw as Ch,cL as Dh,uL as Eh,xw as Fh,_w as Gh,pL as Hh,hL as Ih,fL as Jh,Lw as Kh,yL as Lh,vL as Mh,zw as Nh,Uw as Oh,IL as Ph,xL as Qh,Hw as Rh,Fw as Sh,Gw as Th,Dl as Uh};
|
|
409
|
-
/*! For license information please see chunk-
|
|
410
|
-
//# sourceMappingURL=chunk-
|
|
409
|
+
/*! For license information please see chunk-ZZCZZHOD.js.LEGAL.txt */
|
|
410
|
+
//# sourceMappingURL=chunk-ZZCZZHOD.js.map
|