@zuplo/cli 6.73.10 → 6.73.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/integration/link.integration.test.js +12 -1
- package/dist/__tests__/integration/link.integration.test.js.map +1 -1
- package/dist/link/handler.d.ts.map +1 -1
- package/dist/link/handler.js +7 -0
- package/dist/link/handler.js.map +1 -1
- package/dist/link/project-type.d.ts +22 -0
- package/dist/link/project-type.d.ts.map +1 -0
- package/dist/link/project-type.js +140 -0
- package/dist/link/project-type.js.map +1 -0
- package/dist/link/project-type.test.d.ts +2 -0
- package/dist/link/project-type.test.d.ts.map +1 -0
- package/dist/link/project-type.test.js +225 -0
- package/dist/link/project-type.test.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/README.md +1 -4
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwks/remote.d.ts +3 -3
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key_to_jwk.js +4 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
- package/node_modules/@posthog/core/dist/error-tracking/parsers/node.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/error-tracking/parsers/node.js +4 -0
- package/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs +4 -0
- package/node_modules/@posthog/core/dist/posthog-core.d.ts +5 -2
- package/node_modules/@posthog/core/dist/posthog-core.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/posthog-core.js +9 -3
- package/node_modules/@posthog/core/dist/posthog-core.mjs +9 -3
- package/node_modules/@posthog/core/dist/types.d.ts +4 -0
- package/node_modules/@posthog/core/dist/types.d.ts.map +1 -1
- package/node_modules/@posthog/core/package.json +2 -2
- package/node_modules/@posthog/core/src/error-tracking/parsers/node.spec.ts +19 -0
- package/node_modules/@posthog/core/src/error-tracking/parsers/node.ts +8 -0
- package/node_modules/@posthog/core/src/posthog-core.ts +10 -5
- package/node_modules/@posthog/core/src/types.ts +5 -0
- package/node_modules/@posthog/types/dist/feature-flags.d.ts +9 -0
- package/node_modules/@posthog/types/dist/feature-flags.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/index.d.ts +1 -1
- package/node_modules/@posthog/types/dist/index.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/posthog.d.ts +6 -2
- package/node_modules/@posthog/types/dist/posthog.d.ts.map +1 -1
- package/node_modules/@posthog/types/package.json +1 -1
- package/node_modules/@posthog/types/src/feature-flags.ts +10 -0
- package/node_modules/@posthog/types/src/index.ts +1 -0
- package/node_modules/@posthog/types/src/posthog.ts +4 -1
- 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-7POELG2I.js → chunk-7Z5GGYF5.js} +3 -3
- package/node_modules/@zuplo/runtime/out/esm/chunk-7Z5GGYF5.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/node_modules/brace-expansion/README.md +12 -0
- package/node_modules/brace-expansion/dist/commonjs/index.d.ts +2 -0
- package/node_modules/brace-expansion/dist/commonjs/index.d.ts.map +1 -1
- package/node_modules/brace-expansion/dist/commonjs/index.js +138 -86
- package/node_modules/brace-expansion/dist/commonjs/index.js.map +1 -1
- package/node_modules/brace-expansion/dist/esm/index.d.ts +2 -0
- package/node_modules/brace-expansion/dist/esm/index.d.ts.map +1 -1
- package/node_modules/brace-expansion/dist/esm/index.js +137 -85
- package/node_modules/brace-expansion/dist/esm/index.js.map +1 -1
- package/node_modules/brace-expansion/package.json +2 -2
- package/node_modules/media-typer/README.md +15 -14
- package/node_modules/media-typer/index.js +0 -8
- package/node_modules/media-typer/package.json +16 -12
- package/package.json +6 -6
- package/node_modules/@zuplo/runtime/out/esm/chunk-7POELG2I.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-7POELG2I.js.LEGAL.txt → chunk-7Z5GGYF5.js.LEGAL.txt} +0 -0
|
@@ -239,7 +239,7 @@ spurious results.`)}}return!1},"instanceOf");var Yo=class{static{s(this,"Source"
|
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
|
-
`}s(qc,"getIntrospectionQuery");var rx=2,qL=1,ZL=0,HL=0,Ap=4294967295,FL=["first","last","limit","pageSize","take"],GL=new Set(["__typename","__schema","__type"]);function ox(t,e={}){let n=new Map,o,r;for(let c of t.definitions)c.kind===ue.FRAGMENT_DEFINITION?n.set(c.name.value,c):c.kind===ue.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??FL),expanding:new Set};return ix(Zc(i.selectionSet,rx,a))}s(ox,"computeComplexity");function Zc(t,e,n){let o=e,r=0;for(let i of t.selections)if(!WL(i.directives,n.variables))switch(i.kind){case ue.FIELD:{o+=BL(i,n);break}case ue.FRAGMENT_SPREAD:{let a=i.name.value,c=n.fragments.get(a);if(!c||n.expanding.has(a))break;n.expanding.add(a),o+=Zc(c.selectionSet,HL,n),n.expanding.delete(a);break}case ue.INLINE_FRAGMENT:{let a=Zc(i.selectionSet,ZL,n);a>r&&(r=a);break}}return o+r}s(Zc,"selectionSetCost");function BL(t,e){if(GL.has(t.name.value))return 0;let n=t.selectionSet?Zc(t.selectionSet,rx,e):qL,o=VL(t.arguments,e);return o!==null&&(n=ix(n*o)),n}s(BL,"fieldCost");function VL(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=JL(o.value,e.variables);(n===null||r>n)&&(n=r)}return n}s(VL,"resolveMultiplier");function JL(t,e){if(t.kind===ue.INT)return tx(Number.parseInt(t.value,10));if(t.kind===ue.VARIABLE){let n=e[t.name.value];return typeof n!="number"||!Number.isInteger(n)?1:tx(n)}return 0}s(JL,"resolveMultiplierValue");function tx(t){if(!Number.isFinite(t))return 1;let e=Math.abs(t);return e>Ap?1:e}s(tx,"normalizeMultiplier");function WL(t,e){if(!t||t.length===0)return!1;for(let n of t){let o=n.name.value;if(o==="skip"){if(nx(n,e)===!0)return!0}else if(o==="include"&&nx(n,e)===!1)return!0}return!1}s(WL,"isExcludedByDirective");function nx(t,e){let n=t.arguments?.find(r=>r.name.value==="if");if(!n)return;let o=n.value;if(o.kind===ue.BOOLEAN)return o.value;if(o.kind===ue.VARIABLE){let r=e[o.name.value];return typeof r=="boolean"?r:void 0}}s(nx,"resolveIfArgument");function ix(t){return Number.isNaN(t)||t<=0?0:t>Ap?Ap:Math.trunc(t)}s(ix,"clampU32");var sx=4*1024,KL="0".repeat(64);async function cx(t,e,n){let o=ax(t,sx),r;try{r=Uc(t)}catch(g){return{ast:null,documentHash:KL,documentSnippet:o,operationType:"",operationName:"",maxDepth:0,complexity:null,syntaxError:g instanceof rr?g:new rr(g instanceof Error?g.message:String(g))}}let i=QL(r),a=jc(i),c=await tN(a),{operationType:u,operationName:d}=XL(i,e),p=eN(i),m=ox(r,{operationName:e,variables:n});return{ast:r,documentHash:c,documentSnippet:ax(a,sx),operationType:u,operationName:d,maxDepth:p,complexity:m,syntaxError:null}}s(cx,"analyzeDocument");var YL="?";function QL(t){let e=s(()=>({kind:ue.STRING,value:YL}),"toPlaceholder");return eo(t,{IntValue:e,FloatValue:e,StringValue:e,BooleanValue:e,EnumValue:e})}s(QL,"scrubLiterals");function XL(t,e){let n=null;for(let o of t.definitions){if(o.kind!==ue.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(XL,"selectOperation");function eN(t){let e=0,n=0;return eo(t,{SelectionSet:{enter(){n+=1,n>e&&(e=n)},leave(){n-=1}}}),e}s(eN,"computeMaxDepth");async function tN(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(tN,"sha256Hex");function ax(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(ax,"truncate");function to(t,e,n){try{t.log?.debug?.({event:e,errorName:n instanceof Error?n.name:"unknown"},"graphql analytics internal error")}catch{}}s(to,"safeLog");function ux(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(ux,"deriveClientKind");var nN="apollographql-client-name",rN="apollographql-client-version",oN="x-graphql-document-id";function lx(t){let{context:e,operation:n,request:o,httpStatusCode:r,totalLatencyMs:i}=t;try{let a=sN(o),c=o.headers.get(nN),u=o.headers.get(rN),d=n.errors.count,p=n.errors.classes(),m=d===0?"success":"failure",g=n.persistedQueryHash??o.headers.get(oN),h={operationType:n.operationType,operationName:n.operationName,documentHash:n.documentHash??"",documentSnippet:n.documentSnippet??"",persistedQueryHash:g??null,maxDepth:n.maxDepth,complexity:n.complexity,routePath:iN(e),clientName:c??null,clientKind:ux(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){to(e,"graphql_analytics_operation_emit_failed",a)}}s(lx,"emitGraphqlOperationEvent");function iN(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}s(iN,"readRoutePath");function sN(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(sN,"readSubject");var aN=1*1024*1024;function cN(t){if(typeof t.raw!="function")return!1;try{return t.raw()?.["x-graphql"]===!0}catch{return!1}}s(cN,"isGraphqlRoute");var Pp=s(async(t,e,n)=>{let o=iI();if(sI(e,o),t.method==="GET")try{await dN(t,o)}catch(a){to(e,"graphql_analytics_url_analysis_failed",a)}let r=uN(t)?t.clone():null,i;try{i=await n(t)}catch(a){o.errors.record("resolver"),i=await yn(t,e,"GraphQL analytics: downstream processor threw past handler error wrapping.",a)}if(r)try{await lN(r,o)}catch(a){to(e,"graphql_analytics_body_analysis_failed",a)}return pN(e,o,i.status),i},"graphqlAnalyticsProcessor");Pp.shouldApply=t=>cN(t);function uN(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>aN)return!1}return!0}s(uN,"hasReadableJsonBody");async function lN(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 px(e,{query:c,operationName:i,persistedHash:typeof a=="string"?a:null,variables:dx(r.variables)})}s(lN,"analyzeRequestBody");async function dN(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=dx(JSON.parse(d))}catch{}await px(e,{query:r,operationName:i,persistedHash:a,variables:u})}s(dN,"analyzeUrlParams");function dx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}s(dx,"asVariables");async function px(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 cx(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(px,"populateFromGraphqlInputs");function pN(t,e,n){let o=s(a=>{e.errors.classes().includes(a)||e.errors.record(a)},"recordIfNew");if(n!==null){let a=oI(n);a&&o(a)}let r=it.getContextExtensions(t).latestRequest,i=performance.now()-e.startTimeMs;lx({context:t,operation:e,request:r,httpStatusCode:n,totalLatencyMs:i})}s(pN,"finalizeAndEmit");var gs=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:jo,module:jo}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var kp=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 Ae(`Invalid path '${e}'. ${r.message}`)}}urlPattern;fullPath;config;executableHandler},Hc=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,n){if(!(e instanceof Tr||e instanceof yt||e instanceof gs))throw new Ae("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 kp(o,e,n);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new gc(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}addPluginRoute(e){let n=new St({processors:e.processors??[],handler:e.handler}),o=new gs({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 Uo(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 Uo(r.config,r.executableHandler,i.pathname.groups);n.push(a)}}return n}};import{AsyncLocalStorage as mN}from"node:async_hooks";var or={context:new mN};function no(){let t=or.context.getStore()?.context;if(!t)throw new Error("No context found. This should not happen.");return t}s(no,"getCurrentContext");var Ep;function mx(t){Ep=t}s(mx,"setGlobalZuploEventContext");function Pr(){if(Ep===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Ep}s(Pr,"getGlobalZuploEventContext");function fx({headers:t,removeAllVendorHeadersExceptListed:e}){let n=new Headers(t);if(e){for(let[o]of t){let r=o.substring(0,3);TS.includes(r.toLowerCase())&&!CS.includes(o.toLowerCase())&&n.delete(o)}n.delete(ip)}else xS.forEach(o=>{n.delete(o)});return IS.forEach(o=>{n.delete(o)}),n}s(fx,"normalizeIncomingRequestHeaders");var ro=ze("zuplo:runtime"),hs=s(t=>(...e)=>{let n=or.context.getStore();n&&n.context?.log[t](...e)},"consoleLogFn");console.log=hs("log");console.info=hs("info");console.debug=hs("debug");console.warn=hs("warn");console.error=hs("error");var He=class t{constructor(e,n,o,r){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=r;ro("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(ro("Gateway.initialize"),!t.#e){let i=await Oc.init(o),a=await e(),c={...a,corsPolicies:RI(a.corsPolicies),getInboundPolicyInstance:s(d=>PI(d,a.policies),"getInboundPolicyInstance")},u=new t(c,n,i,r);t.#e=u}if(!t.#e)throw new Ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){ro("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new Ae("Gateway cannot be used before it is initialized");return t.#e}#t;#r;#n=[Cc,Pp,Zo,Gt,DI];setupRoutes=s(()=>{ro("Gateway.setupRoutes");let e=this.routeData,n=new Hc;if(e.routes.length===0)return sp(n),lp(n),up(n,this.runtimeSettings,this.routeData.corsPolicies),II(n),n;let{enabled:o,type:r,basePath:i}=this.runtimeSettings.developerPortal;o&&r==="legacy"&&(NI(n,i),LI(n,i)),sp(n),lp(n),up(n,this.runtimeSettings,this.routeData.corsPolicies);for(let a of An)a instanceof pt&&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 Tr(a);n.addRoute(p,d.execute)}),xI(n),n},"setupRoutes");async handleRequest(e,n,o){let r=e.headers.get(Eo)??e.headers.get(JR)??o?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(_o);mx(n);let a=fx({headers:e.headers,removeAllVendorHeadersExceptListed:C.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Eo,r);let c=new Request(e,{headers:a}),u=e.headers.get(YR)||e.headers.get(KR)||e.headers.get(QR);if(u){let P=e.url.replace(/^(http|https):\/\//,`${u}://`);c=new Request(P,c)}if(["GET","HEAD"].includes(c.method)&&c.body){let P=new Headers(c.headers);P.set(WR,"true"),c=new Request(c,{headers:P,body:null})}let d=e.headers.get(RS);if(d){let P=new URL(c.url),N=new URL(`local://${d}${P.pathname}${P.search}`);c=new Request(N.toString(),c)}c=await hI(c);let p=new URL(c.url),m=p.pathname,g=this.#r.lookup(m,c.method);if(!g){if(C.instance.build.COMPATIBILITY_FLAGS.return501ForUnsupportedHttpMethods){let P=$.getProblemFromStatus(501,{instance:m,trace:{timestamp:new Date().toISOString(),requestId:r,buildId:C.instance.build.BUILD_ID,...i?{rayId:i}:{}}});return new Response(JSON.stringify(P),{status:501,statusText:Yi[501],headers:{"content-type":"application/problem+json",[Eo]:r}})}throw new Ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`)}let h={},{userRequestLogger:f,systemRequestLogger:w}=this.#t.createRequestLoggers(r,i,n,h,c,g.routeConfiguration);zo(p)||f.debug(`Request received '${p.pathname}'`,{method:c.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let b=new Fc(e.headers),v=new we(c,{params:g.params},e),S=new Gc({logger:f,route:g.routeConfiguration,requestId:r,event:n,custom:h,incomingRequestProperties:b,parentContext:o?.parentContext}),x=or.context.getStore();x&&(x.context=S);let T=g.routeConfiguration.raw();fN.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Yt.RoutePathPattern]:S.route.pathPattern,[Yt.RouteOperationId]:T.operationId,[Yt.RouteTrace]:T["x-zuplo-trace"],[Yt.RouteSystem]:zo(p)?!0:void 0,"net.colo":b.colo,"net.country":b.country,"net.asn":b.asn}),it.initialize(S,v);try{if(H.addLogger(S,w),C.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!zo(p):!p.pathname.startsWith("/__zuplo")){let ne=await mI(v,S);if(ne instanceof Response)return ne;{let V=it.getContextExtensions(S);v=ne,V.latestRequest=v}}let P=g.executableHandler;gN(P,g,c),ro("Gateway.handleRequest - call user handler");let N=await P(v,S);if(ro("Gateway.handleRequest - user handler"),!(N instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof N}`);if(N.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let q;if(N.headers.get(Eo)===null&&!N.webSocket&&N.status!==101){let ne=new Headers(N.headers);ne.set(Eo,r),q=new Response(N.body,{status:N.status,statusText:N.statusText,headers:ne,cf:N.cf})}else q=N;return q}catch(P){return P instanceof Z?(f.error(P),w.warn(P)):w.error(P),await yn(v,S,"Error executing handler",P)}}};function gN(t,e,n){if(ro("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(gN,"checkHandler");Function.prototype.toString=function(){return"[native code]"};var Bc=globalThis,gx=Bc.caches;if(gx){let t=gx.open;Bc.caches.open=function(e){let n=C.instance.deploymentName??C.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Bc.caches.default,Object.freeze(Bc.caches)}var hN="Error initializing gateway. Check your configuration for errors or contact support.",yN="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",_p=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)=>{C.initialize({build:this.buildEnvironment,runtime:n});try{await yI(this.runtimeInit)}catch(i){this.handleError(i,yN,e)}return dI(s(async(i,a)=>{let c;try{c=await He.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(d){return this.handleError(d,hN,i)}let u={context:void 0};return or.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:C.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Op=new re(Symbol("ai-gateway-request-analytics"));function hx(t){let e=Op.get(t);return e||(e={cacheState:null,servedFromCache:!1,similarity:null,teamId:null,appId:null},Op.set(t,e)),e}s(hx,"getOrCreateEntry");function qn(t,e,n){let o=hx(t);o.cacheState=e,n?.similarity!==void 0&&(o.similarity=n.similarity),n?.servedFromCache!==void 0&&(o.servedFromCache=n.servedFromCache)}s(qn,"recordAiGatewayCacheState");function ir(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(ir,"extractTeamAppAttribution");function $p(t,e){let{teamId:n,appId:o}=ir(e);if(n===null&&o===null)return;let r=hx(t);r.teamId=n,r.appId=o}s($p,"recordAiGatewayAttribution");function oo(t){return Op.get(t)}s(oo,"getAiGatewayRequestAnalytics");var Lp=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??C.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,n){let o=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});We(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Ae(`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"});We(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Ae(`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"});We(i,o.requestId);let a=await fetch(r,{method:"POST",headers:i,body:JSON.stringify({increments:n})});if(!a.ok)throw new Ae(`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"});We(a,o.requestId);let c;try{c=H.getLogger(o)}catch{}let u=await ft({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 Ae(`Failed to send monetization v3 usage events: ${u.status} ${u.statusText}`)}},Mp=null,Qo={get instance(){return Mp===null&&(Mp=new Lp),Mp}};var yx=$o.object({environmentVariable:$o.string().min(1),model:$o.string().min(1),provider:$o.string().min(1)}),bx=$o.object({completions:yx.optional(),embeddings:yx.optional()});var wx=ze("zuplo:policies:AIGatewayMeteringInboundPolicy"),vx=Symbol("ai-gateway-meter-increments"),Rx=Symbol("ai-gateway-quota-fallback"),tt=class t extends pe{static{s(this,"AIGatewayMeteringInboundPolicy")}static policyType="ai-gateway-metering";static setIncrements(e,n){re.set(e,vx,n)}static getIncrements(e){return re.get(e,vx)??{}}static setQuotaFallback(e,n){re.set(e,Rx,n)}static getQuotaFallback(e){return re.get(e,Rx)}async handler(e,n){let o=Date.now(),r=H.getLogger(n),i=s((a,c)=>{if(this.options.throwOnFailure)throw new Ae(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),w=this.resolveQuotaFallback(u,f,r);if(w){let b=f?u.models[f]?.[0]:void 0,v=f?w[f]:void 0,S=b?`${b.provider}/${b.model}`:"the primary model",x=v?`${v.provider}/${v.model}`:"the configured fallback model";t.setQuotaFallback(n,w),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:v?.model,fallbackProvider:v?.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);wx(`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;wx(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,n,o){try{return await Qo.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){let r=e.quotaFallback;if(!r)return;let i=bx.safeParse(r);if(!i.success){o.error(i.error,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Invalid quotaFallback configuration; blocking instead of falling back`);return}if(!(!n||!i.data[n]))return i.data}async checkHierarchicalQuotaLimits(e,n,o){try{return await Qo.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 Qo.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 bN(t){return t>=500&&t<600?!0:t===408||t===425||t===429}s(bN,"isRetryableUpstreamStatus");function Sx(t){return t instanceof Lt?bN(t.status):t instanceof Error?t.name==="AbortError"||t.name==="TypeError":!1}s(Sx,"isRetryableError");async function Xt(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(Xt,"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 en(t,e){if(!C.instance.remoteLogURL){H.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}let n=oo(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 Cr(t,{endpoint:new URL("/v2/analytics",C.instance.remoteLogURL).toString()}).pushEvents(p)}s(en,"sendStreamAnalytics");async function kr(t,e){let n=e.userContext?.configuration?.id;n&&await tt.incrementMeters(n,{requests:1,tokens:0,costs:0},t),await en(t,{promptTokens:0,completionTokens:0,model:e.model,provider:e.provider,configId:n||"unknown",cost:0,consumerSub:e.userContext?.sub??null})}s(kr,"recordStreamUsageBaseline");function tn(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=wN(o,e,i);a!==void 0&&Ix(n,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;Ix(n,i.param,a)}}}return n}s(tn,"validateAndTransformRequest");function wN(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(wN,"getValue");function Ix(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(Ix,"setNestedProperty");var vN=["authorization","proxy-authorization","cookie","cookie2","set-cookie","x-api-key","content-type","content-length","content-encoding","accept-encoding","connection","transfer-encoding","host"];function xx(t,e){let n=new Headers(t),o=n.get("anthropic-version");for(let r of vN)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(xx,"buildAnthropicPassthroughHeaders");var Tx={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(qc,"getIntrospectionQuery");var rx=2,qL=1,ZL=0,HL=0,Ap=4294967295,FL=["first","last","limit","pageSize","take"],GL=new Set(["__typename","__schema","__type"]);function ox(t,e={}){let n=new Map,o,r;for(let c of t.definitions)c.kind===ue.FRAGMENT_DEFINITION?n.set(c.name.value,c):c.kind===ue.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??FL),expanding:new Set};return ix(Zc(i.selectionSet,rx,a))}s(ox,"computeComplexity");function Zc(t,e,n){let o=e,r=0;for(let i of t.selections)if(!WL(i.directives,n.variables))switch(i.kind){case ue.FIELD:{o+=BL(i,n);break}case ue.FRAGMENT_SPREAD:{let a=i.name.value,c=n.fragments.get(a);if(!c||n.expanding.has(a))break;n.expanding.add(a),o+=Zc(c.selectionSet,HL,n),n.expanding.delete(a);break}case ue.INLINE_FRAGMENT:{let a=Zc(i.selectionSet,ZL,n);a>r&&(r=a);break}}return o+r}s(Zc,"selectionSetCost");function BL(t,e){if(GL.has(t.name.value))return 0;let n=t.selectionSet?Zc(t.selectionSet,rx,e):qL,o=VL(t.arguments,e);return o!==null&&(n=ix(n*o)),n}s(BL,"fieldCost");function VL(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=JL(o.value,e.variables);(n===null||r>n)&&(n=r)}return n}s(VL,"resolveMultiplier");function JL(t,e){if(t.kind===ue.INT)return tx(Number.parseInt(t.value,10));if(t.kind===ue.VARIABLE){let n=e[t.name.value];return typeof n!="number"||!Number.isInteger(n)?1:tx(n)}return 0}s(JL,"resolveMultiplierValue");function tx(t){if(!Number.isFinite(t))return 1;let e=Math.abs(t);return e>Ap?1:e}s(tx,"normalizeMultiplier");function WL(t,e){if(!t||t.length===0)return!1;for(let n of t){let o=n.name.value;if(o==="skip"){if(nx(n,e)===!0)return!0}else if(o==="include"&&nx(n,e)===!1)return!0}return!1}s(WL,"isExcludedByDirective");function nx(t,e){let n=t.arguments?.find(r=>r.name.value==="if");if(!n)return;let o=n.value;if(o.kind===ue.BOOLEAN)return o.value;if(o.kind===ue.VARIABLE){let r=e[o.name.value];return typeof r=="boolean"?r:void 0}}s(nx,"resolveIfArgument");function ix(t){return Number.isNaN(t)||t<=0?0:t>Ap?Ap:Math.trunc(t)}s(ix,"clampU32");var sx=4*1024,KL="0".repeat(64);async function cx(t,e,n){let o=ax(t,sx),r;try{r=Uc(t)}catch(g){return{ast:null,documentHash:KL,documentSnippet:o,operationType:"",operationName:"",maxDepth:0,complexity:null,syntaxError:g instanceof rr?g:new rr(g instanceof Error?g.message:String(g))}}let i=QL(r),a=jc(i),c=await tN(a),{operationType:u,operationName:d}=XL(i,e),p=eN(i),m=ox(r,{operationName:e,variables:n});return{ast:r,documentHash:c,documentSnippet:ax(a,sx),operationType:u,operationName:d,maxDepth:p,complexity:m,syntaxError:null}}s(cx,"analyzeDocument");var YL="?";function QL(t){let e=s(()=>({kind:ue.STRING,value:YL}),"toPlaceholder");return eo(t,{IntValue:e,FloatValue:e,StringValue:e,BooleanValue:e,EnumValue:e})}s(QL,"scrubLiterals");function XL(t,e){let n=null;for(let o of t.definitions){if(o.kind!==ue.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(XL,"selectOperation");function eN(t){let e=0,n=0;return eo(t,{SelectionSet:{enter(){n+=1,n>e&&(e=n)},leave(){n-=1}}}),e}s(eN,"computeMaxDepth");async function tN(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(tN,"sha256Hex");function ax(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(ax,"truncate");function to(t,e,n){try{t.log?.debug?.({event:e,errorName:n instanceof Error?n.name:"unknown"},"graphql analytics internal error")}catch{}}s(to,"safeLog");function ux(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(ux,"deriveClientKind");var nN="apollographql-client-name",rN="apollographql-client-version",oN="x-graphql-document-id";function lx(t){let{context:e,operation:n,request:o,httpStatusCode:r,totalLatencyMs:i}=t;try{let a=sN(o),c=o.headers.get(nN),u=o.headers.get(rN),d=n.errors.count,p=n.errors.classes(),m=d===0?"success":"failure",g=n.persistedQueryHash??o.headers.get(oN),h={operationType:n.operationType,operationName:n.operationName,documentHash:n.documentHash??"",documentSnippet:n.documentSnippet??"",persistedQueryHash:g??null,maxDepth:n.maxDepth,complexity:n.complexity,routePath:iN(e),clientName:c??null,clientKind:ux(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){to(e,"graphql_analytics_operation_emit_failed",a)}}s(lx,"emitGraphqlOperationEvent");function iN(t){let e=t.route?.path;return typeof e=="string"&&e.length>0?e:null}s(iN,"readRoutePath");function sN(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(sN,"readSubject");var aN=1*1024*1024;function cN(t){if(typeof t.raw!="function")return!1;try{return t.raw()?.["x-graphql"]===!0}catch{return!1}}s(cN,"isGraphqlRoute");var Pp=s(async(t,e,n)=>{let o=iI();if(sI(e,o),t.method==="GET")try{await dN(t,o)}catch(a){to(e,"graphql_analytics_url_analysis_failed",a)}let r=uN(t)?t.clone():null,i;try{i=await n(t)}catch(a){o.errors.record("resolver"),i=await yn(t,e,"GraphQL analytics: downstream processor threw past handler error wrapping.",a)}if(r)try{await lN(r,o)}catch(a){to(e,"graphql_analytics_body_analysis_failed",a)}return pN(e,o,i.status),i},"graphqlAnalyticsProcessor");Pp.shouldApply=t=>cN(t);function uN(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>aN)return!1}return!0}s(uN,"hasReadableJsonBody");async function lN(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 px(e,{query:c,operationName:i,persistedHash:typeof a=="string"?a:null,variables:dx(r.variables)})}s(lN,"analyzeRequestBody");async function dN(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=dx(JSON.parse(d))}catch{}await px(e,{query:r,operationName:i,persistedHash:a,variables:u})}s(dN,"analyzeUrlParams");function dx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}s(dx,"asVariables");async function px(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 cx(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(px,"populateFromGraphqlInputs");function pN(t,e,n){let o=s(a=>{e.errors.classes().includes(a)||e.errors.record(a)},"recordIfNew");if(n!==null){let a=oI(n);a&&o(a)}let r=it.getContextExtensions(t).latestRequest,i=performance.now()-e.startTimeMs;lx({context:t,operation:e,request:r,httpStatusCode:n,totalLatencyMs:i})}s(pN,"finalizeAndEmit");var gs=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:jo,module:jo}}label;path;methods;handler;corsPolicy;policies;metadata;raw(){return{}}};var kp=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 Ae(`Invalid path '${e}'. ${r.message}`)}}urlPattern;fullPath;config;executableHandler},Hc=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,n){if(!(e instanceof Tr||e instanceof yt||e instanceof gs))throw new Ae("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 kp(o,e,n);Object.freeze(r.config),this.routeEntries.push(r)}catch(r){throw new gc(`addRoute-error: Invalid path '${o}'. '${r.message}'`,{cause:r})}}addPluginRoute(e){let n=new St({processors:e.processors??[],handler:e.handler}),o=new gs({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 Uo(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 Uo(r.config,r.executableHandler,i.pathname.groups);n.push(a)}}return n}};import{AsyncLocalStorage as mN}from"node:async_hooks";var or={context:new mN};function no(){let t=or.context.getStore()?.context;if(!t)throw new Error("No context found. This should not happen.");return t}s(no,"getCurrentContext");var Ep;function mx(t){Ep=t}s(mx,"setGlobalZuploEventContext");function Pr(){if(Ep===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Ep}s(Pr,"getGlobalZuploEventContext");function fx({headers:t,removeAllVendorHeadersExceptListed:e}){let n=new Headers(t);if(e){for(let[o]of t){let r=o.substring(0,3);TS.includes(r.toLowerCase())&&!CS.includes(o.toLowerCase())&&n.delete(o)}n.delete(ip)}else xS.forEach(o=>{n.delete(o)});return IS.forEach(o=>{n.delete(o)}),n}s(fx,"normalizeIncomingRequestHeaders");var ro=ze("zuplo:runtime"),hs=s(t=>(...e)=>{let n=or.context.getStore();n&&n.context?.log[t](...e)},"consoleLogFn");console.log=hs("log");console.info=hs("info");console.debug=hs("debug");console.warn=hs("warn");console.error=hs("error");var He=class t{constructor(e,n,o,r){this.routeData=e;this.runtimeSettings=n;this.schemaValidator=r;ro("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(ro("Gateway.initialize"),!t.#e){let i=await Oc.init(o),a=await e(),c={...a,corsPolicies:RI(a.corsPolicies),getInboundPolicyInstance:s(d=>PI(d,a.policies),"getInboundPolicyInstance")},u=new t(c,n,i,r);t.#e=u}if(!t.#e)throw new Ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return t.#e}static purgeGatewayCache(){ro("Gateway.purgeGatewayCache"),t.#e=void 0}static get instance(){if(!t.#e)throw new Ae("Gateway cannot be used before it is initialized");return t.#e}#t;#r;#n=[Cc,Pp,Zo,Gt,DI];setupRoutes=s(()=>{ro("Gateway.setupRoutes");let e=this.routeData,n=new Hc;if(e.routes.length===0)return sp(n),lp(n),up(n,this.runtimeSettings,this.routeData.corsPolicies),II(n),n;let{enabled:o,type:r,basePath:i}=this.runtimeSettings.developerPortal;o&&r==="legacy"&&(NI(n,i),LI(n,i)),sp(n),lp(n),up(n,this.runtimeSettings,this.routeData.corsPolicies);for(let a of An)a instanceof pt&&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 Tr(a);n.addRoute(p,d.execute)}),xI(n),n},"setupRoutes");async handleRequest(e,n,o){let r=e.headers.get(Eo)??e.headers.get(JR)??o?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(_o);mx(n);let a=fx({headers:e.headers,removeAllVendorHeadersExceptListed:C.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Eo,r);let c=new Request(e,{headers:a}),u=e.headers.get(YR)||e.headers.get(KR)||e.headers.get(QR);if(u){let P=e.url.replace(/^(http|https):\/\//,`${u}://`);c=new Request(P,c)}if(["GET","HEAD"].includes(c.method)&&c.body){let P=new Headers(c.headers);P.set(WR,"true"),c=new Request(c,{headers:P,body:null})}let d=e.headers.get(RS);if(d){let P=new URL(c.url),N=new URL(`local://${d}${P.pathname}${P.search}`);c=new Request(N.toString(),c)}c=await hI(c);let p=new URL(c.url),m=p.pathname,g=this.#r.lookup(m,c.method);if(!g){if(C.instance.build.COMPATIBILITY_FLAGS.return501ForUnsupportedHttpMethods){let P=$.getProblemFromStatus(501,{instance:m,trace:{timestamp:new Date().toISOString(),requestId:r,buildId:C.instance.build.BUILD_ID,...i?{rayId:i}:{}}});return new Response(JSON.stringify(P),{status:501,statusText:Yi[501],headers:{"content-type":"application/problem+json",[Eo]:r}})}throw new Ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${m}'`)}let h={},{userRequestLogger:f,systemRequestLogger:w}=this.#t.createRequestLoggers(r,i,n,h,c,g.routeConfiguration);zo(p)||f.debug(`Request received '${p.pathname}'`,{method:c.method,url:p.pathname,hostname:p.hostname,route:g.routeConfiguration.path});let b=new Fc(e.headers),v=new we(c,{params:g.params},e),S=new Gc({logger:f,route:g.routeConfiguration,requestId:r,event:n,custom:h,incomingRequestProperties:b,parentContext:o?.parentContext}),x=or.context.getStore();x&&(x.context=S);let T=g.routeConfiguration.raw();fN.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Yt.RoutePathPattern]:S.route.pathPattern,[Yt.RouteOperationId]:T.operationId,[Yt.RouteTrace]:T["x-zuplo-trace"],[Yt.RouteSystem]:zo(p)?!0:void 0,"net.colo":b.colo,"net.country":b.country,"net.asn":b.asn}),it.initialize(S,v);try{if(H.addLogger(S,w),C.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!zo(p):!p.pathname.startsWith("/__zuplo")){let ne=await mI(v,S);if(ne instanceof Response)return ne;{let V=it.getContextExtensions(S);v=ne,V.latestRequest=v}}let P=g.executableHandler;gN(P,g,c),ro("Gateway.handleRequest - call user handler");let N=await P(v,S);if(ro("Gateway.handleRequest - user handler"),!(N instanceof Response))throw new Z(`Invalid Response type from the request handler: ${typeof N}`);if(N.bodyUsed)throw new Z("The response object has already been used. Return a new response instead.");let q;if(N.headers.get(Eo)===null&&!N.webSocket&&N.status!==101){let ne=new Headers(N.headers);ne.set(Eo,r),q=new Response(N.body,{status:N.status,statusText:N.statusText,headers:ne,cf:N.cf})}else q=N;return q}catch(P){return P instanceof Z?(f.error(P),w.warn(P)):w.error(P),await yn(v,S,"Error executing handler",P)}}};function gN(t,e,n){if(ro("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(gN,"checkHandler");Function.prototype.toString=function(){return"[native code]"};var Bc=globalThis,gx=Bc.caches;if(gx){let t=gx.open;Bc.caches.open=function(e){let n=C.instance.deploymentName??C.instance.build.BUILD_ID;return t.call(this,`${n}-${e}`)},delete Bc.caches.default,Object.freeze(Bc.caches)}var hN="Error initializing gateway. Check your configuration for errors or contact support.",yN="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",_p=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)=>{C.initialize({build:this.buildEnvironment,runtime:n});try{await yI(this.runtimeInit)}catch(i){return this.handleError(i,yN,e)}return dI(s(async(i,a)=>{let c;try{c=await He.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(d){return this.handleError(d,hN,i)}let u={context:void 0};return or.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:C.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(r,null,2),{status:500,headers:{"content-type":"application/json"}})}};var Op=new re(Symbol("ai-gateway-request-analytics"));function hx(t){let e=Op.get(t);return e||(e={cacheState:null,servedFromCache:!1,similarity:null,teamId:null,appId:null},Op.set(t,e)),e}s(hx,"getOrCreateEntry");function qn(t,e,n){let o=hx(t);o.cacheState=e,n?.similarity!==void 0&&(o.similarity=n.similarity),n?.servedFromCache!==void 0&&(o.servedFromCache=n.servedFromCache)}s(qn,"recordAiGatewayCacheState");function ir(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(ir,"extractTeamAppAttribution");function $p(t,e){let{teamId:n,appId:o}=ir(e);if(n===null&&o===null)return;let r=hx(t);r.teamId=n,r.appId=o}s($p,"recordAiGatewayAttribution");function oo(t){return Op.get(t)}s(oo,"getAiGatewayRequestAnalytics");var Lp=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??C.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,n){let o=new URL(`/v1/hierarchical-quota/${e}`,this.baseUrl).toString(),r=new Headers({"Content-Type":"application/json"});We(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Ae(`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"});We(r,n.requestId);let i=await fetch(o,{method:"GET",headers:r});if(!i.ok)throw new Ae(`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"});We(i,o.requestId);let a=await fetch(r,{method:"POST",headers:i,body:JSON.stringify({increments:n})});if(!a.ok)throw new Ae(`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"});We(a,o.requestId);let c;try{c=H.getLogger(o)}catch{}let u=await ft({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 Ae(`Failed to send monetization v3 usage events: ${u.status} ${u.statusText}`)}},Mp=null,Qo={get instance(){return Mp===null&&(Mp=new Lp),Mp}};var yx=$o.object({environmentVariable:$o.string().min(1),model:$o.string().min(1),provider:$o.string().min(1)}),bx=$o.object({completions:yx.optional(),embeddings:yx.optional()});var wx=ze("zuplo:policies:AIGatewayMeteringInboundPolicy"),vx=Symbol("ai-gateway-meter-increments"),Rx=Symbol("ai-gateway-quota-fallback"),tt=class t extends pe{static{s(this,"AIGatewayMeteringInboundPolicy")}static policyType="ai-gateway-metering";static setIncrements(e,n){re.set(e,vx,n)}static getIncrements(e){return re.get(e,vx)??{}}static setQuotaFallback(e,n){re.set(e,Rx,n)}static getQuotaFallback(e){return re.get(e,Rx)}async handler(e,n){let o=Date.now(),r=H.getLogger(n),i=s((a,c)=>{if(this.options.throwOnFailure)throw new Ae(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),w=this.resolveQuotaFallback(u,f,r);if(w){let b=f?u.models[f]?.[0]:void 0,v=f?w[f]:void 0,S=b?`${b.provider}/${b.model}`:"the primary model",x=v?`${v.provider}/${v.model}`:"the configured fallback model";t.setQuotaFallback(n,w),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:v?.model,fallbackProvider:v?.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);wx(`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;wx(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,n,o){try{return await Qo.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){let r=e.quotaFallback;if(!r)return;let i=bx.safeParse(r);if(!i.success){o.error(i.error,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Invalid quotaFallback configuration; blocking instead of falling back`);return}if(!(!n||!i.data[n]))return i.data}async checkHierarchicalQuotaLimits(e,n,o){try{return await Qo.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 Qo.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 bN(t){return t>=500&&t<600?!0:t===408||t===425||t===429}s(bN,"isRetryableUpstreamStatus");function Sx(t){return t instanceof Lt?bN(t.status):t instanceof Error?t.name==="AbortError"||t.name==="TypeError":!1}s(Sx,"isRetryableError");async function Xt(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(Xt,"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 en(t,e){if(!C.instance.remoteLogURL){H.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}let n=oo(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 Cr(t,{endpoint:new URL("/v2/analytics",C.instance.remoteLogURL).toString()}).pushEvents(p)}s(en,"sendStreamAnalytics");async function kr(t,e){let n=e.userContext?.configuration?.id;n&&await tt.incrementMeters(n,{requests:1,tokens:0,costs:0},t),await en(t,{promptTokens:0,completionTokens:0,model:e.model,provider:e.provider,configId:n||"unknown",cost:0,consumerSub:e.userContext?.sub??null})}s(kr,"recordStreamUsageBaseline");function tn(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=wN(o,e,i);a!==void 0&&Ix(n,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;Ix(n,i.param,a)}}}return n}s(tn,"validateAndTransformRequest");function wN(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(wN,"getValue");function Ix(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(Ix,"setNestedProperty");var vN=["authorization","proxy-authorization","cookie","cookie2","set-cookie","x-api-key","content-type","content-length","content-encoding","accept-encoding","connection","transfer-encoding","host"];function xx(t,e){let n=new Headers(t),o=n.get("anthropic-version");for(let r of vN)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(xx,"buildAnthropicPassthroughHeaders");var Tx={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}},Vc=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=tn(Tx,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 Xt(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=tn(Tx,{...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 v=await Xt(a,S=>S.error?.message);throw new Lt("anthropic",a.status,v)}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((v,S)=>{let x=`data: ${JSON.stringify(v)}
|
|
244
244
|
|
|
245
245
|
`;S.enqueue(u.encode(x))},"enqueueChunk"),g=s((v=!1)=>{let S=new TextDecoder,x="",T=0,P=0,N="",q=s((ne,V=null,ie)=>({id:N,object:"chat.completion.chunk",created:d,model:e.model,choices:[{index:0,delta:ne,finish_reason:V}],...ie&&{usage:ie}}),"createOpenAIChunk");return new TransformStream({transform(ne,V){x+=S.decode(ne,{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"),A=R,E="",O="";this.entityExpansionCount=0,this.currentExpandedLength=0;let _=new w(this.options.processEntities);for(let F=0;F<y.length;F++)if(y[F]==="<")if(y[F+1]==="/"){let J=fn(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)),A&&(E=this.saveTextToParentTag(E,A,O));let Le=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;Le&&this.options.unpairedTags.indexOf(Le)!==-1?(ye=O.lastIndexOf(".",O.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ye=O.lastIndexOf("."),O=O.substring(0,ye),A=this.tagsNodeStack.pop(),E="",F=J}else if(y[F+1]==="?"){let J=Rr(y,F,!1,"?>");if(!J)throw new Error("Pi Tag is not closed.");if(E=this.saveTextToParentTag(E,A,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(A,G,O,F)}F=J.closeIndex+1}else if(y.substr(F+1,3)==="!--"){let J=fn(y,"-->",F+4,"Comment is not closed.");if(this.options.commentPropName){let G=y.substring(F+4,J-2);E=this.saveTextToParentTag(E,A,O),A.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=fn(y,"]]>",F,"CDATA is not closed.")-2,G=y.substring(F+9,J);E=this.saveTextToParentTag(E,A,O);let Le=this.parseTextData(G,A.tagname,O,!0,!1,!0,!0);Le==null&&(Le=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:G}]):A.add(this.options.textNodeName,Le),F=J+2}else{let J=Rr(y,F,this.options.removeNSPrefix),G=J.tagName,Le=J.rawTagName,ye=J.tagExp,zt=J.attrExpPresent,BR=J.closeIndex;if(this.options.transformTagName){let jt=this.options.transformTagName(G);ye===G&&(ye=jt),G=jt}A&&E&&A.tagname!=="!xml"&&(E=this.saveTextToParentTag(E,A,O,!1));let VR=A;VR&&this.options.unpairedTags.indexOf(VR.tagname)!==-1&&(A=this.tagsNodeStack.pop(),O=O.substring(0,O.lastIndexOf("."))),G!==R.tagname&&(O+=O?"."+G:G);let Td=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 Cd=this.readStopNodeData(y,Le,BR+1);if(!Cd)throw new Error(`Unexpected end of ${Le}`);F=Cd.i,jt=Cd.tagContent}let ko=new f(G);G!==ye&&zt&&(ko[":@"]=this.buildAttributesMap(ye,O,G)),jt&&(jt=this.parseTextData(jt,G,O,!0,zt,!0,!0)),O=O.substr(0,O.lastIndexOf(".")),ko.add(this.options.textNodeName,jt),this.addChild(A,ko,O,Td)}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 ko=this.options.transformTagName(G);ye===G&&(ye=ko),G=ko}let jt=new f(G);G!==ye&&zt&&(jt[":@"]=this.buildAttributesMap(ye,O,G)),this.addChild(A,jt,O,Td),O=O.substr(0,O.lastIndexOf("."))}else{let jt=new f(G);this.tagsNodeStack.push(A),G!==ye&&zt&&(jt[":@"]=this.buildAttributesMap(ye,O,G)),this.addChild(A,jt,O,Td),A=jt}E="",F=BR}}else E+=y[F];return R.child},"parseXml");function Ce(y,R,A,E){this.options.captureMetaData||(E=void 0);let O=this.options.updateTag(R.tagname,A,R[":@"]);O===!1||(typeof O=="string"&&(R.tagname=O),y.addChild(R,E))}s(Ce,"addChild"),n(Ce,"addChild");var Ne=n(function(y,R,A){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,A))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 de=y.length;if(y=y.replace(_.regx,_.val),E.maxExpandedLength&&(this.currentExpandedLength+=y.length-de,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,A,E){return y&&(E===void 0&&(E=R.child.length===0),y=this.parseTextData(y,R.tagname,A,!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 Ct(y,R,A,E){return!!(R&&R.has(E)||y&&y.has(A))}s(Ct,"isItStopNode"),n(Ct,"isItStopNode");function Dn(y,R,A=">"){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===A[0])if(A[1]){if(y[_+1]===A[1])return{data:O,index:_}}else return{data:O,index:_};else F===" "&&(F=" ");O+=F}}s(Dn,"tagExpWithClosingIndex"),n(Dn,"tagExpWithClosingIndex");function fn(y,R,A,E){let O=y.indexOf(R,A);if(O===-1)throw new Error(E);return O+R.length-1}s(fn,"findClosingIndex"),n(fn,"findClosingIndex");function Rr(y,R,A,E=">"){let O=Dn(y,R+1,E);if(!O)return;let _=O.data,F=O.index,de=_.search(/\s/),J=_,G=!0;de!==-1&&(J=_.substring(0,de),_=_.substring(de+1).trimStart());let Le=J;if(A){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:Le}}s(Rr,"readTagExp"),n(Rr,"readTagExp");function Ao(y,R,A){let E=A,O=1;for(;A<y.length;A++)if(y[A]==="<")if(y[A+1]==="/"){let _=fn(y,">",A,`${R} is not closed`);if(y.substring(A+2,_).trim()===R&&(O--,O===0))return{tagContent:y.substring(E,A),i:_};A=_}else if(y[A+1]==="?")A=fn(y,"?>",A+1,"StopNode is not closed.");else if(y.substr(A+1,3)==="!--")A=fn(y,"-->",A+3,"StopNode is not closed.");else if(y.substr(A+1,2)==="![")A=fn(y,"]]>",A,"StopNode is not closed.")-2;else{let _=Rr(y,A,">");_&&((_&&_.tagName)===R&&_.tagExp[_.tagExp.length-1]!=="/"&&O++,A=_.closeIndex)}}s(Ao,"readStopNodeData"),n(Ao,"readStopNodeData");function Ga(y,R,A){if(R&&typeof y=="string"){let E=y.trim();return E==="true"?!0:E==="false"?!1:N(y,A)}else return g(y)?y:""}s(Ga,"parseValue"),n(Ga,"parseValue");function bd(y,R,A){let E=Number.parseInt(y,R);return E>=0&&E<=1114111?String.fromCodePoint(E):A+y+";"}s(bd,"fromCodePoint"),n(bd,"fromCodePoint");var wd=f.getMetaDataSymbol();function DR(y,R){return vd(y,R)}s(DR,"prettify"),n(DR,"prettify");function vd(y,R,A){let E,O={};for(let _=0;_<y.length;_++){let F=y[_],de=UR(F),J="";if(A===void 0?J=de:J=A+"."+de,de===R.textNodeName)E===void 0?E=F[de]:E+=""+F[de];else{if(de===void 0)continue;if(F[de]){let G=vd(F[de],R,J),Le=jR(G,R);F[wd]!==void 0&&(G[wd]=F[wd]),F[":@"]?zR(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[de]!==void 0&&O.hasOwnProperty(de)?(Array.isArray(O[de])||(O[de]=[O[de]]),O[de].push(G)):R.isArray(de,J,Le)?O[de]=[G]:O[de]=G}}}return typeof E=="string"?E.length>0&&(O[R.textNodeName]=E):E!==void 0&&(O[R.textNodeName]=E),O}s(vd,"compress"),n(vd,"compress");function UR(y){let R=Object.keys(y);for(let A=0;A<R.length;A++){let E=R[A];if(E!==":@")return E}}s(UR,"propName"),n(UR,"propName");function zR(y,R,A,E){if(R){let O=Object.keys(R),_=O.length;for(let F=0;F<_;F++){let de=O[F];E.isArray(de,A+"."+de,!0,!0)?y[de]=[R[de]]:y[de]=R[de]}}}s(zR,"assignAttributes"),n(zR,"assignAttributes");function jR(y,R){let{textNodeName:A}=R,E=Object.keys(y).length;return!!(E===0||E===1&&(y[A]||typeof y[A]=="boolean"||y[A]===0))}s(jR,"isLeafTag"),n(jR,"isLeafTag");var z0={allowBooleanAttributes:!1,unpairedTags:[]};function qR(y,R){R=Object.assign({},z0,R);let A=[],E=!1,O=!1;y[0]==="\uFEFF"&&(y=y.substr(1));for(let _=0;_<y.length;_++)if(y[_]==="<"&&y[_+1]==="?"){if(_+=2,_=Sd(y,_),_.err)return _}else if(y[_]==="<"){let F=_;if(_++,y[_]==="!"){_=Id(y,_);continue}else{let de=!1;y[_]==="/"&&(de=!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),_--),!L(J)){let ye;return J.trim().length===0?ye="Invalid space after '<'.":ye="Tag '"+J+"' is an invalid name.",dt("InvalidTag",ye,Mt(y,_))}let G=ZR(y,_);if(G===!1)return dt("InvalidAttr","Attributes for '"+J+"' have open quote.",Mt(y,_));let Le=G.value;if(_=G.index,Le[Le.length-1]==="/"){let ye=_-Le.length;Le=Le.substring(0,Le.length-1);let zt=xd(Le,R);if(zt===!0)E=!0;else return dt(zt.err.code,zt.err.msg,Mt(y,ye+zt.err.line))}else if(de)if(G.tagClosed){if(Le.trim().length>0)return dt("InvalidTag","Closing tag '"+J+"' can't have attributes or invalid starting.",Mt(y,F));if(A.length===0)return dt("InvalidTag","Closing tag '"+J+"' has not been opened.",Mt(y,F));{let ye=A.pop();if(J!==ye.tagName){let zt=Mt(y,ye.tagStartPos);return dt("InvalidTag","Expected closing tag '"+ye.tagName+"' (opened in line "+zt.line+", col "+zt.col+") instead of closing tag '"+J+"'.",Mt(y,F))}A.length==0&&(O=!0)}}else return dt("InvalidTag","Closing tag '"+J+"' doesn't have proper closing.",Mt(y,_));else{let ye=xd(Le,R);if(ye!==!0)return dt(ye.err.code,ye.err.msg,Mt(y,_-Le.length+ye.err.line));if(O===!0)return dt("InvalidXml","Multiple possible root nodes found.",Mt(y,_));R.unpairedTags.indexOf(J)!==-1||A.push({tagName:J,tagStartPos:F}),E=!0}for(_++;_<y.length;_++)if(y[_]==="<")if(y[_+1]==="!"){_++,_=Id(y,_);continue}else if(y[_+1]==="?"){if(_=Sd(y,++_),_.err)return _}else break;else if(y[_]==="&"){let ye=FR(y,_);if(ye==-1)return dt("InvalidChar","char '&' is not expected.",Mt(y,_));_=ye}else if(O===!0&&!Rd(y[_]))return dt("InvalidXml","Extra text at the end",Mt(y,_));y[_]==="<"&&_--}}else{if(Rd(y[_]))continue;return dt("InvalidChar","char '"+y[_]+"' is not expected.",Mt(y,_))}if(E){if(A.length==1)return dt("InvalidTag","Unclosed tag '"+A[0].tagName+"'.",Mt(y,A[0].tagStartPos));if(A.length>0)return dt("InvalidXml","Invalid '"+JSON.stringify(A.map(_=>_.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return dt("InvalidXml","Start tag expected.",1);return!0}s(qR,"validate"),n(qR,"validate");function Rd(y){return y===" "||y===" "||y===`
|
|
383
383
|
`||y==="\r"}s(Rd,"isWhiteSpace"),n(Rd,"isWhiteSpace");function Sd(y,R){let A=R;for(;R<y.length;R++)if(y[R]=="?"||y[R]==" "){let E=y.substr(A,R-A);if(R>5&&E==="xml")return dt("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(Sd,"readPI"),n(Sd,"readPI");function Id(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 A=1;for(R+=8;R<y.length;R++)if(y[R]==="<")A++;else if(y[R]===">"&&(A--,A===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(Id,"readCommentAndCDATA"),n(Id,"readCommentAndCDATA");var j0='"',q0="'";function ZR(y,R){let A="",E="",O=!1;for(;R<y.length;R++){if(y[R]===j0||y[R]===q0)E===""?E=y[R]:E!==y[R]||(E="");else if(y[R]===">"&&E===""){O=!0;break}A+=y[R]}return E!==""?!1:{value:A,index:R,tagClosed:O}}s(ZR,"readAttributeStr"),n(ZR,"readAttributeStr");var Z0=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function xd(y,R){let A=p(y,Z0),E={};for(let O=0;O<A.length;O++){if(A[O][1].length===0)return dt("InvalidAttr","Attribute '"+A[O][2]+"' has no space in starting.",Po(A[O]));if(A[O][3]!==void 0&&A[O][4]===void 0)return dt("InvalidAttr","Attribute '"+A[O][2]+"' is without value.",Po(A[O]));if(A[O][3]===void 0&&!R.allowBooleanAttributes)return dt("InvalidAttr","boolean attribute '"+A[O][2]+"' is not allowed.",Po(A[O]));let _=A[O][2];if(!GR(_))return dt("InvalidAttr","Attribute '"+_+"' is an invalid name.",Po(A[O]));if(!E.hasOwnProperty(_))E[_]=1;else return dt("InvalidAttr","Attribute '"+_+"' is repeated.",Po(A[O]))}return!0}s(xd,"validateAttributeString"),n(xd,"validateAttributeString");function HR(y,R){let A=/\d/;for(y[R]==="x"&&(R++,A=/[\da-fA-F]/);R<y.length;R++){if(y[R]===";")return R;if(!y[R].match(A))break}return-1}s(HR,"validateNumberAmpersand"),n(HR,"validateNumberAmpersand");function FR(y,R){if(R++,y[R]===";")return-1;if(y[R]==="#")return R++,HR(y,R);let A=0;for(;R<y.length;R++,A++)if(!(y[R].match(/\w/)&&A<20)){if(y[R]===";")break;return-1}return R}s(FR,"validateAmpersand"),n(FR,"validateAmpersand");function dt(y,R,A){return{err:{code:y,msg:R,line:A.line||A,col:A.col}}}s(dt,"getErrorObject"),n(dt,"getErrorObject");function GR(y){return m(y)}s(GR,"validateAttrName"),n(GR,"validateAttrName");function L(y){return m(y)}s(L,"validateTagName"),n(L,"validateTagName");function Mt(y,R){let A=y.substring(0,R).split(/\r?\n/);return{line:A.length,col:A[A.length-1].length+1}}s(Mt,"getLineNumberForPosition"),n(Mt,"getLineNumberForPosition");function Po(y){return y.startIndex+y[1].length}s(Po,"getPositionFromMatch"),n(Po,"getPositionFromMatch");var H0=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=qR(y,R);if(O!==!0)throw Error(`${O.err.msg}:${O.err.line}:${O.err.col}`)}let A=new Oe(this.options);A.addExternalEntities(this.externalEntities);let E=A.parseXml(y);return this.options.preserveOrder||E===void 0?E:DR(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 H0(t)},"getXmlParser");var MR=class extends xr{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?jn(e.parseOnStatusCodes):void 0,this.parser=_0({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 LR=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new Ae(`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 NR=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=De("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){B("utility.get-consumer");let n=no(),o=this.bucketId??je.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 Ue(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 Ld(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 O0=10,$0=3e4,ha=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=$0,this.#n=O0}else{let o=n;this.#r=o.ttlSeconds*1e3,this.#o=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:$0,this.#n=O0}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 $V(()=>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);Pr().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 $V(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($V,"waitUntilTrue");import{SpanStatusCode as M0,trace as L0}from"@opentelemetry/api";var N0=s(async(t,e,n)=>{let o=He.instance.routeData.policies,r=Fo([t],o);if(r.length===0)throw new Z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=r[0];return await L0.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{Ho(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:M0.ERROR}),u.recordException(p),p}}finally{u.end()}})},"invokeInboundPolicy"),D0=s(async(t,e,n,o)=>{let r=He.instance.routeData.policies,i=ss([t],r);if(i.length===0)throw new Z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=i[0];return await L0.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async d=>{try{Ho(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:M0.ERROR}),d.recordException(m),m}}finally{d.end()}})},"invokeOutboundPolicy");function MV(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[Qa]=o.asnum),o.zip&&(e[Xa]=o.zip.split("+")[0]),o.dma&&(e[ec]=o.dma),o.region_code&&(e[tc]=o.region_code),o.timezone&&(e[nc]=o.timezone),o.city&&(e[Va]=o.city),o.continent&&(e[Ja]=o.continent),o.country_code&&(e[Wa]=o.country_code),o.long&&(e[Ka]=o.long),o.lat&&(e[Ya]=o.lat),e}catch{return{}}}s(MV,"parseEdgeScapeHeader");function U0(t,e){let n=MV(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}s(U0,"setZpHeadersFromAkamaiEdgeScapeHeader");var Fc=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(SS);if(n){let o=new Headers(e);U0(o,n),this.#e=o}}get asn(){try{let e=this.#e.get(Qa);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(yS)??void 0}get city(){return this.#e.get(XR)??this.#e.get(Va)??void 0}get continent(){return this.#e.get(eS)??this.#e.get(Ja)??void 0}get country(){return this.#e.get(tS)??this.#e.get(Wa)??void 0}get latitude(){return this.#e.get(rS)??this.#e.get(Ya)??void 0}get longitude(){return this.#e.get(nS)??this.#e.get(Ka)??void 0}get colo(){return this.#e.get(bS)??void 0}get postalCode(){return this.#e.get(aS)??this.#e.get(Xa)??void 0}get metroCode(){return this.#e.get(sS)??this.#e.get(ec)??void 0}get region(){return this.#e.get(oS)??this.#e.get(wS)??void 0}get regionCode(){return this.#e.get(iS)??this.#e.get(tc)??void 0}get timezone(){return this.#e.get(cS)??this.#e.get(nc)??void 0}get httpProtocol(){return this.#e.get(vS)??void 0}get clientCert(){return this.#e.get(uS)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(lS)??void 0}get clientMtlsVerificationReason(){return this.#e.get(dS)??void 0}get clientCertFingerprintSha256(){return this.#e.get(pS)??void 0}get clientCertNotBefore(){return this.#e.get(mS)??void 0}get clientCertNotAfter(){return this.#e.get(fS)??void 0}get clientCertIssuerDn(){return this.#e.get(gS)??void 0}get clientCertSubjectDn(){return this.#e.get(hS)??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 rs=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},os=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=C.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")},Gc=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)=>N0(u,d,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,d,p)=>D0(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 He.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 AS(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{ac as a,$d as b,ht as c,eM as d,tM as e,Md as f,ct as g,Br as h,nM as i,Vr as j,B as k,Ld as l,Dd as m,Yt as n,Sr as o,Yi as p,Jr as q,$ as r,pt as s,Wr as t,zd as u,jd as v,be as w,Gt as x,pe as y,xr as z,Vd as A,Qd as B,AM as C,Uo as D,rs as E,os as F,_p as G,tt as H,Dx as I,Ux as J,GN as K,Fx as L,Zp as M,eD as N,Hp as O,M as P,VU as Q,qe as R,vt as S,wz as T,$e as U,se as V,Nt as W,fe as X,Uz as Y,xy as Z,l as _,Re as $,ZA as aa,HA as ba,FA as ca,GA as da,BA as ea,VA as fa,JA as ga,YA as ha,Wy 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,Tb as va,pa as wa,ma as xa,fa as ya,Eb as za,ya as Aa,$b as Ba,Mb as Ca,Gq as Da,Lb as Ea,Nb as Fa,dP as Ga,pP as Ha,Ub as Ia,wP as Ja,IP as Ka,xP as La,_P as Ma,OP as Na,$P as Oa,MP as Pa,zP as Qa,jP as Ra,Xb as Sa,HP as Ta,Ml as Ua,zZ as Va,ew as Wa,Dt as Xa,YP as Ya,iw as Za,sw as _a,ek as $a,uw as ab,nk as bb,rk as cb,ok as db,ik as eb,sk as fb,ak as gb,mk as hb,yk as ib,yw as jb,vk as kb,Rk as lb,Sk as mb,$k as nb,Mk as ob,Lk as pb,Nk as qb,qk as rb,Bk as sb,Vk as tb,Hl as ub,X1 as vb,Yk as wb,Xk as xb,eE as yb,Zr as zb,Mi as Ab,Ge as Bb,at as Cb,Kn as Db,ESe as Eb,Pa as Fb,MSe as Gb,LSe as Hb,dn as Ib,USe as Jb,zSe as Kb,jSe as Lb,qSe as Mb,ka as Nb,ZSe as Ob,So as Pb,VSe as Qb,Vl as Rb,Io as Sb,Ni as Tb,Kw as Ub,iIe as Vb,Yw as Wb,Qw as Xb,Xw as Yb,ev as Zb,tv as _b,nv as $b,rv as ac,ov as bc,iv as cc,sv as dc,av as ec,iTe as fc,Sn as gc,pn as hc,GE as ic,ed as jc,dF as kc,Ql as lc,WE as mc,DG as nc,uv as oc,mt as pc,h_ as qc,XG as rc,eB as sc,yv as tc,DTe as uc,UTe as vc,zTe as wc,E_ as xc,__ as yc,aCe as zc,cCe as Ac,bv as Bc,Na as Cc,od as Dc,uCe as Ec,M_ as Fc,mCe as Gc,Da as Hc,vB as Ic,RB as Jc,vv as Kc,SCe as Lc,U_ as Mc,z_ as Nc,CCe as Oc,ACe as Pc,PCe as Qc,kCe as Rc,j_ as Sc,q_ as Tc,H_ as Uc,Yn as Vc,vr as Wc,xB as Xc,TB as Yc,DCe as Zc,UCe as _c,zCe as $c,jCe as ad,Qn as bd,kB as cd,QCe as dd,B_ as ed,uAe as fd,xv as gd,_B as hd,zB as id,qB as jd,W_ as kd,xAe as ld,TAe as md,CAe as nd,X_ as od,EAe as pd,_Ae as qd,OAe as rd,Ev as sd,cd as td,_v as ud,qAe as vd,ZAe as wd,HAe as xd,FAe as yd,WO as zd,Tn as Ad,Gv as Bd,SPe as Cd,KO as Dd,IPe as Ed,Wv as Fd,Kv as Gd,t$ as Hd,x4 as Id,s$ as Jd,nR as Kd,h$ as Ld,oR as Md,T$ as Nd,iR as Od,aR as Pd,A$ as Qd,P$ as Rd,k$ as Sd,lR as Td,pR as Ud,N$ as Vd,D$ as Wd,U$ as Xd,z$ as Yd,j$ as Zd,Z$ as _d,gR as $d,G4 as ae,V$ as be,wR as ce,X$ as de,e0 as ee,t0 as fe,oV as ge,n0 as he,r0 as ie,o0 as je,i0 as ke,s0 as le,IR as me,c0 as ne,u0 as oe,xR as pe,TR as qe,p0 as re,f0 as se,g0 as te,PR as ue,y0 as ve,I0 as we,OR as xe,x0 as ye,E0 as ze,MR as Ae,LR as Be,NR as Ce,ha as De};
|
|
384
|
-
/*! For license information please see chunk-
|
|
385
|
-
//# sourceMappingURL=chunk-
|
|
384
|
+
/*! For license information please see chunk-7Z5GGYF5.js.LEGAL.txt */
|
|
385
|
+
//# sourceMappingURL=chunk-7Z5GGYF5.js.map
|