@zuplo/cli 7.0.1 → 7.0.2

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.
@@ -260,7 +260,7 @@ data:
260
260
  `;return o&&(r+=`id: ${o}
261
261
  `),r+=`data: ${JSON.stringify(n)}
262
262
 
263
- `,t.enqueue(e.encode(r)),!0}catch(r){return this.onerror?.(r),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,e){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!_v(t.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o=t,r;if(e?.parsedBody===void 0)try{r=await t.json()}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=e.parsedBody;let s;try{s=Array.isArray(r)?r.map(R=>mi.parse(R)):[mi.parse(r)]}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=s.some(R=>Hf(R));if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let R=this.validateSession(t);if(R)return R;let w=this.validateProtocolVersion(t);if(w)return w}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!s.some(R=>Ks(R))){for(let R of s)this.onmessage?.(R,{authInfo:e?.authInfo,request:o});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=s.find(R=>Hf(R)),l=u?u.params.protocolVersion:t.headers.get("mcp-protocol-version")??up;if(this._enableJsonResponse)return new Promise(R=>{this._streamMapping.set(c,{resolveJson:R,cleanup:i(()=>{this._streamMapping.delete(c)},"cleanup")});for(let w of s)Ks(w)&&this._requestToStreamMapping.set(w.id,c);for(let w of s)this.onmessage?.(w,{authInfo:e?.authInfo,request:o})});let d=new TextEncoder,m,f,b=new ReadableStream({start:i(R=>{m=R},"start"),cancel:i(()=>{f!==void 0&&clearInterval(f),this._streamMapping.get(c)?.controller===m&&this._streamMapping.delete(c)},"cancel")}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(g["mcp-session-id"]=this.sessionId);for(let R of s)Ks(R)&&(this._streamMapping.set(c,{controller:m,encoder:d,cleanup:i(()=>{f!==void 0&&clearInterval(f),this._streamMapping.delete(c);try{m.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(R.id,c));await this.writePrimingEvent(m,d,c,l);for(let R of s){let w,C;Ks(R)&&this._eventStore&&this.supportsEmptySSEData(l)&&(w=i(()=>{this.closeSSEStream(R.id)},"closeSSEStream"),C=i(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(R,{authInfo:e?.authInfo,request:o,closeSSEStream:w,closeStandaloneSSEStream:C})}return this._streamMapping.get(c)?.controller===m&&(f=this.startKeepAlive(m,d)),new Response(b,{status:200,headers:g})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let e=this.validateSession(t);if(e)return e;let n=this.validateProtocolVersion(t);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let e=t.headers.get("mcp-session-id");if(!e)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(e!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let e=t.headers.get("mcp-protocol-version");if(e!==null&&!this._supportedProtocolVersions.includes(e)){let n=`Bad Request: Unsupported protocol version: ${e} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(400,-32e3,n)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:t}of this._streamMapping.values())t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let e=this._requestToStreamMapping.get(t);if(!e)return;let n=this._streamMapping.get(e);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,e){let n=e?.relatedRequestId;if((Js(t)||Wu(t))&&(n=t.id),n===void 0){if(Js(t)||Wu(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(s===void 0||!a.replayedEventIds?.has(s))&&this.writeSSEEvent(a.controller,a.encoder,t,s);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let r=this._streamMapping.get(o);if(!this._enableJsonResponse){let s;this._eventStore&&(s=await this._eventStore.storeEvent(o,t),r=this._streamMapping.get(o)),r?.controller&&r?.encoder&&(s===void 0||!r.replayedEventIds?.has(s))&&this.writeSSEEvent(r.controller,r.encoder,t,s)}if(Js(t)||Wu(t)){this._requestResponseMap.set(n,t);let s=[...this._requestToStreamMapping.entries()].filter(([a,c])=>c===o).map(([a])=>a);if(s.every(a=>this._requestResponseMap.has(a))){if(!r){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(this._enableJsonResponse&&r.resolveJson){let a={"Content-Type":"application/json"};this.sessionId!==void 0&&(a["mcp-session-id"]=this.sessionId);let c=s.map(u=>this._requestResponseMap.get(u));c.length===1?r.resolveJson(Response.json(c[0],{status:200,headers:a})):r.resolveJson(Response.json(c,{status:200,headers:a})),r.cleanup()}else r.cleanup();for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a)}}}};var Dv=2,Wf=4,Uv=24,jv=16,Yf=512,b$=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,S$=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,R$=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,w$=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,C$=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,I$=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Hv(t){let e=t.route;return e&&typeof e=="object"?e:void 0}i(Hv,"readRoute");function v$(t){let e=Hv(t)?.path;return typeof e=="string"&&e.length>0?e:void 0}i(v$,"readRoutePath");function T$(t){let e=Hv(t)?.raw;if(typeof e!="function")return;let n=e();if(!n||typeof n!="object")return;let o=n.operationId;return typeof o=="string"&&o.length>0?o:void 0}i(T$,"readRouteOperationId");function Fv(t){if(!(t===void 0||!Number.isFinite(t)||t<100))return`${Math.trunc(t/100)}xx`}i(Fv,"deriveStatusClass");function Gv(t,e){if(!(!t&&!e))return t==="user"?e==="user-oauth"?"upstream_user_attributed":"gateway_user_attributed_only":t==="shared"?"shared_upstream_identity":t==="none"?"machine_identity":"unknown"}i(Gv,"deriveOriginAttributionMode");function Zv(t){if(!t)return;let e=t.toLowerCase();return e.includes("desktop")||e.includes("claude")||e.includes("chatgpt")?"desktop":e.includes("vscode")||e.includes("cursor")||e.includes("zed")||e.includes("jetbrains")||e.includes("ide")?"ide":e.includes("extension")?"extension":e.includes("agent")||e.includes("bot")||e.includes("worker")||e.includes("service")?"service":"unknown"}i(Zv,"deriveClientKind");function Bv(t,e){return e==="success"?"none":t===ee.MCP_REQUEST_RECEIVED||t===ee.MCP_REQUEST_REJECTED||t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_INITIALIZE_NEGOTIATED?"routing":t.startsWith("mcp_capability_")?"upstream":t===ee.MCP_REQUEST_COMPLETED?"egress":"none"}i(Bv,"deriveFailureStage");function Vv(t,e){return e==="success"?"none":e==="application_error"?"mcp_application":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_CAPABILITY_FAILED||t===ee.MCP_CAPABILITY_CONNECT_REQUIRED?"upstream":t===ee.MCP_REQUEST_REJECTED||t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}i(Vv,"deriveFailureOrigin");function Jv(t,e){return e==="success"?"none":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR||t===ee.MCP_REQUEST_REJECTED?"protocol":"none"}i(Jv,"deriveReasonClass");function P$(t){return t.length<=Yf?t:`${t.slice(0,Yf)}...`}i(P$,"truncateAnalyticsString");function A$(t){return P$(t.replace(S$,"$1[REDACTED]$3").replace(w$,"$1$2[REDACTED]").replace(R$,"$1$2[REDACTED]").replace(C$,"Bearer [REDACTED]").replace(I$,"Basic [REDACTED]"))}i(A$,"redactAnalyticsString");function Kv(t,e){if(t!==void 0){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return A$(t);if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return e>=Wf?"[DEPTH_LIMIT]":t.slice(0,jv).map(n=>Kv(n,e+1)).filter(n=>n!==void 0);if(typeof t=="object")return t instanceof Date?t.toISOString():e>=Wf?"[DEPTH_LIMIT]":Qf(t,e+1)}}i(Kv,"sanitizeAnalyticsValue");function Qf(t,e=0){if(!t)return;let n={};for(let[o,r]of Object.entries(t).slice(0,Uv)){if(b$.test(o)){n[o]="[REDACTED]";continue}let s=Kv(r,e);s!==void 0&&(n[o]=s)}return Object.keys(n).length===0?void 0:n}i(Qf,"sanitizeMcpAnalyticsAttributes");function Re(t){return t===void 0?null:t}i(Re,"nullable");function E$(t){let e=t.environment;return e&&typeof e=="object"&&typeof e.name=="string"?e.name:null}i(E$,"readEnvironment");function O$(t){let e=t.requestId;return typeof e=="string"&&e.length>0?e:null}i(O$,"readRequestId");function k$(t){if(t===void 0)return null;try{return JSON.stringify(t)}catch{return null}}i(k$,"attributesToJsonString");function Xf(t,e){let n=Qf(e.attributes),o=O$(t),r=e.ownerMode??null,s=e.upstreamAuthMode??null,a=e.clientKind??Zv(e.clientName)??null,c=Gv(r??void 0,s??void 0)??null,u=Fv(e.httpStatusCode)??null,l=e.reasonClass??Jv(e.eventType,e.outcome),d=e.failureOrigin??Vv(e.eventType,e.outcome),m=e.failureStage??Bv(e.eventType,e.outcome);return{schemaVersion:Dv,outcome:e.outcome,subjectId:Re(e.subjectId),environment:E$(t),traceId:e.traceId??o,spanId:Re(e.spanId),parentEventId:Re(e.parentEventId),mcpSessionId:Re(e.mcpSessionId),routeSurface:Re(e.routeSurface),routePath:e.routePath??v$(t)??null,operationId:e.operationId??T$(t)??null,virtualServerName:Re(e.virtualServerName),virtualServerTitle:Re(e.virtualServerTitle),upstreamServerName:Re(e.upstreamServerName),upstreamServerTitle:Re(e.upstreamServerTitle),upstreamBindingId:Re(e.upstreamBindingId),clientName:Re(e.clientName),clientTitle:Re(e.clientTitle),clientVersion:Re(e.clientVersion),clientKind:a,authProfileId:Re(e.authProfileId),upstreamAuthMode:s,ownerMode:r,authMethod:Re(e.authMethod),originAttributionMode:c,apiKeySub:Re(e.apiKeySub),httpMethod:Re(e.httpMethod),httpStatusCode:Re(e.httpStatusCode),statusClass:u,mcpMethod:Re(e.mcpMethod),mcpProtocolVersion:Re(e.mcpProtocolVersion),mcpStatus:Re(e.mcpStatus),mcpErrorType:Re(e.mcpErrorType),applicationError:Re(e.applicationError),applicationErrorCode:Re(e.applicationErrorCode),toolResultIsError:Re(e.toolResultIsError),transport:Re(e.transport),sessionId:Re(e.sessionId),capabilityType:Re(e.capabilityType),capabilityName:Re(e.capabilityName),capabilityTitle:Re(e.capabilityTitle),upstreamCapabilityName:Re(e.upstreamCapabilityName),upstreamCapabilityTitle:Re(e.upstreamCapabilityTitle),capabilitySchemaHash:Re(e.capabilitySchemaHash),toolPath:Re(e.toolPath),toolMethod:Re(e.toolMethod),toolOperationId:Re(e.toolOperationId),resourceUri:Re(e.resourceUri),resourceMimeType:Re(e.resourceMimeType),policyId:Re(e.policyId),policyAction:Re(e.policyAction),guardrailType:Re(e.guardrailType),guardrailDirection:Re(e.guardrailDirection),guardrailFindingCount:Re(e.guardrailFindingCount),redactionCount:Re(e.redactionCount),requestMutated:Re(e.requestMutated),responseMutated:Re(e.responseMutated),latencyMs:Re(e.latencyMs),gatewayLatencyMs:Re(e.gatewayLatencyMs),upstreamLatencyMs:Re(e.upstreamLatencyMs),authLatencyMs:Re(e.authLatencyMs),policyLatencyMs:Re(e.policyLatencyMs),requestBytes:Re(e.requestBytes),responseBytes:Re(e.responseBytes),estimatedInputTokens:Re(e.estimatedInputTokens),estimatedOutputTokens:Re(e.estimatedOutputTokens),estimatedContextTokens:Re(e.estimatedContextTokens),contextPressureBucket:Re(e.contextPressureBucket),responseMimeTypes:Re(e.responseMimeTypes),base64Suspected:Re(e.base64Suspected),truncated:Re(e.truncated),isLargePayloadRequest:Re(e.isLargePayloadRequest),isLargePayloadResponse:Re(e.isLargePayloadResponse),payloadCaptureMode:Re(e.payloadCaptureMode),reasonCode:Re(e.reasonCode),reasonClass:l,errorType:e.errorType??e.reasonCode??null,failureOrigin:d,failureStage:m,errorCode:Re(e.errorCode),customMetadataJson:Re(e.customMetadataJson),attributesJson:k$(n)}}i(Xf,"buildMcpAnalyticsMetadata");function Wv(t,e){try{t.analyticsContext.addAnalyticsEvent(e.value??1,e.eventType,Xf(t,e),e.unit)}catch(n){t.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:n instanceof Error?n.name:"unknown"})}}i(Wv,"emitMcpAnalyticsEvent");function Yp(t,e){if(!t||typeof t!="object")return;let n=t[e];return typeof n=="string"?n:void 0}i(Yp,"readStringProperty");function Yv(t){let e=Yp(t,"method");if(!e)return;let n=t&&typeof t=="object"?t.params:void 0;switch(e){case"tools/call":return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"tool",capabilityName:Yp(n,"name"),mcpMethod:"tools/call"};case"prompts/get":return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"prompt",capabilityName:Yp(n,"name"),mcpMethod:"prompts/get"};case"resources/read":{let o=Yp(n,"uri");return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"resource",capabilityName:o,resourceUri:o,mcpMethod:"resources/read"}}default:return}}i(Yv,"buildCapabilityInvokedAnalyticsInput");var xr=class{constructor(e,n){this.schema=e;this.validateFn=n}schema;validateFn;static{i(this,"CustomValidator")}validate(e){return this.validateFn(e)}};function Qv(t,e){let n=t.virtualServerName??e;return n===void 0?t:{...t,virtualServerName:n}}i(Qv,"injectMcpServerName");import{AsyncLocalStorage as _$}from"node:async_hooks";var Qp=new _$;function Xv(t,e,n){return Qp.run({zuploContext:t,requestData:e},n)}i(Xv,"runWithInvokeContext");function eg(){return Qp.getStore()?.requestData.headers??{}}i(eg,"getInvokeHeaders");function Ws(){let t=Qp.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}i(Ws,"getInvokeContext");function eT(){return Qp.getStore()?.requestData.user?.sub}i(eT,"getInvokeSubjectId");var tl=class{static{i(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,n,o,r,s){this.type=t,this.name=e,this.prefix=n,this.value=o,this.suffix=r,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},x$=/[$_\p{ID_Start}]/u,M$=/[$_\u200C\u200D\p{ID_Continue}]/u,ng=".*";function L$(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}i(L$,"Re");function oT(t,e=!1){let n=[],o=0;for(;o<t.length;){let r=t[o],s=i(function(a){if(!e)throw new TypeError(a);n.push({type:"INVALID_CHAR",index:o,value:t[o++]})},"c");if(r==="*"){n.push({type:"ASTERISK",index:o,value:t[o++]});continue}if(r==="+"||r==="?"){n.push({type:"OTHER_MODIFIER",index:o,value:t[o++]});continue}if(r==="\\"){n.push({type:"ESCAPED_CHAR",index:o++,value:t[o++]});continue}if(r==="{"){n.push({type:"OPEN",index:o,value:t[o++]});continue}if(r==="}"){n.push({type:"CLOSE",index:o,value:t[o++]});continue}if(r===":"){let a="",c=o+1;for(;c<t.length;){let u=t.substr(c,1);if(c===o+1&&x$.test(u)||c!==o+1&&M$.test(u)){a+=t[c++];continue}break}if(!a){s(`Missing parameter name at ${o}`);continue}n.push({type:"NAME",index:o,value:a}),o=c;continue}if(r==="("){let a=1,c="",u=o+1,l=!1;if(t[u]==="?"){s(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!L$(t[u],!1)){s(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){s(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){s(`Unbalanced pattern at ${o}`);continue}if(!c){s(`Missing pattern at ${o}`);continue}n.push({type:"REGEX",index:o,value:c}),o=u;continue}n.push({type:"CHAR",index:o,value:t[o++]})}return n.push({type:"END",index:o,value:""}),n}i(oT,"v");function rT(t,e={}){let n=oT(t);e.delimiter??="/#?",e.prefixes??="./";let o=`[^${Un(e.delimiter)}]+?`,r=[],s=0,a=0,c="",u=new Set,l=i(P=>{if(a<n.length&&n[a].type===P)return n[a++].value},"a"),d=i(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),m=i(P=>{let A=l(P);if(A!==void 0)return A;let{type:x,index:L}=n[a];throw new TypeError(`Unexpected ${x} at ${L}, expected ${P}`)},"d"),f=i(()=>{let P="",A;for(;A=l("CHAR")??l("ESCAPED_CHAR");)P+=A;return P},"T"),b=i(P=>P,"Se"),g=e.encodePart||b,R="",w=i(P=>{R+=P},"U"),C=i(()=>{R.length&&(r.push(new tl(3,"","",g(R),"",3)),R="")},"$"),v=i((P,A,x,L,U)=>{let oe=3;switch(U){case"?":oe=1;break;case"*":oe=0;break;case"+":oe=2;break}if(!A&&!x&&oe===3){w(P);return}if(C(),!A&&!x){if(!P)return;r.push(new tl(3,"","",g(P),"",oe));return}let B;x?x==="*"?B=ng:B=x:B=o;let te=2;B===o?(te=1,B=""):B===ng&&(te=0,B="");let he;if(A?he=A:x&&(he=s++),u.has(he))throw new TypeError(`Duplicate name '${he}'.`);u.add(he),r.push(new tl(te,he,g(P),B,g(L),oe))},"V");for(;a<n.length;){let P=l("CHAR"),A=l("NAME"),x=l("REGEX");if(!A&&!x&&(x=l("ASTERISK")),A||x){let U=P??"";e.prefixes.indexOf(U)===-1&&(w(U),U=""),C();let oe=d();v(U,A,x,"",oe);continue}let L=P??l("ESCAPED_CHAR");if(L){w(L);continue}if(l("OPEN")){let U=f(),oe=l("NAME"),B=l("REGEX");!oe&&!B&&(B=l("ASTERISK"));let te=f();m("CLOSE");let he=d();v(U,oe,B,te,he);continue}C(),m("END")}return r}i(rT,"D");function Un(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(Un,"S");function tT(t){return t&&t.ignoreCase?"ui":"u"}i(tT,"X");function N$(t,e,n){return iT(rT(t,n),e,n)}i(N$,"Z");function Ys(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}i(Ys,"k");function iT(t,e,n={}){n.delimiter??="/#?",n.prefixes??="./",n.sensitive??=!1,n.strict??=!1,n.end??=!0,n.start??=!0,n.endsWith="";let o=n.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?o+=Un(c.value):o+=`(?:${Un(c.value)})${Ys(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${Un(n.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=ng),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?o+=`(${l})${Ys(c.modifier)}`:o+=`((?:${l})${Ys(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){o+=`(?:${Un(c.prefix)}(${l})${Un(c.suffix)})`,o+=Ys(c.modifier);continue}o+=`(?:${Un(c.prefix)}`,o+=`((?:${l})(?:`,o+=Un(c.suffix),o+=Un(c.prefix),o+=`(?:${l}))*)${Un(c.suffix)})`,c.modifier===0&&(o+="?")}let r=`[${Un(n.endsWith)}]|$`,s=`[${Un(n.delimiter)}]`;if(n.end)return n.strict||(o+=`${s}?`),n.endsWith.length?o+=`(?=${r})`:o+="$",new RegExp(o,tT(n));n.strict||(o+=`(?:${s}(?=${r}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=n.delimiter.indexOf(c)>-1)}return a||(o+=`(?=${s}|${r})`),new RegExp(o,tT(n))}i(iT,"F");var Lr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},q$={delimiter:".",prefixes:"",sensitive:!0,strict:!0},$$={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function z$(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}i(z$,"J");function sT(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}i(sT,"Q");function D$(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}i(D$,"Ee");function aT(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}i(aT,"W");var cT=["ftp","file","http","https","ws","wss"];function uT(t){if(!t)return!0;for(let e of cT)if(t.test(e))return!0;return!1}i(uT,"N");function U$(t,e){if(t=sT(t,"#"),e||t==="")return t;let n=new URL("https://example.com");return n.hash=t,n.hash?n.hash.substring(1,n.hash.length):""}i(U$,"te");function j$(t,e){if(t=sT(t,"?"),e||t==="")return t;let n=new URL("https://example.com");return n.search=t,n.search?n.search.substring(1,n.search.length):""}i(j$,"re");function H$(t,e){return e||t===""?t:aT(t)?pT(t):dT(t)}i(H$,"ne");function F$(t,e){if(e||t==="")return t;let n=new URL("https://example.com");return n.password=t,n.password}i(F$,"se");function G$(t,e){if(e||t==="")return t;let n=new URL("https://example.com");return n.username=t,n.username}i(G$,"ie");function Z$(t,e,n){if(n||t==="")return t;if(e&&!cT.includes(e))return new URL(`${e}:${t}`).pathname;let o=t[0]=="/";return t=new URL(o?t:"/-"+t,"https://example.com").pathname,o||(t=t.substring(2,t.length)),t}i(Z$,"ae");function B$(t,e,n){return lT(e)===t&&(t=""),n||t===""?t:mT(t)}i(B$,"oe");function V$(t,e){return t=D$(t,":"),e||t===""?t:og(t)}i(V$,"ce");function lT(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}i(lT,"_");function og(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}i(og,"y");function J$(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}i(J$,"le");function K$(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}i(K$,"fe");function dT(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}i(dT,"z");function pT(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}i(pT,"j");function mT(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}i(mT,"K");function W$(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}i(W$,"he");function Y$(t){return t===""?t:new URL(`data:${t}`).pathname}i(Y$,"ue");function Q$(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}i(Q$,"de");function X$(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}i(X$,"pe");var ez=class{static{i(this,"H")}#e;#t=[];#o={};#n=0;#r=1;#i=0;#s=0;#a=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#o}parse(){for(this.#t=oT(this.#e,!0);this.#n<this.#t.length;this.#n+=this.#r){if(this.#r=1,this.#t[this.#n].type==="END"){if(this.#s===0){this.#g(),this.#f()?this.#c(9,1):this.#y()?this.#c(8,1):this.#c(7,0);continue}else if(this.#s===2){this.#h(5);continue}this.#c(10,0);break}if(this.#a>0)if(this.#P())this.#a-=1;else continue;if(this.#T()){this.#a+=1;continue}switch(this.#s){case 0:this.#w()&&this.#h(1);break;case 1:if(this.#w()){this.#O();let t=7,e=1;this.#C()?(t=2,e=3):this.#l&&(t=2),this.#c(t,e)}break;case 2:this.#S()?this.#h(3):(this.#R()||this.#y()||this.#f())&&this.#h(5);break;case 3:this.#I()?this.#c(4,1):this.#S()&&this.#c(5,1);break;case 4:this.#S()&&this.#c(5,1);break;case 5:this.#A()?this.#u+=1:this.#E()&&(this.#u-=1),this.#v()&&!this.#u?this.#c(6,1):this.#R()?this.#c(7,0):this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 6:this.#R()?this.#c(7,0):this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 7:this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 8:this.#f()&&this.#c(9,1);break;case 9:break;case 10:break}}this.#o.hostname!==void 0&&this.#o.port===void 0&&(this.#o.port="")}#c(t,e){switch(this.#s){case 0:break;case 1:this.#o.protocol=this.#m();break;case 2:break;case 3:this.#o.username=this.#m();break;case 4:this.#o.password=this.#m();break;case 5:this.#o.hostname=this.#m();break;case 6:this.#o.port=this.#m();break;case 7:this.#o.pathname=this.#m();break;case 8:this.#o.search=this.#m();break;case 9:this.#o.hash=this.#m();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#o.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#o.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#o.search??="")),this.#d(t,e)}#d(t,e){this.#s=t,this.#i=this.#n+e,this.#n+=e,this.#r=0}#g(){this.#n=this.#i,this.#r=0}#h(t){this.#g(),this.#s=t}#b(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#p(t,e){let n=this.#b(t);return n.value===e&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#w(){return this.#p(this.#n,":")}#C(){return this.#p(this.#n+1,"/")&&this.#p(this.#n+2,"/")}#S(){return this.#p(this.#n,"@")}#I(){return this.#p(this.#n,":")}#v(){return this.#p(this.#n,":")}#R(){return this.#p(this.#n,"/")}#y(){if(this.#p(this.#n,"?"))return!0;if(this.#t[this.#n].value!=="?")return!1;let t=this.#b(this.#n-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#p(this.#n,"#")}#T(){return this.#t[this.#n].type=="OPEN"}#P(){return this.#t[this.#n].type=="CLOSE"}#A(){return this.#p(this.#n,"[")}#E(){return this.#p(this.#n,"]")}#m(){let t=this.#t[this.#n],e=this.#b(this.#i).index;return this.#e.substring(e,t.index)}#O(){let t={};Object.assign(t,Lr),t.encodePart=og;let e=N$(this.#m(),void 0,t);this.#l=uT(e)}},tg=["protocol","username","password","hostname","port","pathname","search","hash"],Mr="*";function nT(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let n=new URL(t,e);return{protocol:n.protocol.substring(0,n.protocol.length-1),username:n.username,password:n.password,hostname:n.hostname,port:n.port,pathname:n.pathname,search:n.search!==""?n.search.substring(1,n.search.length):void 0,hash:n.hash!==""?n.hash.substring(1,n.hash.length):void 0}}i(nT,"ge");function Qo(t,e){return e?el(t):t}i(Qo,"b");function Xu(t,e,n){let o;if(typeof e.baseURL=="string")try{o=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Qo(o.protocol.substring(0,o.protocol.length-1),n)),!n&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Qo(o.username,n)),!n&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Qo(o.password,n)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Qo(o.hostname,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Qo(o.port,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Qo(o.pathname,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Qo(o.search.substring(1,o.search.length),n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Qo(o.hash.substring(1,o.hash.length),n))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=V$(e.protocol,n)),typeof e.username=="string"&&(t.username=G$(e.username,n)),typeof e.password=="string"&&(t.password=F$(e.password,n)),typeof e.hostname=="string"&&(t.hostname=H$(e.hostname,n)),typeof e.port=="string"&&(t.port=B$(e.port,t.protocol,n)),typeof e.pathname=="string"){if(t.pathname=e.pathname,o&&!z$(t.pathname,n)){let r=o.pathname.lastIndexOf("/");r>=0&&(t.pathname=Qo(o.pathname.substring(0,r+1),n)+t.pathname)}t.pathname=Z$(t.pathname,t.protocol,n)}return typeof e.search=="string"&&(t.search=j$(e.search,n)),typeof e.hash=="string"&&(t.hash=U$(e.hash,n)),t}i(Xu,"w");function el(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}i(el,"C");function tz(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(tz,"Oe");function nz(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let n=".*",o=`[^${tz(e.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){s+=el(c.value);continue}s+=`{${el(c.value)}}${Ys(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,m=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&m&&!m.prefix.length&&!m.suffix.length)if(m.type===3){let f=m.value.length>0?m.value[0]:"";l=r.test(f)}else l=!m.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let f=d.value[d.value.length-1];l=e.prefixes.includes(f)}l&&(s+="{"),s+=el(c.prefix),u&&(s+=`:${c.name}`),c.type===2?s+=`(${c.value})`:c.type===1?u||(s+=`(${o})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?s+="*":s+=`(${n})`),c.type===1&&u&&c.suffix.length&&r.test(c.suffix[0])&&(s+="\\"),s+=el(c.suffix),l&&(s+="}"),c.modifier!==3&&(s+=Ys(c.modifier))}return s}i(nz,"ke");var Xp=class{static{i(this,"me")}#e;#t={};#o={};#n={};#r={};#i=!1;constructor(t={},e,n){try{let o;if(typeof e=="string"?o=e:n=e,typeof t=="string"){let c=new ez(t);if(c.parse(),t=c.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let r={ignoreCase:n.ignoreCase===!0},s={pathname:Mr,protocol:Mr,username:Mr,password:Mr,hostname:Mr,port:Mr,search:Mr,hash:Mr};this.#e=Xu(s,t,!0),lT(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of tg){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#o[a]=[],a){case"protocol":Object.assign(c,Lr),c.encodePart=og;break;case"username":Object.assign(c,Lr),c.encodePart=J$;break;case"password":Object.assign(c,Lr),c.encodePart=K$;break;case"hostname":Object.assign(c,q$),aT(u)?c.encodePart=pT:c.encodePart=dT;break;case"port":Object.assign(c,Lr),c.encodePart=mT;break;case"pathname":uT(this.#t.protocol)?(Object.assign(c,$$,r),c.encodePart=W$):(Object.assign(c,Lr,r),c.encodePart=Y$);break;case"search":Object.assign(c,Lr,r),c.encodePart=Q$;break;case"hash":Object.assign(c,Lr,r),c.encodePart=X$;break}try{this.#r[a]=rT(u,c),this.#t[a]=iT(this.#r[a],this.#o[a],c),this.#n[a]=nz(this.#r[a],c),this.#i=this.#i||this.#r[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},e){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?n=Xu(n,t,!1):n=Xu(n,nT(t,e),!1)}catch{return!1}let o;for(o of tg)if(!this.#t[o].exec(n[o]))return!1;return!0}exec(t={},e){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=Xu(n,t,!1):n=Xu(n,nT(t,e),!1)}catch{return null}let o={};e?o.inputs=[t,e]:o.inputs=[t];let r;for(r of tg){let s=this.#t[r].exec(n[r]);if(!s)return null;let a={};for(let[c,u]of this.#o[r].entries())if(typeof u=="string"||typeof u=="number"){let l=s[c+1];a[u]=l}o[r]={input:n[r]??"",groups:a}}return o}static compareComponent(t,e,n){let o=i((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),r=new tl(3,"","","","",3),s=new tl(0,"","","","",3),a=i((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=o(c[l],u[l]);if(d)return d}return c.length===u.length?0:o(c[l]??r,u[l]??r)},"s");return!e.#n[t]&&!n.#n[t]?0:e.#n[t]&&!n.#n[t]?a(e.#r[t],[s]):!e.#n[t]&&n.#n[t]?a([s],n.#r[t]):a(e.#r[t],n.#r[t])}get protocol(){return this.#n.protocol}get username(){return this.#n.username}get password(){return this.#n.password}get hostname(){return this.#n.hostname}get port(){return this.#n.port}get pathname(){return this.#n.pathname}get search(){return this.#n.search}get hash(){return this.#n.hash}get hasRegExpGroups(){return this.#i}};var em=class{static{i(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new Xp({pathname:e});let n=/:(\w+)(\([^)]*\))?[*+?]?/g,o;for(;(o=n.exec(e))!==null;)this.expectedPathParams.add(o[1])}addParameter(e,n,o){let r=this.getParameterValue(e,n,o);if(r!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new I(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,r);break;case"query":this.addQueryParameter(e.name,r);break;default:break}}getParameterValue(e,n,o){switch(e.in){case"path":return n?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,n){this.pathParams[e]=String(n)}addQueryParameter(e,n){Array.isArray(n)?n.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof n=="object"&&n!==null?this.searchParams.append(e,JSON.stringify(n)):this.searchParams.append(e,String(n))}toString(){let e=[...this.expectedPathParams].filter(s=>!this.seenPathParams.has(s));if(e.length>0)throw new I(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let n=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(s,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):s),o=this.cleanupUrlPatternSyntax(n),r=this.searchParams.toString();return r?`${o}?${r}`:o}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var tm=class{constructor(e){this.routeData=e}routeData;static{i(this,"McpUrlBuilder")}build(e,n){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,r=this.routeData.raw()?.parameters||[],s=new em(o);for(let a of r)s.addParameter(a,e,n);return s.toString()}};var nm=class t{static{i(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>p.email()],["uri",()=>p.url()],["url",()=>p.url()],["date",()=>p.iso.date()],["date-time",()=>p.iso.datetime()],["time",()=>p.iso.time()],["ipv4",()=>p.ipv4()],["ipv6",()=>p.ipv6()],["uuid",()=>p.guid()],["int32",()=>p.int32()],["int64",()=>p.int64()],["float",()=>p.number()],["double",()=>p.number()]]);static get(e){return t.formatter.get(e)}static register(e,n){t.formatter.set(e,n)}},Qs=class t{static{i(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,n){let o={path:[],definitions:{},visitedRefs:new Set,...n};return t.transpileSchema(e,o)}static transpileSchema(e,n){if(!e)return p.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,n);if(e.allOf)return t.transpileAllOf(e.allOf,n);if(e.oneOf)return t.transpileOneOf(e.oneOf,n);if(e.anyOf)return t.transpileAnyOf(e.anyOf,n);if(e.not)return t.transpileNot(e.not,n);let o=t.transpileByType(e,n);return o=t.applyCommonModifiers(o,e),o}catch(o){let r=n.path.join(".");throw new Error(`Failed to transpile schema at path "${r}": ${o.message}`)}}static transpileByType(e,n){let o=e.type;!o&&e.properties&&(o="object");let r=t.typeTranspilers.get(o||"unknown");return r?r(e,n):p.unknown()}static transpileString(e,n){if(e.enum)return p.enum(e.enum);let o=e.format?nm.get(e.format):null,r=o?o():p.string();if(r instanceof p.ZodString){let s=r;return e.minLength!==void 0&&(s=s.min(e.minLength)),e.maxLength!==void 0&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),s}else e.minLength||e.maxLength||e.pattern;return r}static applyNumericConstraints(e,n,o){let r=e;if(n.minimum!==void 0&&(r=r.min(n.minimum)),n.maximum!==void 0&&(r=r.max(n.maximum)),n.exclusiveMinimum!==void 0){let s;if(typeof n.exclusiveMinimum=="number")s=n.exclusiveMinimum;else if(n.minimum!==void 0)s=n.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${o.path.join(".")}"`);r=r.gt(s)}if(n.exclusiveMaximum!==void 0){let s;if(typeof n.exclusiveMaximum=="number")s=n.exclusiveMaximum;else if(n.maximum!==void 0)s=n.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${o.path.join(".")}"`);r=r.lt(s)}return r}static transpileNumber(e,n){let o=p.number();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileInteger(e,n){let o=p.int();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileBoolean(e,n){return p.boolean()}static transpileArray(e,n){let o=e.items?t.transpileSchema(e.items,{...n,path:[...n.path,"items"]}):p.unknown(),r=p.array(o);return e.minItems!==void 0&&(r=r.min(e.minItems)),e.maxItems!==void 0&&(r=r.max(e.maxItems)),e.uniqueItems&&(r=r.refine(s=>new Set(s).size===s.length,{message:"Array must contain unique items"})),r}static transpileObject(e,n){let o;if(e.properties){let r={},s=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...n,path:[...n.path,c]},d=t.transpileSchema(u,l);s.has(c)||(d=d.optional()),r[c]=d}let a=p.object(r);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),o=a}else if(e.additionalProperties===!1)o=p.object({}).strict();else if(typeof e.additionalProperties=="object"){let r=t.transpileSchema(e.additionalProperties,n);o=p.record(p.string(),r)}else o=p.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(o=o.refine(r=>{let s=Object.keys(r).length;return!(e.minProperties!==void 0&&s<e.minProperties||e.maxProperties!==void 0&&s>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),o}static buildPropertyCountErrorMessage(e,n){return e!==void 0&&n!==void 0?`Object must have between ${e} and ${n} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${n} properties`}static transpileNull(e,n){return p.null()}static transpileAllOf(e,n){let r=e.map((a,c)=>t.transpileSchema(a,{...n,path:[...n.path,`allOf[${c}]`]})).reduce((a,c)=>a.and(c)),s=e.filter(a=>a.additionalProperties===!1).map(a=>Object.keys(a.properties??{}));return s.length===0?r:r.superRefine((a,c)=>{if(!(typeof a!="object"||a===null||Array.isArray(a)))for(let u of s){let l=Object.keys(a).filter(d=>!u.includes(d));l.length>0&&c.addIssue({code:"custom",message:`Unrecognized key(s) in object: ${l.map(d=>`'${d}'`).join(", ")}`})}})}static transpileOneOf(e,n){let o=e.map((r,s)=>t.transpileSchema(r,{...n,path:[...n.path,`oneOf[${s}]`]}));return o.length===0?p.never():o.length===1?o[0]:p.union(o)}static transpileAnyOf(e,n){return t.transpileOneOf(e,n)}static transpileNot(e,n){let o=t.transpileSchema(e,{...n,path:[...n.path,"not"]});return p.unknown().refine(r=>!o.safeParse(r).success,{message:"Value must not match the schema"})}static resolveReference(e,n){if(n.visitedRefs?.has(e))return p.lazy(()=>t.resolveReference(e,n));n.visitedRefs?.add(e);let o=e.split("/");if(o[0]==="#"&&o[1]==="definitions"&&n.definitions){let r=n.definitions[o[2]];if(r)return t.transpileSchema(r,n)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,n){let o=e;return n.nullable&&(o=o.nullable()),n.default!==void 0&&(o=o.default(n.default)),n.description&&(o=o.describe(n.description)),n.examples&&n.examples.length>0&&(o=o.meta({examples:n.examples})),o}static registerTypeTranspiler(e,n){t.typeTranspilers.set(e,n)}static registerFormatSchema(e,n){nm.register(e,n)}};var om=class{constructor(e){this.schema=e}schema;static{i(this,"JSONSchemaBuilder")}build(){return Qs.run(this.schema)}},rm=class{constructor(e,n){this.routeData=e;this.contentType=n}routeData;contentType;static{i(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let n=e.content[this.contentType].schema;return n?Qs.run(n):null}},im=class{constructor(e){this.parameters=e}parameters;static{i(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let n of this.parameters)e[n.name]=this.buildParameterSchema(n);return p.object(e)}buildParameterSchema(e){let n;e.schema?n=Qs.run(e.schema):n=p.string(),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description));let o=[];if(e.schema?.example!==void 0&&o.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&o.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?o.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(r=>{r?.value!==void 0&&o.push(r.value)})),e.example!==void 0&&o.push(e.example),o.length>0){let r=[...new Set(o.map(s=>JSON.stringify(s)))].map(s=>JSON.parse(s));n=n.meta({examples:r})}return n}};var Ti=class t{static{i(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let n=new t;return n.root=e,n}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let n=p.toJSONSchema(e);return new xr(n,o=>{let r=e.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}buildFromComponents(){let e=p.strictObject(this.components),n=p.toJSONSchema(e);return new xr(n,o=>{let r=e.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1},n=p.strictObject({});return new xr(e,o=>{let r=n.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}},Xs=class t{static{i(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new om(e)}static createRequestBodyBuilder(e,n){return new rm(e,n)}static createParameterBuilder(e,n){let o=n?e.filter(r=>r.in===n):e;return new im(o)}static createValidatorBuilder(e,n){let o=new Ti,r=e.raw()?.parameters||[];if(n){let u=t.createRequestBodyBuilder(e,n);o.withBody(u.build())}let s=t.createParameterBuilder(r,"query");o.withQueryParams(s.build());let a=t.createParameterBuilder(r,"path");o.withPathParams(a.build());let c=t.createParameterBuilder(r,"header");return o.withHeaders(c.build()),o}static createPromptValidatorBuilder(e){let n=new Ti,r=e.raw()?.requestBody;if(!r?.content||!r.content["application/json"])return n;let a=t.createRequestBodyBuilder(e,"application/json");return Ti.withRoot(a.build())}static createObjectValidatorBuilder(e){let n=new Ti;if(!e||Object.keys(e).length===0)return n;let o=t.createJsonSchemaBuilder(e);return Ti.withRoot(o.build())}};function rg(t){let e;try{e=JSON.parse(t)}catch{return}if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}i(rg,"parseStructuredContent");function oz(t){let e=t.headers.get("accept");if(!e)return t;let n=e.replace(/application\/json/gi,"application/json").replace(/text\/event-stream/gi,"text/event-stream").replace(/(^|[ ,;])event-stream($|[ ,;])/i,"$1text/event-stream$2");if(!n.includes("text/event-stream")){if(!n.includes("application/json"))return t;n=`${n}, text/event-stream`}if(n===e)return t;let o=new Request(t,{headers:new Headers(t.headers)});return o.headers.set("accept",n),o}i(oz,"normalizeLegacyAcceptHeader");function rz(t){let e=t;return e.properties?Object.entries(e.properties).map(([n,o])=>({name:n,description:o?.description??`Prompt for ${n}`,required:e.required?.includes(n)??!1})):[]}i(rz,"jsonSchemaToPromptArguments");var sm=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:n,key:o}){let r=e.debugMode??!1,s=t.instances.get(o);if(s)r&&n.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(s=new t(e,n),s.registerFromOperations(s.opts.operations??[]),s.registerToolsFromFileSources(s.opts.files??[]),s.registerPromptsFromFileSources(s.opts.prompts??[]),s.registerResourcesFromFileSources(s.opts.resources??[]),t.instances.set(o,s),r){let c=s.tools.size,u=s.prompts.size,l=s.resources.size,d=Date.now()-a;n.log.debug("MCP Server cold start",{routeKey:o,toolCount:c,promptCount:u,resourceCount:l,totalElapsedMs:d,debugMode:r,includeOutputSchema:s.includeOutputSchema,includeStructuredContent:s.includeStructuredContent})}}return s}opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;tools=new Map;prompts=new Map;resources=new Map;includeOutputSchema;includeStructuredContent;debugMode;jsonSchemaValidator=new vi({draft:"7",shortcircuit:!1});constructor(e,n){this.debugMode=e.debugMode??!1,this.context=n,this.opts=e,this.serverName=e.name??n.route?.path??void 0,this.serverDisplayName=e.name??"Zuplo MCP Server",this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}emitEvent(e,n){let o=Qv(n,this.serverName),r=o.subjectId??eT();Wv(e,r===void 0?o:{...o,subjectId:r})}async handleRequest(e,n){let o=Date.now(),r=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null,s=e.user?.sub;try{let a=await e.clone().json().catch(()=>({})),c=typeof a?.method=="string"?a.method:null;c==="tools/call"&&(n.custom.mcpCallToolRequest=a),this.emitEvent(n,{eventType:ee.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:c??void 0,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s}),s!==void 0&&this.emitEvent(n,{eventType:ee.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s});let u=Yv(a);u&&this.emitEvent(n,{...u,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0});try{dt.getContextExtensions(n).addHandlerResponseHook(g=>{let R=Date.now()-o;this.emitEvent(n,{eventType:ee.MCP_REQUEST_COMPLETED,outcome:g.status>=400?"failure":"success",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:g.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:R,subjectId:s})})}catch{}if(this.debugMode)switch(n.log.debug("MCP Server request start",{method:a.method,requestId:a.id,routePath:n.route?.path}),a.method){case"tools/list":n.log.debug("MCP Server list tools request",{toolCount:this.tools.size,toolNames:Array.from(this.tools.keys())});break;case"prompts/list":n.log.debug("MCP Server list prompts request",{promptCount:this.prompts.size,promptNames:Array.from(this.prompts.keys())});break;case"resources/list":n.log.debug("MCP Server list resources request",{resourceCount:this.resources.size,resourceNames:Array.from(this.resources.keys())});break}let l=new Kf({name:this.serverDisplayName,version:this.opts.version??"0.0.0"},{jsonSchemaValidator:this.jsonSchemaValidator,capabilities:{tools:{supported:!0,available:Array.from(this.tools.keys())},prompts:{},resources:{}}});this.wireRequestHandlers(l);let d=new zv({enableJsonResponse:!0});await l.connect(d);let m=await d.handleRequest(oz(e)),f=Date.now()-o,b=m.status>=200&&m.status<300;switch(a.method){case"initialize":{let g=a?.params?.clientInfo,R=a?.params?.protocolVersion,w=typeof g?.name=="string"?g.name:void 0,C=typeof g?.title=="string"?g.title:void 0,v=typeof g?.version=="string"?g.version:void 0,P=typeof R=="string"?R:void 0;this.emitEvent(n,{eventType:ee.MCP_INITIALIZE_NEGOTIATED,outcome:b?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:w,clientTitle:C,clientVersion:v,mcpProtocolVersion:P,latencyMs:f}),b||this.emitEvent(n,{eventType:ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:w,clientVersion:v,mcpProtocolVersion:P,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break;case"resources/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break;case"prompts/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break}if(this.debugMode){let g=await m.clone().json().catch(()=>({}));n.log.debug("MCP Server response complete",{status:m.status,requestMethod:a.method,requestId:a.id,totalElapsedMs:f,respData:g})}return m}catch(a){let c=Date.now()-o;return n.log.error("MCP server internal error",{elapsedMs:c,err:a}),new Response("Internal error",{status:500})}}wireRequestHandlers(e){e.setRequestHandler("tools/list",async()=>({tools:Array.from(this.tools.entries()).map(([n,o])=>({name:n,description:o.description,inputSchema:o.validator.schema,...o.outputSchema&&{outputSchema:o.outputSchema},...o.annotations&&{annotations:o.annotations},...o._meta&&{_meta:o._meta}}))})),e.setRequestHandler("tools/call",async n=>{let o=n.params.name,r=this.tools.get(o);if(!r)throw new je(fe.InvalidParams,`Tool "${o}" not found`);let s=n.params.arguments??{},a=r.validator.validate(s);if(!a.success)throw new je(fe.InvalidParams,a.errorMessage?`Invalid arguments for tool '${o}': ${a.errorMessage}`:`Invalid arguments for tool '${o}'`,a.errorData);try{return await r.handler(a.data,n.params._meta)}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:"Tool execution error"}],isError:!0}}}),e.setRequestHandler("prompts/list",async()=>({prompts:Array.from(this.prompts.entries()).map(([n,o])=>({name:n,description:o.description,arguments:rz(o.validator.schema)}))})),e.setRequestHandler("prompts/get",async n=>{let o=n.params.name,r=this.prompts.get(o);if(!r)throw new je(fe.InvalidParams,`Prompt "${o}" not found`);let s=n.params.arguments??{},a=r.validator.validate(s);if(!a.success)throw new je(fe.InvalidParams,a.errorMessage?`Invalid arguments for prompt '${o}': ${a.errorMessage}`:`Invalid arguments for prompt '${o}'`,a.errorData);try{let c=await r.generator(a.data);return{...r.description!==void 0&&{description:r.description},messages:c}}catch(c){throw new je(fe.InternalError,c instanceof Error?c.message:"Prompt generation error")}}),e.setRequestHandler("resources/list",async()=>({resources:Array.from(this.resources.entries()).map(([n,o])=>({name:n,uri:o.uri,...o.metadata.title!==void 0&&{title:o.metadata.title},...o.metadata.description!==void 0&&{description:o.metadata.description},...o.metadata.mimeType!==void 0&&{mimeType:o.metadata.mimeType},...o.metadata._meta!==void 0&&{_meta:o.metadata._meta}}))})),e.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:[]})),e.setRequestHandler("resources/read",async n=>{let o=n.params.uri,r=Array.from(this.resources.values()).find(s=>s.uri===o);if(!r)throw new Ku(o);try{return await r.reader()}catch(s){throw new je(fe.InternalError,s instanceof Error?s.message:"Resource read error")}})}addToolInternal(e){this.tools.set(e.name,{description:e.description,validator:e.validator,...e.outputSchema&&{outputSchema:e.outputSchema},...e.annotations&&{annotations:e.annotations},...e._meta&&{_meta:e._meta},handler:e.handler})}addPromptInternal(e){this.prompts.set(e.name,{description:e.description,validator:e.validator,generator:e.generator})}addResourceInternal(e,n,o,r){this.resources.set(e,{uri:n,metadata:o,reader:r})}generatePromptDescriptionFromSpec(e){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:n}=Xe.instance.routeData,o=n.filter(s=>s.metadata?.filepath===e);if(o.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let r=new Map;for(let s of o){let a=s?.raw().operationId;if(a){r.set(a,{routeConfig:s});let c=s?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],m=c["x-zuplo-mcp-resource"],f=c["x-zuplo-route"]?.mcp;(u||l||d||m||f)&&r.set(a,{routeConfig:s,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:m||void 0,routeMcpExtension:f||void 0})}}return r}registerFromOperations(e){let n=new Map;for(let o of e){let r=n.get(o.file)??[];r.push(o.id),n.set(o.file,r)}for(let[o,r]of n.entries()){let s=t.getOperationsMetadataForFile(o);for(let a of r){let c=s.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let n of e){let o=t.getOperationsMetadataForFile(n.path),r=new Set;for(let s of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${s}" from file: "${n.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(s);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${s}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??s;if(r.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);r.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:s});continue}this.registerPromptForOperation(l,d,c,s)}}}registerPromptForOperation(e,n,o,r){try{if(o.handler?.export==="mcpServerHandler")return;let a=Xs.createPromptValidatorBuilder(o).build();this.addPromptInternal({name:e,description:n,validator:a,generator:i(async c=>{let u=Ws(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:c});let d=this.buildToolUrl(o,{body:c}),m=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let f=Date.now(),b=await u.invokeRoute(d,m),g=Date.now()-f,R=await b.json();if(!b.ok)throw new Error(`Route returned ${b.status}: ${R}`);let w;try{if(w=R.messages||R,!Array.isArray(w))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let C=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:b.status,elapsedMs:C,downstreamElapsedMs:g,messageCount:w.length}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:C}),w}catch(d){let m=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:m,err:d}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:m,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP prompt invocation failed for prompt '${e}': ${f}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:r,path:o.path})}catch(s){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:r,error:s instanceof Error?s.message:String(s)}),new Error(`Failed to register prompt "${e}" for operation "${r}": ${s instanceof Error?s.message:String(s)}`)}}registerResourcesFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${s}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${s}" in file ${o.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:s});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${s}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${s}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${s}" uses ${d} method. Resources are read-only and must use GET method only.`);let m=u?.name?.trim()||s.trim()||"";if(!m)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${s}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(n.has(m))throw new Error(`MCP Resource configuration error: Duplicate resource name "${m}". Resource names must be unique across all configured resources.`);n.add(m);let f=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${m}`,b=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(m)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(m,b,f,c,s,g)}}}registerResourceForOperation(e,n,o,r,s,a,c){try{if(r.handler?.export==="mcpServerHandler")return;this.addResourceInternal(e,n,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=Ws(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,uri:n});let d=this.buildToolUrl(r,{}),m=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let f=Date.now(),b=await u.invokeRoute(d,m),g=Date.now()-f,R=await b.text(),w=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:r.raw()?.operationId,status:b.status,elapsedMs:w,downstreamElapsedMs:g,declaredMimeType:a,contentLength:R.length}),this.emitEvent(u,{eventType:b.ok?ee.MCP_CAPABILITY_COMPLETED:ee.MCP_CAPABILITY_FAILED,outcome:b.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:w,...b.ok?{}:{errorCode:b.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:n,mimeType:a,text:R,...c&&{_meta:c}}]}}catch(d){let m=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,elapsedMs:m,err:d}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:m,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${f}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:s,path:r.path,uri:n,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:s,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${s}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredToolNames.has(s))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${n}". The tool name "${s}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${n}".`);this.registeredToolNames.add(s);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${s}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=o?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${n}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:s,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredPromptNames.has(s))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${s}" for operation ID "${n}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(s);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(s,a,e,n)}registerResource(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:n});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${n}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${n}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let s=e.methods[0].toUpperCase();if(s!=="GET")throw new Error(`MCP Resource configuration error: Operation "${n}" uses ${s} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||n;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,n,l,o?._meta)}registerToolsFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(r.keys())});for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${s}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${s}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(r.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:s,path:o.path});continue}let c=a.toolExtension?.name?.trim()??s,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${s}" in file "${o.path}"`);if(n.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${s}".`);n.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${s}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(s,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,n,o){let r=o?.introspectionTool?.name?.trim()||`${e}_introspect`,s=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(r))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${r}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(s))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${s}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(r),this.registeredToolNames.add(s);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=n.path,d=Xs.createObjectValidatorBuilder({}).build();this.addToolInternal({name:r,description:a,validator:d,handler:i(async()=>{let f=Ws(),b=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL introspection tool invoked",{toolName:r,operationId:e,path:u});let g=zd(),R=this.buildToolUrl(n,{}),w=this.buildToolRequest("POST","application/json",{body:{query:g}}),C=Date.now(),v=await f.invokeRoute(R,w),P=Date.now()-C,A=await v.text(),x=Date.now()-b;this.debugMode&&(v.ok?f.log.debug("MCP GraphQL introspection tool ok response",{toolName:r,operationId:e,status:v.status,elapsedMs:x,downstreamElapsedMs:P}):f.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:r,operationId:e,status:v.status,elapsedMs:x,downstreamElapsedMs:P,response:A}));let L=rg(A);return this.debugMode&&L===void 0&&f.log.debug("MCP GraphQL introspection structuredContent skipped (non-object)",{toolName:r,bodyPreview:A.slice(0,200)}),{content:[{type:"text",text:A}],...L&&{structuredContent:L},isError:!v.ok}}catch(g){let R=Date.now()-b,w=g instanceof Error?`${g.name}: ${g.message}`:String(g);throw f.log.error("MCP GraphQL introspection tool invocation failed",{toolName:r,operationId:e,path:u,elapsedMs:R,err:g}),new Error(`MCP GraphQL introspection tool call failed for '${r}': ${w}`)}},"handler")});let m={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.addToolInternal({name:s,description:c,validator:new xr(m,f=>typeof f=="object"&&f!==null&&"query"in f&&typeof f?.query=="string"?{success:!0,data:f,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:i(async f=>{let b=Ws(),g=Date.now();try{this.debugMode&&b.log.debug("MCP GraphQL execute tool invoked",{toolName:s,operationId:e,path:u,queryPreview:f.query.substring(0,100)});let R=this.buildToolUrl(n,{}),w={query:f.query};f.variables&&(w.variables=f.variables);let C=this.buildToolRequest("POST","application/json",{body:w}),v=Date.now(),P=await b.invokeRoute(R,C),A=Date.now()-v,x=await P.text(),L=Date.now()-g;this.debugMode&&(P.ok?b.log.debug("MCP GraphQL execute tool ok response",{toolName:s,operationId:e,status:P.status,elapsedMs:L,downstreamElapsedMs:A}):b.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:s,operationId:e,status:P.status,elapsedMs:L,downstreamElapsedMs:A,response:x}));let U=rg(x);return this.debugMode&&U===void 0&&b.log.debug("MCP GraphQL execute structuredContent skipped (non-object)",{toolName:s,bodyPreview:x.slice(0,200)}),{content:[{type:"text",text:x}],...U&&{structuredContent:U},isError:!P.ok}}catch(R){let w=Date.now()-g,C=R instanceof Error?`${R.name}: ${R.message}`:String(R);throw b.log.error("MCP GraphQL execute tool invocation failed",{toolName:s,operationId:e,path:u,elapsedMs:w,err:R}),new Error(`MCP GraphQL execute tool call failed for '${s}': ${C}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:r,executeToolName:s,path:u})}registerToolsForMethod({routeData:e,method:n,name:o,description:r,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let m=Object.keys(e.raw().requestBody?.content).length>1?`${o}_${l.replace(/[^\w]/g,"_")}`:o;this.registerGenericToolSpec({name:m,description:r,routeData:e,method:n,contentType:l,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:o,description:r,routeData:e,method:n,contentType:null,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:n,routeData:o,method:r,contentType:s,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(o,s);if(!d)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${r.toUpperCase()} ${o.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let m=a?this.extractOutputSchema(o):void 0;try{this.addToolInternal({name:e,description:n,validator:d,...m&&{outputSchema:m},...u&&{annotations:u},...l&&{_meta:l},handler:i(async(f,b)=>{let g=Ws(),R=Date.now();try{this.debugMode&&g.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:r,path:o.path,args:f});let w=this.buildToolUrl(o,f),C=this.buildToolRequest(r,s,f);this.debugMode&&g.log.debug("MCP tool downstream call",{toolName:e,url:w,method:r,headers:C.headers?Object.keys(C.headers).join(", "):"",bodyPreview:f.body});let v=Date.now(),P=await g.invokeRoute(w,C),A=Date.now()-v,x=await P.text(),L=c?rg(x):void 0;this.debugMode&&c&&L===void 0&&g.log.debug("MCP tool structuredContent skipped (non-object or unparseable)",{toolName:e,bodyPreview:x.slice(0,200)});let U=Date.now()-R;return this.emitEvent(g,{eventType:P.ok?ee.MCP_CAPABILITY_COMPLETED:ee.MCP_CAPABILITY_FAILED,outcome:P.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:r,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:U,...P.ok?{}:{errorCode:P.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),this.debugMode&&(P.ok?g.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:P.status,elapsedMs:U,downstreamElapsedMs:A}):g.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:P.status,elapsedMs:U,downstreamElapsedMs:A,response:x})),{content:[{type:"text",text:x}],...P.ok&&L&&{structuredContent:L},isError:!P.ok,_meta:g.custom.mcpCallToolResponse?._meta??{}}}catch(w){let C=Date.now()-R,v=w instanceof Error?`${w.name}: ${w.message}`:String(w);return g.log.error("MCP server tool invocation failed",{toolName:e,operationId:o.raw()?.operationId,method:r,path:o.path,elapsedMs:C,err:w}),this.emitEvent(g,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:r,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:C,reasonCode:"gateway_error",reasonClass:"upstream",errorType:w instanceof Error?w.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${v}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:r.toUpperCase(),path:o.path,operationId:o.raw()?.operationId,contentType:s||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!m})}catch(f){throw new Error(`Failed to add tool ${r} ${o.path}`,f)}}buildToolUrl(e,n){return new tm(e).build(n.pathParams,n.queryParams)}buildToolRequest(e,n,o){let r=this.buildToolHeaders(e,n,o),s={method:e,headers:r};return this.shouldIncludeBody(e,n,o)&&(s.body=this.serializeBody(o.body,n)),s}buildToolHeaders(e,n,o){let r={...eg()};return delete r["content-type"],o.headers&&Object.entries(o.headers).forEach(([s,a])=>{r[s.toLowerCase()]=a}),n&&o.body!==void 0&&(r["content-type"]=n),this.isBodyMethod(e||"")&&o.body!==void 0&&!r["content-type"]&&(r["content-type"]="application/json"),r}shouldIncludeBody(e,n,o){return o.body===void 0?!1:this.isBodyMethod(e)?!0:n!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,n){return JSON.stringify(e)}buildUniversalValidator(e,n){try{let r=Xs.createValidatorBuilder(e,n).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:n||"none",operationId:e.raw()?.operationId}),r}catch(o){let r=o instanceof Error?o.message:String(o);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:n||"none",operationId:e.raw()?.operationId,error:r}),o}}extractOutputSchema(e){try{let n=e.raw(),o=n?.responses;if(!o){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:n?.operationId});return}for(let r of Object.keys(o))if(r.startsWith("2")){let a=o[r]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:n?.operationId,statusCode:r,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:n?.operationId,statusCodes:Object.keys(o).join(", ")});return}catch(n){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0});return}}};async function hT(t,e){if(Q("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new I(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let n={};t.headers.forEach((a,c)=>{n[c]=a});let o=e.route?.handler?.options??{},r=e.route?.path??"unknown-route",s=await sm.getInstance({opts:o,context:e,key:r});return Xv(e,{headers:n,user:t.user},()=>s.handleRequest(t,e))}i(hT,"mcpServerHandler");It("mcp-server",hT);var iz=[502,503,504];function am(t){if(t!=null){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new I(`The 'requestTimeoutSeconds' handler option must be a positive number of seconds. Received: ${String(t)}. Remove the option to disable the request timeout.`);return AbortSignal.timeout(t*1e3)}}i(am,"getRequestTimeoutSignal");function cm(t){if(typeof t!="object"||t===null)return!1;let e=t.name;return e==="TimeoutError"||e==="AbortError"}i(cm,"isRequestTimeoutError");async function ea(t,e){if(iz.includes(t.status)){let n=Y.getLogger(e),r=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:r,headers:s})}}i(ea,"logBadGatewayResponses");var ig;function ta(t){if(ig===void 0){let n=_.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),ig=n}return t.log[ig]}i(ta,"getHandlerUserLogFunction");async function fT(t,e){Q("handler.open-api");let n=_.instance.build.BUILD_ID,{buildAssetsUrl:o}=_.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new I("Open API Spec Handler must have 'openApiFilePath' specified");let a=sz(s);if(!a.isValid)throw new I(a.error);let c=`${o}/${n}${s.substring(1)}`,u=await H.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return z.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};_.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return ea(d,e),d}i(fT,"openApiSpecHandler");var sz=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");It("open-api",fT);async function gT(t,e){Q("handler.redirect");let n=e.route.handler.options;if(!n.location)throw new I("Redirect Handler must have 'location' specified");let o=n.status??302;return new Response(null,{status:o,headers:{location:n.location}})}i(gT,"redirectHandler");It("redirect",gT);async function yT(t){if(Q("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new I("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,_.instance.zuploEdgeApiUrl),n=new Headers(t.headers);return n.set("Authorization",`Bearer ${_.instance.authApiJWT}`),H.fetch(e,{method:t.method,headers:n,body:t.body})}i(yT,"zuploServiceProxy");It("service-proxy",yT);function az(t,e){let n=t.endsWith("/"),o=e.startsWith("/");return n&&o?`${t.substring(0,t.length-1)}${e}`:!n&&!o?`${t}/${e}`:`${t}${e}`}i(az,"join");async function bT(t,e){Q("handler.url-forward");let n=ta(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s;if(_.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&Q("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new I("Invalid options for this route");let a=na(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=az(u,c.pathname),d=r?`${l}${c.search}`:l.toString(),m=Date.now();n(`URL Forwarding to '${d}'`);let f=t.body;if(s==="follow"&&t.body)try{f=await t.arrayBuffer()}catch(w){throw new Error(`Failed to buffer request body for redirect handling: ${w}`)}let b=am(o.requestTimeoutSeconds),g;try{g=await fetch(d,{method:t.method,body:f,headers:t.headers,redirect:s,signal:b,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(w){if(b&&cm(w)){let C=Date.now()-m;return n(`URL Forward to '${d}' timed out after ${C}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),z.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw w}let R=Date.now()-m;return n(`URL Forward received response ${g.status} - ${g.statusText} in ${R}ms`),ea(g,e),g}i(bT,"urlForwardHandler");It("url-forward",bT);var cz=i((t,e)=>{let n=new URL(t),o=new URL(e);for(let[r,s]of o.searchParams.entries())n.searchParams.append(r,s);return n.toString()},"addQuery");async function ST(t,e){Q("handler.url-rewrite");let n=ta(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new I("Invalid options for this route");let a=na(e),c=o.__rewriteFunction(t,a),u=r?cz(c,t.url):c,l=am(o.requestTimeoutSeconds),d=Date.now();n(`URL Rewriting to '${u}'`);let m;try{m=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual",signal:l,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(b){if(l&&cm(b)){let g=Date.now()-d;return n(`URL Rewrite to '${u}' timed out after ${g}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),z.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw b}let f=Date.now()-d;return n(`URL Rewrite received response ${m.status} - ${m.statusText} in ${f}ms`),ea(m,e),m}i(ST,"urlRewriteHandler");It("url-rewrite",ST);var sg=i((t,e)=>t.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${r+1}, export name: ${o.export}`;throw new I(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions"),RT=i(t=>{let e;if(typeof t.module=="object"&&(e=t.module[t.export]),!e||typeof e!="function")throw new I(`WebSocketOnOpenHook - Websocket onOpen hook must be a valid function (export name: ${t.export})`);return e},"getWebSocketOnOpenHook"),wT=i(async(t,e,n,o,r,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,n,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function uz(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}i(uz,"createDeferred");async function lz(t,e,n){n(`Attempting WebSocket connection to '${e}'`);let o=new WebSocket(e);await new Promise((a,c)=>{let u=i(()=>{d(),n("WebSocket connection established with upstream"),a()},"onOpen"),l=i(m=>{d(),n(`WebSocket connection error: ${m}`),c(new Error("Upstream open failed"))},"onErr"),d=i(()=>{o.removeEventListener("open",u),o.removeEventListener("error",l)},"cleanup");o.addEventListener("open",u),o.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:r,response:s}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:r,outgoingSocket:o,response:s}}i(lz,"getDenoClientAndServerSockets");function dz(t){return t>=400&&t<600}i(dz,"isUpstreamHttpErrorStatus");async function pz(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(r.status!==101||!r.webSocket)return n(`WebSocket upgrade failed: ${r.status} ${r.statusText}`),{ok:!1,response:r};if(n(`WebSocket connected, received response ${r.status} - ${r.statusText}`),o)return{ok:!0,passthrough:!0,response:new Response(null,{status:101,webSocket:r.webSocket})};let s=new WebSocketPair,[a,c]=Object.values(s);r.webSocket.accept(),c.accept();let u=new Response(null,{status:101,webSocket:a});return{ok:!0,passthrough:!1,clientSocket:a,outgoingSocket:r.webSocket,serverSocket:c,response:u}}i(pz,"getCfClientAndServerSockets");function mz(t,e,n,o){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:"incoming"}),e.close()}),e.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:"outgoing"}),t.close()});let r=i((s,a)=>{if(o===void 0){s.addEventListener("message",c=>{a.send(c.data)});return}s.addEventListener("message",c=>{n.waitUntil(o.then(()=>a.send(c.data)).catch(n.log.error))})},"relayMessages");r(t,e),r(e,t)}i(mz,"wireUpPassthrough");function CT(t,e,n,o,r,s,a){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{o.log.error("WebSocket pipeline error",{direction:s}),e.close()}),t.addEventListener("message",c=>{try{let l=i(async d=>{await a;let m=await wT(d,t,e,n,o,r);m!==void 0&&e.send(m)},"innerPipeline")(c).catch(o.log.error);o.waitUntil(l)}catch(u){o.log.error(u)}})}i(CT,"wireUpListeners");async function ag(t,e){Q("handler.websocket-pipeline");let n=e.route.handler.options,o=ta(e);if(!n||!n.rewritePattern)throw new I("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=t.headers.get("Upgrade");if(!r||r!=="websocket")return z.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new I("Invalid options for this route");let s=na(e),a=n.__rewriteFunction(t,s),c=n.policies?.inbound?sg(n.policies.inbound,"inbound"):[],u=n.policies?.outbound?sg(n.policies.outbound,"outbound"):[],l=n.onOpen?RT(n.onOpen):void 0,d=c.length>0||u.length>0,m=d||l!==void 0,f,b,g;if(_.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let w=await lz(t.originalRequest,a,o);f=w.clientSocket,b=w.outgoingSocket,g=w.response}else{a=a.replace(/^(ws)/,"http");let w=await pz(t,a,o,!m);if(!w.ok){let C=w.response;if(dz(C.status))return C;let v=await C.text(),P=`WebSocket connection error - ${C.status}: ${C.statusText}, content: '${v}'`;return e.log.warn({outgoingUrl:a,status:C.status},P),z.badGateway(t,e,{detail:P})}if(w.passthrough)return w.response;f=w.serverSocket,b=w.outgoingSocket,g=w.response}let R=uz();if(R.promise.catch(()=>{}),d?(CT(f,b,t,e,c,"inbound",R.promise),CT(b,f,t,e,u,"outbound",R.promise)):mz(f,b,e,l?R.promise:void 0),l)try{await l(b,f,t,e),R.resolve()}catch(w){R.reject(w);try{f.close(1011,"onOpen hook failed")}catch{}try{b.close(1011,"onOpen hook failed")}catch{}throw new I("WebSocket onOpen hook failed",{cause:w})}else R.resolve();return g}i(ag,"webSocketPipelineHandler");It("websocket-pipeline",ag);var hz=ag;var cg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"AWSLoggingPlugin")}getTransport(){return new ug(this.options)}},ug=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new qe({name:"aws-log-transport",msDelay:10,dispatchFunction:i(async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n});o.ok||await He({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await He({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}},"dispatchFunction")});constructor({accessKeyId:e,logStreamName:n,logGroupName:o,secretAccessKey:r,region:s,fields:a}){Q("logging.aws"),this.awsClient=new td({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=n,this.region=s,this.environmentType=_.instance.loggingEnvironmentType,this.environmentStage=_.instance.loggingEnvironmentStage,this.environment=_.instance.deploymentName,this.fields=a??{}}log(e,n){e.messages.forEach(o=>{let r={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:In(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,n.properties??{}))};this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var lg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new dg(this.options)}},dg=class{static{i(this,"DynaTraceTransport")}constructor(e){Q("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#o;#n;#r;#i;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:In(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#o,"custom.environmentStage":this.#r,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let n=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});n.ok||await He({level:"error",messages:[`Failed to send logs to Dynatrace: ${n.status} - ${n.statusText}`]},n)}catch{await He({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"dyna-trace-log-transport",msDelay:10,dispatchFunction:this.#s})};var pg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"LokiLoggingPlugin")}getTransport(){return new hg(this.options)}},mg=class{static{i(this,"LokiStream")}constructor(e,n,o,r,s,a){this.level=e,this.environment=n,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function fz(t,e){return btoa(`${t}:${e}`)}i(fz,"createBasicDigest");var hg=class{static{i(this,"LokiTransport")}constructor(e){Q("logging.loki"),this.#o=e.url,this.#n=fz(e.username,e.password),this.#i=_.instance.loggingEnvironmentType,this.#s=_.instance.loggingEnvironmentStage,this.#r=_.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#o;#n;#r;#i;#s;#a;log(e,n){let o=new mg(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:In(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,n.properties??{});this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#u=i(e=>{let n={streams:[]};return e.forEach(o=>{let r=n.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},n.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),n},"#convertToLokiStreamsBatch");#l=i(async e=>{if(e.length===0)return;let n=this.#u(e);try{let o=await H.fetch(this.#o,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});o.ok||await He({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await He({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"loki-log-transport",msDelay:10,dispatchFunction:this.#l})};var fg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new gg(this.options)}},gg=class{static{i(this,"NewRelicTransport")}constructor(e){Q("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#o;#n;#r;#i;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({message:In(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#r,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let n=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});n.ok||await He({level:"error",messages:[`Failed to send logs to New Relic: ${n.status} - ${n.statusText}`]},n)}catch{await He({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"new-relic-log-transport",msDelay:10,dispatchFunction:this.#a})};var yg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"SplunkLoggingPlugin")}getTransport(){return new bg(this.options)}},bg=class{static{i(this,"SplunkTransport")}constructor(e){Q("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#o;#n;#r;#i;#s;#a;#u;#l;log(e,n){e.messages.forEach(o=>{let s={event:{message:In(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#r,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i,...n.properties??{}},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#c=i(async e=>{if(e.length!==0)try{for(let n of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let r=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:o});if(!r.ok){let s=await r.text();await He({level:"error",messages:[`Failed to send logs to Splunk: ${r.status} - ${r.statusText}`,`Response: ${s}`]},r)}}}catch(n){await He({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"#dispatchFunction");batcher=new qe({name:"splunk-log-transport",msDelay:10,dispatchFunction:this.#c})};var Sg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rg(this.options)}},Rg=class{static{i(this,"SumoLogicTransport")}constructor(e){Q("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#o=_.instance.loggingEnvironmentType,this.#n=_.instance.loggingEnvironmentStage,this.#t=_.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#o;#n;#r;#i;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:In(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#o,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId},this.#s,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let n=e.map(r=>JSON.stringify(r)).join(`
263
+ `,t.enqueue(e.encode(r)),!0}catch(r){return this.onerror?.(r),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,e){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!_v(t.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o=t,r;if(e?.parsedBody===void 0)try{r=await t.json()}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=e.parsedBody;let s;try{s=Array.isArray(r)?r.map(R=>mi.parse(R)):[mi.parse(r)]}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=s.some(R=>Hf(R));if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let R=this.validateSession(t);if(R)return R;let w=this.validateProtocolVersion(t);if(w)return w}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!s.some(R=>Ks(R))){for(let R of s)this.onmessage?.(R,{authInfo:e?.authInfo,request:o});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=s.find(R=>Hf(R)),l=u?u.params.protocolVersion:t.headers.get("mcp-protocol-version")??up;if(this._enableJsonResponse)return new Promise(R=>{this._streamMapping.set(c,{resolveJson:R,cleanup:i(()=>{this._streamMapping.delete(c)},"cleanup")});for(let w of s)Ks(w)&&this._requestToStreamMapping.set(w.id,c);for(let w of s)this.onmessage?.(w,{authInfo:e?.authInfo,request:o})});let d=new TextEncoder,m,f,b=new ReadableStream({start:i(R=>{m=R},"start"),cancel:i(()=>{f!==void 0&&clearInterval(f),this._streamMapping.get(c)?.controller===m&&this._streamMapping.delete(c)},"cancel")}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(g["mcp-session-id"]=this.sessionId);for(let R of s)Ks(R)&&(this._streamMapping.set(c,{controller:m,encoder:d,cleanup:i(()=>{f!==void 0&&clearInterval(f),this._streamMapping.delete(c);try{m.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(R.id,c));await this.writePrimingEvent(m,d,c,l);for(let R of s){let w,C;Ks(R)&&this._eventStore&&this.supportsEmptySSEData(l)&&(w=i(()=>{this.closeSSEStream(R.id)},"closeSSEStream"),C=i(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(R,{authInfo:e?.authInfo,request:o,closeSSEStream:w,closeStandaloneSSEStream:C})}return this._streamMapping.get(c)?.controller===m&&(f=this.startKeepAlive(m,d)),new Response(b,{status:200,headers:g})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let e=this.validateSession(t);if(e)return e;let n=this.validateProtocolVersion(t);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let e=t.headers.get("mcp-session-id");if(!e)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(e!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let e=t.headers.get("mcp-protocol-version");if(e!==null&&!this._supportedProtocolVersions.includes(e)){let n=`Bad Request: Unsupported protocol version: ${e} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(400,-32e3,n)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:t}of this._streamMapping.values())t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let e=this._requestToStreamMapping.get(t);if(!e)return;let n=this._streamMapping.get(e);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,e){let n=e?.relatedRequestId;if((Js(t)||Wu(t))&&(n=t.id),n===void 0){if(Js(t)||Wu(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(s===void 0||!a.replayedEventIds?.has(s))&&this.writeSSEEvent(a.controller,a.encoder,t,s);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let r=this._streamMapping.get(o);if(!this._enableJsonResponse){let s;this._eventStore&&(s=await this._eventStore.storeEvent(o,t),r=this._streamMapping.get(o)),r?.controller&&r?.encoder&&(s===void 0||!r.replayedEventIds?.has(s))&&this.writeSSEEvent(r.controller,r.encoder,t,s)}if(Js(t)||Wu(t)){this._requestResponseMap.set(n,t);let s=[...this._requestToStreamMapping.entries()].filter(([a,c])=>c===o).map(([a])=>a);if(s.every(a=>this._requestResponseMap.has(a))){if(!r){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(this._enableJsonResponse&&r.resolveJson){let a={"Content-Type":"application/json"};this.sessionId!==void 0&&(a["mcp-session-id"]=this.sessionId);let c=s.map(u=>this._requestResponseMap.get(u));c.length===1?r.resolveJson(Response.json(c[0],{status:200,headers:a})):r.resolveJson(Response.json(c,{status:200,headers:a})),r.cleanup()}else r.cleanup();for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a)}}}};var Dv=2,Wf=4,Uv=24,jv=16,Yf=512,b$=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,S$=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,R$=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,w$=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,C$=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,I$=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Hv(t){let e=t.route;return e&&typeof e=="object"?e:void 0}i(Hv,"readRoute");function v$(t){let e=Hv(t)?.path;return typeof e=="string"&&e.length>0?e:void 0}i(v$,"readRoutePath");function T$(t){let e=Hv(t)?.raw;if(typeof e!="function")return;let n=e();if(!n||typeof n!="object")return;let o=n.operationId;return typeof o=="string"&&o.length>0?o:void 0}i(T$,"readRouteOperationId");function Fv(t){if(!(t===void 0||!Number.isFinite(t)||t<100))return`${Math.trunc(t/100)}xx`}i(Fv,"deriveStatusClass");function Gv(t,e){if(!(!t&&!e))return t==="user"?e==="user-oauth"?"upstream_user_attributed":"gateway_user_attributed_only":t==="shared"?"shared_upstream_identity":t==="none"?"machine_identity":"unknown"}i(Gv,"deriveOriginAttributionMode");function Zv(t){if(!t)return;let e=t.toLowerCase();return e.includes("desktop")||e.includes("claude")||e.includes("chatgpt")?"desktop":e.includes("vscode")||e.includes("cursor")||e.includes("zed")||e.includes("jetbrains")||e.includes("ide")?"ide":e.includes("extension")?"extension":e.includes("agent")||e.includes("bot")||e.includes("worker")||e.includes("service")?"service":"unknown"}i(Zv,"deriveClientKind");function Bv(t,e){return e==="success"?"none":t===ee.MCP_REQUEST_RECEIVED||t===ee.MCP_REQUEST_REJECTED||t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_INITIALIZE_NEGOTIATED?"routing":t.startsWith("mcp_capability_")?"upstream":t===ee.MCP_REQUEST_COMPLETED?"egress":"none"}i(Bv,"deriveFailureStage");function Vv(t,e){return e==="success"?"none":e==="application_error"?"mcp_application":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_CAPABILITY_FAILED||t===ee.MCP_CAPABILITY_CONNECT_REQUIRED?"upstream":t===ee.MCP_REQUEST_REJECTED||t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}i(Vv,"deriveFailureOrigin");function Jv(t,e){return e==="success"?"none":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR||t===ee.MCP_REQUEST_REJECTED?"protocol":"none"}i(Jv,"deriveReasonClass");function P$(t){return t.length<=Yf?t:`${t.slice(0,Yf)}...`}i(P$,"truncateAnalyticsString");function A$(t){return P$(t.replace(S$,"$1[REDACTED]$3").replace(w$,"$1$2[REDACTED]").replace(R$,"$1$2[REDACTED]").replace(C$,"Bearer [REDACTED]").replace(I$,"Basic [REDACTED]"))}i(A$,"redactAnalyticsString");function Kv(t,e){if(t!==void 0){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return A$(t);if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return e>=Wf?"[DEPTH_LIMIT]":t.slice(0,jv).map(n=>Kv(n,e+1)).filter(n=>n!==void 0);if(typeof t=="object")return t instanceof Date?t.toISOString():e>=Wf?"[DEPTH_LIMIT]":Qf(t,e+1)}}i(Kv,"sanitizeAnalyticsValue");function Qf(t,e=0){if(!t)return;let n={};for(let[o,r]of Object.entries(t).slice(0,Uv)){if(b$.test(o)){n[o]="[REDACTED]";continue}let s=Kv(r,e);s!==void 0&&(n[o]=s)}return Object.keys(n).length===0?void 0:n}i(Qf,"sanitizeMcpAnalyticsAttributes");function Re(t){return t===void 0?null:t}i(Re,"nullable");function E$(t){let e=t.environment;return e&&typeof e=="object"&&typeof e.name=="string"?e.name:null}i(E$,"readEnvironment");function O$(t){let e=t.requestId;return typeof e=="string"&&e.length>0?e:null}i(O$,"readRequestId");function k$(t){if(t===void 0)return null;try{return JSON.stringify(t)}catch{return null}}i(k$,"attributesToJsonString");function Xf(t,e){let n=Qf(e.attributes),o=O$(t),r=e.ownerMode??null,s=e.upstreamAuthMode??null,a=e.clientKind??Zv(e.clientName)??null,c=Gv(r??void 0,s??void 0)??null,u=Fv(e.httpStatusCode)??null,l=e.reasonClass??Jv(e.eventType,e.outcome),d=e.failureOrigin??Vv(e.eventType,e.outcome),m=e.failureStage??Bv(e.eventType,e.outcome);return{schemaVersion:Dv,outcome:e.outcome,subjectId:Re(e.subjectId),environment:E$(t),traceId:e.traceId??o,spanId:Re(e.spanId),parentEventId:Re(e.parentEventId),mcpSessionId:Re(e.mcpSessionId),routeSurface:Re(e.routeSurface),routePath:e.routePath??v$(t)??null,operationId:e.operationId??T$(t)??null,virtualServerName:Re(e.virtualServerName),virtualServerTitle:Re(e.virtualServerTitle),upstreamServerName:Re(e.upstreamServerName),upstreamServerTitle:Re(e.upstreamServerTitle),upstreamBindingId:Re(e.upstreamBindingId),clientName:Re(e.clientName),clientTitle:Re(e.clientTitle),clientVersion:Re(e.clientVersion),clientKind:a,authProfileId:Re(e.authProfileId),upstreamAuthMode:s,ownerMode:r,authMethod:Re(e.authMethod),originAttributionMode:c,apiKeySub:Re(e.apiKeySub),httpMethod:Re(e.httpMethod),httpStatusCode:Re(e.httpStatusCode),statusClass:u,mcpMethod:Re(e.mcpMethod),mcpProtocolVersion:Re(e.mcpProtocolVersion),mcpStatus:Re(e.mcpStatus),mcpErrorType:Re(e.mcpErrorType),applicationError:Re(e.applicationError),applicationErrorCode:Re(e.applicationErrorCode),toolResultIsError:Re(e.toolResultIsError),transport:Re(e.transport),sessionId:Re(e.sessionId),capabilityType:Re(e.capabilityType),capabilityName:Re(e.capabilityName),capabilityTitle:Re(e.capabilityTitle),upstreamCapabilityName:Re(e.upstreamCapabilityName),upstreamCapabilityTitle:Re(e.upstreamCapabilityTitle),capabilitySchemaHash:Re(e.capabilitySchemaHash),toolPath:Re(e.toolPath),toolMethod:Re(e.toolMethod),toolOperationId:Re(e.toolOperationId),resourceUri:Re(e.resourceUri),resourceMimeType:Re(e.resourceMimeType),policyId:Re(e.policyId),policyAction:Re(e.policyAction),guardrailType:Re(e.guardrailType),guardrailDirection:Re(e.guardrailDirection),guardrailFindingCount:Re(e.guardrailFindingCount),redactionCount:Re(e.redactionCount),requestMutated:Re(e.requestMutated),responseMutated:Re(e.responseMutated),latencyMs:Re(e.latencyMs),gatewayLatencyMs:Re(e.gatewayLatencyMs),upstreamLatencyMs:Re(e.upstreamLatencyMs),authLatencyMs:Re(e.authLatencyMs),policyLatencyMs:Re(e.policyLatencyMs),requestBytes:Re(e.requestBytes),responseBytes:Re(e.responseBytes),estimatedInputTokens:Re(e.estimatedInputTokens),estimatedOutputTokens:Re(e.estimatedOutputTokens),estimatedContextTokens:Re(e.estimatedContextTokens),contextPressureBucket:Re(e.contextPressureBucket),responseMimeTypes:Re(e.responseMimeTypes),base64Suspected:Re(e.base64Suspected),truncated:Re(e.truncated),isLargePayloadRequest:Re(e.isLargePayloadRequest),isLargePayloadResponse:Re(e.isLargePayloadResponse),payloadCaptureMode:Re(e.payloadCaptureMode),reasonCode:Re(e.reasonCode),reasonClass:l,errorType:e.errorType??e.reasonCode??null,failureOrigin:d,failureStage:m,errorCode:Re(e.errorCode),customMetadataJson:Re(e.customMetadataJson),attributesJson:k$(n)}}i(Xf,"buildMcpAnalyticsMetadata");function Wv(t,e){try{t.analyticsContext.addAnalyticsEvent(e.value??1,e.eventType,Xf(t,e),e.unit)}catch(n){t.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:n instanceof Error?n.name:"unknown"})}}i(Wv,"emitMcpAnalyticsEvent");function Yp(t,e){if(!t||typeof t!="object")return;let n=t[e];return typeof n=="string"?n:void 0}i(Yp,"readStringProperty");function Yv(t){let e=Yp(t,"method");if(!e)return;let n=t&&typeof t=="object"?t.params:void 0;switch(e){case"tools/call":return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"tool",capabilityName:Yp(n,"name"),mcpMethod:"tools/call"};case"prompts/get":return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"prompt",capabilityName:Yp(n,"name"),mcpMethod:"prompts/get"};case"resources/read":{let o=Yp(n,"uri");return{eventType:ee.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"resource",capabilityName:o,resourceUri:o,mcpMethod:"resources/read"}}default:return}}i(Yv,"buildCapabilityInvokedAnalyticsInput");var xr=class{constructor(e,n){this.schema=e;this.validateFn=n}schema;validateFn;static{i(this,"CustomValidator")}validate(e){return this.validateFn(e)}};function Qv(t,e){let n=t.virtualServerName??e;return n===void 0?t:{...t,virtualServerName:n}}i(Qv,"injectMcpServerName");import{AsyncLocalStorage as _$}from"node:async_hooks";var Qp=new _$;function Xv(t,e,n){return Qp.run({zuploContext:t,requestData:e},n)}i(Xv,"runWithInvokeContext");function eg(){return Qp.getStore()?.requestData.headers??{}}i(eg,"getInvokeHeaders");function Ws(){let t=Qp.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}i(Ws,"getInvokeContext");function eT(){return Qp.getStore()?.requestData.user?.sub}i(eT,"getInvokeSubjectId");var tl=class{static{i(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,n,o,r,s){this.type=t,this.name=e,this.prefix=n,this.value=o,this.suffix=r,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},x$=/[$_\p{ID_Start}]/u,M$=/[$_\u200C\u200D\p{ID_Continue}]/u,ng=".*";function L$(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}i(L$,"Re");function oT(t,e=!1){let n=[],o=0;for(;o<t.length;){let r=t[o],s=i(function(a){if(!e)throw new TypeError(a);n.push({type:"INVALID_CHAR",index:o,value:t[o++]})},"c");if(r==="*"){n.push({type:"ASTERISK",index:o,value:t[o++]});continue}if(r==="+"||r==="?"){n.push({type:"OTHER_MODIFIER",index:o,value:t[o++]});continue}if(r==="\\"){n.push({type:"ESCAPED_CHAR",index:o++,value:t[o++]});continue}if(r==="{"){n.push({type:"OPEN",index:o,value:t[o++]});continue}if(r==="}"){n.push({type:"CLOSE",index:o,value:t[o++]});continue}if(r===":"){let a="",c=o+1;for(;c<t.length;){let u=t.substr(c,1);if(c===o+1&&x$.test(u)||c!==o+1&&M$.test(u)){a+=t[c++];continue}break}if(!a){s(`Missing parameter name at ${o}`);continue}n.push({type:"NAME",index:o,value:a}),o=c;continue}if(r==="("){let a=1,c="",u=o+1,l=!1;if(t[u]==="?"){s(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!L$(t[u],!1)){s(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){s(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){s(`Unbalanced pattern at ${o}`);continue}if(!c){s(`Missing pattern at ${o}`);continue}n.push({type:"REGEX",index:o,value:c}),o=u;continue}n.push({type:"CHAR",index:o,value:t[o++]})}return n.push({type:"END",index:o,value:""}),n}i(oT,"v");function rT(t,e={}){let n=oT(t);e.delimiter??="/#?",e.prefixes??="./";let o=`[^${Un(e.delimiter)}]+?`,r=[],s=0,a=0,c="",u=new Set,l=i(P=>{if(a<n.length&&n[a].type===P)return n[a++].value},"a"),d=i(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),m=i(P=>{let A=l(P);if(A!==void 0)return A;let{type:x,index:L}=n[a];throw new TypeError(`Unexpected ${x} at ${L}, expected ${P}`)},"d"),f=i(()=>{let P="",A;for(;A=l("CHAR")??l("ESCAPED_CHAR");)P+=A;return P},"T"),b=i(P=>P,"Se"),g=e.encodePart||b,R="",w=i(P=>{R+=P},"U"),C=i(()=>{R.length&&(r.push(new tl(3,"","",g(R),"",3)),R="")},"$"),v=i((P,A,x,L,U)=>{let oe=3;switch(U){case"?":oe=1;break;case"*":oe=0;break;case"+":oe=2;break}if(!A&&!x&&oe===3){w(P);return}if(C(),!A&&!x){if(!P)return;r.push(new tl(3,"","",g(P),"",oe));return}let B;x?x==="*"?B=ng:B=x:B=o;let te=2;B===o?(te=1,B=""):B===ng&&(te=0,B="");let he;if(A?he=A:x&&(he=s++),u.has(he))throw new TypeError(`Duplicate name '${he}'.`);u.add(he),r.push(new tl(te,he,g(P),B,g(L),oe))},"V");for(;a<n.length;){let P=l("CHAR"),A=l("NAME"),x=l("REGEX");if(!A&&!x&&(x=l("ASTERISK")),A||x){let U=P??"";e.prefixes.indexOf(U)===-1&&(w(U),U=""),C();let oe=d();v(U,A,x,"",oe);continue}let L=P??l("ESCAPED_CHAR");if(L){w(L);continue}if(l("OPEN")){let U=f(),oe=l("NAME"),B=l("REGEX");!oe&&!B&&(B=l("ASTERISK"));let te=f();m("CLOSE");let he=d();v(U,oe,B,te,he);continue}C(),m("END")}return r}i(rT,"D");function Un(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(Un,"S");function tT(t){return t&&t.ignoreCase?"ui":"u"}i(tT,"X");function N$(t,e,n){return iT(rT(t,n),e,n)}i(N$,"Z");function Ys(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}i(Ys,"k");function iT(t,e,n={}){n.delimiter??="/#?",n.prefixes??="./",n.sensitive??=!1,n.strict??=!1,n.end??=!0,n.start??=!0,n.endsWith="";let o=n.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?o+=Un(c.value):o+=`(?:${Un(c.value)})${Ys(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${Un(n.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=ng),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?o+=`(${l})${Ys(c.modifier)}`:o+=`((?:${l})${Ys(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){o+=`(?:${Un(c.prefix)}(${l})${Un(c.suffix)})`,o+=Ys(c.modifier);continue}o+=`(?:${Un(c.prefix)}`,o+=`((?:${l})(?:`,o+=Un(c.suffix),o+=Un(c.prefix),o+=`(?:${l}))*)${Un(c.suffix)})`,c.modifier===0&&(o+="?")}let r=`[${Un(n.endsWith)}]|$`,s=`[${Un(n.delimiter)}]`;if(n.end)return n.strict||(o+=`${s}?`),n.endsWith.length?o+=`(?=${r})`:o+="$",new RegExp(o,tT(n));n.strict||(o+=`(?:${s}(?=${r}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=n.delimiter.indexOf(c)>-1)}return a||(o+=`(?=${s}|${r})`),new RegExp(o,tT(n))}i(iT,"F");var Lr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},q$={delimiter:".",prefixes:"",sensitive:!0,strict:!0},$$={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function z$(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}i(z$,"J");function sT(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}i(sT,"Q");function D$(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}i(D$,"Ee");function aT(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}i(aT,"W");var cT=["ftp","file","http","https","ws","wss"];function uT(t){if(!t)return!0;for(let e of cT)if(t.test(e))return!0;return!1}i(uT,"N");function U$(t,e){if(t=sT(t,"#"),e||t==="")return t;let n=new URL("https://example.com");return n.hash=t,n.hash?n.hash.substring(1,n.hash.length):""}i(U$,"te");function j$(t,e){if(t=sT(t,"?"),e||t==="")return t;let n=new URL("https://example.com");return n.search=t,n.search?n.search.substring(1,n.search.length):""}i(j$,"re");function H$(t,e){return e||t===""?t:aT(t)?pT(t):dT(t)}i(H$,"ne");function F$(t,e){if(e||t==="")return t;let n=new URL("https://example.com");return n.password=t,n.password}i(F$,"se");function G$(t,e){if(e||t==="")return t;let n=new URL("https://example.com");return n.username=t,n.username}i(G$,"ie");function Z$(t,e,n){if(n||t==="")return t;if(e&&!cT.includes(e))return new URL(`${e}:${t}`).pathname;let o=t[0]=="/";return t=new URL(o?t:"/-"+t,"https://example.com").pathname,o||(t=t.substring(2,t.length)),t}i(Z$,"ae");function B$(t,e,n){return lT(e)===t&&(t=""),n||t===""?t:mT(t)}i(B$,"oe");function V$(t,e){return t=D$(t,":"),e||t===""?t:og(t)}i(V$,"ce");function lT(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}i(lT,"_");function og(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}i(og,"y");function J$(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}i(J$,"le");function K$(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}i(K$,"fe");function dT(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}i(dT,"z");function pT(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}i(pT,"j");function mT(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}i(mT,"K");function W$(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}i(W$,"he");function Y$(t){return t===""?t:new URL(`data:${t}`).pathname}i(Y$,"ue");function Q$(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}i(Q$,"de");function X$(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}i(X$,"pe");var ez=class{static{i(this,"H")}#e;#t=[];#o={};#n=0;#r=1;#i=0;#s=0;#a=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#o}parse(){for(this.#t=oT(this.#e,!0);this.#n<this.#t.length;this.#n+=this.#r){if(this.#r=1,this.#t[this.#n].type==="END"){if(this.#s===0){this.#g(),this.#f()?this.#c(9,1):this.#y()?this.#c(8,1):this.#c(7,0);continue}else if(this.#s===2){this.#h(5);continue}this.#c(10,0);break}if(this.#a>0)if(this.#P())this.#a-=1;else continue;if(this.#T()){this.#a+=1;continue}switch(this.#s){case 0:this.#w()&&this.#h(1);break;case 1:if(this.#w()){this.#O();let t=7,e=1;this.#C()?(t=2,e=3):this.#l&&(t=2),this.#c(t,e)}break;case 2:this.#S()?this.#h(3):(this.#R()||this.#y()||this.#f())&&this.#h(5);break;case 3:this.#I()?this.#c(4,1):this.#S()&&this.#c(5,1);break;case 4:this.#S()&&this.#c(5,1);break;case 5:this.#A()?this.#u+=1:this.#E()&&(this.#u-=1),this.#v()&&!this.#u?this.#c(6,1):this.#R()?this.#c(7,0):this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 6:this.#R()?this.#c(7,0):this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 7:this.#y()?this.#c(8,1):this.#f()&&this.#c(9,1);break;case 8:this.#f()&&this.#c(9,1);break;case 9:break;case 10:break}}this.#o.hostname!==void 0&&this.#o.port===void 0&&(this.#o.port="")}#c(t,e){switch(this.#s){case 0:break;case 1:this.#o.protocol=this.#m();break;case 2:break;case 3:this.#o.username=this.#m();break;case 4:this.#o.password=this.#m();break;case 5:this.#o.hostname=this.#m();break;case 6:this.#o.port=this.#m();break;case 7:this.#o.pathname=this.#m();break;case 8:this.#o.search=this.#m();break;case 9:this.#o.hash=this.#m();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#o.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#o.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#o.search??="")),this.#d(t,e)}#d(t,e){this.#s=t,this.#i=this.#n+e,this.#n+=e,this.#r=0}#g(){this.#n=this.#i,this.#r=0}#h(t){this.#g(),this.#s=t}#b(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#p(t,e){let n=this.#b(t);return n.value===e&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#w(){return this.#p(this.#n,":")}#C(){return this.#p(this.#n+1,"/")&&this.#p(this.#n+2,"/")}#S(){return this.#p(this.#n,"@")}#I(){return this.#p(this.#n,":")}#v(){return this.#p(this.#n,":")}#R(){return this.#p(this.#n,"/")}#y(){if(this.#p(this.#n,"?"))return!0;if(this.#t[this.#n].value!=="?")return!1;let t=this.#b(this.#n-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#p(this.#n,"#")}#T(){return this.#t[this.#n].type=="OPEN"}#P(){return this.#t[this.#n].type=="CLOSE"}#A(){return this.#p(this.#n,"[")}#E(){return this.#p(this.#n,"]")}#m(){let t=this.#t[this.#n],e=this.#b(this.#i).index;return this.#e.substring(e,t.index)}#O(){let t={};Object.assign(t,Lr),t.encodePart=og;let e=N$(this.#m(),void 0,t);this.#l=uT(e)}},tg=["protocol","username","password","hostname","port","pathname","search","hash"],Mr="*";function nT(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let n=new URL(t,e);return{protocol:n.protocol.substring(0,n.protocol.length-1),username:n.username,password:n.password,hostname:n.hostname,port:n.port,pathname:n.pathname,search:n.search!==""?n.search.substring(1,n.search.length):void 0,hash:n.hash!==""?n.hash.substring(1,n.hash.length):void 0}}i(nT,"ge");function Qo(t,e){return e?el(t):t}i(Qo,"b");function Xu(t,e,n){let o;if(typeof e.baseURL=="string")try{o=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Qo(o.protocol.substring(0,o.protocol.length-1),n)),!n&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Qo(o.username,n)),!n&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Qo(o.password,n)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Qo(o.hostname,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Qo(o.port,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Qo(o.pathname,n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Qo(o.search.substring(1,o.search.length),n)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Qo(o.hash.substring(1,o.hash.length),n))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=V$(e.protocol,n)),typeof e.username=="string"&&(t.username=G$(e.username,n)),typeof e.password=="string"&&(t.password=F$(e.password,n)),typeof e.hostname=="string"&&(t.hostname=H$(e.hostname,n)),typeof e.port=="string"&&(t.port=B$(e.port,t.protocol,n)),typeof e.pathname=="string"){if(t.pathname=e.pathname,o&&!z$(t.pathname,n)){let r=o.pathname.lastIndexOf("/");r>=0&&(t.pathname=Qo(o.pathname.substring(0,r+1),n)+t.pathname)}t.pathname=Z$(t.pathname,t.protocol,n)}return typeof e.search=="string"&&(t.search=j$(e.search,n)),typeof e.hash=="string"&&(t.hash=U$(e.hash,n)),t}i(Xu,"w");function el(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}i(el,"C");function tz(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(tz,"Oe");function nz(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let n=".*",o=`[^${tz(e.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){s+=el(c.value);continue}s+=`{${el(c.value)}}${Ys(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,m=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&m&&!m.prefix.length&&!m.suffix.length)if(m.type===3){let f=m.value.length>0?m.value[0]:"";l=r.test(f)}else l=!m.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let f=d.value[d.value.length-1];l=e.prefixes.includes(f)}l&&(s+="{"),s+=el(c.prefix),u&&(s+=`:${c.name}`),c.type===2?s+=`(${c.value})`:c.type===1?u||(s+=`(${o})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?s+="*":s+=`(${n})`),c.type===1&&u&&c.suffix.length&&r.test(c.suffix[0])&&(s+="\\"),s+=el(c.suffix),l&&(s+="}"),c.modifier!==3&&(s+=Ys(c.modifier))}return s}i(nz,"ke");var Xp=class{static{i(this,"me")}#e;#t={};#o={};#n={};#r={};#i=!1;constructor(t={},e,n){try{let o;if(typeof e=="string"?o=e:n=e,typeof t=="string"){let c=new ez(t);if(c.parse(),t=c.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let r={ignoreCase:n.ignoreCase===!0},s={pathname:Mr,protocol:Mr,username:Mr,password:Mr,hostname:Mr,port:Mr,search:Mr,hash:Mr};this.#e=Xu(s,t,!0),lT(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of tg){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#o[a]=[],a){case"protocol":Object.assign(c,Lr),c.encodePart=og;break;case"username":Object.assign(c,Lr),c.encodePart=J$;break;case"password":Object.assign(c,Lr),c.encodePart=K$;break;case"hostname":Object.assign(c,q$),aT(u)?c.encodePart=pT:c.encodePart=dT;break;case"port":Object.assign(c,Lr),c.encodePart=mT;break;case"pathname":uT(this.#t.protocol)?(Object.assign(c,$$,r),c.encodePart=W$):(Object.assign(c,Lr,r),c.encodePart=Y$);break;case"search":Object.assign(c,Lr,r),c.encodePart=Q$;break;case"hash":Object.assign(c,Lr,r),c.encodePart=X$;break}try{this.#r[a]=rT(u,c),this.#t[a]=iT(this.#r[a],this.#o[a],c),this.#n[a]=nz(this.#r[a],c),this.#i=this.#i||this.#r[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},e){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?n=Xu(n,t,!1):n=Xu(n,nT(t,e),!1)}catch{return!1}let o;for(o of tg)if(!this.#t[o].exec(n[o]))return!1;return!0}exec(t={},e){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=Xu(n,t,!1):n=Xu(n,nT(t,e),!1)}catch{return null}let o={};e?o.inputs=[t,e]:o.inputs=[t];let r;for(r of tg){let s=this.#t[r].exec(n[r]);if(!s)return null;let a={};for(let[c,u]of this.#o[r].entries())if(typeof u=="string"||typeof u=="number"){let l=s[c+1];a[u]=l}o[r]={input:n[r]??"",groups:a}}return o}static compareComponent(t,e,n){let o=i((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),r=new tl(3,"","","","",3),s=new tl(0,"","","","",3),a=i((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=o(c[l],u[l]);if(d)return d}return c.length===u.length?0:o(c[l]??r,u[l]??r)},"s");return!e.#n[t]&&!n.#n[t]?0:e.#n[t]&&!n.#n[t]?a(e.#r[t],[s]):!e.#n[t]&&n.#n[t]?a([s],n.#r[t]):a(e.#r[t],n.#r[t])}get protocol(){return this.#n.protocol}get username(){return this.#n.username}get password(){return this.#n.password}get hostname(){return this.#n.hostname}get port(){return this.#n.port}get pathname(){return this.#n.pathname}get search(){return this.#n.search}get hash(){return this.#n.hash}get hasRegExpGroups(){return this.#i}};var em=class{static{i(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new Xp({pathname:e});let n=/:(\w+)(\([^)]*\))?[*+?]?/g,o;for(;(o=n.exec(e))!==null;)this.expectedPathParams.add(o[1])}addParameter(e,n,o){let r=this.getParameterValue(e,n,o);if(r!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new I(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,r);break;case"query":this.addQueryParameter(e.name,r);break;default:break}}getParameterValue(e,n,o){switch(e.in){case"path":return n?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,n){this.pathParams[e]=String(n)}addQueryParameter(e,n){Array.isArray(n)?n.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof n=="object"&&n!==null?this.searchParams.append(e,JSON.stringify(n)):this.searchParams.append(e,String(n))}toString(){let e=[...this.expectedPathParams].filter(s=>!this.seenPathParams.has(s));if(e.length>0)throw new I(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let n=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(s,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):s),o=this.cleanupUrlPatternSyntax(n),r=this.searchParams.toString();return r?`${o}?${r}`:o}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var tm=class{constructor(e){this.routeData=e}routeData;static{i(this,"McpUrlBuilder")}build(e,n){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,r=this.routeData.raw()?.parameters||[],s=new em(o);for(let a of r)s.addParameter(a,e,n);return s.toString()}};var nm=class t{static{i(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>p.email()],["uri",()=>p.url()],["url",()=>p.url()],["date",()=>p.iso.date()],["date-time",()=>p.iso.datetime()],["time",()=>p.iso.time()],["ipv4",()=>p.ipv4()],["ipv6",()=>p.ipv6()],["uuid",()=>p.guid()],["int32",()=>p.int32()],["int64",()=>p.int64()],["float",()=>p.number()],["double",()=>p.number()]]);static get(e){return t.formatter.get(e)}static register(e,n){t.formatter.set(e,n)}},Qs=class t{static{i(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,n){let o={path:[],definitions:{},visitedRefs:new Set,...n};return t.transpileSchema(e,o)}static transpileSchema(e,n){if(!e)return p.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,n);if(e.allOf)return t.transpileAllOf(e.allOf,n);if(e.oneOf)return t.transpileOneOf(e.oneOf,n);if(e.anyOf)return t.transpileAnyOf(e.anyOf,n);if(e.not)return t.transpileNot(e.not,n);let o=t.transpileByType(e,n);return o=t.applyCommonModifiers(o,e),o}catch(o){let r=n.path.join(".");throw new Error(`Failed to transpile schema at path "${r}": ${o.message}`)}}static transpileByType(e,n){let o=e.type;!o&&e.properties&&(o="object");let r=t.typeTranspilers.get(o||"unknown");return r?r(e,n):p.unknown()}static transpileString(e,n){if(e.enum)return p.enum(e.enum);let o=e.format?nm.get(e.format):null,r=o?o():p.string();if(r instanceof p.ZodString){let s=r;return e.minLength!==void 0&&(s=s.min(e.minLength)),e.maxLength!==void 0&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),s}else e.minLength||e.maxLength||e.pattern;return r}static applyNumericConstraints(e,n,o){let r=e;if(n.minimum!==void 0&&(r=r.min(n.minimum)),n.maximum!==void 0&&(r=r.max(n.maximum)),n.exclusiveMinimum!==void 0){let s;if(typeof n.exclusiveMinimum=="number")s=n.exclusiveMinimum;else if(n.minimum!==void 0)s=n.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${o.path.join(".")}"`);r=r.gt(s)}if(n.exclusiveMaximum!==void 0){let s;if(typeof n.exclusiveMaximum=="number")s=n.exclusiveMaximum;else if(n.maximum!==void 0)s=n.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${o.path.join(".")}"`);r=r.lt(s)}return r}static transpileNumber(e,n){let o=p.number();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileInteger(e,n){let o=p.int();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileBoolean(e,n){return p.boolean()}static transpileArray(e,n){let o=e.items?t.transpileSchema(e.items,{...n,path:[...n.path,"items"]}):p.unknown(),r=p.array(o);return e.minItems!==void 0&&(r=r.min(e.minItems)),e.maxItems!==void 0&&(r=r.max(e.maxItems)),e.uniqueItems&&(r=r.refine(s=>new Set(s).size===s.length,{message:"Array must contain unique items"})),r}static transpileObject(e,n){let o;if(e.properties){let r={},s=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...n,path:[...n.path,c]},d=t.transpileSchema(u,l);s.has(c)||(d=d.optional()),r[c]=d}let a=p.object(r);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),o=a}else if(e.additionalProperties===!1)o=p.object({}).strict();else if(typeof e.additionalProperties=="object"){let r=t.transpileSchema(e.additionalProperties,n);o=p.record(p.string(),r)}else o=p.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(o=o.refine(r=>{let s=Object.keys(r).length;return!(e.minProperties!==void 0&&s<e.minProperties||e.maxProperties!==void 0&&s>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),o}static buildPropertyCountErrorMessage(e,n){return e!==void 0&&n!==void 0?`Object must have between ${e} and ${n} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${n} properties`}static transpileNull(e,n){return p.null()}static transpileAllOf(e,n){let o=e.map((a,c)=>t.transpileSchema(a,{...n,path:[...n.path,`allOf[${c}]`]}));if(o.length===0)return p.unknown();let r=o.reduce((a,c)=>a.and(c)),s=e.filter(a=>a?.additionalProperties===!1).map(a=>Object.keys(a.properties??{}));return s.length===0?r:r.superRefine((a,c)=>{if(!(typeof a!="object"||a===null||Array.isArray(a)))for(let u of s){let l=Object.keys(a).filter(d=>!u.includes(d));l.length>0&&c.addIssue({code:"custom",message:`Unrecognized key(s) in object: ${l.map(d=>`'${d}'`).join(", ")}`})}})}static transpileOneOf(e,n){let o=e.map((r,s)=>t.transpileSchema(r,{...n,path:[...n.path,`oneOf[${s}]`]}));return o.length===0?p.never():o.length===1?o[0]:p.union(o)}static transpileAnyOf(e,n){return t.transpileOneOf(e,n)}static transpileNot(e,n){let o=t.transpileSchema(e,{...n,path:[...n.path,"not"]});return p.unknown().refine(r=>!o.safeParse(r).success,{message:"Value must not match the schema"})}static resolveReference(e,n){if(n.visitedRefs?.has(e))return p.lazy(()=>t.resolveReference(e,n));n.visitedRefs?.add(e);let o=e.split("/");if(o[0]==="#"&&o[1]==="definitions"&&n.definitions){let r=n.definitions[o[2]];if(r)return t.transpileSchema(r,n)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,n){let o=e;return n.nullable&&(o=o.nullable()),n.default!==void 0&&(o=o.default(n.default)),n.description&&(o=o.describe(n.description)),n.examples&&n.examples.length>0&&(o=o.meta({examples:n.examples})),o}static registerTypeTranspiler(e,n){t.typeTranspilers.set(e,n)}static registerFormatSchema(e,n){nm.register(e,n)}};var om=class{constructor(e){this.schema=e}schema;static{i(this,"JSONSchemaBuilder")}build(){return Qs.run(this.schema)}},rm=class{constructor(e,n){this.routeData=e;this.contentType=n}routeData;contentType;static{i(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let n=e.content[this.contentType].schema;return n?Qs.run(n):null}},im=class{constructor(e){this.parameters=e}parameters;static{i(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let n of this.parameters)e[n.name]=this.buildParameterSchema(n);return p.object(e)}buildParameterSchema(e){let n;e.schema?n=Qs.run(e.schema):n=p.string(),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description));let o=[];if(e.schema?.example!==void 0&&o.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&o.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?o.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(r=>{r?.value!==void 0&&o.push(r.value)})),e.example!==void 0&&o.push(e.example),o.length>0){let r=[...new Set(o.map(s=>JSON.stringify(s)))].map(s=>JSON.parse(s));n=n.meta({examples:r})}return n}};var Ti=class t{static{i(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let n=new t;return n.root=e,n}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let n=p.toJSONSchema(e);return new xr(n,o=>{let r=e.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}buildFromComponents(){let e=p.strictObject(this.components),n=p.toJSONSchema(e);return new xr(n,o=>{let r=e.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1},n=p.strictObject({});return new xr(e,o=>{let r=n.safeParse(o);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:p.prettifyError(r.error),errorData:p.treeifyError(r.error)}})}},Xs=class t{static{i(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new om(e)}static createRequestBodyBuilder(e,n){return new rm(e,n)}static createParameterBuilder(e,n){let o=n?e.filter(r=>r.in===n):e;return new im(o)}static createValidatorBuilder(e,n){let o=new Ti,r=e.raw()?.parameters||[];if(n){let u=t.createRequestBodyBuilder(e,n);o.withBody(u.build())}let s=t.createParameterBuilder(r,"query");o.withQueryParams(s.build());let a=t.createParameterBuilder(r,"path");o.withPathParams(a.build());let c=t.createParameterBuilder(r,"header");return o.withHeaders(c.build()),o}static createPromptValidatorBuilder(e){let n=new Ti,r=e.raw()?.requestBody;if(!r?.content||!r.content["application/json"])return n;let a=t.createRequestBodyBuilder(e,"application/json");return Ti.withRoot(a.build())}static createObjectValidatorBuilder(e){let n=new Ti;if(!e||Object.keys(e).length===0)return n;let o=t.createJsonSchemaBuilder(e);return Ti.withRoot(o.build())}};function rg(t){let e;try{e=JSON.parse(t)}catch{return}if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}i(rg,"parseStructuredContent");function oz(t){let e=t.headers.get("accept");if(!e)return t;let n=e.replace(/application\/json/gi,"application/json").replace(/text\/event-stream/gi,"text/event-stream").replace(/(^|[ ,;])event-stream($|[ ,;])/i,"$1text/event-stream$2");if(!n.includes("text/event-stream")){if(!n.includes("application/json"))return t;n=`${n}, text/event-stream`}if(n===e)return t;let o=new Request(t,{headers:new Headers(t.headers)});return o.headers.set("accept",n),o}i(oz,"normalizeLegacyAcceptHeader");function rz(t){let e=t;return e.properties?Object.entries(e.properties).map(([n,o])=>({name:n,description:o?.description??`Prompt for ${n}`,required:e.required?.includes(n)??!1})):[]}i(rz,"jsonSchemaToPromptArguments");var sm=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:n,key:o}){let r=e.debugMode??!1,s=t.instances.get(o);if(s)r&&n.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(s=new t(e,n),s.registerFromOperations(s.opts.operations??[]),s.registerToolsFromFileSources(s.opts.files??[]),s.registerPromptsFromFileSources(s.opts.prompts??[]),s.registerResourcesFromFileSources(s.opts.resources??[]),t.instances.set(o,s),r){let c=s.tools.size,u=s.prompts.size,l=s.resources.size,d=Date.now()-a;n.log.debug("MCP Server cold start",{routeKey:o,toolCount:c,promptCount:u,resourceCount:l,totalElapsedMs:d,debugMode:r,includeOutputSchema:s.includeOutputSchema,includeStructuredContent:s.includeStructuredContent})}}return s}opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;tools=new Map;prompts=new Map;resources=new Map;includeOutputSchema;includeStructuredContent;debugMode;jsonSchemaValidator=new vi({draft:"7",shortcircuit:!1});constructor(e,n){this.debugMode=e.debugMode??!1,this.context=n,this.opts=e,this.serverName=e.name??n.route?.path??void 0,this.serverDisplayName=e.name??"Zuplo MCP Server",this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}emitEvent(e,n){let o=Qv(n,this.serverName),r=o.subjectId??eT();Wv(e,r===void 0?o:{...o,subjectId:r})}async handleRequest(e,n){let o=Date.now(),r=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null,s=e.user?.sub;try{let a=await e.clone().json().catch(()=>({})),c=typeof a?.method=="string"?a.method:null;c==="tools/call"&&(n.custom.mcpCallToolRequest=a),this.emitEvent(n,{eventType:ee.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:c??void 0,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s}),s!==void 0&&this.emitEvent(n,{eventType:ee.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s});let u=Yv(a);u&&this.emitEvent(n,{...u,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0});try{dt.getContextExtensions(n).addHandlerResponseHook(g=>{let R=Date.now()-o;this.emitEvent(n,{eventType:ee.MCP_REQUEST_COMPLETED,outcome:g.status>=400?"failure":"success",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:g.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:R,subjectId:s})})}catch{}if(this.debugMode)switch(n.log.debug("MCP Server request start",{method:a.method,requestId:a.id,routePath:n.route?.path}),a.method){case"tools/list":n.log.debug("MCP Server list tools request",{toolCount:this.tools.size,toolNames:Array.from(this.tools.keys())});break;case"prompts/list":n.log.debug("MCP Server list prompts request",{promptCount:this.prompts.size,promptNames:Array.from(this.prompts.keys())});break;case"resources/list":n.log.debug("MCP Server list resources request",{resourceCount:this.resources.size,resourceNames:Array.from(this.resources.keys())});break}let l=new Kf({name:this.serverDisplayName,version:this.opts.version??"0.0.0"},{jsonSchemaValidator:this.jsonSchemaValidator,capabilities:{tools:{supported:!0,available:Array.from(this.tools.keys())},prompts:{},resources:{}}});this.wireRequestHandlers(l);let d=new zv({enableJsonResponse:!0});await l.connect(d);let m=await d.handleRequest(oz(e)),f=Date.now()-o,b=m.status>=200&&m.status<300;switch(a.method){case"initialize":{let g=a?.params?.clientInfo,R=a?.params?.protocolVersion,w=typeof g?.name=="string"?g.name:void 0,C=typeof g?.title=="string"?g.title:void 0,v=typeof g?.version=="string"?g.version:void 0,P=typeof R=="string"?R:void 0;this.emitEvent(n,{eventType:ee.MCP_INITIALIZE_NEGOTIATED,outcome:b?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:w,clientTitle:C,clientVersion:v,mcpProtocolVersion:P,latencyMs:f}),b||this.emitEvent(n,{eventType:ee.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:w,clientVersion:v,mcpProtocolVersion:P,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break;case"resources/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break;case"prompts/list":this.emitEvent(n,{eventType:ee.MCP_CAPABILITY_LISTED,outcome:b?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:m.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:f});break}if(this.debugMode){let g=await m.clone().json().catch(()=>({}));n.log.debug("MCP Server response complete",{status:m.status,requestMethod:a.method,requestId:a.id,totalElapsedMs:f,respData:g})}return m}catch(a){let c=Date.now()-o;return n.log.error("MCP server internal error",{elapsedMs:c,err:a}),new Response("Internal error",{status:500})}}wireRequestHandlers(e){e.setRequestHandler("tools/list",async()=>({tools:Array.from(this.tools.entries()).map(([n,o])=>({name:n,description:o.description,inputSchema:o.validator.schema,...o.outputSchema&&{outputSchema:o.outputSchema},...o.annotations&&{annotations:o.annotations},...o._meta&&{_meta:o._meta}}))})),e.setRequestHandler("tools/call",async n=>{let o=n.params.name,r=this.tools.get(o);if(!r)throw new je(fe.InvalidParams,`Tool "${o}" not found`);let s=n.params.arguments??{},a=r.validator.validate(s);if(!a.success)throw new je(fe.InvalidParams,a.errorMessage?`Invalid arguments for tool '${o}': ${a.errorMessage}`:`Invalid arguments for tool '${o}'`,a.errorData);try{return await r.handler(a.data,n.params._meta)}catch(c){return{content:[{type:"text",text:c instanceof Error?c.message:"Tool execution error"}],isError:!0}}}),e.setRequestHandler("prompts/list",async()=>({prompts:Array.from(this.prompts.entries()).map(([n,o])=>({name:n,description:o.description,arguments:rz(o.validator.schema)}))})),e.setRequestHandler("prompts/get",async n=>{let o=n.params.name,r=this.prompts.get(o);if(!r)throw new je(fe.InvalidParams,`Prompt "${o}" not found`);let s=n.params.arguments??{},a=r.validator.validate(s);if(!a.success)throw new je(fe.InvalidParams,a.errorMessage?`Invalid arguments for prompt '${o}': ${a.errorMessage}`:`Invalid arguments for prompt '${o}'`,a.errorData);try{let c=await r.generator(a.data);return{...r.description!==void 0&&{description:r.description},messages:c}}catch(c){throw new je(fe.InternalError,c instanceof Error?c.message:"Prompt generation error")}}),e.setRequestHandler("resources/list",async()=>({resources:Array.from(this.resources.entries()).map(([n,o])=>({name:n,uri:o.uri,...o.metadata.title!==void 0&&{title:o.metadata.title},...o.metadata.description!==void 0&&{description:o.metadata.description},...o.metadata.mimeType!==void 0&&{mimeType:o.metadata.mimeType},...o.metadata._meta!==void 0&&{_meta:o.metadata._meta}}))})),e.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:[]})),e.setRequestHandler("resources/read",async n=>{let o=n.params.uri,r=Array.from(this.resources.values()).find(s=>s.uri===o);if(!r)throw new Ku(o);try{return await r.reader()}catch(s){throw new je(fe.InternalError,s instanceof Error?s.message:"Resource read error")}})}addToolInternal(e){this.tools.set(e.name,{description:e.description,validator:e.validator,...e.outputSchema&&{outputSchema:e.outputSchema},...e.annotations&&{annotations:e.annotations},...e._meta&&{_meta:e._meta},handler:e.handler})}addPromptInternal(e){this.prompts.set(e.name,{description:e.description,validator:e.validator,generator:e.generator})}addResourceInternal(e,n,o,r){this.resources.set(e,{uri:n,metadata:o,reader:r})}generatePromptDescriptionFromSpec(e){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:n}=Xe.instance.routeData,o=n.filter(s=>s.metadata?.filepath===e);if(o.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let r=new Map;for(let s of o){let a=s?.raw().operationId;if(a){r.set(a,{routeConfig:s});let c=s?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],m=c["x-zuplo-mcp-resource"],f=c["x-zuplo-route"]?.mcp;(u||l||d||m||f)&&r.set(a,{routeConfig:s,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:m||void 0,routeMcpExtension:f||void 0})}}return r}registerFromOperations(e){let n=new Map;for(let o of e){let r=n.get(o.file)??[];r.push(o.id),n.set(o.file,r)}for(let[o,r]of n.entries()){let s=t.getOperationsMetadataForFile(o);for(let a of r){let c=s.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let n of e){let o=t.getOperationsMetadataForFile(n.path),r=new Set;for(let s of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${s}" from file: "${n.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(s);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${s}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??s;if(r.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);r.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:s});continue}this.registerPromptForOperation(l,d,c,s)}}}registerPromptForOperation(e,n,o,r){try{if(o.handler?.export==="mcpServerHandler")return;let a=Xs.createPromptValidatorBuilder(o).build();this.addPromptInternal({name:e,description:n,validator:a,generator:i(async c=>{let u=Ws(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:c});let d=this.buildToolUrl(o,{body:c}),m=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let f=Date.now(),b=await u.invokeRoute(d,m),g=Date.now()-f,R=await b.json();if(!b.ok)throw new Error(`Route returned ${b.status}: ${R}`);let w;try{if(w=R.messages||R,!Array.isArray(w))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let C=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:b.status,elapsedMs:C,downstreamElapsedMs:g,messageCount:w.length}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:C}),w}catch(d){let m=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:m,err:d}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:m,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP prompt invocation failed for prompt '${e}': ${f}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:r,path:o.path})}catch(s){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:r,error:s instanceof Error?s.message:String(s)}),new Error(`Failed to register prompt "${e}" for operation "${r}": ${s instanceof Error?s.message:String(s)}`)}}registerResourcesFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${s}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${s}" in file ${o.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:s});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${s}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${s}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${s}" uses ${d} method. Resources are read-only and must use GET method only.`);let m=u?.name?.trim()||s.trim()||"";if(!m)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${s}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(n.has(m))throw new Error(`MCP Resource configuration error: Duplicate resource name "${m}". Resource names must be unique across all configured resources.`);n.add(m);let f=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${m}`,b=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(m)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(m,b,f,c,s,g)}}}registerResourceForOperation(e,n,o,r,s,a,c){try{if(r.handler?.export==="mcpServerHandler")return;this.addResourceInternal(e,n,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=Ws(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,uri:n});let d=this.buildToolUrl(r,{}),m=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let f=Date.now(),b=await u.invokeRoute(d,m),g=Date.now()-f,R=await b.text(),w=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:r.raw()?.operationId,status:b.status,elapsedMs:w,downstreamElapsedMs:g,declaredMimeType:a,contentLength:R.length}),this.emitEvent(u,{eventType:b.ok?ee.MCP_CAPABILITY_COMPLETED:ee.MCP_CAPABILITY_FAILED,outcome:b.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:w,...b.ok?{}:{errorCode:b.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:n,mimeType:a,text:R,...c&&{_meta:c}}]}}catch(d){let m=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,elapsedMs:m,err:d}),this.emitEvent(u,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:m,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${f}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:s,path:r.path,uri:n,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:s,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${s}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredToolNames.has(s))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${n}". The tool name "${s}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${n}".`);this.registeredToolNames.add(s);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${s}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=o?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${n}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:s,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredPromptNames.has(s))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${s}" for operation ID "${n}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(s);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(s,a,e,n)}registerResource(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:n});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${n}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${n}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let s=e.methods[0].toUpperCase();if(s!=="GET")throw new Error(`MCP Resource configuration error: Operation "${n}" uses ${s} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||n;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,n,l,o?._meta)}registerToolsFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(r.keys())});for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${s}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${s}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(r.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:s,path:o.path});continue}let c=a.toolExtension?.name?.trim()??s,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${s}" in file "${o.path}"`);if(n.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${s}".`);n.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${s}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(s,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,n,o){let r=o?.introspectionTool?.name?.trim()||`${e}_introspect`,s=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(r))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${r}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(s))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${s}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(r),this.registeredToolNames.add(s);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=n.path,d=Xs.createObjectValidatorBuilder({}).build();this.addToolInternal({name:r,description:a,validator:d,handler:i(async()=>{let f=Ws(),b=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL introspection tool invoked",{toolName:r,operationId:e,path:u});let g=zd(),R=this.buildToolUrl(n,{}),w=this.buildToolRequest("POST","application/json",{body:{query:g}}),C=Date.now(),v=await f.invokeRoute(R,w),P=Date.now()-C,A=await v.text(),x=Date.now()-b;this.debugMode&&(v.ok?f.log.debug("MCP GraphQL introspection tool ok response",{toolName:r,operationId:e,status:v.status,elapsedMs:x,downstreamElapsedMs:P}):f.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:r,operationId:e,status:v.status,elapsedMs:x,downstreamElapsedMs:P,response:A}));let L=rg(A);return this.debugMode&&L===void 0&&f.log.debug("MCP GraphQL introspection structuredContent skipped (non-object)",{toolName:r,bodyPreview:A.slice(0,200)}),{content:[{type:"text",text:A}],...L&&{structuredContent:L},isError:!v.ok}}catch(g){let R=Date.now()-b,w=g instanceof Error?`${g.name}: ${g.message}`:String(g);throw f.log.error("MCP GraphQL introspection tool invocation failed",{toolName:r,operationId:e,path:u,elapsedMs:R,err:g}),new Error(`MCP GraphQL introspection tool call failed for '${r}': ${w}`)}},"handler")});let m={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.addToolInternal({name:s,description:c,validator:new xr(m,f=>typeof f=="object"&&f!==null&&"query"in f&&typeof f?.query=="string"?{success:!0,data:f,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:i(async f=>{let b=Ws(),g=Date.now();try{this.debugMode&&b.log.debug("MCP GraphQL execute tool invoked",{toolName:s,operationId:e,path:u,queryPreview:f.query.substring(0,100)});let R=this.buildToolUrl(n,{}),w={query:f.query};f.variables&&(w.variables=f.variables);let C=this.buildToolRequest("POST","application/json",{body:w}),v=Date.now(),P=await b.invokeRoute(R,C),A=Date.now()-v,x=await P.text(),L=Date.now()-g;this.debugMode&&(P.ok?b.log.debug("MCP GraphQL execute tool ok response",{toolName:s,operationId:e,status:P.status,elapsedMs:L,downstreamElapsedMs:A}):b.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:s,operationId:e,status:P.status,elapsedMs:L,downstreamElapsedMs:A,response:x}));let U=rg(x);return this.debugMode&&U===void 0&&b.log.debug("MCP GraphQL execute structuredContent skipped (non-object)",{toolName:s,bodyPreview:x.slice(0,200)}),{content:[{type:"text",text:x}],...U&&{structuredContent:U},isError:!P.ok}}catch(R){let w=Date.now()-g,C=R instanceof Error?`${R.name}: ${R.message}`:String(R);throw b.log.error("MCP GraphQL execute tool invocation failed",{toolName:s,operationId:e,path:u,elapsedMs:w,err:R}),new Error(`MCP GraphQL execute tool call failed for '${s}': ${C}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:r,executeToolName:s,path:u})}registerToolsForMethod({routeData:e,method:n,name:o,description:r,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let m=Object.keys(e.raw().requestBody?.content).length>1?`${o}_${l.replace(/[^\w]/g,"_")}`:o;this.registerGenericToolSpec({name:m,description:r,routeData:e,method:n,contentType:l,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:o,description:r,routeData:e,method:n,contentType:null,includeOutputSchema:s,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:n,routeData:o,method:r,contentType:s,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(o,s);if(!d){this.context.log.warn("MCP tool skipped: could not build parameter validator",{toolName:e,method:r.toUpperCase(),path:o.path,operationId:o.raw()?.operationId,suggestion:"Check the OpenAPI parameter and request body definitions for this route."});return}let m=a?this.extractOutputSchema(o):void 0;try{this.addToolInternal({name:e,description:n,validator:d,...m&&{outputSchema:m},...u&&{annotations:u},...l&&{_meta:l},handler:i(async(f,b)=>{let g=Ws(),R=Date.now();try{this.debugMode&&g.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:r,path:o.path,args:f});let w=this.buildToolUrl(o,f),C=this.buildToolRequest(r,s,f);this.debugMode&&g.log.debug("MCP tool downstream call",{toolName:e,url:w,method:r,headers:C.headers?Object.keys(C.headers).join(", "):"",bodyPreview:f.body});let v=Date.now(),P=await g.invokeRoute(w,C),A=Date.now()-v,x=await P.text(),L=c?rg(x):void 0;this.debugMode&&c&&L===void 0&&g.log.debug("MCP tool structuredContent skipped (non-object or unparseable)",{toolName:e,bodyPreview:x.slice(0,200)});let U=Date.now()-R;return this.emitEvent(g,{eventType:P.ok?ee.MCP_CAPABILITY_COMPLETED:ee.MCP_CAPABILITY_FAILED,outcome:P.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:r,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:U,...P.ok?{}:{errorCode:P.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),this.debugMode&&(P.ok?g.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:P.status,elapsedMs:U,downstreamElapsedMs:A}):g.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:P.status,elapsedMs:U,downstreamElapsedMs:A,response:x})),{content:[{type:"text",text:x}],...P.ok&&L&&{structuredContent:L},isError:!P.ok,_meta:g.custom.mcpCallToolResponse?._meta??{}}}catch(w){let C=Date.now()-R,v=w instanceof Error?`${w.name}: ${w.message}`:String(w);return g.log.error("MCP server tool invocation failed",{toolName:e,operationId:o.raw()?.operationId,method:r,path:o.path,elapsedMs:C,err:w}),this.emitEvent(g,{eventType:ee.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:r,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:C,reasonCode:"gateway_error",reasonClass:"upstream",errorType:w instanceof Error?w.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${v}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:r.toUpperCase(),path:o.path,operationId:o.raw()?.operationId,contentType:s||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!m})}catch(f){throw new Error(`Failed to add tool ${r} ${o.path}`,f)}}buildToolUrl(e,n){return new tm(e).build(n.pathParams,n.queryParams)}buildToolRequest(e,n,o){let r=this.buildToolHeaders(e,n,o),s={method:e,headers:r};return this.shouldIncludeBody(e,n,o)&&(s.body=this.serializeBody(o.body,n)),s}buildToolHeaders(e,n,o){let r={...eg()};return delete r["content-type"],o.headers&&Object.entries(o.headers).forEach(([s,a])=>{r[s.toLowerCase()]=a}),n&&o.body!==void 0&&(r["content-type"]=n),this.isBodyMethod(e||"")&&o.body!==void 0&&!r["content-type"]&&(r["content-type"]="application/json"),r}shouldIncludeBody(e,n,o){return o.body===void 0?!1:this.isBodyMethod(e)?!0:n!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,n){return JSON.stringify(e)}buildUniversalValidator(e,n){try{let r=Xs.createValidatorBuilder(e,n).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:n||"none",operationId:e.raw()?.operationId}),r}catch(o){let r=o instanceof Error?o.message:String(o);this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:n||"none",operationId:e.raw()?.operationId,error:r});return}}extractOutputSchema(e){try{let n=e.raw(),o=n?.responses;if(!o){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:n?.operationId});return}for(let r of Object.keys(o))if(r.startsWith("2")){let a=o[r]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:n?.operationId,statusCode:r,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:n?.operationId,statusCodes:Object.keys(o).join(", ")});return}catch(n){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0});return}}};async function hT(t,e){if(Q("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new I(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let n={};t.headers.forEach((a,c)=>{n[c]=a});let o=e.route?.handler?.options??{},r=e.route?.path??"unknown-route",s=await sm.getInstance({opts:o,context:e,key:r});return Xv(e,{headers:n,user:t.user},()=>s.handleRequest(t,e))}i(hT,"mcpServerHandler");It("mcp-server",hT);var iz=[502,503,504];function am(t){if(t!=null){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new I(`The 'requestTimeoutSeconds' handler option must be a positive number of seconds. Received: ${String(t)}. Remove the option to disable the request timeout.`);return AbortSignal.timeout(t*1e3)}}i(am,"getRequestTimeoutSignal");function cm(t){if(typeof t!="object"||t===null)return!1;let e=t.name;return e==="TimeoutError"||e==="AbortError"}i(cm,"isRequestTimeoutError");async function ea(t,e){if(iz.includes(t.status)){let n=Y.getLogger(e),r=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:r,headers:s})}}i(ea,"logBadGatewayResponses");var ig;function ta(t){if(ig===void 0){let n=_.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),ig=n}return t.log[ig]}i(ta,"getHandlerUserLogFunction");async function fT(t,e){Q("handler.open-api");let n=_.instance.build.BUILD_ID,{buildAssetsUrl:o}=_.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new I("Open API Spec Handler must have 'openApiFilePath' specified");let a=sz(s);if(!a.isValid)throw new I(a.error);let c=`${o}/${n}${s.substring(1)}`,u=await H.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return z.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};_.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return ea(d,e),d}i(fT,"openApiSpecHandler");var sz=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");It("open-api",fT);async function gT(t,e){Q("handler.redirect");let n=e.route.handler.options;if(!n.location)throw new I("Redirect Handler must have 'location' specified");let o=n.status??302;return new Response(null,{status:o,headers:{location:n.location}})}i(gT,"redirectHandler");It("redirect",gT);async function yT(t){if(Q("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new I("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,_.instance.zuploEdgeApiUrl),n=new Headers(t.headers);return n.set("Authorization",`Bearer ${_.instance.authApiJWT}`),H.fetch(e,{method:t.method,headers:n,body:t.body})}i(yT,"zuploServiceProxy");It("service-proxy",yT);function az(t,e){let n=t.endsWith("/"),o=e.startsWith("/");return n&&o?`${t.substring(0,t.length-1)}${e}`:!n&&!o?`${t}/${e}`:`${t}${e}`}i(az,"join");async function bT(t,e){Q("handler.url-forward");let n=ta(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s;if(_.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&Q("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new I("Invalid options for this route");let a=na(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=az(u,c.pathname),d=r?`${l}${c.search}`:l.toString(),m=Date.now();n(`URL Forwarding to '${d}'`);let f=t.body;if(s==="follow"&&t.body)try{f=await t.arrayBuffer()}catch(w){throw new Error(`Failed to buffer request body for redirect handling: ${w}`)}let b=am(o.requestTimeoutSeconds),g;try{g=await fetch(d,{method:t.method,body:f,headers:t.headers,redirect:s,signal:b,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(w){if(b&&cm(w)){let C=Date.now()-m;return n(`URL Forward to '${d}' timed out after ${C}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),z.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw w}let R=Date.now()-m;return n(`URL Forward received response ${g.status} - ${g.statusText} in ${R}ms`),ea(g,e),g}i(bT,"urlForwardHandler");It("url-forward",bT);var cz=i((t,e)=>{let n=new URL(t),o=new URL(e);for(let[r,s]of o.searchParams.entries())n.searchParams.append(r,s);return n.toString()},"addQuery");async function ST(t,e){Q("handler.url-rewrite");let n=ta(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new I("Invalid options for this route");let a=na(e),c=o.__rewriteFunction(t,a),u=r?cz(c,t.url):c,l=am(o.requestTimeoutSeconds),d=Date.now();n(`URL Rewriting to '${u}'`);let m;try{m=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual",signal:l,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(b){if(l&&cm(b)){let g=Date.now()-d;return n(`URL Rewrite to '${u}' timed out after ${g}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),z.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw b}let f=Date.now()-d;return n(`URL Rewrite received response ${m.status} - ${m.statusText} in ${f}ms`),ea(m,e),m}i(ST,"urlRewriteHandler");It("url-rewrite",ST);var sg=i((t,e)=>t.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${r+1}, export name: ${o.export}`;throw new I(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions"),RT=i(t=>{let e;if(typeof t.module=="object"&&(e=t.module[t.export]),!e||typeof e!="function")throw new I(`WebSocketOnOpenHook - Websocket onOpen hook must be a valid function (export name: ${t.export})`);return e},"getWebSocketOnOpenHook"),wT=i(async(t,e,n,o,r,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,n,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function uz(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}i(uz,"createDeferred");async function lz(t,e,n){n(`Attempting WebSocket connection to '${e}'`);let o=new WebSocket(e);await new Promise((a,c)=>{let u=i(()=>{d(),n("WebSocket connection established with upstream"),a()},"onOpen"),l=i(m=>{d(),n(`WebSocket connection error: ${m}`),c(new Error("Upstream open failed"))},"onErr"),d=i(()=>{o.removeEventListener("open",u),o.removeEventListener("error",l)},"cleanup");o.addEventListener("open",u),o.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:r,response:s}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:r,outgoingSocket:o,response:s}}i(lz,"getDenoClientAndServerSockets");function dz(t){return t>=400&&t<600}i(dz,"isUpstreamHttpErrorStatus");async function pz(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(r.status!==101||!r.webSocket)return n(`WebSocket upgrade failed: ${r.status} ${r.statusText}`),{ok:!1,response:r};if(n(`WebSocket connected, received response ${r.status} - ${r.statusText}`),o)return{ok:!0,passthrough:!0,response:new Response(null,{status:101,webSocket:r.webSocket})};let s=new WebSocketPair,[a,c]=Object.values(s);r.webSocket.accept(),c.accept();let u=new Response(null,{status:101,webSocket:a});return{ok:!0,passthrough:!1,clientSocket:a,outgoingSocket:r.webSocket,serverSocket:c,response:u}}i(pz,"getCfClientAndServerSockets");function mz(t,e,n,o){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:"incoming"}),e.close()}),e.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:"outgoing"}),t.close()});let r=i((s,a)=>{if(o===void 0){s.addEventListener("message",c=>{a.send(c.data)});return}s.addEventListener("message",c=>{n.waitUntil(o.then(()=>a.send(c.data)).catch(n.log.error))})},"relayMessages");r(t,e),r(e,t)}i(mz,"wireUpPassthrough");function CT(t,e,n,o,r,s,a){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{o.log.error("WebSocket pipeline error",{direction:s}),e.close()}),t.addEventListener("message",c=>{try{let l=i(async d=>{await a;let m=await wT(d,t,e,n,o,r);m!==void 0&&e.send(m)},"innerPipeline")(c).catch(o.log.error);o.waitUntil(l)}catch(u){o.log.error(u)}})}i(CT,"wireUpListeners");async function ag(t,e){Q("handler.websocket-pipeline");let n=e.route.handler.options,o=ta(e);if(!n||!n.rewritePattern)throw new I("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=t.headers.get("Upgrade");if(!r||r!=="websocket")return z.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new I("Invalid options for this route");let s=na(e),a=n.__rewriteFunction(t,s),c=n.policies?.inbound?sg(n.policies.inbound,"inbound"):[],u=n.policies?.outbound?sg(n.policies.outbound,"outbound"):[],l=n.onOpen?RT(n.onOpen):void 0,d=c.length>0||u.length>0,m=d||l!==void 0,f,b,g;if(_.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let w=await lz(t.originalRequest,a,o);f=w.clientSocket,b=w.outgoingSocket,g=w.response}else{a=a.replace(/^(ws)/,"http");let w=await pz(t,a,o,!m);if(!w.ok){let C=w.response;if(dz(C.status))return C;let v=await C.text(),P=`WebSocket connection error - ${C.status}: ${C.statusText}, content: '${v}'`;return e.log.warn({outgoingUrl:a,status:C.status},P),z.badGateway(t,e,{detail:P})}if(w.passthrough)return w.response;f=w.serverSocket,b=w.outgoingSocket,g=w.response}let R=uz();if(R.promise.catch(()=>{}),d?(CT(f,b,t,e,c,"inbound",R.promise),CT(b,f,t,e,u,"outbound",R.promise)):mz(f,b,e,l?R.promise:void 0),l)try{await l(b,f,t,e),R.resolve()}catch(w){R.reject(w);try{f.close(1011,"onOpen hook failed")}catch{}try{b.close(1011,"onOpen hook failed")}catch{}throw new I("WebSocket onOpen hook failed",{cause:w})}else R.resolve();return g}i(ag,"webSocketPipelineHandler");It("websocket-pipeline",ag);var hz=ag;var cg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"AWSLoggingPlugin")}getTransport(){return new ug(this.options)}},ug=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new qe({name:"aws-log-transport",msDelay:10,dispatchFunction:i(async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n});o.ok||await He({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await He({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}},"dispatchFunction")});constructor({accessKeyId:e,logStreamName:n,logGroupName:o,secretAccessKey:r,region:s,fields:a}){Q("logging.aws"),this.awsClient=new td({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=n,this.region=s,this.environmentType=_.instance.loggingEnvironmentType,this.environmentStage=_.instance.loggingEnvironmentStage,this.environment=_.instance.deploymentName,this.fields=a??{}}log(e,n){e.messages.forEach(o=>{let r={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:In(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,n.properties??{}))};this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var lg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new dg(this.options)}},dg=class{static{i(this,"DynaTraceTransport")}constructor(e){Q("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#o;#n;#r;#i;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:In(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#o,"custom.environmentStage":this.#r,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let n=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});n.ok||await He({level:"error",messages:[`Failed to send logs to Dynatrace: ${n.status} - ${n.statusText}`]},n)}catch{await He({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"dyna-trace-log-transport",msDelay:10,dispatchFunction:this.#s})};var pg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"LokiLoggingPlugin")}getTransport(){return new hg(this.options)}},mg=class{static{i(this,"LokiStream")}constructor(e,n,o,r,s,a){this.level=e,this.environment=n,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function fz(t,e){return btoa(`${t}:${e}`)}i(fz,"createBasicDigest");var hg=class{static{i(this,"LokiTransport")}constructor(e){Q("logging.loki"),this.#o=e.url,this.#n=fz(e.username,e.password),this.#i=_.instance.loggingEnvironmentType,this.#s=_.instance.loggingEnvironmentStage,this.#r=_.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#o;#n;#r;#i;#s;#a;log(e,n){let o=new mg(e.level,this.#r,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:In(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,n.properties??{});this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#u=i(e=>{let n={streams:[]};return e.forEach(o=>{let r=n.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},n.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),n},"#convertToLokiStreamsBatch");#l=i(async e=>{if(e.length===0)return;let n=this.#u(e);try{let o=await H.fetch(this.#o,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});o.ok||await He({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await He({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"loki-log-transport",msDelay:10,dispatchFunction:this.#l})};var fg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new gg(this.options)}},gg=class{static{i(this,"NewRelicTransport")}constructor(e){Q("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#o;#n;#r;#i;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({message:In(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#r,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let n=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});n.ok||await He({level:"error",messages:[`Failed to send logs to New Relic: ${n.status} - ${n.statusText}`]},n)}catch{await He({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"new-relic-log-transport",msDelay:10,dispatchFunction:this.#a})};var yg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"SplunkLoggingPlugin")}getTransport(){return new bg(this.options)}},bg=class{static{i(this,"SplunkTransport")}constructor(e){Q("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#o;#n;#r;#i;#s;#a;#u;#l;log(e,n){e.messages.forEach(o=>{let s={event:{message:In(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#r,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i,...n.properties??{}},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#c=i(async e=>{if(e.length!==0)try{for(let n of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let r=await H.fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:o});if(!r.ok){let s=await r.text();await He({level:"error",messages:[`Failed to send logs to Splunk: ${r.status} - ${r.statusText}`,`Response: ${s}`]},r)}}}catch(n){await He({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"#dispatchFunction");batcher=new qe({name:"splunk-log-transport",msDelay:10,dispatchFunction:this.#c})};var Sg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new Rg(this.options)}},Rg=class{static{i(this,"SumoLogicTransport")}constructor(e){Q("logging.sumologic"),this.#e=e.url,this.#r=e.category,this.#i=e.name,this.#o=_.instance.loggingEnvironmentType,this.#n=_.instance.loggingEnvironmentStage,this.#t=_.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#o;#n;#r;#i;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:In(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#o,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId},this.#s,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let n=e.map(r=>JSON.stringify(r)).join(`
264
264
  `),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&o.set("X-Sumo-Name",this.#i),this.#r&&o.set("X-Sumo-Category",this.#r);try{let r=await H.fetch(this.#e,{method:"POST",body:n,headers:o});r.ok||await He({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`]},r)}catch{await He({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"sumo-logic-log-transport",msDelay:10,dispatchFunction:this.#a})};var gz="d3a5b78f823648f5b1df4fe269d41172",wg=class extends ht{constructor(n){super();this.options=n}options;static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Cg(this.options)}},Cg=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){Q("logging.vmware-loginsight");let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??gz}`)}catch{throw new I(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#n=_.instance.loggingEnvironmentType,this.#r=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,r])=>({name:o,content:r})))}#e;#t;#o;#n;#r;#i;#s;log(e,n){let o=this.buildEntry(e,n);this.batcher.enqueue(o),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let o=vw(e.messages);this.#t?.forEach(s=>{o=o.replaceAll(s[0],s[1])});let r={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#r},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#o&&r.fields.push({name:"environment",content:this.#o}),this.#s&&r.fields.push(...this.#s),n.properties&&Object.entries(n.properties).forEach(([s,a])=>{let c=ad(a);c&&r.fields.push({name:s,content:c})}),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let c=ad(a);c&&r.fields.push({name:s,content:c})}),this.#i&&(r=this.#i(r)),r}#a=i(async e=>{if(e.length!==0)try{let n=await H.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});n.ok||await He({level:"error",messages:[`Failed to send logs to Log Insight: ${n.status} - ${n.statusText}`]},n)}catch{await He({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new qe({name:"vmware-log-insights-log-transport",msDelay:10,dispatchFunction:this.#a})};var Ig=class{static{i(this,"ZuploMcpSdk")}context;constructor(e){this.context=e}getRawCallToolRequest(){let e=null;return this.context.custom.mcpCallToolRequest&&(e=this.context.custom.mcpCallToolRequest),this.context.parentContext?.custom.mcpCallToolRequest&&(e=this.context.parentContext.custom.mcpCallToolRequest),e}setRawCallToolResult(e){if(this.context.parentContext?.custom.mcpCallToolRequest){this.context.parentContext.custom.mcpCallToolResponse=e;return}this.context.custom.mcpCallToolResponse=e}};var Tg=new ce(Symbol("datadog-metrics-context")),yz={tags:[]},IT="https://api.datadoghq.com",lm="/api/v2/series",um="/api/v1/distribution_points",bz=`${IT}${lm}`,Sz=`${IT}${um}`,Rz=".v2",wz="zuplo.request.latency",Cz="zuplo.request.content_length",Iz="zuplo.response.content_length",vg=i((t,e)=>e?`${t}${Rz}`:t,"getMetricNameForMode"),vz=i((t,e)=>{try{let n=new URL(t);return n.pathname.replace(/\/+$/,"")===""?(n.pathname=e,n.search="",n.toString()):t}catch{return t}},"normalizeDatadogApiUrl"),Tz=i(t=>{try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"");if(n==="")return e.pathname=um,e.search="",e.toString();if(n.endsWith(lm)){let o=n.length-lm.length;return e.pathname=n.slice(0,o)+um,e.search="",e.toString()}return e.pathname=um,e.search="",e.toString()}catch{}return Sz},"getDefaultDistributionUrl"),Pz=i(t=>[...t].sort(),"normalizeTagsForGrouping"),Pg=class extends Dn{constructor(n){super();this.options=n;Q("metrics.datadog")}options;static{i(this,"DataDogMetricsPlugin")}#e;getTransport(){return this.#e??=new Ag(this.options),this.#e}static setContext(n,o){let r=Tg.get(n);r||(r=yz);let s=Object.assign({...r},o);Tg.set(n,s)}},Ag=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#o;#n;#r;#i;#s;#a=void 0;#u=void 0;constructor(e){this.#e=e.apiKey,this.#t=vz(e.url??bz,lm),this.#o=Tz(this.#t),this.#s=e.metricMode==="distributionMode",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#r=e.tags??[]}#l(e){return this.#a===void 0&&(this.#a=new qe({name:"data-dog-metrics-transport",msDelay:10,dispatchFunction:this.dispatchSeriesFunction,systemLogger:Y.getLogger(e)})),this.#a}#c(e){return this.#u===void 0&&(this.#u=new qe({name:"data-dog-metrics-distribution-transport",msDelay:10,dispatchFunction:this.dispatchDistributionFunction,systemLogger:Y.getLogger(e)})),this.#u}#d(e,n,o,r,s){this.#c(e).enqueue({metric:n,timestamp:o,value:r,tags:s})}pushMetrics(e,n){let o=Math.floor(e.timestamp.getTime()/1e3),r=vg(wz,this.#s),s=vg(Cz,this.#s),a=vg(Iz,this.#s),c=this.#r.concat(Tg.get(n)?.tags??[]);if(this.#i.country&&c.push(`country:${e.country}`),this.#i.httpMethod&&c.push(`httpMethod:${e.method}`),this.#i.statusCode&&c.push(`statusCode:${e.statusCode}`),this.#i.path){let u=e.systemRouteName||e.routePath;c.push(`path:${u}`)}this.#n.latency&&(this.#s?this.#d(n,r,o,e.durationMs,c):this.#l(n).enqueue({metric:r,type:3,points:[{timestamp:o,value:e.durationMs}],tags:c})),this.#n.requestContentLength&&e.requestContentLength&&(this.#s?this.#d(n,s,o,e.requestContentLength,c):this.#l(n).enqueue({metric:s,type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:c})),this.#n.responseContentLength&&e.responseContentLength&&(this.#s?this.#d(n,a,o,e.responseContentLength,c):this.#l(n).enqueue({metric:a,type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:c})),this.#a&&n.waitUntil(this.#a.waitUntilFlushed()),this.#u&&n.waitUntil(this.#u.waitUntilFlushed())}dispatchSeriesFunction=i(async e=>{if(e.length!==0)try{let n=JSON.stringify({series:e}),o=await H.fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});o.ok||await He({level:"error",messages:["Failed to send metrics to DataDog."]},o)}catch{await He({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchSeriesFunction");dispatchDistributionFunction=i(async e=>{if(e.length!==0)try{let n=new Map;e.forEach(s=>{let a=Pz(s.tags),c=`${s.metric}:${s.timestamp}:${JSON.stringify(a)}`,u=n.get(c);if(u){u.points[0][1].push(s.value);return}n.set(c,{metric:s.metric,points:[[s.timestamp,[s.value]]],tags:a})});let o=JSON.stringify({series:[...n.values()]}),r=await H.fetch(this.#o,{method:"POST",body:o,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await He({level:"error",messages:["Failed to send latency distributions to DataDog."]},r)}catch{await He({level:"error",messages:["Failed to connect to DataDog metrics distribution service. Check that the URL is correct."]})}},"dispatchDistributionFunction")};var Eg=new ce(Symbol("dynatrace-metrics-context")),Az={dimensions:[]},Og=class extends Dn{constructor(n){super();this.options=n;Q("metrics.dynatrace")}options;static{i(this,"DynatraceMetricsPlugin")}#e;getTransport(){return this.#e??=new kg(this.options),this.#e}static setContext(n,o){let r=Eg.get(n);r||(r=Az);let s=Object.assign({...r},o);Eg.set(n,s)}},kg=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#o;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#n===void 0&&(this.#n=new qe({name:"dynatrace-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:Y.getLogger(n)}));let o=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(Eg.get(n)?.dimensions??[]);if(this.#o.country&&r.push(`country="${e.country}"`),this.#o.httpMethod&&r.push(`http_method="${e.method}"`),this.#o.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#o.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let s=r.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${o}`),n.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=e.join(`
265
265
  `),o=await H.fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});o.ok||await He({level:"error",messages:["Failed to send metrics to Dynatrace."]},o)}catch{await He({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var _g=new ce(Symbol("new-relic-metrics-context")),Ez={attributes:{}},xg=class extends Dn{constructor(n){super();this.options=n;Q("metrics.newrelic")}options;static{i(this,"NewRelicMetricsPlugin")}#e;getTransport(){return this.#e??=new Mg(this.options),this.#e}static setContext(n,o){let r=_g.get(n);r||(r=Ez);let s=Object.assign({...r},o);_g.set(n,s)}},Mg=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#o;#n;#r;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#o=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#n=e.attributes??{service:"zuplo"}}pushMetrics(e,n){this.#i===void 0&&(this.#i=new qe({name:"new-relic-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:Y.getLogger(n)}));let o=Math.floor(e.timestamp.getTime()),r={...this.#n,..._g.get(n)?.attributes};if(this.#r.country&&(r.country=e.country),this.#r.httpMethod&&(r.httpMethod=e.method),this.#r.statusCode&&(r.statusCode=e.statusCode.toString()),this.#r.path){let s=e.systemRouteName||e.routePath;r.path=s}this.#o.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:o,attributes:r}),this.#o.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:o,attributes:r}),this.#o.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:o,attributes:r}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=JSON.stringify([{metrics:e}]),o=await ct({retries:3,retryDelayMs:300,logger:H.console},this.#t,{method:"POST",body:n,headers:{"Content-Type":"application/json","Api-Key":this.#e}});o.ok||await He({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${o.status} ${o.statusText}`]},o)}catch(n){await He({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"dispatchFunction")};var Lg=new ce(Symbol("otel-metrics-context")),Oz={attributes:{}},Ng=class extends Dn{constructor(n){super();this.options=n;Q("metrics.otel")}options;static{i(this,"OTelMetricsPlugin")}#e;getTransport(){return this.#e??=new qg(this.options),this.#e}static setContext(n,o){let r=Lg.get(n);r||(r=Oz);let s=Object.assign({...r},o);Lg.set(n,s)}};function kz(t){let e=[];for(let[n,o]of Object.entries(t))o!==void 0&&(typeof o=="string"?e.push({key:n,value:{stringValue:o}}):typeof o=="number"?Number.isInteger(o)?e.push({key:n,value:{intValue:o.toString()}}):e.push({key:n,value:{doubleValue:o}}):typeof o=="boolean"&&e.push({key:n,value:{boolValue:o}}));return e}i(kz,"attributesToOTLP");var qg=class{static{i(this,"OTelMetricsTransport")}#e;#t;#o;#n;#r;#i=void 0;constructor(e){this.#e=e.url,this.#t=e.headers??{},this.#o=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#n=e.attributes??{}}pushMetrics(e,n){this.#i===void 0&&(this.#i=new qe({name:"otel-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:Y.getLogger(n)}));let o=(e.timestamp.getTime()*1e6).toString(),r={...this.#n},s=Lg.get(n)?.attributes??{};if(Object.assign(r,s),this.#r.country&&e.country&&(r["client.geo.country_iso_code"]=e.country),this.#r.httpMethod&&(r["http.request.method"]=e.method),this.#r.statusCode&&(r["http.response.status_code"]=e.statusCode),this.#r.path){let c=e.systemRouteName||e.routePath;r["http.route"]=c}let a=kz(r);this.#o.latency&&this.#i.enqueue({name:"http.server.request.duration",unit:"ms",value:e.durationMs,timeUnixNano:o,attributes:[...a]}),this.#o.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"http.server.request.body.size",unit:"By",value:e.requestContentLength,timeUnixNano:o,attributes:[...a]}),this.#o.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"http.server.response.body.size",unit:"By",value:e.responseContentLength,timeUnixNano:o,attributes:[...a]}),n.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=e.map(a=>({name:a.name,unit:a.unit,gauge:{dataPoints:[{timeUnixNano:a.timeUnixNano,asDouble:a.value,attributes:a.attributes}]}})),r=JSON.stringify({resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:"zuplo",version:"1.0.0"},metrics:n}]}]}),s=await H.fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"application/json",...this.#t}});s.ok||await He({level:"error",messages:["Failed to send metrics to OpenTelemetry collector."]},s)}catch{await He({level:"error",messages:["Failed to connect to OpenTelemetry metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var $g=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,Q("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async n=>{await H.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))},"writeLogBatch")};var zg=class extends Ct{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n,Q("audit-logs")}#e;#t;async initialize(e){new Dg(e,this.#e,this.#t)}},vT=i(t=>{let e={};return t.forEach((n,o)=>{e[o]=n}),e},"serializableHeaders"),_z={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Dg=class{static{i(this,"AuditPluginImpl")}constructor(e,n,o){this.#t=n;let r={..._z};o?.requestFilter&&(r.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(r,o.include.request),o?.include?.response&&Object.assign(r,o.include.response),this.#e=r,e.addRequestHook(this.#i),this.#o=new qe({name:"audit-log",msDelay:10,dispatchFunction:this.#n})}#e;#t;#o;#n=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#r=i(async(e,n,o,r,s,a)=>{try{let c={timestamp:r,durationMs:s,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?vT(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?vT(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#o.enqueue(c),o.waitUntil(this.#o.waitUntilFlushed())}catch(c){o.log.error(c)}},"#asyncPrepLogs");#i=i(async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let r=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),m=this.#r(d,a,n,r,l-s,u.user?.sub).catch(f=>{n.log.error(f)});n.waitUntil(m)}),e}catch(o){return n.log.error(o),e}},"#auditHook")};import{importJWK as xz,SignJWT as Mz}from"jose";var TT="EdDSA",PT=["EdDSA","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],AT=!1,nl=class t extends Ct{static{i(this,"JwtServicePlugin")}#e;static#t=void 0;static#o=void 0;static#n=void 0;static#r=void 0;static#i=TT;static async signJwt({audience:e,subject:n,expiresIn:o=t.#n,...r}){if(!t.#o){let u=_.instance.authPrivateKey;if(!u)throw new I("JwtServicePlugin - Cannot sign JWT. Private key configured for this Zuplo project.");try{t.#o=await xz(JSON.parse(u),t.#i)}catch(l){throw new I(`JwtServicePlugin - Failed to import private key. Ensure it is a valid JWK format and matches the configured algorithm "${t.#i}".`,{cause:l})}}if(!t.#t)throw new I("JwtServicePlugin - Cannot sign JWT. The issuer URL is not configured. Ensure the plugin is initialized.");if(!t.#n)throw new I("JwtServicePlugin - Cannot sign JWT. The token expiration is not configured. Ensure the plugin is initialized.");let s=o??t.#n,a=typeof s=="number"?new Date(Date.now()+s*1e3):s,c=new Mz(r).setProtectedHeader({alg:t.#i}).setIssuer(t.#t).setIssuedAt(new Date).setExpirationTime(a);return e&&c.setAudience(e),n&&c.setSubject(n),await c.sign(t.#o)}constructor(e){if(super(),AT)throw new I("JwtServicePlugin - Only one instance of JwtServicePlugin can be created. Ensure you are not creating multiple instances in your code.");let n=e?.algorithm??TT;if(!PT.includes(n))throw new I(`JwtServicePlugin - Unsupported signing algorithm "${n}". Supported algorithms: ${PT.join(", ")}.`);Q("plugin.jwt-service"),AT=!0,this.#e=e?.basePath??"/__zuplo/issuer",t.#n=e?.expiresIn??"1h",t.#i=n,this.#e.endsWith("/")&&(this.#e=this.#e.slice(0,-1))}registerRoutes({runtimeSettings:e,router:n}){let o=e.api.urls?.defaultUrl;if(!o)throw new I("JwtServicePlugin - Cannot determine issuer URL. Ensure the API is properly configured.");let r=new URL(this.#e,o).toString();t.#t=r,n.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/openid-configuration`,handler:i(async()=>{let s={issuer:r,jwks_uri:`${r}/.well-known/jwks.json`,id_token_signing_alg_values_supported:[t.#i],subject_types_supported:["public"]};return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")}),n.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/jwks.json`,handler:i(async()=>{if(!t.#r)try{let s=_.instance.authPublicKey;if(!s)throw new I("JwtServicePlugin - Public key is not configured for this Zuplo project");let a={keys:[JSON.parse(s)]};t.#r=JSON.stringify(a)}catch(s){throw new I("JwtServicePlugin - Failed to export public key as JWK.",{cause:s})}return new Response(t.#r,{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")})}};var oa=class extends Ct{static{i(this,"OAuthProtectedResourceBasePlugin")}createOauthProtectedResourceHandler(){return async(e,n)=>{let o=new URL(e.url),r=e.params.resourcePath,s=r?`${o.origin}/${r}`:o.origin,a;try{a=await this.getMetadataOptions(e,n)}catch(u){return n.log.warn({err:u},"Failed to get metadata options for OAuth protected resource"),new Response("Not Found",{status:404})}let c={resource:s,authorization_servers:a.authorizationServers,resource_name:a.resourceName};return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}registerRoutes(e){let{router:n}=e;n.addPluginRoute({methods:["GET"],path:"/.well-known/oauth-protected-resource/:resourcePath*",handler:this.createOauthProtectedResourceHandler(),corsPolicy:"anything-goes",processors:[es]})}};var ol=class extends oa{static{i(this,"McpGatewayOAuthProtectedResourcePlugin")}authServerBaseUrl;constructor(e){super(),this.authServerBaseUrl=e}async getMetadataOptions(e,n){let r=e.params.resourcePath.split("/").pop();if(!r)throw new Error("Failed to extract resource from path");return{authorizationServers:[`${this.authServerBaseUrl}/${r}`],resource:r,resourceName:"Zuplo MCP Gateway"}}};var rl=class extends oa{static{i(this,"OAuthProtectedResourcePlugin")}options;constructor(e){super(),this.options=e}async getMetadataOptions(e,n){return{authorizationServers:this.options.authorizationServers,resourceName:this.options.resourceName}}};var Ug={None:0,JsonEscape:1},il=class{constructor(e,n={}){this.stream=e;this.options=n;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}stream;options;static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),n=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;n.push(u)}}finally{e.releaseLock()}let o=n.reduce((c,u)=>c+u.length,0),r=new Uint8Array(o),s=0;for(let c of n)r.set(c,s),s+=c.length;let a=new TextDecoder().decode(r);return this.options.base64Encode&&(a=btoa(a)),a}},dm=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,n=>{switch(n){case"\\":return"\\\\";case'"':return'\\"';case`
266
266
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return n}})}async toString(){let n=this.getStream().getReader(),o=new TextDecoder,r="";for(;;){let{done:s,value:a}=await n.read();if(s)break;r+=o.decode(a,{stream:!0})}return r+=o.decode(),r}getStream(){let e=this.template,n=this.flags,o=new TextEncoder,r=new Map;for(let b of this.tokens)r.set(b.getSafeToken(),b);let s=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=s.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let b=r.get(u[1]);b?a.push({type:"token",token:b,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let b=r.get(u[2]);b?a.push({type:"token",token:b,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=s.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g=new Uint8Array(0);return new TransformStream({transform(R,w){let C=new Uint8Array(g.length+R.length);C.set(g),C.set(R,g.length);let v=C.length%3,P=C.length-v;if(P>0){let A=C.subarray(0,P),x="";for(let L=0;L<A.length;L+=3){let U=A[L],oe=A[L+1],B=A[L+2],te=U<<16|oe<<8|B;x+=b[te>>18&63],x+=b[te>>12&63],x+=b[te>>6&63],x+=b[te&63]}w.enqueue(x)}g=C.subarray(C.length-v)},flush(R){if(g.length>0){let w=g[0],C=g.length>1?g[1]:0,v=w<<16|C<<8,P="";P+=b[v>>18&63],P+=b[v>>12&63],P+=g.length===2?b[v>>6&63]:"=",P+="=",R.enqueue(P)}}})}i(l,"createBase64EncodeTransformStream");function d(){let b=new TextDecoder;return new TransformStream({transform(g,R){let w=new Uint8Array(g.byteLength);w.set(g),R.enqueue(b.decode(w,{stream:!0}))},flush(g){let R=b.decode();R.length>0&&g.enqueue(R)}})}i(d,"createTextDecodeTransformStream");function m(){return new TransformStream({transform(b,g){let R=b.replace(/[\\\"\n\r\t\f\b]/g,w=>{switch(w){case"\\":return"\\\\";case'"':return'\\"';case`
@@ -368,5 +368,5 @@ Signature verification is impossible without access to the original signed mater
368
368
  `);let y=new v("!xml"),T=y,O="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let M=new P(this.options.processEntities);for(let E=0;E<h.length;E++)if(h[E]==="<")if(h[E+1]==="/"){let F=Jt(h,">",E,"Closing Tag is not closed."),D=h.substring(E+2,F).trim();if(this.options.removeNSPrefix){let be=D.indexOf(":");be!==-1&&(D=D.substr(be+1))}D=Rn(this.options.transformTagName,D,"",this.options).tagName,T&&(O=this.saveTextToParentTag(O,T,this.matcher));let ae=this.matcher.getCurrentTag();if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);ae&&this.options.unpairedTags.indexOf(ae)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,T=this.tagsNodeStack.pop(),O="",E=F}else if(h[E+1]==="?"){let F=nn(h,E,!1,"?>");if(!F)throw new Error("Pi Tag is not closed.");if(O=this.saveTextToParentTag(O,T,this.matcher),!(this.options.ignoreDeclaration&&F.tagName==="?xml"||this.options.ignorePiTags)){let D=new v(F.tagName);D.add(this.options.textNodeName,""),F.tagName!==F.tagExp&&F.attrExpPresent&&(D[":@"]=this.buildAttributesMap(F.tagExp,this.matcher,F.tagName)),this.addChild(T,D,this.matcher,E)}E=F.closeIndex+1}else if(h.substr(E+1,3)==="!--"){let F=Jt(h,"-->",E+4,"Comment is not closed.");if(this.options.commentPropName){let D=h.substring(E+4,F-2);O=this.saveTextToParentTag(O,T,this.matcher),T.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}E=F}else if(h.substr(E+1,2)==="!D"){let F=M.readDocType(h,E);this.docTypeEntities=F.entities,E=F.i}else if(h.substr(E+1,2)==="!["){let F=Jt(h,"]]>",E,"CDATA is not closed.")-2,D=h.substring(E+9,F);O=this.saveTextToParentTag(O,T,this.matcher);let ae=this.parseTextData(D,T.tagname,this.matcher,!0,!1,!0,!0);ae==null&&(ae=""),this.options.cdataPropName?T.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):T.add(this.options.textNodeName,ae),E=F+2}else{let F=nn(h,E,this.options.removeNSPrefix);if(!F){let Lt=h.substring(Math.max(0,E-50),Math.min(h.length,E+50));throw new Error(`readTagExp returned undefined at position ${E}. Context: "${Lt}"`)}let D=F.tagName,ae=F.rawTagName,be=F.tagExp,_e=F.attrExpPresent,st=F.closeIndex;if({tagName:D,tagExp:be}=Rn(this.options.transformTagName,D,be,this.options),this.options.strictReservedNames&&(D===this.options.commentPropName||D===this.options.cdataPropName||D===this.options.textNodeName||D===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${D}`);T&&O&&T.tagname!=="!xml"&&(O=this.saveTextToParentTag(O,T,this.matcher,!1));let Ht=T;Ht&&this.options.unpairedTags.indexOf(Ht.tagname)!==-1&&(T=this.tagsNodeStack.pop(),this.matcher.pop());let dr=!1;be.length>0&&be.lastIndexOf("/")===be.length-1&&(dr=!0,D[D.length-1]==="/"?(D=D.substr(0,D.length-1),be=D):be=be.substr(0,be.length-1),_e=D!==be);let at=null,rn={},pr;pr=Zn(ae),D!==y.tagname&&this.matcher.push(D,{},pr),D!==be&&_e&&(at=this.buildAttributesMap(be,this.matcher,D),at&&(rn=bn(at,this.options))),D!==y.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let Wt=E;if(this.isCurrentNodeStopNode){let Lt="";if(dr)E=F.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)E=F.closeIndex;else{let hr=this.readStopNodeData(h,ae,st+1);if(!hr)throw new Error(`Unexpected end of ${ae}`);E=hr.i,Lt=hr.tagContent}let mr=new v(D);at&&(mr[":@"]=at),mr.add(this.options.textNodeName,Lt),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(T,mr,this.matcher,Wt)}else{if(dr){({tagName:D,tagExp:be}=Rn(this.options.transformTagName,D,be,this.options));let Lt=new v(D);at&&(Lt[":@"]=at),this.addChild(T,Lt,this.matcher,Wt),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(D)!==-1){let Lt=new v(D);at&&(Lt[":@"]=at),this.addChild(T,Lt,this.matcher,Wt),this.matcher.pop(),this.isCurrentNodeStopNode=!1,E=F.closeIndex;continue}else{let Lt=new v(D);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(T),at&&(Lt[":@"]=at),this.addChild(T,Lt,this.matcher,Wt),T=Lt}O="",E=st}}else O+=h[E];return y.child},"parseXml");function le(h,y,T,O){this.options.captureMetaData||(O=void 0);let M=this.options.jPath?T.toString():T,E=this.options.updateTag(y.tagname,M,y[":@"]);E===!1||(typeof E=="string"&&(y.tagname=E),h.addChild(y,O))}i(le,"addChild"),n(le,"addChild");function re(h,y,T){let O=this.options.processEntities;if(!O||!O.enabled)return h;if(O.allowedTags){let M=this.options.jPath?T.toString():T;if(!(Array.isArray(O.allowedTags)?O.allowedTags.includes(y):O.allowedTags(y,M)))return h}if(O.tagFilter){let M=this.options.jPath?T.toString():T;if(!O.tagFilter(y,M))return h}for(let M of Object.keys(this.docTypeEntities)){let E=this.docTypeEntities[M],V=h.match(E.regx);if(V){if(this.entityExpansionCount+=V.length,O.maxTotalExpansions&&this.entityExpansionCount>O.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${O.maxTotalExpansions}`);let F=h.length;if(h=h.replace(E.regx,E.val),O.maxExpandedLength&&(this.currentExpandedLength+=h.length-F,this.currentExpandedLength>O.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${O.maxExpandedLength}`)}}for(let M of Object.keys(this.lastEntities)){let E=this.lastEntities[M],V=h.match(E.regex);if(V&&(this.entityExpansionCount+=V.length,O.maxTotalExpansions&&this.entityExpansionCount>O.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${O.maxTotalExpansions}`);h=h.replace(E.regex,E.val)}if(h.indexOf("&")===-1)return h;if(this.options.htmlEntities)for(let M of Object.keys(this.htmlEntities)){let E=this.htmlEntities[M],V=h.match(E.regex);if(V&&(this.entityExpansionCount+=V.length,O.maxTotalExpansions&&this.entityExpansionCount>O.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${O.maxTotalExpansions}`);h=h.replace(E.regex,E.val)}return h=h.replace(this.ampEntity.regex,this.ampEntity.val),h}i(re,"replaceEntitiesValue"),n(re,"replaceEntitiesValue");function Ee(h,y,T,O){return h&&(O===void 0&&(O=y.child.length===0),h=this.parseTextData(h,y.tagname,T,!1,y[":@"]?Object.keys(y[":@"]).length!==0:!1,O),h!==void 0&&h!==""&&y.add(this.options.textNodeName,h),h=""),h}i(Ee,"saveTextToParentTag"),n(Ee,"saveTextToParentTag");function Pe(h,y){if(!h||h.length===0)return!1;for(let T=0;T<h.length;T++)if(y.matches(h[T]))return!0;return!1}i(Pe,"isItStopNode"),n(Pe,"isItStopNode");function q(h,y,T=">"){let O,M="";for(let E=y;E<h.length;E++){let V=h[E];if(O)V===O&&(O="");else if(V==='"'||V==="'")O=V;else if(V===T[0])if(T[1]){if(h[E+1]===T[1])return{data:M,index:E}}else return{data:M,index:E};else V===" "&&(V=" ");M+=V}}i(q,"tagExpWithClosingIndex"),n(q,"tagExpWithClosingIndex");function Jt(h,y,T,O){let M=h.indexOf(y,T);if(M===-1)throw new Error(O);return M+y.length-1}i(Jt,"findClosingIndex"),n(Jt,"findClosingIndex");function nn(h,y,T,O=">"){let M=q(h,y+1,O);if(!M)return;let E=M.data,V=M.index,F=E.search(/\s/),D=E,ae=!0;F!==-1&&(D=E.substring(0,F),E=E.substring(F+1).trimStart());let be=D;if(T){let _e=D.indexOf(":");_e!==-1&&(D=D.substr(_e+1),ae=D!==M.data.substr(_e+1))}return{tagName:D,tagExp:E,closeIndex:V,attrExpPresent:ae,rawTagName:be}}i(nn,"readTagExp"),n(nn,"readTagExp");function ro(h,y,T){let O=T,M=1;for(;T<h.length;T++)if(h[T]==="<")if(h[T+1]==="/"){let E=Jt(h,">",T,`${y} is not closed`);if(h.substring(T+2,E).trim()===y&&(M--,M===0))return{tagContent:h.substring(O,T),i:E};T=E}else if(h[T+1]==="?")T=Jt(h,"?>",T+1,"StopNode is not closed.");else if(h.substr(T+1,3)==="!--")T=Jt(h,"-->",T+3,"StopNode is not closed.");else if(h.substr(T+1,2)==="![")T=Jt(h,"]]>",T,"StopNode is not closed.")-2;else{let E=nn(h,T,">");E&&((E&&E.tagName)===y&&E.tagExp[E.tagExp.length-1]!=="/"&&M++,T=E.closeIndex)}}i(ro,"readStopNodeData"),n(ro,"readStopNodeData");function Nn(h,y,T){if(y&&typeof h=="string"){let O=h.trim();return O==="true"?!0:O==="false"?!1:Rt(h,T)}else return l(h)?h:""}i(Nn,"parseValue"),n(Nn,"parseValue");function To(h,y,T){let O=Number.parseInt(h,y);return O>=0&&O<=1114111?String.fromCodePoint(O):T+h+";"}i(To,"fromCodePoint"),n(To,"fromCodePoint");function Rn(h,y,T,O){if(h){let M=h(y);T===y&&(T=M),y=M}return y=Po(y,O),{tagName:y,tagExp:T}}i(Rn,"transformTagName"),n(Rn,"transformTagName");function Po(h,y){if(m.includes(h))throw new Error(`[SECURITY] Invalid name: "${h}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(h)?y.onDangerousProperty(h):h}i(Po,"sanitizeName"),n(Po,"sanitizeName");var Kt=v.getMetaDataSymbol();function Ao(h,y){if(!h||typeof h!="object")return{};if(!y)return h;let T={};for(let O in h)if(O.startsWith(y)){let M=O.substring(y.length);T[M]=h[O]}else T[O]=h[O];return T}i(Ao,"stripAttributePrefix"),n(Ao,"stripAttributePrefix");function Eo(h,y,T){return Bn(h,y,T)}i(Eo,"prettify"),n(Eo,"prettify");function Bn(h,y,T){let O,M={};for(let E=0;E<h.length;E++){let V=h[E],F=rr(V);if(F!==void 0&&F!==y.textNodeName){let D=Ao(V[":@"]||{},y.attributeNamePrefix);T.push(F,D)}if(F===y.textNodeName)O===void 0?O=V[F]:O+=""+V[F];else{if(F===void 0)continue;if(V[F]){let D=Bn(V[F],y,T),ae=io(D,y);if(V[":@"]?Oo(D,V[":@"],T,y):Object.keys(D).length===1&&D[y.textNodeName]!==void 0&&!y.alwaysCreateTextNode?D=D[y.textNodeName]:Object.keys(D).length===0&&(y.alwaysCreateTextNode?D[y.textNodeName]="":D=""),V[Kt]!==void 0&&typeof D=="object"&&D!==null&&(D[Kt]=V[Kt]),M[F]!==void 0&&Object.prototype.hasOwnProperty.call(M,F))Array.isArray(M[F])||(M[F]=[M[F]]),M[F].push(D);else{let be=y.jPath?T.toString():T;y.isArray(F,be,ae)?M[F]=[D]:M[F]=D}F!==void 0&&F!==y.textNodeName&&T.pop()}}}return typeof O=="string"?O.length>0&&(M[y.textNodeName]=O):O!==void 0&&(M[y.textNodeName]=O),M}i(Bn,"compress"),n(Bn,"compress");function rr(h){let y=Object.keys(h);for(let T=0;T<y.length;T++){let O=y[T];if(O!==":@")return O}}i(rr,"propName"),n(rr,"propName");function Oo(h,y,T,O){if(y){let M=Object.keys(y),E=M.length;for(let V=0;V<E;V++){let F=M[V],D=F.startsWith(O.attributeNamePrefix)?F.substring(O.attributeNamePrefix.length):F,ae=O.jPath?T.toString()+"."+D:T;O.isArray(F,ae,!0,!0)?h[F]=[y[F]]:h[F]=y[F]}}}i(Oo,"assignAttributes"),n(Oo,"assignAttributes");function io(h,y){let{textNodeName:T}=y,O=Object.keys(h).length;return!!(O===0||O===1&&(h[T]||typeof h[T]=="boolean"||h[T]===0))}i(io,"isLeafTag"),n(io,"isLeafTag");var ir={allowBooleanAttributes:!1,unpairedTags:[]};function ko(h,y){y=Object.assign({},ir,y);let T=[],O=!1,M=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let E=0;E<h.length;E++)if(h[E]==="<"&&h[E+1]==="?"){if(E+=2,E=At(h,E),E.err)return E}else if(h[E]==="<"){let V=E;if(E++,h[E]==="!"){E=_o(h,E);continue}else{let F=!1;h[E]==="/"&&(F=!0,E++);let D="";for(;E<h.length&&h[E]!==">"&&h[E]!==" "&&h[E]!==" "&&h[E]!==`
369
369
  `&&h[E]!=="\r";E++)D+=h[E];if(D=D.trim(),D[D.length-1]==="/"&&(D=D.substring(0,D.length-1),E--),!jr(D)){let _e;return D.trim().length===0?_e="Invalid space after '<'.":_e="Tag '"+D+"' is an invalid name.",ot("InvalidTag",_e,wt(h,E))}let ae=ar(h,E);if(ae===!1)return ot("InvalidAttr","Attributes for '"+D+"' have open quote.",wt(h,E));let be=ae.value;if(E=ae.index,be[be.length-1]==="/"){let _e=E-be.length;be=be.substring(0,be.length-1);let st=xo(be,y);if(st===!0)O=!0;else return ot(st.err.code,st.err.msg,wt(h,_e+st.err.line))}else if(F)if(ae.tagClosed){if(be.trim().length>0)return ot("InvalidTag","Closing tag '"+D+"' can't have attributes or invalid starting.",wt(h,V));if(T.length===0)return ot("InvalidTag","Closing tag '"+D+"' has not been opened.",wt(h,V));{let _e=T.pop();if(D!==_e.tagName){let st=wt(h,_e.tagStartPos);return ot("InvalidTag","Expected closing tag '"+_e.tagName+"' (opened in line "+st.line+", col "+st.col+") instead of closing tag '"+D+"'.",wt(h,V))}T.length==0&&(M=!0)}}else return ot("InvalidTag","Closing tag '"+D+"' doesn't have proper closing.",wt(h,E));else{let _e=xo(be,y);if(_e!==!0)return ot(_e.err.code,_e.err.msg,wt(h,E-be.length+_e.err.line));if(M===!0)return ot("InvalidXml","Multiple possible root nodes found.",wt(h,E));y.unpairedTags.indexOf(D)!==-1||T.push({tagName:D,tagStartPos:V}),O=!0}for(E++;E<h.length;E++)if(h[E]==="<")if(h[E+1]==="!"){E++,E=_o(h,E);continue}else if(h[E+1]==="?"){if(E=At(h,++E),E.err)return E}else break;else if(h[E]==="&"){let _e=ur(h,E);if(_e==-1)return ot("InvalidChar","char '&' is not expected.",wt(h,E));E=_e}else if(M===!0&&!so(h[E]))return ot("InvalidXml","Extra text at the end",wt(h,E));h[E]==="<"&&E--}}else{if(so(h[E]))continue;return ot("InvalidChar","char '"+h[E]+"' is not expected.",wt(h,E))}if(O){if(T.length==1)return ot("InvalidTag","Unclosed tag '"+T[0].tagName+"'.",wt(h,T[0].tagStartPos));if(T.length>0)return ot("InvalidXml","Invalid '"+JSON.stringify(T.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return ot("InvalidXml","Start tag expected.",1);return!0}i(ko,"validate"),n(ko,"validate");function so(h){return h===" "||h===" "||h===`
370
370
  `||h==="\r"}i(so,"isWhiteSpace"),n(so,"isWhiteSpace");function At(h,y){let T=y;for(;y<h.length;y++)if(h[y]=="?"||h[y]==" "){let O=h.substr(T,y-T);if(y>5&&O==="xml")return ot("InvalidXml","XML declaration allowed only at the start of the document.",wt(h,y));if(h[y]=="?"&&h[y+1]==">"){y++;break}else continue}return y}i(At,"readPI"),n(At,"readPI");function _o(h,y){if(h.length>y+5&&h[y+1]==="-"&&h[y+2]==="-"){for(y+=3;y<h.length;y++)if(h[y]==="-"&&h[y+1]==="-"&&h[y+2]===">"){y+=2;break}}else if(h.length>y+8&&h[y+1]==="D"&&h[y+2]==="O"&&h[y+3]==="C"&&h[y+4]==="T"&&h[y+5]==="Y"&&h[y+6]==="P"&&h[y+7]==="E"){let T=1;for(y+=8;y<h.length;y++)if(h[y]==="<")T++;else if(h[y]===">"&&(T--,T===0))break}else if(h.length>y+9&&h[y+1]==="["&&h[y+2]==="C"&&h[y+3]==="D"&&h[y+4]==="A"&&h[y+5]==="T"&&h[y+6]==="A"&&h[y+7]==="["){for(y+=8;y<h.length;y++)if(h[y]==="]"&&h[y+1]==="]"&&h[y+2]===">"){y+=2;break}}return y}i(_o,"readCommentAndCDATA"),n(_o,"readCommentAndCDATA");var zi='"',sr="'";function ar(h,y){let T="",O="",M=!1;for(;y<h.length;y++){if(h[y]===zi||h[y]===sr)O===""?O=h[y]:O!==h[y]||(O="");else if(h[y]===">"&&O===""){M=!0;break}T+=h[y]}return O!==""?!1:{value:T,index:y,tagClosed:M}}i(ar,"readAttributeStr"),n(ar,"readAttributeStr");var Ur=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function xo(h,y){let T=c(h,Ur),O={};for(let M=0;M<T.length;M++){if(T[M][1].length===0)return ot("InvalidAttr","Attribute '"+T[M][2]+"' has no space in starting.",on(T[M]));if(T[M][3]!==void 0&&T[M][4]===void 0)return ot("InvalidAttr","Attribute '"+T[M][2]+"' is without value.",on(T[M]));if(T[M][3]===void 0&&!y.allowBooleanAttributes)return ot("InvalidAttr","boolean attribute '"+T[M][2]+"' is not allowed.",on(T[M]));let E=T[M][2];if(!lr(E))return ot("InvalidAttr","Attribute '"+E+"' is an invalid name.",on(T[M]));if(!Object.prototype.hasOwnProperty.call(O,E))O[E]=1;else return ot("InvalidAttr","Attribute '"+E+"' is repeated.",on(T[M]))}return!0}i(xo,"validateAttributeString"),n(xo,"validateAttributeString");function cr(h,y){let T=/\d/;for(h[y]==="x"&&(y++,T=/[\da-fA-F]/);y<h.length;y++){if(h[y]===";")return y;if(!h[y].match(T))break}return-1}i(cr,"validateNumberAmpersand"),n(cr,"validateNumberAmpersand");function ur(h,y){if(y++,h[y]===";")return-1;if(h[y]==="#")return y++,cr(h,y);let T=0;for(;y<h.length;y++,T++)if(!(h[y].match(/\w/)&&T<20)){if(h[y]===";")break;return-1}return y}i(ur,"validateAmpersand"),n(ur,"validateAmpersand");function ot(h,y,T){return{err:{code:h,msg:y,line:T.line||T,col:T.col}}}i(ot,"getErrorObject"),n(ot,"getErrorObject");function lr(h){return u(h)}i(lr,"validateAttrName"),n(lr,"validateAttrName");function jr(h){return u(h)}i(jr,"validateTagName"),n(jr,"validateTagName");function wt(h,y){let T=h.substring(0,y).split(/\r?\n/);return{line:T.length,col:T[T.length-1].length+1}}i(wt,"getLineNumberForPosition"),n(wt,"getLineNumberForPosition");function on(h){return h.startIndex+h[1].length}i(on,"getPositionFromMatch"),n(on,"getPositionFromMatch");var Hr=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(h){this.externalEntities={},this.options=w(h)}parse(h,y){if(typeof h!="string"&&h.toString)h=h.toString();else if(typeof h!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(y){y===!0&&(y={});let M=ko(h,y);if(M!==!0)throw Error(`${M.err.msg}:${M.err.line}:${M.err.col}`)}let T=new Ln(this.options);T.addExternalEntities(this.externalEntities);let O=T.parseXml(h);return this.options.preserveOrder||O===void 0?O:Eo(O,this.options,T.matcher)}addEntity(h,y){if(y.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(h.indexOf("&")!==-1||h.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(y==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[h]=y}static getMetaDataSymbol(){return v.getMetaDataSymbol()}};return new Hr(t)},"getXmlParser");var sR=class extends Mo{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){super(e,n),De(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?lo(e.parseOnStatusCodes):void 0,this.parser=yx({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0,processEntities:{enabled:!0,maxTotalExpansions:1/0,maxEntityCount:1e3}})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new j(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var aR=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new Ue(`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 cR=class{static{i(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Ze("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){Q("utility.get-consumer");let n=ii(),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),s=new Ve(r,n);if(this.cacheDurationSeconds>0){let l=await s.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await lh(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&s.put(e,u,this.cacheDurationSeconds),u}};var bx=10,Sx=3e4,sl=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#r;#i={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#r=Sx,this.#n=bx}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#r=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:Sx,this.#n=bx}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 q2(()=>this.#u(e)!==void 0||!this.#a(e),this.#r+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);Tr().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.#r)]);if(n===void 0)throw new I(`BackgroundLoader: Loader timed out after ${this.#r} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#i[e]--}}};async function q2(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new I(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(q2,"waitUntilTrue");import{SpanStatusCode as wx,trace as $2}from"@opentelemetry/api";var Rx,Cx=i(()=>(Rx??=$2.getTracer("pipeline"),Rx),"tracer"),Ix=i(async(t,e,n)=>{let o=Xe.instance.routeData.policies,r=ns([t],o);if(r.length===0)throw new j(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0];return await Cx().startActiveSpan(`policy:${s.policyName}`,async c=>{try{ts(c,s);let u=await s.handler(e,n);if(u instanceof Request||u instanceof Ne||u instanceof Response)return u instanceof Response||u instanceof Ne?u:new Ne(u);{let l=new I(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`);throw c.setStatus({code:wx.ERROR}),c.recordException(l),l}}finally{c.end()}})},"invokeInboundPolicy"),vx=i(async(t,e,n,o)=>{let r=Xe.instance.routeData.policies,s=Ga([t],r);if(s.length===0)throw new j(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await Cx().startActiveSpan(`policy:${a.policyName}`,async u=>{try{ts(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;{let d=new I(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw u.setStatus({code:wx.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeOutboundPolicy");var z2="127.0.0.1";function Tx(t){let e=_.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?z2:void 0)}i(Tx,"resolveClientIp");function D2(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[s,a]=r.split("=");s&&a&&(o[s.trim()]=a.trim())}),o.asnum&&(e[Vl]=o.asnum),o.zip&&(e[Jl]=o.zip.split("+")[0]),o.dma&&(e[Kl]=o.dma),o.region_code&&(e[Wl]=o.region_code),o.timezone&&(e[Yl]=o.timezone),o.city&&(e[Hl]=o.city),o.continent&&(e[Fl]=o.continent),o.country_code&&(e[Gl]=o.country_code),o.long&&(e[Zl]=o.long),o.lat&&(e[Bl]=o.lat),e}catch{return{}}}i(D2,"parseEdgeScapeHeader");function Px(t,e){let n=D2(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(Px,"setZpHeadersFromAkamaiEdgeScapeHeader");var jd=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(DR);if(n){let o=new Headers(e);Px(o,n),this.#e=o}}get ip(){return Tx(this.#e)}get asn(){try{let e=this.#e.get(Vl);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(LR)??void 0}get city(){return this.#e.get(fR)??this.#e.get(Hl)??void 0}get continent(){return this.#e.get(gR)??this.#e.get(Fl)??void 0}get country(){return this.#e.get(yR)??this.#e.get(Gl)??void 0}get latitude(){return this.#e.get(SR)??this.#e.get(Bl)??void 0}get longitude(){return this.#e.get(bR)??this.#e.get(Zl)??void 0}get colo(){return this.#e.get(NR)??void 0}get postalCode(){return this.#e.get(IR)??this.#e.get(Jl)??void 0}get metroCode(){return this.#e.get(CR)??this.#e.get(Kl)??void 0}get region(){return this.#e.get(RR)??this.#e.get(qR)??void 0}get regionCode(){return this.#e.get(wR)??this.#e.get(Wl)??void 0}get timezone(){return this.#e.get(vR)??this.#e.get(Yl)??void 0}get httpProtocol(){return this.#e.get($R)??void 0}get clientCert(){return this.#e.get(PR)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(AR)??void 0}get clientMtlsVerificationReason(){return this.#e.get(ER)??void 0}get clientCertFingerprintSha256(){return this.#e.get(OR)??void 0}get clientCertNotBefore(){return this.#e.get(kR)??void 0}get clientCertNotAfter(){return this.#e.get(_R)??void 0}get clientCertIssuerDn(){return this.#e.get(xR)??void 0}get clientCertSubjectDn(){return this.#e.get(MR)??void 0}toJSON(){return{ip:this.ip,asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function na(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(na,"createRewriteContext");var ja=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},Ha=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},dt=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n){if(!t.#e.has(e)){let o=new t(n);return t.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new j(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;auditLogEventId="";#t;#o;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#o=[],this.#n=[]}addResponseSendingHook(e){this.#o.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#n.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#t)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=_.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#o)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#n)await r(e,n,o)},"onHandlerResponse")},Hd=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:s,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,l)=>Ix(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>vx(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let m=new Ne(d,l);return Xe.instance.handleRequest(m,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{dt.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{dt.getContextExtensions(this).addResponseSendingFinalHook(u)},this.analyticsContext=new GR(o),Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,n,o){Q("context.addEventListener");let r=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,r,o)}removeEventListener(e,n,o){Q("context.removeEventListener"),super.removeEventListener(e,n,o)}};export{Vi as a,ao as b,Et as c,Dx as d,Ux as e,ch as f,mt as g,Kr as h,jx as i,Wr as j,Q as k,lh as l,ph as m,Cn as n,br as o,Na as p,Yr as q,z as r,Ct as s,Qr as t,hh as u,fh as v,rd as w,qe as x,mn as y,Rr as z,ue as A,Mo as B,Ch as C,Ah as D,p0 as E,Yi as F,ja as G,Ha as H,rf as I,ut as J,RI as K,wI as L,UL as M,AI as N,Sf as O,KL as P,ci as Q,rc as R,ui as S,bs as T,Fo as U,Go as V,Or as W,li as X,Ho as Y,ft as Z,dp as _,Ss as $,Rs as aa,sc as ba,ac as ca,ws as da,Dt as ea,kr as fa,gt as ga,Qt as ha,Gt as ia,Cs as ja,yt as ka,Zo as la,Is as ma,vs as na,di as oa,pi as pa,mi as qa,pp as ra,Ts as sa,cc as ta,Ps as ua,uc as va,Bo as wa,fo as xa,Kn as ya,mp as za,hp as Aa,lc as Ba,dc as Ca,As as Da,Es as Ea,pc as Fa,mc as Ga,hc as Ha,fc as Ia,Os as Ja,gc as Ka,yc as La,ks as Ma,bc as Na,Vo as Oa,Jo as Pa,_s as Qa,xs as Ra,Ms as Sa,Ko as Ta,go as Ua,Ls as Va,Sc as Wa,Rc as Xa,wc as Ya,Cc as Za,Ic as _a,hi as $a,vc as ab,Tc as bb,Pc as cb,Ac as db,Ec as eb,Oc as fb,kc as gb,_c as hb,Ns as ib,xc as jb,Mc as kb,Lc as lb,Nc as mb,qc as nb,$c as ob,zc as pb,Dc as qb,Uc as rb,jc as sb,Hc as tb,Fc as ub,Gc as vb,Zc as wb,fi as xb,gi as yb,yi as zb,Bc as Ab,Vc as Bb,Jc as Cb,bi as Db,Kc as Eb,Wc as Fb,Yc as Gb,Qc as Hb,Xc as Ib,qs as Jb,eu as Kb,tu as Lb,$s as Mb,fp as Nb,nu as Ob,ou as Pb,ru as Qb,Cf as Rb,Wo as Sb,iu as Tb,su as Ub,au as Vb,cu as Wb,uu as Xb,lu as Yb,du as Zb,pu as _b,mu as $b,Er as ac,hu as bc,fu as cc,gu as dc,yu as ec,bu as fc,zs as gc,Si as hc,Ri as ic,Ds as jc,Us as kc,js as lc,Su as mc,Hs as nc,Fs as oc,Ru as pc,wu as qc,Gs as rc,wi as sc,Cu as tc,Iu as uc,vu as vc,Tu as wc,Pu as xc,Au as yc,Eu as zc,Ou as Ac,ku as Bc,_u as Cc,xu as Dc,Mu as Ec,Lu as Fc,Nu as Gc,qu as Hc,gp as Ic,$u as Jc,Yo as Kc,yp as Lc,zu as Mc,bp as Nc,Sp as Oc,Rp as Pc,wp as Qc,Cp as Rc,Ip as Sc,vp as Tc,Tp as Uc,Pp as Vc,Ap as Wc,Ep as Xc,Op as Yc,kp as Zc,_p as _c,xp as $c,Mp as ad,Du as bd,Uu as cd,Lp as dd,Np as ed,qp as fd,$p as gd,ju as hd,Hu as id,zp as jd,Dp as kd,Up as ld,hT as md,fT as nd,gT as od,yT as pd,bT as qd,ST as rd,ag as sd,hz as td,cg as ud,lg as vd,pg as wd,fg as xd,yg as yd,Sg as zd,wg as Ad,Ig as Bd,Pg as Cd,Og as Dd,xg as Ed,Ng as Fd,$g as Gd,zg as Hd,nl as Id,ol as Jd,rl as Kd,Fg as Ld,al as Md,Bg as Nd,Vg as Od,Kz as Pd,Jg as Qd,Kg as Rd,qT as Sd,$T as Td,DT as Ud,ty as Vd,ry as Wd,uy as Xd,dy as Yd,aP as Zd,dP as _d,pP as $d,wP as ae,CP as be,IP as ce,vP as de,OP as ee,kP as fe,Py as ge,MP as he,bm as ie,lU as je,Ay as ke,Xt as le,HP as me,xy as ne,My as oe,ZP as pe,qy as qe,VP as re,nA as se,oA as te,rA as ue,iA as ve,sA as we,aA as xe,mA as ye,gA as ze,Zy as Ae,SA as Be,RA as Ce,wA as De,xA as Ee,MA as Fe,LA as Ge,NA as He,UA as Ie,GA as Je,ZA as Ke,_m as Le,qj as Me,KA as Ne,YA as Oe,Ib as Pe,aE as Qe,zr as Re,ba as Se,tt as Te,pt as Ue,Ro as Ve,Pge as We,Rl as Xe,kge as Ye,_ge as Ze,_n as _e,Lge as $e,Nge as af,qge as bf,$ge as cf,wl as df,zge as ef,xi as ff,Fge as gf,Nm as hf,Mi as if,Ra as jf,Ab as kf,tye as lf,Eb as mf,Ob as nf,kb as of,_b as pf,xb as qf,Mb as rf,Lb as sf,Nb as tf,qb as uf,$b as vf,zb as wf,tSe as xf,Fn as yf,xn as zf,vt as Af,XE as Bf,W1 as Cf,Y1 as Df,Db as Ef,RSe as Ff,wSe as Gf,CSe as Hf,mO as If,hO as Jf,GSe as Kf,ZSe as Lf,Ub as Mf,Il as Nf,jm as Of,BSe as Pf,yO as Qf,WSe as Rf,vl as Sf,yH as Tf,bH as Uf,Hb as Vf,iRe as Wf,wO as Xf,CO as Yf,uRe as Zf,lRe as _f,dRe as $f,pRe as ag,IO as bg,vO as cg,PO as dg,wo as eg,or as fg,wH as gg,CH as hg,RRe as ig,wRe as jg,CRe as kg,IRe as lg,Co as mg,PH as ng,NRe as og,OO as pg,ZRe as qg,Bb as rg,EH as sg,qH as tg,zH as ug,xO as vg,swe as wg,awe as xg,cwe as yg,qO as zg,pwe as Ag,mwe as Bg,hwe as Cg,Qb as Dg,Zm as Eg,Xb as Fg,DO as Gg,Iwe as Hg,vwe as Ig,Twe as Jg,Pwe as Kg,Nk as Lg,Gn as Mg,fS as Ng,rCe as Og,qk as Pg,iCe as Qg,SS as Rg,RS as Sg,jk as Tg,CG as Ug,Bk as Vg,PS as Wg,n_ as Xg,ES as Yg,d_ as Zg,OS as _g,_S as $g,m_ as ah,h_ as bh,f_ as ch,LS as dh,qS as eh,C_ as fh,I_ as gh,v_ as hh,T_ as ih,P_ as jh,E_ as kh,DS as lh,FG as mh,M_ as nh,FS as oh,D_ as ph,U_ as qh,j_ as rh,n2 as sh,H_ as th,F_ as uh,G_ as vh,Z_ as wh,B_ as xh,VS as yh,J_ as zh,K_ as Ah,JS as Bh,KS as Ch,Q_ as Dh,ex as Eh,tx as Fh,QS as Gh,ox as Hh,ux as Ih,oR as Jh,rR as Kh,lx as Lh,gx as Mh,sR as Nh,aR as Oh,cR as Ph,sl as Qh};
371
- /*! For license information please see chunk-YR2FKQJM.js.LEGAL.txt */
372
- //# sourceMappingURL=chunk-YR2FKQJM.js.map
371
+ /*! For license information please see chunk-XLNOQPTE.js.LEGAL.txt */
372
+ //# sourceMappingURL=chunk-XLNOQPTE.js.map