@zuplo/cli 6.73.18 → 6.73.20
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/node_modules/@zuplo/core/customer.cli.minified.js +26 -26
- package/node_modules/@zuplo/core/index.minified.js +33 -33
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/{chunk-JPPAUB3E.js → chunk-DBFG5V2I.js} +3 -3
- package/node_modules/@zuplo/runtime/out/esm/chunk-DBFG5V2I.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/package.json +6 -6
- package/node_modules/@zuplo/runtime/out/esm/chunk-JPPAUB3E.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-JPPAUB3E.js.LEGAL.txt → chunk-DBFG5V2I.js.LEGAL.txt} +0 -0
|
@@ -239,7 +239,7 @@ spurious results.`)}}return!1},"instanceOf");var Xo=class{static{s(this,"Source"
|
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
|
-
`}s(Vc,"getIntrospectionQuery");var dx=2,sN=1,aN=0,cN=0,Ap=4294967295,uN=["first","last","limit","pageSize","take"],lN=new Set(["__typename","__schema","__type"]);function px(t,e={}){let n=new Map,o,r;for(let c of t.definitions)c.kind===le.FRAGMENT_DEFINITION?n.set(c.name.value,c):c.kind===le.OPERATION_DEFINITION&&(o??=c,e.operationName&&c.name?.value===e.operationName&&(r=c));let i=r??o;if(!i)return 0;let a={fragments:n,variables:e.variables??{},multiplierNames:new Set(e.multipliers??uN),expanding:new Set};return mx(Jc(i.selectionSet,dx,a))}s(px,"computeComplexity");function Jc(t,e,n){let o=e,r=0;for(let i of t.selections)if(!fN(i.directives,n.variables))switch(i.kind){case le.FIELD:{o+=dN(i,n);break}case le.FRAGMENT_SPREAD:{let a=i.name.value,c=n.fragments.get(a);if(!c||n.expanding.has(a))break;n.expanding.add(a),o+=Jc(c.selectionSet,cN,n),n.expanding.delete(a);break}case le.INLINE_FRAGMENT:{let a=Jc(i.selectionSet,aN,n);a>r&&(r=a);break}}return o+r}s(Jc,"selectionSetCost");function dN(t,e){if(lN.has(t.name.value))return 0;let n=t.selectionSet?Jc(t.selectionSet,dx,e):sN,o=pN(t.arguments,e);return o!==null&&(n=mx(n*o)),n}s(dN,"fieldCost");function pN(t,e){if(!t||t.length===0)return null;let n=null;for(let o of t){if(!e.multiplierNames.has(o.name.value))continue;let r=mN(o.value,e.variables);(n===null||r>n)&&(n=r)}return n}s(pN,"resolveMultiplier");function mN(t,e){if(t.kind===le.INT)return ux(Number.parseInt(t.value,10));if(t.kind===le.VARIABLE){let n=e[t.name.value];return typeof n!="number"||!Number.isInteger(n)?1:ux(n)}return 0}s(mN,"resolveMultiplierValue");function ux(t){if(!Number.isFinite(t))return 1;let e=Math.abs(t);return e>Ap?1:e}s(ux,"normalizeMultiplier");function fN(t,e){if(!t||t.length===0)return!1;for(let n of t){let o=n.name.value;if(o==="skip"){if(lx(n,e)===!0)return!0}else if(o==="include"&&lx(n,e)===!1)return!0}return!1}s(fN,"isExcludedByDirective");function lx(t,e){let n=t.arguments?.find(r=>r.name.value==="if");if(!n)return;let o=n.value;if(o.kind===le.BOOLEAN)return o.value;if(o.kind===le.VARIABLE){let r=e[o.name.value];return typeof r=="boolean"?r:void 0}}s(lx,"resolveIfArgument");function mx(t){return Number.isNaN(t)||t<=0?0:t>Ap?Ap:Math.trunc(t)}s(mx,"clampU32");var fx=4*1024,gN="0".repeat(64);async function hx(t,e,n){let o=gx(t,fx),r;try{r=Fc(t)}catch(g){return{ast:null,documentHash:gN,documentSnippet:o,operationType:"",operationName:"",maxDepth:0,complexity:null,syntaxError:g instanceof ir?g:new ir(g instanceof Error?g.message:String(g))}}let i=yN(r),a=Bc(i),c=await vN(a),{operationType:u,operationName:d}=bN(i,e),p=wN(i),m=px(r,{operationName:e,variables:n});return{ast:r,documentHash:c,documentSnippet:gx(a,fx),operationType:u,operationName:d,maxDepth:p,complexity:m,syntaxError:null}}s(hx,"analyzeDocument");var hN="?";function yN(t){let e=s(()=>({kind:le.STRING,value:hN}),"toPlaceholder");return ro(t,{IntValue:e,FloatValue:e,StringValue:e,BooleanValue:e,EnumValue:e})}s(yN,"scrubLiterals");function bN(t,e){let n=null;for(let o of t.definitions){if(o.kind!==le.OPERATION_DEFINITION)continue;let r=o.name?.value??"";if(n===null&&(n={operationType:o.operation,operationName:r}),e&&r===e)return{operationType:o.operation,operationName:r}}return n??{operationType:"",operationName:""}}s(bN,"selectOperation");function wN(t){let e=0,n=0;return ro(t,{SelectionSet:{enter(){n+=1,n>e&&(e=n)},leave(){n-=1}}}),e}s(wN,"computeMaxDepth");async function vN(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e),o=new Uint8Array(n),r="";for(let i of o)r+=i.toString(16).padStart(2,"0");return r}s(vN,"sha256Hex");function gx(t,e){let n=new TextEncoder().encode(t);if(n.byteLength<=e)return t;let o=e;for(;o>0&&(n[o]&192)===128;)o--;return new TextDecoder("utf-8").decode(n.subarray(0,o))}s(gx,"truncate");function oo(t,e,n){try{t.log?.debug?.({event:e,errorName:n instanceof Error?n.name:"unknown"},"graphql analytics internal error")}catch{}}s(oo,"safeLog");function yx(t){if(!t)return"unknown";let e=t.toLowerCase();return e.includes("apollo-ios")||e.includes("apollo-kotlin")||e.includes("apollo-android")||e.includes("ios")||e.includes("android")||e.includes("react-native")||e.includes("expo")?"mobile":e.includes("apollo-client")||e.includes("apollo-web")||e.includes("urql")||e.includes("relay")||e.includes("browser")||e.includes("web")?"browser":e.includes("apollo-server")||e.includes("server")||e.includes("node")||e.includes("service")||e.includes("worker")?"service":"unknown"}s(yx,"deriveClientKind");var RN="apollographql-client-name",SN="apollographql-client-version",IN="x-graphql-document-id";function bx(t){let{context:e,operation:n,request:o,httpStatusCode:r,totalLatencyMs:i}=t;try{let a=CN(o),c=o.headers.get(RN),u=o.headers.get(SN),d=n.errors.count,p=n.errors.classes(),m=d===0?"success":"failure",g=n.persistedQueryHash??o.headers.get(IN),h={operationType:n.operationType,operationName:n.operationName,documentHash:n.documentHash??"",documentSnippet:n.documentSnippet??"",persistedQueryHash:g??null,maxDepth:n.maxDepth,complexity:n.complexity,routePath:xN(e),clientName:c??null,clientKind:yx(c),clientVersion:u??null,subjectId:a.subjectId,tenantId:a.tenantId,apiKeySub:a.apiKeySub,authProfileId:a.authProfileId,httpStatusCode:r,totalLatencyMs:i,outcome:m,errorCount:d,errorClasses:p,cacheState:n.cacheState};e.analyticsContext.addAnalyticsEvent(1,Q.GRAPHQL_OPERATION,h)}catch(a){oo(e,"graphql_analytics_operation_emit_failed",a)}}s(bx,"emitGraphqlOperationEvent");function xN(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}s(xN,"readRoutePath");function CN(t){let e=t.user,n=e?.sub??null,o=e?.apiKeyId??null,r=e?.data??{};return{subjectId:typeof n=="string"?n:null,tenantId:typeof r.tenantId=="string"?r.tenantId:typeof r.tenant_id=="string"?r.tenant_id:null,apiKeySub:typeof o=="string"?o:null,authProfileId:null}}s(CN,"readSubject");var TN=1*1024*1024;function PN(t){if(typeof t.raw!="function")return!1;try{return t.raw()?.["x-graphql"]===!0}catch{return!1}}s(PN,"isGraphqlRoute");var kp=s(async(t,e,n)=>{let o=mI();if(fI(e,o),t.method==="GET")try{await EN(t,o)}catch(a){oo(e,"graphql_analytics_url_analysis_failed",a)}let r=AN(t)?t.clone():null,i;try{i=await n(t)}catch(a){o.errors.record("resolver"),i=await bn(t,e,"GraphQL analytics: downstream processor threw past handler error wrapping.",a)}if(r)try{await kN(r,o)}catch(a){oo(e,"graphql_analytics_body_analysis_failed",a)}return _N(e,o,i.status),i},"graphqlAnalyticsProcessor");kp.shouldApply=t=>PN(t);function AN(t){if(!t.body||t.method==="GET")return!1;let e=(t.headers.get("content-type")??"").toLowerCase();if(!e.startsWith("application/json")&&!e.includes("+json"))return!1;let n=t.headers.get("content-length");if(n!==null){let o=Number(n);if(!Number.isFinite(o)||o<0||o>TN)return!1}return!0}s(AN,"hasReadableJsonBody");async function kN(t,e){let n;try{n=await t.text()}catch{return}let o;try{o=JSON.parse(n)}catch{return}let r=o,i=typeof r.operationName=="string"?r.operationName:null,a=r.extensions?.persistedQuery?.sha256Hash,c=typeof r.query=="string"?r.query:null;await vx(e,{query:c,operationName:i,persistedHash:typeof a=="string"?a:null,variables:wx(r.variables)})}s(kN,"analyzeRequestBody");async function EN(t,e){let n;try{n=new URL(t.url)}catch{return}let o=n.searchParams,r=o.get("query"),i=o.get("operationName"),a=null,c=o.get("extensions");if(c)try{let m=JSON.parse(c).persistedQuery?.sha256Hash;typeof m=="string"&&(a=m)}catch{}let u=null,d=o.get("variables");if(d)try{u=wx(JSON.parse(d))}catch{}await vx(e,{query:r,operationName:i,persistedHash:a,variables:u})}s(EN,"analyzeUrlParams");function wx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}s(wx,"asVariables");async function vx(t,e){if(e.persistedHash&&(t.persistedQueryHash=e.persistedHash),e.operationName&&e.operationName.length>0&&(t.operationName=e.operationName),!e.query||e.query.length===0){e.persistedHash&&(t.documentHash="",t.documentSnippet="");return}try{let n=await hx(e.query,e.operationName??void 0,e.variables??void 0);t.documentHash=n.documentHash,t.documentSnippet=n.documentSnippet,t.operationType=n.operationType,t.operationName=e.operationName&&e.operationName.length>0?e.operationName:n.operationName,t.maxDepth=n.maxDepth,t.complexity=n.complexity,n.syntaxError&&t.errors.record("syntax")}catch{t.errors.record("syntax")}}s(vx,"populateFromGraphqlInputs");function _N(t,e,n){let o=s(a=>{e.errors.classes().includes(a)||e.errors.record(a)},"recordIfNew");if(n!==null){let a=pI(n);a&&o(a)}let r=it.getContextExtensions(t).latestRequest,i=performance.now()-e.startTimeMs;bx({context:t,operation:e,request:r,httpStatusCode:n,totalLatencyMs:i})}s(_N,"finalizeAndEmit");var ws=class{static{s(this,"PluginRouteConfiguration")}constructor({path:e,methods:n,corsPolicy:o="none"}){this.path=e,this.methods=n,this.corsPolicy=o,this.handler={export:Zo,module:Zo}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var Ep=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,n,o){this.fullPath=e,this.config=n,this.executableHandler=o;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(r){throw new Pe(`Invalid path '${e}'. ${r.message}`)}}urlPattern;fullPath;config;executableHandler},Kc=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,n){if(!(e instanceof Ar||e instanceof yt||e instanceof ws))throw new Pe("Config must be a valid RouteConfiguration type: UserRouteConfiguration, SystemRouteConfiguration, or PluginRouteConfiguration");let o;"pathPattern"in e&&e.pathPattern?o=e.pathPattern:o=e.path;try{let r=new Ep(o,e,n);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new wc(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}addPluginRoute(e){let n=new St({processors:e.processors??[],handler:e.handler}),o=new ws({methods:e.methods,path:e.path,corsPolicy:e.corsPolicy});this.addRoute(o,n.execute)}lookup(e,n){if(typeof n>"u")throw new I(`Invalid request - Method was undefined. Path: '${e}'`);for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o];if(r.config.methods.includes(n)){let i=r.urlPattern.exec({pathname:e});if(i!==null)return new jo(r.config,r.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let n=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],i=r.urlPattern.exec({pathname:e});if(i!==null){let a=new jo(r.config,r.executableHandler,i.pathname.groups);n.push(a)}}return n}};import{AsyncLocalStorage as ON}from"node:async_hooks";var sr={context:new ON};function io(){let t=sr.context.getStore()?.context;if(!t)throw new Error("No context found. This should not happen.");return t}s(io,"getCurrentContext");var _p;function Rx(t){_p=t}s(Rx,"setGlobalZuploEventContext");function _r(){if(_p===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return _p}s(_r,"getGlobalZuploEventContext");function Sx({headers:t,removeAllVendorHeadersExceptListed:e}){let n=new Headers(t);if(e){for(let[o]of t){let r=o.substring(0,3);$S.includes(r.toLowerCase())&&!MS.includes(o.toLowerCase())&&n.delete(o)}n.delete(cp)}else OS.forEach(o=>{n.delete(o)});return _S.forEach(o=>{n.delete(o)}),n}s(Sx,"normalizeIncomingRequestHeaders");var so=qe("zuplo:runtime"),vs=s(t=>(...e)=>{let n=sr.context.getStore();n&&n.context?.log[t](...e)},"consoleLogFn");console.log=vs("log");console.info=vs("info");console.debug=vs("debug");console.warn=vs("warn");console.error=vs("error");var je=class t{constructor(e,n,o,r){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=r;so("Gateway.constructor"),this.#r=this.setupRoutes(),this.#t=o}routeData;runtimeSettings;schemaValidator;static{s(this,"Gateway")}static#e;static async initialize(e,n,o,r){if(so("Gateway.initialize"),!t.#e){let i=await Uc.init(o),a=await e(),c={...a,corsPolicies:kI(a.corsPolicies),getInboundPolicyInstance:s(d=>_c(d,a.policies),"getInboundPolicyInstance")},u=new t(c,n,i,r);t.#e=u}if(!t.#e)throw new Pe("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){so("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new Pe("Gateway cannot be used before it is initialized");return t.#e}#t;#r;#n=[Oc,kp,Fo,Gt,GI];setupRoutes=s(()=>{so("Gateway.setupRoutes");let e=this.routeData,n=new Kc;if(e.routes.length===0)return up(n),mp(n),pp(n,this.runtimeSettings,this.routeData.corsPolicies),_I(n),n;let{enabled:o,type:r,basePath:i}=this.runtimeSettings.developerPortal;o&&r==="legacy"&&(FI(n,i),HI(n,i)),up(n),mp(n),pp(n,this.runtimeSettings,this.routeData.corsPolicies);for(let a of An)a instanceof mt&&a.registerRoutes({router:n,runtimeSettings:this.runtimeSettings,parsedRouteData:this.routeData});return e.routes.forEach(a=>{let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new I(`Invalid state - No handler on route for path '${a.path}'`);let u=this.#n.filter(m=>!m.shouldApply||m.shouldApply(a)),d=new St({processors:u,handler:c}),p=new Ar(a);n.addRoute(p,d.execute)}),OI(n),n},"setupRoutes");async handleRequest(e,n,o){let r=e.headers.get($o)??e.headers.get(nS)??o?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mo);Rx(n);let a=Sx({headers:e.headers,removeAllVendorHeadersExceptListed:T.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set($o,r);let c=new Request(e,{headers:a}),u=e.headers.get(iS)||e.headers.get(oS)||e.headers.get(sS);if(u){let A=e.url.replace(/^(http|https):\/\//,`${u}://`);c=new Request(A,c)}if(["GET","HEAD"].includes(c.method)&&c.body){let A=new Headers(c.headers);A.set(rS,"true"),c=new Request(c,{headers:A,body:null})}let d=e.headers.get(kS);if(d){let A=new URL(c.url),L=new URL(`local://${d}${A.pathname}${A.search}`);c=new Request(L.toString(),c)}c=await xI(c);let p=new URL(c.url),m=p.pathname,g=this.#r.lookup(m,c.method);if(!g){if(T.instance.build.COMPATIBILITY_FLAGS.return501ForUnsupportedHttpMethods){let A=$.getProblemFromStatus(501,{instance:m,trace:{timestamp:new Date().toISOString(),requestId:r,buildId:T.instance.build.BUILD_ID,...i?{rayId:i}:{}}});return new Response(JSON.stringify(A),{status:501,statusText:es[501],headers:{"content-type":"application/problem+json",[$o]:r}})}throw new Pe(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`)}let h={},{userRequestLogger:f,systemRequestLogger:v}=this.#t.createRequestLoggers(r,i,n,h,c,g.routeConfiguration);qo(p)||f.debug(`Request received '${p.pathname}'`,{method:c.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let b=new Wc(e.headers),w=new we(c,{params:g.params},e),S=new Yc({logger:f,route:g.routeConfiguration,requestId:r,event:n,custom:h,incomingRequestProperties:b,parentContext:o?.parentContext}),x=sr.context.getStore();x&&(x.context=S);let C=g.routeConfiguration.raw();$N.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Qt.RoutePathPattern]:S.route.pathPattern,[Qt.RouteOperationId]:C.operationId,[Qt.RouteTrace]:C["x-zuplo-trace"],[Qt.RouteSystem]:qo(p)?!0:void 0,"net.colo":b.colo,"net.country":b.country,"net.asn":b.asn}),it.initialize(S,w);try{if(H.addLogger(S,v),T.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!qo(p):!p.pathname.startsWith("/__zuplo")){let re=await RI(w,S);if(re instanceof Response)return re;{let V=it.getContextExtensions(S);w=re,V.latestRequest=w}}let A=g.executableHandler;MN(A,g,c),so("Gateway.handleRequest - call user handler");let L=await A(w,S);if(so("Gateway.handleRequest - user handler"),!(L instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof L}`);if(L.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let q;if(L.headers.get($o)===null&&!L.webSocket&&L.status!==101){let re=new Headers(L.headers);re.set($o,r),q=new Response(L.body,{status:L.status,statusText:L.statusText,headers:re,cf:L.cf})}else q=L;return q}catch(A){return A instanceof Z?(f.error(A),v.warn(A)):v.error(A),await bn(w,S,"Error executing handler",A)}}};function MN(t,e,n){if(so("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new I(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new I(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(MN,"checkHandler");Function.prototype.toString=function(){return"[native code]"};var Qc=globalThis,Ix=Qc.caches;if(Ix){let t=Ix.open;Qc.caches.open=function(e){let n=T.instance.deploymentName??T.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Qc.caches.default,Object.freeze(Qc.caches)}var LN="Error initializing gateway. Check your configuration for errors or contact support.",NN="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Op=class{constructor(e,n,o,r,i,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=i;this.runtimeInit=a}routeLoader;buildEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;static{s(this,"Handler")}requestHandler=s(async(e,n,o)=>{T.initialize({build:this.buildEnvironment,runtime:n});try{await CI(this.runtimeInit)}catch(i){return this.handleError(i,NN,e)}return wI(s(async(i,a)=>{let c;try{c=await je.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(d){return this.handleError(d,LN,i)}let u={context:void 0};return sr.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,o)},"requestHandler");handleError(e,n,o){D.console.error("Error initializing gateway.",e),e instanceof I&&(n=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:n,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:T.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};var $p=new ne(Symbol("ai-gateway-request-analytics"));function xx(t){let e=$p.get(t);return e||(e={cacheState:null,servedFromCache:!1,similarity:null,teamId:null,appId:null},$p.set(t,e)),e}s(xx,"getOrCreateEntry");function Zn(t,e,n){let o=xx(t);o.cacheState=e,n?.similarity!==void 0&&(o.similarity=n.similarity),n?.servedFromCache!==void 0&&(o.servedFromCache=n.servedFromCache)}s(Zn,"recordAiGatewayCacheState");function ar(t){if(!t||typeof t!="object")return{teamId:null,appId:null};let e=t,n=e.isApp===!0&&typeof e.id=="string"&&e.id!==""?e.id:null;return{teamId:typeof e.parentId=="string"&&e.parentId!==""?e.parentId:null,appId:n}}s(ar,"extractTeamAppAttribution");function ei(t,e){let{teamId:n,appId:o}=ar(e);if(n===null&&o===null)return;let r=xx(t);r.teamId=n,r.appId=o}s(ei,"recordAiGatewayAttribution");function ao(t){return $p.get(t)}s(ao,"getAiGatewayRequestAnalytics");var Lp=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??T.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,n){let o=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});Ve(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Pe(`Failed to fetch meters: ${i.status} ${i.statusText}`);return await i.json()}async checkHierarchicalQuotaLimits(e,n){let o=new URL(`/v1/hierarchical-quota/${e}/limits`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});Ve(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Pe(`Failed to check quota limits: ${i.status} ${i.statusText}`);return await i.json()}async incrementMeters(e,n,o){let r=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),i=new Headers({"Content-Type":"application/json"});Ve(i,o.requestId);let a=await fetch(r,{method:"POST",headers:i,body:JSON.stringify({increments:n})});if(!a.ok)throw new Pe(`Failed to increment meters: ${a.status} ${a.statusText}`)}async sendUsageEvent(e,n,o,r){let i=new URL(`/v3/metering/${e}/events`,this.baseUrl).toString(),a=new Headers({"Content-Type":"application/json"});Ve(a,o.requestId);let c;try{c=H.getLogger(o)}catch{}let u=await ct({retries:r?.retries??3,retryDelayMs:r?.retryDelayMs??500,logger:c,fetchFn:s((d,p)=>fetch(d,p),"fetchFn")},i,{method:"POST",headers:a,body:JSON.stringify(n)});if(!u.ok)throw new Pe(`Failed to send monetization v3 usage events: ${u.status} ${u.statusText}`)}},Mp=null,ti={get instance(){return Mp===null&&(Mp=new Lp),Mp}};var Cx=Pt.object({environmentVariable:Pt.string().min(1),model:Pt.string().min(1),provider:Pt.string().min(1)}),Tx=Pt.object({completions:Cx.optional(),embeddings:Cx.optional()});var Px=qe("zuplo:policies:AIGatewayMeteringInboundPolicy"),Ax=Symbol("ai-gateway-meter-increments"),kx=Symbol("ai-gateway-quota-fallback"),tt=class t extends ce{static{s(this,"AIGatewayMeteringInboundPolicy")}static policyType="ai-gateway-metering";static setIncrements(e,n){ne.set(e,Ax,n)}static getIncrements(e){return ne.get(e,Ax)??{}}static setQuotaFallback(e,n){ne.set(e,kx,n)}static getQuotaFallback(e){return ne.get(e,kx)}async handler(e,n){let o=Date.now(),r=H.getLogger(n),i=s((a,c)=>{if(this.options.throwOnFailure)throw new Pe(a,{cause:c});r.error(c,a)},"throwOrLog");try{let a=e.user,c=a?.configuration;if(!c)throw new I(`AIGatewayMeteringInboundPolicy '${this.policyName}' - No configuration found in request.user. Ensure ai-gateway-inbound policy runs first.`);let u=c;if(!u.id)throw new I(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Configuration ID not found.`);let d=a?.sub??null,p=await this.fetchCurrentMeters(u.id,n,r),m=this.checkWarnings(u,p);for(let h of m)n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_WARNING_COUNT,{type:`quota-${h.type}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_warning"});let g=await this.checkHierarchicalQuotaLimits(u.id,n,r);if(g.violation){let h=g.violation,f=this.requestCapability(e),v=this.resolveQuotaFallback(u,f,n,r);if(v){let b=f?u.models[f]?.[0]:void 0,w=f?v[f]:void 0,S=b?`${b.provider}/${b.model}`:"the primary model",x=w?`${w.provider}/${w.model}`:"the configured fallback model";t.setQuotaFallback(n,v),n.log.warn(`AI Gateway quota exceeded; falling back from ${S} to ${x} instead of blocking`,{configId:u.id,configLabel:h.configLabel,meter:h.meter,period:h.period,currentUsage:h.currentUsage,limit:h.limit,originalModel:b?.model,originalProvider:b?.provider,fallbackModel:w?.model,fallbackProvider:w?.provider}),n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_FALLBACK_COUNT,{type:`quota-${h.meter}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_fallback"})}else return n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_BLOCKED_COUNT,{type:`quota-${h.meter}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_exceeded"}),this.createHierarchicalQuotaExceededResponse(e,n,h)}return n.addResponseSendingFinalHook(async()=>{try{let h=t.getIncrements(n);Px(`AIGatewayMeteringInboundPolicy '${this.policyName}' - increments ${JSON.stringify(h)}`),Object.keys(h).length>0&&await t.incrementMetersInternal(u.id,h,n,r)}catch(h){i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to increment meters`,h)}}),e}catch(a){if(a instanceof I)throw a;return i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Error`,a),e}finally{let a=Date.now()-o;Px(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,n,o){try{return await ti.instance.fetchCurrentMeters(e,n)}catch(r){throw o.error(r,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to fetch meters`),r}}requestCapability(e){let n;try{n=new URL(e.url).pathname}catch{return}let o=s(r=>n===r||n.endsWith(r),"matchesBase");if(o("/v1/chat/completions")||o("/v1/messages"))return"completions";if(o("/v1/embeddings"))return"embeddings"}resolveQuotaFallback(e,n,o,r){if(n?Cr(o)?.byCapability[n]?.quotaFallback:void 0)return{};let a=e.quotaFallback;if(!a)return;let c=Tx.safeParse(a);if(!c.success){r.error(c.error,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Invalid quotaFallback configuration; blocking instead of falling back`);return}if(!(!n||!c.data[n]))return c.data}async checkHierarchicalQuotaLimits(e,n,o){try{return await ti.instance.checkHierarchicalQuotaLimits(e,n)}catch(r){throw o.error(r,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to check hierarchical quota limits`),r}}static async incrementMeters(e,n,o){let r=H.getLogger(o);return t.incrementMetersInternal(e,n,o,r)}static async incrementMetersInternal(e,n,o,r){try{await ti.instance.incrementMeters(e,n,o)}catch(i){throw r.error(i,"AIGatewayMeteringInboundPolicy - Failed to increment meters"),i}}checkWarnings(e,n){let o=[];for(let[r,i]of Object.entries(e.limits)){if(!i)continue;let a=n.meters[r];if(!a)continue;let c=this.checkQuotaWarning(i.daily,a.daily,r,"daily");c&&o.push(c);let u=this.checkQuotaWarning(i.monthly,a.monthly,r,"monthly");u&&o.push(u)}return o}checkQuotaWarning(e,n,o,r){if(!e?.warning?.enabled||!e?.warning?.threshold||!e?.limit)return null;let i=e.warning.threshold/100*e.limit;return n>=i?{type:o,period:r}:null}createHierarchicalQuotaExceededResponse(e,n,o){let r=`${o.period} ${o.meter} quota exceeded in configuration '${o.configLabel}'. Limit: ${o.limit}, Current: ${o.currentUsage}`;return $.tooManyRequests(e,n,{detail:r})}};var Lt=class extends Error{static{s(this,"UpstreamLlmError")}provider;status;constructor(e,n,o,r){super(`${e} API error (HTTP ${n}): ${o}`,r),this.name="UpstreamLlmError",this.provider=e,this.status=n}};function DN(t){return t>=500&&t<600?!0:t===408||t===425||t===429}s(DN,"isRetryableUpstreamStatus");function Ex(t){return t instanceof Lt?DN(t.status):t instanceof Error?t.name==="AbortError"||t.name==="TypeError":!1}s(Ex,"isRetryableError");async function en(t,e){let n;try{n=await t.text()}catch{return"Unknown error"}if(!n)return"Unknown error";if(e)try{let o=e(JSON.parse(n));if(typeof o=="string"&&o.length>0)return o}catch{}return n.length>500?`${n.slice(0,500)}\u2026`:n}s(en,"extractUpstreamErrorMessage");async function Zt(t,e,n){if(n==null||n<=0)return fetch(t,e);let o=new AbortController,r=setTimeout(()=>{o.abort()},n);try{return await fetch(t,{...e,signal:o.signal})}finally{clearTimeout(r)}}s(Zt,"fetchWithTimeout");async function tn(t,e){if(!T.instance.remoteLogURL){H.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}let n=ao(t);if(n?.servedFromCache){H.getLogger(t).debug("Response served from cache; cache policy emitted analytics, skipping");return}let o=e.consumerSub??null,r=n?.teamId??null,i=n?.appId??null,a=null,c=null,u=n?.cacheState??null,d=e.label??t.custom?.label??e.provider;t.analyticsContext.addAnalyticsEvent(parseFloat(e.cost.toFixed(10)),Q.AI_GATEWAY_COST_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u}),t.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_REQUEST_COUNT,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,routingTarget:null}),t.analyticsContext.addAnalyticsEvent(e.promptTokens,Q.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,tokenType:"prompt"}),t.analyticsContext.addAnalyticsEvent(e.completionTokens,Q.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,tokenType:"completion"});let p=t.analyticsContext.flushAnalyticsEvents();new kr(t,{endpoint:new URL("/v2/analytics",T.instance.remoteLogURL).toString()}).pushEvents(p)}s(tn,"sendStreamAnalytics");async function Or(t,e){let n=e.userContext?.configuration?.id;n&&await tt.incrementMeters(n,{requests:1,tokens:0,costs:0},t),await tn(t,{promptTokens:0,completionTokens:0,model:e.model,provider:e.provider,configId:n||"unknown",cost:0,consumerSub:e.userContext?.sub??null})}s(Or,"recordStreamUsageBaseline");function nn(t,e){let n={};for(let o in t){let r=t[o];Array.isArray(r)||(r=[r]);for(let i of r)if(i.param){if(o in e){let a=UN(o,e,i);a!==void 0&&_x(n,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;_x(n,i.param,a)}}}return n}s(nn,"validateAndTransformRequest");function UN(t,e,n){let o=e[t];return n.transform&&(o=n.transform(e)),o===void 0&&n.default!==void 0&&(o=typeof n.default=="function"?n.default(e):n.default),typeof o=="number"&&(n.min!==void 0&&o<n.min&&(o=n.min),n.max!==void 0&&o>n.max&&(o=n.max)),o}s(UN,"getValue");function _x(t,e,n){if(n===void 0)return;let o=e.split("."),r=t;for(let i=0;i<o.length-1;i++){let a=o[i];r[a]||(r[a]={}),r=r[a]}r[o[o.length-1]]=n}s(_x,"setNestedProperty");var zN=["authorization","proxy-authorization","cookie","cookie2","set-cookie","x-api-key","content-type","content-length","content-encoding","accept-encoding","connection","transfer-encoding","host"];function Ox(t,e){let n=new Headers(t),o=n.get("anthropic-version");for(let r of zN)n.delete(r);return n.set("x-api-key",e),n.set("Content-Type","application/json"),n.set("anthropic-version",o??"2023-06-01"),n}s(Ox,"buildAnthropicPassthroughHeaders");var $x={model:{param:"model",required:!0,default:"claude-sonnet-4-6"},messages:[{param:"messages",required:!0,transform:s(t=>t.messages.filter(n=>n.role!=="system").map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),"transform")},{param:"system",required:!1,transform:s(t=>{let n=t.messages.filter(o=>o.role==="system");if(n.length!==0)return n.map(o=>o.content).join(`
|
|
242
|
+
`}s(Vc,"getIntrospectionQuery");var dx=2,sN=1,aN=0,cN=0,Ap=4294967295,uN=["first","last","limit","pageSize","take"],lN=new Set(["__typename","__schema","__type"]);function px(t,e={}){let n=new Map,o,r;for(let c of t.definitions)c.kind===le.FRAGMENT_DEFINITION?n.set(c.name.value,c):c.kind===le.OPERATION_DEFINITION&&(o??=c,e.operationName&&c.name?.value===e.operationName&&(r=c));let i=r??o;if(!i)return 0;let a={fragments:n,variables:e.variables??{},multiplierNames:new Set(e.multipliers??uN),expanding:new Set};return mx(Jc(i.selectionSet,dx,a))}s(px,"computeComplexity");function Jc(t,e,n){let o=e,r=0;for(let i of t.selections)if(!fN(i.directives,n.variables))switch(i.kind){case le.FIELD:{o+=dN(i,n);break}case le.FRAGMENT_SPREAD:{let a=i.name.value,c=n.fragments.get(a);if(!c||n.expanding.has(a))break;n.expanding.add(a),o+=Jc(c.selectionSet,cN,n),n.expanding.delete(a);break}case le.INLINE_FRAGMENT:{let a=Jc(i.selectionSet,aN,n);a>r&&(r=a);break}}return o+r}s(Jc,"selectionSetCost");function dN(t,e){if(lN.has(t.name.value))return 0;let n=t.selectionSet?Jc(t.selectionSet,dx,e):sN,o=pN(t.arguments,e);return o!==null&&(n=mx(n*o)),n}s(dN,"fieldCost");function pN(t,e){if(!t||t.length===0)return null;let n=null;for(let o of t){if(!e.multiplierNames.has(o.name.value))continue;let r=mN(o.value,e.variables);(n===null||r>n)&&(n=r)}return n}s(pN,"resolveMultiplier");function mN(t,e){if(t.kind===le.INT)return ux(Number.parseInt(t.value,10));if(t.kind===le.VARIABLE){let n=e[t.name.value];return typeof n!="number"||!Number.isInteger(n)?1:ux(n)}return 0}s(mN,"resolveMultiplierValue");function ux(t){if(!Number.isFinite(t))return 1;let e=Math.abs(t);return e>Ap?1:e}s(ux,"normalizeMultiplier");function fN(t,e){if(!t||t.length===0)return!1;for(let n of t){let o=n.name.value;if(o==="skip"){if(lx(n,e)===!0)return!0}else if(o==="include"&&lx(n,e)===!1)return!0}return!1}s(fN,"isExcludedByDirective");function lx(t,e){let n=t.arguments?.find(r=>r.name.value==="if");if(!n)return;let o=n.value;if(o.kind===le.BOOLEAN)return o.value;if(o.kind===le.VARIABLE){let r=e[o.name.value];return typeof r=="boolean"?r:void 0}}s(lx,"resolveIfArgument");function mx(t){return Number.isNaN(t)||t<=0?0:t>Ap?Ap:Math.trunc(t)}s(mx,"clampU32");var fx=4*1024,gN="0".repeat(64);async function hx(t,e,n){let o=gx(t,fx),r;try{r=Fc(t)}catch(g){return{ast:null,documentHash:gN,documentSnippet:o,operationType:"",operationName:"",maxDepth:0,complexity:null,syntaxError:g instanceof ir?g:new ir(g instanceof Error?g.message:String(g))}}let i=yN(r),a=Bc(i),c=await vN(a),{operationType:u,operationName:d}=bN(i,e),p=wN(i),m=px(r,{operationName:e,variables:n});return{ast:r,documentHash:c,documentSnippet:gx(a,fx),operationType:u,operationName:d,maxDepth:p,complexity:m,syntaxError:null}}s(hx,"analyzeDocument");var hN="?";function yN(t){let e=s(()=>({kind:le.STRING,value:hN}),"toPlaceholder");return ro(t,{IntValue:e,FloatValue:e,StringValue:e,BooleanValue:e,EnumValue:e})}s(yN,"scrubLiterals");function bN(t,e){let n=null;for(let o of t.definitions){if(o.kind!==le.OPERATION_DEFINITION)continue;let r=o.name?.value??"";if(n===null&&(n={operationType:o.operation,operationName:r}),e&&r===e)return{operationType:o.operation,operationName:r}}return n??{operationType:"",operationName:""}}s(bN,"selectOperation");function wN(t){let e=0,n=0;return ro(t,{SelectionSet:{enter(){n+=1,n>e&&(e=n)},leave(){n-=1}}}),e}s(wN,"computeMaxDepth");async function vN(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e),o=new Uint8Array(n),r="";for(let i of o)r+=i.toString(16).padStart(2,"0");return r}s(vN,"sha256Hex");function gx(t,e){let n=new TextEncoder().encode(t);if(n.byteLength<=e)return t;let o=e;for(;o>0&&(n[o]&192)===128;)o--;return new TextDecoder("utf-8").decode(n.subarray(0,o))}s(gx,"truncate");function oo(t,e,n){try{t.log?.debug?.({event:e,errorName:n instanceof Error?n.name:"unknown"},"graphql analytics internal error")}catch{}}s(oo,"safeLog");function yx(t){if(!t)return"unknown";let e=t.toLowerCase();return e.includes("apollo-ios")||e.includes("apollo-kotlin")||e.includes("apollo-android")||e.includes("ios")||e.includes("android")||e.includes("react-native")||e.includes("expo")?"mobile":e.includes("apollo-client")||e.includes("apollo-web")||e.includes("urql")||e.includes("relay")||e.includes("browser")||e.includes("web")?"browser":e.includes("apollo-server")||e.includes("server")||e.includes("node")||e.includes("service")||e.includes("worker")?"service":"unknown"}s(yx,"deriveClientKind");var RN="apollographql-client-name",SN="apollographql-client-version",IN="x-graphql-document-id";function bx(t){let{context:e,operation:n,request:o,httpStatusCode:r,totalLatencyMs:i}=t;try{let a=CN(o),c=o.headers.get(RN),u=o.headers.get(SN),d=n.errors.count,p=n.errors.classes(),m=d===0?"success":"failure",g=n.persistedQueryHash??o.headers.get(IN),h={operationType:n.operationType,operationName:n.operationName,documentHash:n.documentHash??"",documentSnippet:n.documentSnippet??"",persistedQueryHash:g??null,maxDepth:n.maxDepth,complexity:n.complexity,routePath:xN(e),clientName:c??null,clientKind:yx(c),clientVersion:u??null,subjectId:a.subjectId,tenantId:a.tenantId,apiKeySub:a.apiKeySub,authProfileId:a.authProfileId,httpStatusCode:r,totalLatencyMs:i,outcome:m,errorCount:d,errorClasses:p,cacheState:n.cacheState};e.analyticsContext.addAnalyticsEvent(1,Q.GRAPHQL_OPERATION,h)}catch(a){oo(e,"graphql_analytics_operation_emit_failed",a)}}s(bx,"emitGraphqlOperationEvent");function xN(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}s(xN,"readRoutePath");function CN(t){let e=t.user,n=e?.sub??null,o=e?.apiKeyId??null,r=e?.data??{};return{subjectId:typeof n=="string"?n:null,tenantId:typeof r.tenantId=="string"?r.tenantId:typeof r.tenant_id=="string"?r.tenant_id:null,apiKeySub:typeof o=="string"?o:null,authProfileId:null}}s(CN,"readSubject");var TN=1*1024*1024;function PN(t){if(typeof t.raw!="function")return!1;try{return t.raw()?.["x-graphql"]===!0}catch{return!1}}s(PN,"isGraphqlRoute");var kp=s(async(t,e,n)=>{let o=mI();if(fI(e,o),t.method==="GET")try{await EN(t,o)}catch(a){oo(e,"graphql_analytics_url_analysis_failed",a)}let r=AN(t)?t.clone():null,i;try{i=await n(t)}catch(a){o.errors.record("resolver"),i=await bn(t,e,"GraphQL analytics: downstream processor threw past handler error wrapping.",a)}if(r)try{await kN(r,o)}catch(a){oo(e,"graphql_analytics_body_analysis_failed",a)}return _N(e,o,i.status),i},"graphqlAnalyticsProcessor");kp.shouldApply=t=>PN(t);function AN(t){if(!t.body||t.method==="GET")return!1;let e=(t.headers.get("content-type")??"").toLowerCase();if(!e.startsWith("application/json")&&!e.includes("+json"))return!1;let n=t.headers.get("content-length");if(n!==null){let o=Number(n);if(!Number.isFinite(o)||o<0||o>TN)return!1}return!0}s(AN,"hasReadableJsonBody");async function kN(t,e){let n;try{n=await t.text()}catch{return}let o;try{o=JSON.parse(n)}catch{return}let r=o,i=typeof r.operationName=="string"?r.operationName:null,a=r.extensions?.persistedQuery?.sha256Hash,c=typeof r.query=="string"?r.query:null;await vx(e,{query:c,operationName:i,persistedHash:typeof a=="string"?a:null,variables:wx(r.variables)})}s(kN,"analyzeRequestBody");async function EN(t,e){let n;try{n=new URL(t.url)}catch{return}let o=n.searchParams,r=o.get("query"),i=o.get("operationName"),a=null,c=o.get("extensions");if(c)try{let m=JSON.parse(c).persistedQuery?.sha256Hash;typeof m=="string"&&(a=m)}catch{}let u=null,d=o.get("variables");if(d)try{u=wx(JSON.parse(d))}catch{}await vx(e,{query:r,operationName:i,persistedHash:a,variables:u})}s(EN,"analyzeUrlParams");function wx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}s(wx,"asVariables");async function vx(t,e){if(e.persistedHash&&(t.persistedQueryHash=e.persistedHash),e.operationName&&e.operationName.length>0&&(t.operationName=e.operationName),!e.query||e.query.length===0){e.persistedHash&&(t.documentHash="",t.documentSnippet="");return}try{let n=await hx(e.query,e.operationName??void 0,e.variables??void 0);t.documentHash=n.documentHash,t.documentSnippet=n.documentSnippet,t.operationType=n.operationType,t.operationName=e.operationName&&e.operationName.length>0?e.operationName:n.operationName,t.maxDepth=n.maxDepth,t.complexity=n.complexity,n.syntaxError&&t.errors.record("syntax")}catch{t.errors.record("syntax")}}s(vx,"populateFromGraphqlInputs");function _N(t,e,n){let o=s(a=>{e.errors.classes().includes(a)||e.errors.record(a)},"recordIfNew");if(n!==null){let a=pI(n);a&&o(a)}let r=it.getContextExtensions(t).latestRequest,i=performance.now()-e.startTimeMs;bx({context:t,operation:e,request:r,httpStatusCode:n,totalLatencyMs:i})}s(_N,"finalizeAndEmit");var ws=class{static{s(this,"PluginRouteConfiguration")}constructor({path:e,methods:n,corsPolicy:o="none"}){this.path=e,this.methods=n,this.corsPolicy=o,this.handler={export:Zo,module:Zo}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var Ep=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,n,o){this.fullPath=e,this.config=n,this.executableHandler=o;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(r){throw new Pe(`Invalid path '${e}'. ${r.message}`)}}urlPattern;fullPath;config;executableHandler},Kc=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,n){if(!(e instanceof Ar||e instanceof yt||e instanceof ws))throw new Pe("Config must be a valid RouteConfiguration type: UserRouteConfiguration, SystemRouteConfiguration, or PluginRouteConfiguration");let o;"pathPattern"in e&&e.pathPattern?o=e.pathPattern:o=e.path;try{let r=new Ep(o,e,n);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new wc(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}addPluginRoute(e){let n=new St({processors:e.processors??[],handler:e.handler}),o=new ws({methods:e.methods,path:e.path,corsPolicy:e.corsPolicy});this.addRoute(o,n.execute)}lookup(e,n){if(typeof n>"u")throw new I(`Invalid request - Method was undefined. Path: '${e}'`);for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o];if(r.config.methods.includes(n)){let i=r.urlPattern.exec({pathname:e});if(i!==null)return new jo(r.config,r.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let n=[];for(let o=0;o<this.routeEntries.length;o++){let r=this.routeEntries[o],i=r.urlPattern.exec({pathname:e});if(i!==null){let a=new jo(r.config,r.executableHandler,i.pathname.groups);n.push(a)}}return n}};import{AsyncLocalStorage as ON}from"node:async_hooks";var sr={context:new ON};function io(){let t=sr.context.getStore()?.context;if(!t)throw new Error("No context found. This should not happen.");return t}s(io,"getCurrentContext");var _p;function Rx(t){_p=t}s(Rx,"setGlobalZuploEventContext");function _r(){if(_p===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return _p}s(_r,"getGlobalZuploEventContext");function Sx({headers:t,removeAllVendorHeadersExceptListed:e}){let n=new Headers(t);if(e){for(let[o]of t){let r=o.substring(0,3);$S.includes(r.toLowerCase())&&!MS.includes(o.toLowerCase())&&n.delete(o)}n.delete(cp)}else OS.forEach(o=>{n.delete(o)});return _S.forEach(o=>{n.delete(o)}),n}s(Sx,"normalizeIncomingRequestHeaders");var so=qe("zuplo:runtime"),vs=s(t=>(...e)=>{let n=sr.context.getStore();n&&n.context?.log[t](...e)},"consoleLogFn");console.log=vs("log");console.info=vs("info");console.debug=vs("debug");console.warn=vs("warn");console.error=vs("error");var je=class t{constructor(e,n,o,r){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=r;so("Gateway.constructor"),this.#r=this.setupRoutes(),this.#t=o}routeData;runtimeSettings;schemaValidator;static{s(this,"Gateway")}static#e;static async initialize(e,n,o,r){if(so("Gateway.initialize"),!t.#e){let i=await Uc.init(o),a=await e(),c={...a,corsPolicies:kI(a.corsPolicies),getInboundPolicyInstance:s(d=>_c(d,a.policies),"getInboundPolicyInstance")},u=new t(c,n,i,r);t.#e=u}if(!t.#e)throw new Pe("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){so("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new Pe("Gateway cannot be used before it is initialized");return t.#e}#t;#r;#n=[Oc,kp,Fo,Gt,GI];setupRoutes=s(()=>{so("Gateway.setupRoutes");let e=this.routeData,n=new Kc;if(e.routes.length===0)return up(n),mp(n),pp(n,this.runtimeSettings,this.routeData.corsPolicies),_I(n),n;let{enabled:o,type:r,basePath:i}=this.runtimeSettings.developerPortal;o&&r==="legacy"&&(FI(n,i),HI(n,i)),up(n),mp(n),pp(n,this.runtimeSettings,this.routeData.corsPolicies);for(let a of An)a instanceof mt&&a.registerRoutes({router:n,runtimeSettings:this.runtimeSettings,parsedRouteData:this.routeData});return e.routes.forEach(a=>{let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new I(`Invalid state - No handler on route for path '${a.path}'`);let u=this.#n.filter(m=>!m.shouldApply||m.shouldApply(a)),d=new St({processors:u,handler:c}),p=new Ar(a);n.addRoute(p,d.execute)}),OI(n),n},"setupRoutes");async handleRequest(e,n,o){let r=e.headers.get($o)??e.headers.get(nS)??o?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mo);Rx(n);let a=Sx({headers:e.headers,removeAllVendorHeadersExceptListed:T.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set($o,r);let c=new Request(e,{headers:a}),u=e.headers.get(iS)||e.headers.get(oS)||e.headers.get(sS);if(u){let A=e.url.replace(/^(http|https):\/\//,`${u}://`);c=new Request(A,c)}if(["GET","HEAD"].includes(c.method)&&c.body){let A=new Headers(c.headers);A.set(rS,"true"),c=new Request(c,{headers:A,body:null})}let d=e.headers.get(kS);if(d){let A=new URL(c.url),L=new URL(`local://${d}${A.pathname}${A.search}`);c=new Request(L.toString(),c)}c=await xI(c);let p=new URL(c.url),m=p.pathname,g=this.#r.lookup(m,c.method);if(!g){if(T.instance.build.COMPATIBILITY_FLAGS.return501ForUnsupportedHttpMethods){let A=$.getProblemFromStatus(501,{instance:m,trace:{timestamp:new Date().toISOString(),requestId:r,buildId:T.instance.build.BUILD_ID,...i?{rayId:i}:{}}});return new Response(JSON.stringify(A),{status:501,statusText:es[501],headers:{"content-type":"application/problem+json",[$o]:r}})}throw new Pe(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`)}let h={},{userRequestLogger:f,systemRequestLogger:v}=this.#t.createRequestLoggers(r,i,n,h,c,g.routeConfiguration);qo(p)||f.debug(`Request received '${p.pathname}'`,{method:c.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let b=new Wc(e.headers),w=new we(c,{params:g.params},e),S=new Yc({logger:f,route:g.routeConfiguration,requestId:r,event:n,custom:h,incomingRequestProperties:b,parentContext:o?.parentContext}),x=sr.context.getStore();x&&(x.context=S);let C=g.routeConfiguration.raw();$N.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Qt.RoutePathPattern]:S.route.pathPattern,[Qt.RouteOperationId]:C.operationId,[Qt.RouteTrace]:C["x-zuplo-trace"],[Qt.RouteSystem]:qo(p)?!0:void 0,"net.colo":b.colo,"net.country":b.country,"net.asn":b.asn}),it.initialize(S,w);try{if(H.addLogger(S,v),T.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!qo(p):!p.pathname.startsWith("/__zuplo")){let re=await RI(w,S);if(re instanceof Response)return re;{let V=it.getContextExtensions(S);w=re,V.latestRequest=w}}let A=g.executableHandler;MN(A,g,c),so("Gateway.handleRequest - call user handler");let L=await A(w,S);if(so("Gateway.handleRequest - user handler"),!(L instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof L}`);if(L.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let q;if(L.headers.get($o)===null&&!L.webSocket&&L.status!==101){let re=new Headers(L.headers);re.set($o,r),q=new Response(L.body,{status:L.status,statusText:L.statusText,headers:re,cf:L.cf})}else q=L;return q}catch(A){return A instanceof Z?(f.error(A),v.warn(A)):v.error(A),await bn(w,S,"Error executing handler",A)}}};function MN(t,e,n){if(so("Gateway.checkHandler"),!t)throw typeof e.routeConfiguration>"u"?new I(`Invalid state - no routeConfiguration for '${n.method}:${n.url}`):new I(`Invalid state. No handler for request '${n.method}':'${e.routeConfiguration.path}'`)}s(MN,"checkHandler");Function.prototype.toString=function(){return"[native code]"};var Qc=globalThis,Ix=Qc.caches;if(Ix){let t=Ix.open;Qc.caches.open=function(e){let n=T.instance.deploymentName??T.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Qc.caches.default,Object.freeze(Qc.caches)}var LN="Error initializing gateway. Check your configuration for errors or contact support.",NN="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Op=class{constructor(e,n,o,r,i,a){this.routeLoader=e;this.buildEnvironment=n;this.runtimeSettings=o;this.serviceProvider=r;this.schemaValidations=i;this.runtimeInit=a}routeLoader;buildEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;static{s(this,"Handler")}requestHandler=s(async(e,n,o)=>{T.initialize({build:this.buildEnvironment,runtime:n});try{await CI(this.runtimeInit)}catch(i){return this.handleError(i,NN,e)}return wI(s(async(i,a)=>{let c;try{c=await je.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(d){return this.handleError(d,LN,i)}let u={context:void 0};return sr.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,o)},"requestHandler");handleError(e,n,o){D.console.error("Error initializing gateway.",e),e instanceof I&&(n=e.message);let r={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:n,instance:o.url,trace:{timestamp:Date.now(),rayId:o.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:T.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};var $p=new ne(Symbol("ai-gateway-request-analytics"));function xx(t){let e=$p.get(t);return e||(e={cacheState:null,servedFromCache:!1,similarity:null,teamId:null,appId:null},$p.set(t,e)),e}s(xx,"getOrCreateEntry");function Zn(t,e,n){let o=xx(t);o.cacheState=e,n?.similarity!==void 0&&(o.similarity=n.similarity),n?.servedFromCache!==void 0&&(o.servedFromCache=n.servedFromCache)}s(Zn,"recordAiGatewayCacheState");function ar(t){if(!t||typeof t!="object")return{teamId:null,appId:null};let e=t,n=e.isApp===!0&&typeof e.id=="string"&&e.id!==""?e.id:null;return{teamId:typeof e.parentId=="string"&&e.parentId!==""?e.parentId:null,appId:n}}s(ar,"extractTeamAppAttribution");function ei(t,e){let{teamId:n,appId:o}=ar(e);if(n===null&&o===null)return;let r=xx(t);r.teamId=n,r.appId=o}s(ei,"recordAiGatewayAttribution");function ao(t){return $p.get(t)}s(ao,"getAiGatewayRequestAnalytics");var Lp=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??T.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,n){let o=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});Ve(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Pe(`Failed to fetch meters: ${i.status} ${i.statusText}`);return await i.json()}async checkHierarchicalQuotaLimits(e,n){let o=new URL(`/v1/hierarchical-quota/${e}/limits`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});Ve(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Pe(`Failed to check quota limits: ${i.status} ${i.statusText}`);return await i.json()}async incrementMeters(e,n,o){let r=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),i=new Headers({"Content-Type":"application/json"});Ve(i,o.requestId);let a=await fetch(r,{method:"POST",headers:i,body:JSON.stringify({increments:n})});if(!a.ok)throw new Pe(`Failed to increment meters: ${a.status} ${a.statusText}`)}async sendUsageEvent(e,n,o,r){let i=new URL(`/v3/metering/${e}/events`,this.baseUrl).toString(),a=new Headers({"Content-Type":"application/json"});Ve(a,o.requestId);let c;try{c=H.getLogger(o)}catch{}let u=await ct({retries:r?.retries??3,retryDelayMs:r?.retryDelayMs??500,logger:c,fetchFn:s((d,p)=>fetch(d,p),"fetchFn")},i,{method:"POST",headers:a,body:JSON.stringify(n)});if(!u.ok)throw new Pe(`Failed to send monetization v3 usage events: ${u.status} ${u.statusText}`)}},Mp=null,ti={get instance(){return Mp===null&&(Mp=new Lp),Mp}};var Cx=Pt.object({environmentVariable:Pt.string().min(1),model:Pt.string().min(1),provider:Pt.string().min(1)}),Tx=Pt.object({completions:Cx.optional(),embeddings:Cx.optional()});var Px=qe("zuplo:policies:AIGatewayMeteringInboundPolicy"),Ax=Symbol("ai-gateway-meter-increments"),kx=Symbol("ai-gateway-quota-fallback"),tt=class t extends ce{static{s(this,"AIGatewayMeteringInboundPolicy")}static policyType="ai-gateway-metering";static setIncrements(e,n){ne.set(e,Ax,n)}static getIncrements(e){return ne.get(e,Ax)??{}}static setQuotaFallback(e,n){ne.set(e,kx,n)}static getQuotaFallback(e){return ne.get(e,kx)}async handler(e,n){let o=Date.now(),r=H.getLogger(n),i=s((a,c)=>{if(this.options.throwOnFailure)throw new Pe(a,{cause:c});r.error(c,a)},"throwOrLog");try{let a=e.user,c=a?.configuration;if(!c)throw new I(`AIGatewayMeteringInboundPolicy '${this.policyName}' - No configuration found in request.user. Ensure ai-gateway-inbound policy runs first.`);let u=c;if(!u.id)throw new I(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Configuration ID not found.`);let d=a?.sub??null,p=await this.fetchCurrentMeters(u.id,n,r),m=this.checkWarnings(u,p);for(let h of m)n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_WARNING_COUNT,{type:`quota-${h.type}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_warning"});let g=await this.checkHierarchicalQuotaLimits(u.id,n,r);if(g.violation){let h=g.violation,f=this.requestCapability(e),v=this.resolveQuotaFallback(u,f,n,r);if(v){let b=f?u.models?.[f]?.[0]:void 0,w=f?v[f]:void 0,S=b?`${b.provider}/${b.model}`:"the primary model",x=w?`${w.provider}/${w.model}`:"the configured fallback model";t.setQuotaFallback(n,v),n.log.warn({configId:u.id,configLabel:h.configLabel,meter:h.meter,period:h.period,currentUsage:h.currentUsage,limit:h.limit,originalModel:b?.model,originalProvider:b?.provider,fallbackModel:w?.model,fallbackProvider:w?.provider},`AI Gateway quota exceeded; falling back from ${S} to ${x} instead of blocking`),n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_FALLBACK_COUNT,{type:`quota-${h.meter}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_fallback"})}else return n.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_BLOCKED_COUNT,{type:`quota-${h.meter}-${h.period}`,configId:u.id,teamId:null,appId:null,consumerSub:d,environment:null,region:null,errorType:"quota_exceeded"}),this.createHierarchicalQuotaExceededResponse(e,n,h)}return n.addResponseSendingFinalHook(async()=>{try{let h=t.getIncrements(n);Px(`AIGatewayMeteringInboundPolicy '${this.policyName}' - increments ${JSON.stringify(h)}`),Object.keys(h).length>0&&await t.incrementMetersInternal(u.id,h,n,r)}catch(h){i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to increment meters`,h)}}),e}catch(a){if(a instanceof I)throw a;return i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Error`,a),e}finally{let a=Date.now()-o;Px(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,n,o){try{return await ti.instance.fetchCurrentMeters(e,n)}catch(r){throw o.error(r,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to fetch meters`),r}}requestCapability(e){let n;try{n=new URL(e.url).pathname}catch{return}let o=s(r=>n===r||n.endsWith(r),"matchesBase");if(o("/v1/chat/completions")||o("/v1/messages"))return"completions";if(o("/v1/embeddings"))return"embeddings"}resolveQuotaFallback(e,n,o,r){if(n?Cr(o)?.byCapability[n]?.quotaFallback:void 0)return{};let a=e.quotaFallback;if(!a)return;let c=Tx.safeParse(a);if(!c.success){r.error(c.error,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Invalid quotaFallback configuration; blocking instead of falling back`);return}if(!(!n||!c.data[n]))return c.data}async checkHierarchicalQuotaLimits(e,n,o){try{return await ti.instance.checkHierarchicalQuotaLimits(e,n)}catch(r){throw o.error(r,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to check hierarchical quota limits`),r}}static async incrementMeters(e,n,o){let r=H.getLogger(o);return t.incrementMetersInternal(e,n,o,r)}static async incrementMetersInternal(e,n,o,r){try{await ti.instance.incrementMeters(e,n,o)}catch(i){throw r.error(i,"AIGatewayMeteringInboundPolicy - Failed to increment meters"),i}}checkWarnings(e,n){let o=[];for(let[r,i]of Object.entries(e.limits)){if(!i)continue;let a=n.meters[r];if(!a)continue;let c=this.checkQuotaWarning(i.daily,a.daily,r,"daily");c&&o.push(c);let u=this.checkQuotaWarning(i.monthly,a.monthly,r,"monthly");u&&o.push(u)}return o}checkQuotaWarning(e,n,o,r){if(!e?.warning?.enabled||!e?.warning?.threshold||!e?.limit)return null;let i=e.warning.threshold/100*e.limit;return n>=i?{type:o,period:r}:null}createHierarchicalQuotaExceededResponse(e,n,o){let r=`${o.period} ${o.meter} quota exceeded in configuration '${o.configLabel}'. Limit: ${o.limit}, Current: ${o.currentUsage}`;return $.tooManyRequests(e,n,{detail:r})}};var Lt=class extends Error{static{s(this,"UpstreamLlmError")}provider;status;constructor(e,n,o,r){super(`${e} API error (HTTP ${n}): ${o}`,r),this.name="UpstreamLlmError",this.provider=e,this.status=n}};function DN(t){return t>=500&&t<600?!0:t===408||t===425||t===429}s(DN,"isRetryableUpstreamStatus");function Ex(t){return t instanceof Lt?DN(t.status):t instanceof Error?t.name==="AbortError"||t.name==="TypeError":!1}s(Ex,"isRetryableError");async function en(t,e){let n;try{n=await t.text()}catch{return"Unknown error"}if(!n)return"Unknown error";if(e)try{let o=e(JSON.parse(n));if(typeof o=="string"&&o.length>0)return o}catch{}return n.length>500?`${n.slice(0,500)}\u2026`:n}s(en,"extractUpstreamErrorMessage");async function Zt(t,e,n){if(n==null||n<=0)return fetch(t,e);let o=new AbortController,r=setTimeout(()=>{o.abort()},n);try{return await fetch(t,{...e,signal:o.signal})}finally{clearTimeout(r)}}s(Zt,"fetchWithTimeout");async function tn(t,e){if(!T.instance.remoteLogURL){H.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}let n=ao(t);if(n?.servedFromCache){H.getLogger(t).debug("Response served from cache; cache policy emitted analytics, skipping");return}let o=e.consumerSub??null,r=n?.teamId??null,i=n?.appId??null,a=null,c=null,u=n?.cacheState??null,d=e.label??t.custom?.label??e.provider;t.analyticsContext.addAnalyticsEvent(parseFloat(e.cost.toFixed(10)),Q.AI_GATEWAY_COST_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u}),t.analyticsContext.addAnalyticsEvent(1,Q.AI_GATEWAY_REQUEST_COUNT,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,routingTarget:null}),t.analyticsContext.addAnalyticsEvent(e.promptTokens,Q.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,tokenType:"prompt"}),t.analyticsContext.addAnalyticsEvent(e.completionTokens,Q.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,label:d,configId:e.configId,teamId:r,appId:i,consumerSub:o,environment:a,region:c,cacheState:u,tokenType:"completion"});let p=t.analyticsContext.flushAnalyticsEvents();new kr(t,{endpoint:new URL("/v2/analytics",T.instance.remoteLogURL).toString()}).pushEvents(p)}s(tn,"sendStreamAnalytics");async function Or(t,e){let n=e.userContext?.configuration?.id;n&&await tt.incrementMeters(n,{requests:1,tokens:0,costs:0},t),await tn(t,{promptTokens:0,completionTokens:0,model:e.model,provider:e.provider,configId:n||"unknown",cost:0,consumerSub:e.userContext?.sub??null})}s(Or,"recordStreamUsageBaseline");function nn(t,e){let n={};for(let o in t){let r=t[o];Array.isArray(r)||(r=[r]);for(let i of r)if(i.param){if(o in e){let a=UN(o,e,i);a!==void 0&&_x(n,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;_x(n,i.param,a)}}}return n}s(nn,"validateAndTransformRequest");function UN(t,e,n){let o=e[t];return n.transform&&(o=n.transform(e)),o===void 0&&n.default!==void 0&&(o=typeof n.default=="function"?n.default(e):n.default),typeof o=="number"&&(n.min!==void 0&&o<n.min&&(o=n.min),n.max!==void 0&&o>n.max&&(o=n.max)),o}s(UN,"getValue");function _x(t,e,n){if(n===void 0)return;let o=e.split("."),r=t;for(let i=0;i<o.length-1;i++){let a=o[i];r[a]||(r[a]={}),r=r[a]}r[o[o.length-1]]=n}s(_x,"setNestedProperty");var zN=["authorization","proxy-authorization","cookie","cookie2","set-cookie","x-api-key","content-type","content-length","content-encoding","accept-encoding","connection","transfer-encoding","host"];function Ox(t,e){let n=new Headers(t),o=n.get("anthropic-version");for(let r of zN)n.delete(r);return n.set("x-api-key",e),n.set("Content-Type","application/json"),n.set("anthropic-version",o??"2023-06-01"),n}s(Ox,"buildAnthropicPassthroughHeaders");var $x={model:{param:"model",required:!0,default:"claude-sonnet-4-6"},messages:[{param:"messages",required:!0,transform:s(t=>t.messages.filter(n=>n.role!=="system").map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),"transform")},{param:"system",required:!1,transform:s(t=>{let n=t.messages.filter(o=>o.role==="system");if(n.length!==0)return n.map(o=>o.content).join(`
|
|
243
243
|
`)},"transform")}],max_tokens:{param:"max_tokens",required:!0,default:1024},temperature:{param:"temperature",default:1,min:0,max:1},top_p:{param:"top_p",default:-1,min:-1,max:1},stop:{param:"stop_sequences",transform:s(t=>{let e=t.stop;if(Array.isArray(e))return e;if(typeof e=="string")return[e]},"transform")},n:{},stream:{param:"stream",default:!1}},Xc=class{static{s(this,"AnthropicProvider")}name="anthropic";async chatComplete(e,n,o){if(e.n&&e.n>1)throw new Error("Multiple completions (n > 1) are not supported by Anthropic provider");let r=nn($x,e),i=await Zt("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"x-api-key":n,"Content-Type":"application/json","anthropic-version":"2023-06-01"},body:JSON.stringify(r)},o);if(!i.ok){let c=await en(i,u=>u.error?.message);throw new Lt("anthropic",i.status,c)}let a=await i.json();return{id:a.id,object:"chat.completion",created:Date.now(),model:e.model,choices:[{index:0,message:{role:"assistant",content:a.content[0]?.text||""},finish_reason:a.stop_reason==="end_turn"?"stop":"length"}],usage:{prompt_tokens:a.usage?.input_tokens||0,completion_tokens:a.usage?.output_tokens||0,total_tokens:(a.usage?.input_tokens||0)+(a.usage?.output_tokens||0)},provider:"anthropic"}}async chatCompleteStream(e,n,o,r){if(e.n&&e.n>1)throw new Error("Multiple completions (n > 1) are not supported by Anthropic provider");let i=nn($x,{...e,stream:!0}),a=await Zt("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"x-api-key":n,"Content-Type":"application/json","anthropic-version":"2023-06-01"},body:JSON.stringify(i)},r);if(!a.ok){let w=await en(a,S=>S.error?.message);throw new Lt("anthropic",a.status,w)}if(!a.body)throw new Error("No response body received from Anthropic API");let c=o.custom.userContext,u=new TextEncoder,d=Math.floor(Date.now()/1e3),p=!1,m=s((w,S)=>{let x=`data: ${JSON.stringify(w)}
|
|
244
244
|
|
|
245
245
|
`;S.enqueue(u.encode(x))},"enqueueChunk"),g=s((w=!1)=>{let S=new TextDecoder,x="",C=0,A=0,L="",q=s((re,V=null,ie)=>({id:L,object:"chat.completion.chunk",created:d,model:e.model,choices:[{index:0,delta:re,finish_reason:V}],...ie&&{usage:ie}}),"createOpenAIChunk");return new TransformStream({transform(re,V){x+=S.decode(re,{stream:!0});let ie;for(;(ie=x.indexOf(`
|
|
@@ -381,5 +381,5 @@ Signature verification is impossible without access to the original signed mater
|
|
|
381
381
|
`);let R=new f("!xml"),P=R,E="",O="";this.entityExpansionCount=0,this.currentExpandedLength=0;let _=new v(this.options.processEntities);for(let F=0;F<y.length;F++)if(y[F]==="<")if(y[F+1]==="/"){let J=gn(y,">",F,"Closing Tag is not closed."),G=y.substring(F+2,J).trim();if(this.options.removeNSPrefix){let zt=G.indexOf(":");zt!==-1&&(G=G.substr(zt+1))}this.options.transformTagName&&(G=this.options.transformTagName(G)),P&&(E=this.saveTextToParentTag(E,P,O));let Ne=O.substring(O.lastIndexOf(".")+1);if(G&&this.options.unpairedTags.indexOf(G)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${G}>`);let ye=0;Ne&&this.options.unpairedTags.indexOf(Ne)!==-1?(ye=O.lastIndexOf(".",O.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ye=O.lastIndexOf("."),O=O.substring(0,ye),P=this.tagsNodeStack.pop(),E="",F=J}else if(y[F+1]==="?"){let J=xr(y,F,!1,"?>");if(!J)throw new Error("Pi Tag is not closed.");if(E=this.saveTextToParentTag(E,P,O),!(this.options.ignoreDeclaration&&J.tagName==="?xml"||this.options.ignorePiTags)){let G=new f(J.tagName);G.add(this.options.textNodeName,""),J.tagName!==J.tagExp&&J.attrExpPresent&&(G[":@"]=this.buildAttributesMap(J.tagExp,O,J.tagName)),this.addChild(P,G,O,F)}F=J.closeIndex+1}else if(y.substr(F+1,3)==="!--"){let J=gn(y,"-->",F+4,"Comment is not closed.");if(this.options.commentPropName){let G=y.substring(F+4,J-2);E=this.saveTextToParentTag(E,P,O),P.add(this.options.commentPropName,[{[this.options.textNodeName]:G}])}F=J}else if(y.substr(F+1,2)==="!D"){let J=_.readDocType(y,F);this.docTypeEntities=J.entities,F=J.i}else if(y.substr(F+1,2)==="!["){let J=gn(y,"]]>",F,"CDATA is not closed.")-2,G=y.substring(F+9,J);E=this.saveTextToParentTag(E,P,O);let Ne=this.parseTextData(G,P.tagname,O,!0,!1,!0,!0);Ne==null&&(Ne=""),this.options.cdataPropName?P.add(this.options.cdataPropName,[{[this.options.textNodeName]:G}]):P.add(this.options.textNodeName,Ne),F=J+2}else{let J=xr(y,F,this.options.removeNSPrefix),G=J.tagName,Ne=J.rawTagName,ye=J.tagExp,zt=J.attrExpPresent,eS=J.closeIndex;if(this.options.transformTagName){let jt=this.options.transformTagName(G);ye===G&&(ye=jt),G=jt}P&&E&&P.tagname!=="!xml"&&(E=this.saveTextToParentTag(E,P,O,!1));let tS=P;tS&&this.options.unpairedTags.indexOf(tS.tagname)!==-1&&(P=this.tagsNodeStack.pop(),O=O.substring(0,O.lastIndexOf("."))),G!==R.tagname&&(O+=O?"."+G:G);let Ed=F;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,O,G)){let jt="";if(ye.length>0&&ye.lastIndexOf("/")===ye.length-1)G[G.length-1]==="/"?(G=G.substr(0,G.length-1),O=O.substr(0,O.length-1),ye=G):ye=ye.substr(0,ye.length-1),F=J.closeIndex;else if(this.options.unpairedTags.indexOf(G)!==-1)F=J.closeIndex;else{let _d=this.readStopNodeData(y,Ne,eS+1);if(!_d)throw new Error(`Unexpected end of ${Ne}`);F=_d.i,jt=_d.tagContent}let Oo=new f(G);G!==ye&&zt&&(Oo[":@"]=this.buildAttributesMap(ye,O,G)),jt&&(jt=this.parseTextData(jt,G,O,!0,zt,!0,!0)),O=O.substr(0,O.lastIndexOf(".")),Oo.add(this.options.textNodeName,jt),this.addChild(P,Oo,O,Ed)}else{if(ye.length>0&&ye.lastIndexOf("/")===ye.length-1){if(G[G.length-1]==="/"?(G=G.substr(0,G.length-1),O=O.substr(0,O.length-1),ye=G):ye=ye.substr(0,ye.length-1),this.options.transformTagName){let Oo=this.options.transformTagName(G);ye===G&&(ye=Oo),G=Oo}let jt=new f(G);G!==ye&&zt&&(jt[":@"]=this.buildAttributesMap(ye,O,G)),this.addChild(P,jt,O,Ed),O=O.substr(0,O.lastIndexOf("."))}else{let jt=new f(G);this.tagsNodeStack.push(P),G!==ye&&zt&&(jt[":@"]=this.buildAttributesMap(ye,O,G)),this.addChild(P,jt,O,Ed),P=jt}E="",F=eS}}else E+=y[F];return R.child},"parseXml");function Te(y,R,P,E){this.options.captureMetaData||(E=void 0);let O=this.options.updateTag(R.tagname,P,R[":@"]);O===!1||(typeof O=="string"&&(R.tagname=O),y.addChild(R,E))}s(Te,"addChild"),n(Te,"addChild");var Ue=n(function(y,R,P){if(y.indexOf("&")===-1)return y;let E=this.options.processEntities;if(!E.enabled||E.allowedTags&&!E.allowedTags.includes(R)||E.tagFilter&&!E.tagFilter(R,P))return y;for(let O in this.docTypeEntities){let _=this.docTypeEntities[O],F=y.match(_.regx);if(F){if(this.entityExpansionCount+=F.length,E.maxTotalExpansions&&this.entityExpansionCount>E.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${E.maxTotalExpansions}`);let pe=y.length;if(y=y.replace(_.regx,_.val),E.maxExpandedLength&&(this.currentExpandedLength+=y.length-pe,this.currentExpandedLength>E.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${E.maxExpandedLength}`)}}if(y.indexOf("&")===-1)return y;for(let O in this.lastEntities){let _=this.lastEntities[O];y=y.replace(_.regex,_.val)}if(y.indexOf("&")===-1)return y;if(this.options.htmlEntities)for(let O in this.htmlEntities){let _=this.htmlEntities[O];y=y.replace(_.regex,_.val)}return y=y.replace(this.ampEntity.regex,this.ampEntity.val),y},"replaceEntitiesValue");function Ee(y,R,P,E){return y&&(E===void 0&&(E=R.child.length===0),y=this.parseTextData(y,R.tagname,P,!1,R[":@"]?Object.keys(R[":@"]).length!==0:!1,E),y!==void 0&&y!==""&&R.add(this.options.textNodeName,y),y=""),y}s(Ee,"saveTextToParentTag"),n(Ee,"saveTextToParentTag");function Tt(y,R,P,E){return!!(R&&R.has(E)||y&&y.has(P))}s(Tt,"isItStopNode"),n(Tt,"isItStopNode");function Un(y,R,P=">"){let E,O="";for(let _=R;_<y.length;_++){let F=y[_];if(E)F===E&&(E="");else if(F==='"'||F==="'")E=F;else if(F===P[0])if(P[1]){if(y[_+1]===P[1])return{data:O,index:_}}else return{data:O,index:_};else F===" "&&(F=" ");O+=F}}s(Un,"tagExpWithClosingIndex"),n(Un,"tagExpWithClosingIndex");function gn(y,R,P,E){let O=y.indexOf(R,P);if(O===-1)throw new Error(E);return O+R.length-1}s(gn,"findClosingIndex"),n(gn,"findClosingIndex");function xr(y,R,P,E=">"){let O=Un(y,R+1,E);if(!O)return;let _=O.data,F=O.index,pe=_.search(/\s/),J=_,G=!0;pe!==-1&&(J=_.substring(0,pe),_=_.substring(pe+1).trimStart());let Ne=J;if(P){let ye=J.indexOf(":");ye!==-1&&(J=J.substr(ye+1),G=J!==O.data.substr(ye+1))}return{tagName:J,tagExp:_,closeIndex:F,attrExpPresent:G,rawTagName:Ne}}s(xr,"readTagExp"),n(xr,"readTagExp");function Eo(y,R,P){let E=P,O=1;for(;P<y.length;P++)if(y[P]==="<")if(y[P+1]==="/"){let _=gn(y,">",P,`${R} is not closed`);if(y.substring(P+2,_).trim()===R&&(O--,O===0))return{tagContent:y.substring(E,P),i:_};P=_}else if(y[P+1]==="?")P=gn(y,"?>",P+1,"StopNode is not closed.");else if(y.substr(P+1,3)==="!--")P=gn(y,"-->",P+3,"StopNode is not closed.");else if(y.substr(P+1,2)==="![")P=gn(y,"]]>",P,"StopNode is not closed.")-2;else{let _=xr(y,P,">");_&&((_&&_.tagName)===R&&_.tagExp[_.tagExp.length-1]!=="/"&&O++,P=_.closeIndex)}}s(Eo,"readStopNodeData"),n(Eo,"readStopNodeData");function Ka(y,R,P){if(R&&typeof y=="string"){let E=y.trim();return E==="true"?!0:E==="false"?!1:L(y,P)}else return g(y)?y:""}s(Ka,"parseValue"),n(Ka,"parseValue");function Id(y,R,P){let E=Number.parseInt(y,R);return E>=0&&E<=1114111?String.fromCodePoint(E):P+y+";"}s(Id,"fromCodePoint"),n(Id,"fromCodePoint");var xd=f.getMetaDataSymbol();function GR(y,R){return Cd(y,R)}s(GR,"prettify"),n(GR,"prettify");function Cd(y,R,P){let E,O={};for(let _=0;_<y.length;_++){let F=y[_],pe=BR(F),J="";if(P===void 0?J=pe:J=P+"."+pe,pe===R.textNodeName)E===void 0?E=F[pe]:E+=""+F[pe];else{if(pe===void 0)continue;if(F[pe]){let G=Cd(F[pe],R,J),Ne=JR(G,R);F[xd]!==void 0&&(G[xd]=F[xd]),F[":@"]?VR(G,F[":@"],J,R):Object.keys(G).length===1&&G[R.textNodeName]!==void 0&&!R.alwaysCreateTextNode?G=G[R.textNodeName]:Object.keys(G).length===0&&(R.alwaysCreateTextNode?G[R.textNodeName]="":G=""),O[pe]!==void 0&&O.hasOwnProperty(pe)?(Array.isArray(O[pe])||(O[pe]=[O[pe]]),O[pe].push(G)):R.isArray(pe,J,Ne)?O[pe]=[G]:O[pe]=G}}}return typeof E=="string"?E.length>0&&(O[R.textNodeName]=E):E!==void 0&&(O[R.textNodeName]=E),O}s(Cd,"compress"),n(Cd,"compress");function BR(y){let R=Object.keys(y);for(let P=0;P<R.length;P++){let E=R[P];if(E!==":@")return E}}s(BR,"propName"),n(BR,"propName");function VR(y,R,P,E){if(R){let O=Object.keys(R),_=O.length;for(let F=0;F<_;F++){let pe=O[F];E.isArray(pe,P+"."+pe,!0,!0)?y[pe]=[R[pe]]:y[pe]=R[pe]}}}s(VR,"assignAttributes"),n(VR,"assignAttributes");function JR(y,R){let{textNodeName:P}=R,E=Object.keys(y).length;return!!(E===0||E===1&&(y[P]||typeof y[P]=="boolean"||y[P]===0))}s(JR,"isLeafTag"),n(JR,"isLeafTag");var rM={allowBooleanAttributes:!1,unpairedTags:[]};function KR(y,R){R=Object.assign({},rM,R);let P=[],E=!1,O=!1;y[0]==="\uFEFF"&&(y=y.substr(1));for(let _=0;_<y.length;_++)if(y[_]==="<"&&y[_+1]==="?"){if(_+=2,_=Pd(y,_),_.err)return _}else if(y[_]==="<"){let F=_;if(_++,y[_]==="!"){_=Ad(y,_);continue}else{let pe=!1;y[_]==="/"&&(pe=!0,_++);let J="";for(;_<y.length&&y[_]!==">"&&y[_]!==" "&&y[_]!==" "&&y[_]!==`
|
|
382
382
|
`&&y[_]!=="\r";_++)J+=y[_];if(J=J.trim(),J[J.length-1]==="/"&&(J=J.substring(0,J.length-1),_--),!N(J)){let ye;return J.trim().length===0?ye="Invalid space after '<'.":ye="Tag '"+J+"' is an invalid name.",pt("InvalidTag",ye,Mt(y,_))}let G=WR(y,_);if(G===!1)return pt("InvalidAttr","Attributes for '"+J+"' have open quote.",Mt(y,_));let Ne=G.value;if(_=G.index,Ne[Ne.length-1]==="/"){let ye=_-Ne.length;Ne=Ne.substring(0,Ne.length-1);let zt=kd(Ne,R);if(zt===!0)E=!0;else return pt(zt.err.code,zt.err.msg,Mt(y,ye+zt.err.line))}else if(pe)if(G.tagClosed){if(Ne.trim().length>0)return pt("InvalidTag","Closing tag '"+J+"' can't have attributes or invalid starting.",Mt(y,F));if(P.length===0)return pt("InvalidTag","Closing tag '"+J+"' has not been opened.",Mt(y,F));{let ye=P.pop();if(J!==ye.tagName){let zt=Mt(y,ye.tagStartPos);return pt("InvalidTag","Expected closing tag '"+ye.tagName+"' (opened in line "+zt.line+", col "+zt.col+") instead of closing tag '"+J+"'.",Mt(y,F))}P.length==0&&(O=!0)}}else return pt("InvalidTag","Closing tag '"+J+"' doesn't have proper closing.",Mt(y,_));else{let ye=kd(Ne,R);if(ye!==!0)return pt(ye.err.code,ye.err.msg,Mt(y,_-Ne.length+ye.err.line));if(O===!0)return pt("InvalidXml","Multiple possible root nodes found.",Mt(y,_));R.unpairedTags.indexOf(J)!==-1||P.push({tagName:J,tagStartPos:F}),E=!0}for(_++;_<y.length;_++)if(y[_]==="<")if(y[_+1]==="!"){_++,_=Ad(y,_);continue}else if(y[_+1]==="?"){if(_=Pd(y,++_),_.err)return _}else break;else if(y[_]==="&"){let ye=QR(y,_);if(ye==-1)return pt("InvalidChar","char '&' is not expected.",Mt(y,_));_=ye}else if(O===!0&&!Td(y[_]))return pt("InvalidXml","Extra text at the end",Mt(y,_));y[_]==="<"&&_--}}else{if(Td(y[_]))continue;return pt("InvalidChar","char '"+y[_]+"' is not expected.",Mt(y,_))}if(E){if(P.length==1)return pt("InvalidTag","Unclosed tag '"+P[0].tagName+"'.",Mt(y,P[0].tagStartPos));if(P.length>0)return pt("InvalidXml","Invalid '"+JSON.stringify(P.map(_=>_.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return pt("InvalidXml","Start tag expected.",1);return!0}s(KR,"validate"),n(KR,"validate");function Td(y){return y===" "||y===" "||y===`
|
|
383
383
|
`||y==="\r"}s(Td,"isWhiteSpace"),n(Td,"isWhiteSpace");function Pd(y,R){let P=R;for(;R<y.length;R++)if(y[R]=="?"||y[R]==" "){let E=y.substr(P,R-P);if(R>5&&E==="xml")return pt("InvalidXml","XML declaration allowed only at the start of the document.",Mt(y,R));if(y[R]=="?"&&y[R+1]==">"){R++;break}else continue}return R}s(Pd,"readPI"),n(Pd,"readPI");function Ad(y,R){if(y.length>R+5&&y[R+1]==="-"&&y[R+2]==="-"){for(R+=3;R<y.length;R++)if(y[R]==="-"&&y[R+1]==="-"&&y[R+2]===">"){R+=2;break}}else if(y.length>R+8&&y[R+1]==="D"&&y[R+2]==="O"&&y[R+3]==="C"&&y[R+4]==="T"&&y[R+5]==="Y"&&y[R+6]==="P"&&y[R+7]==="E"){let P=1;for(R+=8;R<y.length;R++)if(y[R]==="<")P++;else if(y[R]===">"&&(P--,P===0))break}else if(y.length>R+9&&y[R+1]==="["&&y[R+2]==="C"&&y[R+3]==="D"&&y[R+4]==="A"&&y[R+5]==="T"&&y[R+6]==="A"&&y[R+7]==="["){for(R+=8;R<y.length;R++)if(y[R]==="]"&&y[R+1]==="]"&&y[R+2]===">"){R+=2;break}}return R}s(Ad,"readCommentAndCDATA"),n(Ad,"readCommentAndCDATA");var oM='"',iM="'";function WR(y,R){let P="",E="",O=!1;for(;R<y.length;R++){if(y[R]===oM||y[R]===iM)E===""?E=y[R]:E!==y[R]||(E="");else if(y[R]===">"&&E===""){O=!0;break}P+=y[R]}return E!==""?!1:{value:P,index:R,tagClosed:O}}s(WR,"readAttributeStr"),n(WR,"readAttributeStr");var sM=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function kd(y,R){let P=p(y,sM),E={};for(let O=0;O<P.length;O++){if(P[O][1].length===0)return pt("InvalidAttr","Attribute '"+P[O][2]+"' has no space in starting.",_o(P[O]));if(P[O][3]!==void 0&&P[O][4]===void 0)return pt("InvalidAttr","Attribute '"+P[O][2]+"' is without value.",_o(P[O]));if(P[O][3]===void 0&&!R.allowBooleanAttributes)return pt("InvalidAttr","boolean attribute '"+P[O][2]+"' is not allowed.",_o(P[O]));let _=P[O][2];if(!XR(_))return pt("InvalidAttr","Attribute '"+_+"' is an invalid name.",_o(P[O]));if(!E.hasOwnProperty(_))E[_]=1;else return pt("InvalidAttr","Attribute '"+_+"' is repeated.",_o(P[O]))}return!0}s(kd,"validateAttributeString"),n(kd,"validateAttributeString");function YR(y,R){let P=/\d/;for(y[R]==="x"&&(R++,P=/[\da-fA-F]/);R<y.length;R++){if(y[R]===";")return R;if(!y[R].match(P))break}return-1}s(YR,"validateNumberAmpersand"),n(YR,"validateNumberAmpersand");function QR(y,R){if(R++,y[R]===";")return-1;if(y[R]==="#")return R++,YR(y,R);let P=0;for(;R<y.length;R++,P++)if(!(y[R].match(/\w/)&&P<20)){if(y[R]===";")break;return-1}return R}s(QR,"validateAmpersand"),n(QR,"validateAmpersand");function pt(y,R,P){return{err:{code:y,msg:R,line:P.line||P,col:P.col}}}s(pt,"getErrorObject"),n(pt,"getErrorObject");function XR(y){return m(y)}s(XR,"validateAttrName"),n(XR,"validateAttrName");function N(y){return m(y)}s(N,"validateTagName"),n(N,"validateTagName");function Mt(y,R){let P=y.substring(0,R).split(/\r?\n/);return{line:P.length,col:P[P.length-1].length+1}}s(Mt,"getLineNumberForPosition"),n(Mt,"getLineNumberForPosition");function _o(y){return y.startIndex+y[1].length}s(_o,"getPositionFromMatch"),n(_o,"getPositionFromMatch");var aM=class{static{s(this,"XMLParser")}static{n(this,"XMLParser")}constructor(y){this.externalEntities={},this.options=i(y)}parse(y,R){if(typeof y!="string"&&y.toString)y=y.toString();else if(typeof y!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(R){R===!0&&(R={});let O=KR(y,R);if(O!==!0)throw Error(`${O.err.msg}:${O.err.line}:${O.err.col}`)}let P=new Oe(this.options);P.addExternalEntities(this.externalEntities);let E=P.parseXml(y);return this.options.preserveOrder||E===void 0?E:GR(E,this.options)}addEntity(y,R){if(R.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(y.indexOf("&")!==-1||y.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(R==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[y]=R}static getMetaDataSymbol(){return f.getMetaDataSymbol()}};return new aM(t)},"getXmlParser");var ZR=class extends rr{static{s(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){super(e,n),Se(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?qn(e.parseOnStatusCodes):void 0,this.parser=K0({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})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new Z(u)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:i})}};var HR=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new Pe(`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 FR=class{static{s(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Me("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){B("utility.get-consumer");let n=io(),o=this.bucketId??ze.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),i=new De(r,n);if(this.cacheDurationSeconds>0){let d=await i.get(e);if(d)return d}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await Ud(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&&i.put(e,u,this.cacheDurationSeconds),u}};var W0=10,Y0=3e4,va=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#r;#n;#o;#i={};constructor(e,n){if(typeof n=="number"){let o=n;this.#r=o*1e3,this.#o=Y0,this.#n=W0}else{let o=n;this.#r=o.ttlSeconds*1e3,this.#o=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:Y0,this.#n=W0}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let n=this.#i[e];return!(n===void 0||n===0)}#u(e){let n=this.#e.get(e);if(n&&!this.#s(n))return n.data}async get(e){let n=this.#u(e);if(n)return this.#l(e),n;if(this.#a(e))try{await c6(()=>this.#u(e)!==void 0||!this.#a(e),this.#o+this.#n+1,this.#n);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let n=this.#c(e);_r().waitUntil(n)}}async#c(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.#o)]);if(n===void 0)throw new I(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#r)}),n}finally{this.#i[e]--}}};async function c6(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)}}s(c6,"waitUntilTrue");import{SpanStatusCode as Q0,trace as X0}from"@opentelemetry/api";var eM=s(async(t,e,n)=>{let o=je.instance.routeData.policies,r=Bo([t],o);if(r.length===0)throw new Z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=r[0];return await X0.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{Go(u,i);let d=await i.handler(e,n);if(d instanceof Request||d instanceof we||d instanceof Response)return d instanceof Response||d instanceof we?d:new we(d);{let p=new I(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Q0.ERROR}),u.recordException(p),p}}finally{u.end()}})},"invokeInboundPolicy"),tM=s(async(t,e,n,o)=>{let r=je.instance.routeData.policies,i=us([t],r);if(i.length===0)throw new Z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=i[0];return await X0.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async d=>{try{Go(d,a);let p=await a.handler(e,n,o);if(p instanceof Response)return p;{let m=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 d.setStatus({code:Q0.ERROR}),d.recordException(m),m}}finally{d.end()}})},"invokeOutboundPolicy");function u6(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[i,a]=r.split("=");i&&a&&(o[i.trim()]=a.trim())}),o.asnum&&(e[nc]=o.asnum),o.zip&&(e[rc]=o.zip.split("+")[0]),o.dma&&(e[oc]=o.dma),o.region_code&&(e[ic]=o.region_code),o.timezone&&(e[sc]=o.timezone),o.city&&(e[Ya]=o.city),o.continent&&(e[Qa]=o.continent),o.country_code&&(e[Xa]=o.country_code),o.long&&(e[ec]=o.long),o.lat&&(e[tc]=o.lat),e}catch{return{}}}s(u6,"parseEdgeScapeHeader");function nM(t,e){let n=u6(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}s(nM,"setZpHeadersFromAkamaiEdgeScapeHeader");var Wc=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(ES);if(n){let o=new Headers(e);nM(o,n),this.#e=o}}get asn(){try{let e=this.#e.get(nc);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(CS)??void 0}get city(){return this.#e.get(aS)??this.#e.get(Ya)??void 0}get continent(){return this.#e.get(cS)??this.#e.get(Qa)??void 0}get country(){return this.#e.get(uS)??this.#e.get(Xa)??void 0}get latitude(){return this.#e.get(dS)??this.#e.get(tc)??void 0}get longitude(){return this.#e.get(lS)??this.#e.get(ec)??void 0}get colo(){return this.#e.get(TS)??void 0}get postalCode(){return this.#e.get(gS)??this.#e.get(rc)??void 0}get metroCode(){return this.#e.get(fS)??this.#e.get(oc)??void 0}get region(){return this.#e.get(pS)??this.#e.get(PS)??void 0}get regionCode(){return this.#e.get(mS)??this.#e.get(ic)??void 0}get timezone(){return this.#e.get(hS)??this.#e.get(sc)??void 0}get httpProtocol(){return this.#e.get(AS)??void 0}get clientCert(){return this.#e.get(yS)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(bS)??void 0}get clientMtlsVerificationReason(){return this.#e.get(wS)??void 0}get clientCertFingerprintSha256(){return this.#e.get(vS)??void 0}get clientCertNotBefore(){return this.#e.get(RS)??void 0}get clientCertNotAfter(){return this.#e.get(SS)??void 0}get clientCertIssuerDn(){return this.#e.get(IS)??void 0}get clientCertSubjectDn(){return this.#e.get(xS)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,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 Zr(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}s(Zr,"createRewriteContext");var ss=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},as=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},it=class t{static{s(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 Z(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;auditLogEventId="";#t;#r;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#r=[],this.#n=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#n.push(e)}onResponseSendingFinal=s(async(e,n,o)=>{for(let r of this.#t)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=s(async(e,n,o)=>{let r=e,i=T.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#r)r=await a(i?r:e,n,o);return r},"onResponseSending");onHandlerResponse=s(async(e,n,o)=>{for(let r of this.#n)await r(e,n,o)},"onHandlerResponse")},Yc=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,d)=>eM(u,d,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,d,p)=>tM(u,d,p,this),this.invokeRoute=async(u,d)=>{let p=u;typeof u=="string"&&u.startsWith("/")&&(p=new URL(u,"http://localhost"));let m=new we(p,d);return je.instance.handleRequest(m,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{it.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{it.getContextExtensions(this).addResponseSendingFinalHook(u)},this.analyticsContext=new LS(o),Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,o){B("context.addEventListener");let r=s(i=>{try{typeof n=="function"?n(i):n.handleEvent(i)}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){B("context.removeEventListener"),super.removeEventListener(e,n,o)}};export{dc as a,No as b,ht as c,wM as d,vM as e,Dd as f,ut as g,Kr as h,RM as i,Wr as j,B as k,Ud as l,jd as m,Qt as n,Tr as o,es as p,Yr as q,$ as r,mt as s,Qr as t,Zd as u,Hd as v,be as w,Gt as x,ce as y,rr as z,Wd as A,tp as B,BM as C,jo as D,ss as E,as as F,Op as G,tt as H,Gx as I,Bx as J,lD as K,Qx as L,Zp as M,wD as N,Hp as O,M as P,pz as Q,Ze as R,vt as S,Uz as T,$e as U,se as V,Nt as W,fe as X,rj as Y,xy as Z,l as _,Re as $,WP as aa,YP as ba,QP as ca,XP as da,eA as ea,tA as fa,nA as ga,iA as ha,Ky as ia,Yy as ja,Xy as ka,nb as la,ob as ma,sb as na,cb as oa,lb as pa,mb as qa,hb as ra,wb as sa,Sb as ta,xb as ua,Cb as va,ha as wa,ya as xa,ba as ya,Eb as za,Ra as Aa,$b as Ba,Mb as Ca,lZ as Da,Lb as Ea,Nb as Fa,wA as Ga,vA as Ha,RA as Ia,jb as Ja,Hb as Ka,Bb as La,NA as Ma,jA as Na,qA as Oa,KA as Pa,WA as Qa,YA as Ra,QA as Sa,rk as Ta,ok as Ua,aw as Va,ak as Wa,zl as Xa,f1 as Ya,cw as Za,Dt as _a,gk as $a,mw as ab,fw as bb,bk as cb,yw as db,vk as eb,Rk as fb,Sk as gb,Ik as hb,xk as ib,Ck as jb,_k as kb,Lk as lb,Cw as mb,Uk as nb,zk as ob,jk as pb,Yk as qb,Qk as rb,Xk as sb,eE as tb,iE as ub,lE as vb,dE as wb,Jl as xb,AH as yb,gE as zb,yE as Ab,bE as Bb,Gr as Cb,Di as Db,Ge as Eb,at as Fb,Yn as Gb,GIe as Hb,Oa as Ib,KIe as Jb,WIe as Kb,pn as Lb,XIe as Mb,exe as Nb,txe as Ob,nxe as Pb,$a as Qb,rxe as Rb,Co as Sb,cxe as Tb,Ql as Ub,To as Vb,zi as Wb,ov as Xb,vxe as Yb,iv as Zb,sv as _b,av as $b,cv as ac,uv as bc,lv as cc,dv as dc,pv as ec,mv as fc,fv as gc,gv as hc,vTe as ic,xn as jc,mn as kc,u_ as lc,id as mc,jF as nc,rd as oc,m_ as pc,pB as qc,yv as rc,ft as sc,M_ as tc,AB as uc,kB as vc,Cv as wc,QTe as xc,XTe as yc,ePe as zc,J_ as Ac,K_ as Bc,SPe as Cc,IPe as Dc,Tv as Ec,ja as Fc,ud as Gc,xPe as Hc,Q_ as Ic,APe as Jc,qa as Kc,KB as Lc,WB as Mc,Av as Nc,DPe as Oc,nO as Pc,rO as Qc,qPe as Rc,ZPe as Sc,HPe as Tc,FPe as Uc,oO as Vc,iO as Wc,aO as Xc,Qn as Yc,Ir as Zc,XB as _c,e2 as $c,QPe as ad,XPe as bd,eAe as cd,tAe as dd,Xn as ed,o2 as fd,mAe as gd,lO as hd,xAe as id,Ov as jd,s2 as kd,f2 as ld,h2 as md,mO as nd,zAe as od,jAe as pd,qAe as qd,yO as rd,GAe as sd,BAe as td,VAe as ud,Uv as vd,md as wd,zv as xd,nke as yd,rke as zd,oke as Ad,ike as Bd,m$ as Cd,Pn as Dd,Xv as Ed,Dke as Fd,f$ as Gd,Uke as Hd,rR as Id,oR as Jd,w$ as Kd,X4 as Ld,x$ as Md,lR as Nd,M$ as Od,pR as Pd,H$ as Qd,mR as Rd,gR as Sd,G$ as Td,B$ as Ud,V$ as Vd,bR as Wd,vR as Xd,e0 as Yd,t0 as Zd,n0 as _d,r0 as $d,o0 as ae,s0 as be,IR as ce,vV as de,d0 as ee,PR as fe,y0 as ge,b0 as he,w0 as ie,$V as je,v0 as ke,R0 as le,S0 as me,I0 as ne,x0 as oe,_R as pe,T0 as qe,P0 as re,OR as se,$R as te,E0 as ue,O0 as ve,$0 as we,NR as xe,L0 as ye,q0 as ze,jR as Ae,Z0 as Be,J0 as Ce,ZR as De,HR as Ee,FR as Fe,va as Ge};
|
|
384
|
-
/*! For license information please see chunk-
|
|
385
|
-
//# sourceMappingURL=chunk-
|
|
384
|
+
/*! For license information please see chunk-DBFG5V2I.js.LEGAL.txt */
|
|
385
|
+
//# sourceMappingURL=chunk-DBFG5V2I.js.map
|