UNPKG

@sentry/core

Version:
2,910 lines • 127 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_fetch = require("./chunks/fetch.js");
const require_cacheOrigin = require("./chunks/cacheOrigin.js");
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_conventions_op = require("@sentry/conventions/op");
// src/transports/userAgent.ts
/**
* Takes the SDK metadata and adds the user-agent header to the transport options.
* This ensures that the SDK sends the user-agent header with SDK name and version to
* all requests made by the transport.
*
* @see https://develop.sentry.dev/sdk/overview/#user-agent
*/
function addUserAgentToTransportHeaders(options) {
	const sdkMetadata = options._metadata?.sdk;
	const sdkUserAgent = sdkMetadata?.name && sdkMetadata?.version ? `${sdkMetadata?.name}/${sdkMetadata?.version}` : void 0;
	options.transportOptions = {
		...options.transportOptions,
		headers: {
			...sdkUserAgent && { "user-agent": sdkUserAgent },
			...options.transportOptions?.headers
		}
	};
}
// src/utils/tunnelDefaults.ts
/**
* Sets framework-known tunnel settings for the current and every later server client, so per-request clients
* (Cloudflare) start with them. Settings from `init` win. Framework SDKs call this once at load.
*/
function setTunnelDefaults(defaults) {
	require_fetch.setStoredTunnelDefaults({
		...require_fetch.getStoredTunnelDefaults(),
		...defaults.tunnel && {
			tunnel: defaults.tunnel,
			forward: defaults.forward
		},
		...defaults.basePath !== void 0 && { basePath: defaults.basePath }
	});
	applyServerTunnelDefaults(require_cacheOrigin.getClient());
}
/**
* Enables the managed tunnel on a server client, from `serveTunnelIntegration`.
*/
function enableManagedTunnel(client, tunnelOptions, forward) {
	client.getOptions()._managedTunnel = { ...tunnelOptions };
	require_fetch.setClientTunnel(client, { forward });
	applyServerTunnelDefaults(client);
}
/**
* Resolves a server client's managed tunnel (from `serveTunnelIntegration` or the defaults), computes its paths and
* allowed DSNs, and installs its span filters. Runs when a server client is created and from
* {@link setTunnelDefaults}.
*/
function applyServerTunnelDefaults(client) {
	const tunnelDefaults = require_fetch.getStoredTunnelDefaults();
	const options = client?.getOptions();
	const tunnelOptions = options?._managedTunnel ?? tunnelDefaults?.tunnel;
	const forward = client && (require_fetch.getClientTunnel(client)?.forward ?? tunnelDefaults?.forward);
	if (!client || !options || !tunnelOptions || !forward) return;
	const basePath = require_fetch.normalizeTunnelBasePath(tunnelDefaults?.basePath);
	const resolved = tunnelOptions.basePath === void 0 && !tunnelOptions.path && basePath ? {
		...tunnelOptions,
		basePath
	} : tunnelOptions;
	options._managedTunnel = resolved;
	const { paths } = require_fetch.setServedTunnel(client, resolved, forward);
	const previousFilters = require_fetch.getClientTunnel(client)?.spanFilters ?? [];
	const spanFilters = require_fetch.getTunnelIgnoreSpanFilters(resolved, paths);
	options.ignoreSpans = [...(options.ignoreSpans ?? []).filter((filter) => !previousFilters.includes(filter)), ...spanFilters];
	require_fetch.setClientTunnel(client, { spanFilters });
}
/**
* Resets {@link setTunnelDefaults}, for tests.
*
* @internal
*/
function _INTERNAL_resetTunnelDefaults() {
	require_fetch.setStoredTunnelDefaults(void 0);
}
// src/server-runtime-client.ts
/**
* The Sentry Server Runtime Client SDK.
*/
var ServerRuntimeClient = class extends require_fetch.Client {
	/**
	* Creates a new Edge SDK instance.
	* @param options Configuration options for this SDK.
	*/
	constructor(options) {
		addUserAgentToTransportHeaders(options);
		if ((typeof __SENTRY_TRACING__ === "undefined" || __SENTRY_TRACING__) && options.traceLifecycle !== "static" && !options.integrations.some((i) => i.name === "SpanStreaming")) options.integrations.push(require_cacheOrigin.spanStreamingIntegration());
		super(options);
		this._disposeCallbacks = [];
		applyServerTunnelDefaults(this);
		this._setUpMetricsProcessing();
	}
	/**
	* @inheritDoc
	*/
	eventFromException(exception, hint) {
		const event = require_fetch.eventFromUnknownInput(this, this._options.stackParser, exception, hint);
		event.level = "error";
		return require_cacheOrigin.resolvedSyncPromise(event);
	}
	/**
	* @inheritDoc
	*/
	eventFromMessage(message, level = "info", hint) {
		return require_cacheOrigin.resolvedSyncPromise(require_fetch.eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace));
	}
	/**
	* @inheritDoc
	*/
	captureException(exception, hint, scope) {
		setCurrentRequestSessionErroredOrCrashed(hint);
		return super.captureException(exception, hint, scope);
	}
	/**
	* @inheritDoc
	*/
	captureEvent(event, hint, scope) {
		if (!event.type && event.exception?.values && event.exception.values.length > 0) setCurrentRequestSessionErroredOrCrashed(hint);
		return super.captureEvent(event, hint, scope);
	}
	/**
	* Create a cron monitor check in and send it to Sentry.
	*
	* @param checkIn An object that describes a check in.
	* @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want
	* to create a monitor automatically when sending a check in.
	*/
	captureCheckIn(checkIn, monitorConfig, scope) {
		const id = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : require_cacheOrigin.uuid4();
		if (!this._isEnabled()) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("SDK not enabled, will not capture check-in.");
			return id;
		}
		const { release, environment, tunnel } = this.getOptions();
		const serializedCheckIn = {
			check_in_id: id,
			monitor_slug: checkIn.monitorSlug,
			status: checkIn.status,
			release,
			environment
		};
		if ("duration" in checkIn) serializedCheckIn.duration = checkIn.duration;
		if (monitorConfig) serializedCheckIn.monitor_config = {
			schedule: monitorConfig.schedule,
			checkin_margin: monitorConfig.checkinMargin,
			max_runtime: monitorConfig.maxRuntime,
			timezone: monitorConfig.timezone,
			failure_issue_threshold: monitorConfig.failureIssueThreshold,
			recovery_threshold: monitorConfig.recoveryThreshold
		};
		const [dynamicSamplingContext, traceContext] = require_fetch._getTraceInfoFromScope(this, scope);
		if (traceContext) serializedCheckIn.contexts = { trace: traceContext };
		const envelope = require_fetch.createCheckInEnvelope(serializedCheckIn, dynamicSamplingContext, this.getSdkMetadata(), tunnel, this.getDsn());
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Sending checkin:", checkIn.monitorSlug, checkIn.status);
		this.sendEnvelope(envelope);
		return id;
	}
	/**
	* @inheritDoc
	*/
	registerCleanup(callback) {
		this._disposeCallbacks.push(callback);
	}
	/**
	* Disposes of the client and releases all resources.
	*
	* This method clears all internal state to allow the client to be garbage collected.
	* It clears hooks, event processors, integrations, transport, and other internal references.
	*
	* Call this method after flushing to allow the client to be garbage collected.
	* After calling dispose(), the client should not be used anymore.
	*
	* Subclasses should override this method to clean up their own resources and call `super.dispose()`.
	*/
	dispose() {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Disposing client...");
		for (const callback of this._disposeCallbacks) try {
			callback();
		} catch {}
		this._disposeCallbacks.length = 0;
		for (const hookName of Object.keys(this._hooks)) this._hooks[hookName]?.clear();
		this._hooks = {};
		this._eventProcessors.length = 0;
		this._integrations = {};
		this._outcomes = {};
		this._transport = void 0;
		this._promiseBuffer = require_fetch.makePromiseBuffer(64);
	}
	/**
	* @inheritDoc
	*/
	_prepareEvent(event, hint, currentScope, isolationScope) {
		if (this._options.platform) event.platform = event.platform || this._options.platform;
		if (this._options.runtime) event.contexts = {
			...event.contexts,
			runtime: event.contexts?.runtime || this._options.runtime
		};
		if (this._options.serverName) event.server_name = event.server_name || this._options.serverName;
		return super._prepareEvent(event, hint, currentScope, isolationScope);
	}
	/**
	* Process a server-side metric before it is captured.
	*/
	_setUpMetricsProcessing() {
		this.on("processMetric", (metric) => {
			if (this._options.serverName) metric.attributes = {
				[_sentry_conventions_attributes.SERVER_ADDRESS]: this._options.serverName,
				...metric.attributes
			};
		});
	}
};
function setCurrentRequestSessionErroredOrCrashed(eventHint) {
	const requestSession = require_cacheOrigin.getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;
	if (requestSession) {
		const isHandledException = eventHint?.mechanism?.handled ?? true;
		if (isHandledException && requestSession.status !== "crashed") requestSession.status = "errored";
		else if (!isHandledException) requestSession.status = "crashed";
	}
}
// src/integrations/serveTunnel.ts
const _serveTunnelIntegration = ((options = {}) => {
	return {
		name: "ServeTunnel",
		setup(client) {
			enableManagedTunnel(client, options, require_fetch.forwardTunnelRequest);
		}
	};
});
/**
* Lets your server forward the events of a browser SDK set up with `tunnel: true` to Sentry.
*
* With this integration on the server and `tunnel: true` in the browser `init`, the browser sends its events to your
* own server instead of Sentry, where ad-blockers can't drop them, and your server forwards them to Sentry.
*
* The server SDKs answer the tunnel requests before the app sees them. To serve them from your own code instead, set
* `intercept: false` and call `handleTunnelRequestIfMatched`.
*
* By default only envelopes for the server's own DSN are forwarded.
*
* @example
* ```js
* // Server
* Sentry.init({
*   dsn: '__DSN__',
*   integrations: [Sentry.serveTunnelIntegration()],
* });
*
* // Browser
* Sentry.init({
*   dsn: '__DSN__',
*   tunnel: true,
* });
* ```
*/
const serveTunnelIntegration = require_cacheOrigin.defineIntegration(_serveTunnelIntegration);
// src/trpc.ts
const trpcCaptureContext = { mechanism: {
	handled: false,
	type: "auto.rpc.trpc.middleware"
} };
function captureIfError(nextResult) {
	if (typeof nextResult === "object" && nextResult !== null && "ok" in nextResult && !nextResult.ok && "error" in nextResult) require_cacheOrigin.captureException(nextResult.error, trpcCaptureContext);
}
/**
* Sentry tRPC middleware that captures errors and creates spans for tRPC procedures.
*/
function trpcMiddleware(options = {}) {
	return async function(opts) {
		const { path, type, next, rawInput, getRawInput } = opts;
		const client = require_cacheOrigin.getClient();
		const clientOptions = client?.getOptions();
		const dataCollection = client?.getDataCollectionOptions();
		const trpcContext = {
			procedure_path: path,
			procedure_type: type
		};
		require_cacheOrigin.setNormalizationDepthOverrideHint(trpcContext, 1 + (clientOptions?.normalizeDepth ?? 5));
		if (options.attachRpcInput !== void 0 ? options.attachRpcInput : dataCollection?.httpBodies.includes("incomingRequest")) {
			if (rawInput !== void 0) trpcContext.input = require_cacheOrigin.normalize(rawInput);
			if (getRawInput !== void 0 && typeof getRawInput === "function") try {
				const rawRes = await getRawInput();
				trpcContext.input = require_cacheOrigin.normalize(rawRes);
			} catch {}
		}
		return require_cacheOrigin.withIsolationScope((scope) => {
			scope.setContext("trpc", trpcContext);
			return require_cacheOrigin.startSpanManual$1({
				name: `trpc/${path}`,
				attributes: {
					[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.RPC,
					[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "route",
					[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.rpc.trpc",
					[_sentry_conventions_attributes.RPC_SYSTEM_NAME]: "trpc",
					[_sentry_conventions_attributes.RPC_METHOD]: String(path),
					[_sentry_conventions_attributes.TRPC_PROCEDURE_PATH]: String(path),
					[_sentry_conventions_attributes.TRPC_PROCEDURE_TYPE]: String(type)
				},
				forceTransaction: !!options.forceTransaction
			}, async (span) => {
				try {
					const nextResult = await next();
					captureIfError(nextResult);
					span.end();
					return nextResult;
				} catch (e) {
					require_cacheOrigin.captureException(e, trpcCaptureContext);
					span.end();
					throw e;
				}
			});
		});
	};
}
// src/integrations/mcp-server/errorCapture.ts
/**
* Safe error capture utilities for MCP server instrumentation
*
* Ensures error reporting never interferes with MCP server operation.
* All capture operations are wrapped in try-catch to prevent side effects.
*/
/**
* Classifies JSON-RPC errors using MCP server semantic conventions.
* @param code - JSON-RPC error code
* @see https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md#server
*/
function isJsonRpcServerError(code) {
	return ![
		-32700,
		-32600,
		-32601,
		-32602,
		-32002
	].includes(code);
}
/**
* Captures an error without affecting MCP server operation.
*
* The active span already contains all MCP context (method, tool, arguments, etc.)
* @param error - Error to capture
* @param errorType - Classification of error type for filtering
* @param extraData - Additional context data to include
*/
function captureError(error, errorType, extraData) {
	try {
		if (!require_cacheOrigin.getClient()) return;
		const activeSpan = require_cacheOrigin.getActiveSpan();
		if (activeSpan?.isRecording()) activeSpan.setStatus({
			code: 2,
			message: "internal_error"
		});
		require_cacheOrigin.captureException(error, { mechanism: {
			type: "auto.ai.mcp_server",
			handled: false,
			data: {
				error_type: errorType || "handler_execution",
				...extraData
			}
		} });
	} catch {}
}
// src/integrations/mcp-server/handlers.ts
/**
* Handler method wrapping for MCP server instrumentation
*
* Provides automatic error capture and span correlation for tool, resource,
* and prompt handlers.
*/
/**
* Generic function to wrap MCP server method handlers
* @internal
* @param serverInstance - MCP server instance
* @param methodName - Method name to wrap (tool, resource, prompt)
*/
function wrapMethodHandler(serverInstance, methodName) {
	require_cacheOrigin.fill(serverInstance, methodName, (originalMethod) => {
		return function(name, ...args) {
			const handler = args[args.length - 1];
			if (typeof handler !== "function") return originalMethod.call(this, name, ...args);
			const wrappedHandler = createWrappedHandler(handler, methodName, name);
			return originalMethod.call(this, name, ...args.slice(0, -1), wrappedHandler);
		};
	});
}
/**
* Creates a wrapped handler with span correlation and error capture
* @internal
* @param originalHandler - Original handler function
* @param methodName - MCP method name
* @param handlerName - Handler identifier
* @returns Wrapped handler function
*/
function createWrappedHandler(originalHandler, methodName, handlerName) {
	return function(...handlerArgs) {
		try {
			const result = originalHandler.apply(this, handlerArgs);
			if (require_cacheOrigin.isObjectLike(result) && typeof result.then === "function") return Promise.resolve(result).catch((error) => {
				captureHandlerError(error, methodName, handlerName);
				throw error;
			});
			return result;
		} catch (error) {
			captureHandlerError(error, methodName, handlerName);
			throw error;
		}
	};
}
/**
* Captures handler execution errors based on handler type
* @internal
* @param error - Error to capture
* @param methodName - MCP method name
* @param handlerName - Handler identifier
*/
function captureHandlerError(error, methodName, handlerName) {
	try {
		const extraData = {};
		if (methodName === "tool" || methodName === "registerTool") {
			extraData.tool_name = handlerName;
			if (error.name === "ProtocolValidationError" || error.message.includes("validation") || error.message.includes("protocol")) captureError(error, "validation", extraData);
			else if (error.name === "ServerTimeoutError" || error.message.includes("timed out") || error.message.includes("timeout")) captureError(error, "timeout", extraData);
			else captureError(error, "tool_execution", extraData);
		} else if (methodName === "resource" || methodName === "registerResource") {
			extraData.resource_uri = handlerName;
			captureError(error, "resource_execution", extraData);
		} else if (methodName === "prompt" || methodName === "registerPrompt") {
			extraData.prompt_name = handlerName;
			captureError(error, "prompt_execution", extraData);
		}
	} catch {}
}
/**
* Wraps tool handlers to associate them with request spans.
* Instruments both `tool` (legacy API) and `registerTool` (new API) if present.
* @param serverInstance - MCP server instance
*/
function wrapToolHandlers(serverInstance) {
	if (typeof serverInstance.tool === "function") wrapMethodHandler(serverInstance, "tool");
	if (typeof serverInstance.registerTool === "function") wrapMethodHandler(serverInstance, "registerTool");
}
/**
* Wraps resource handlers to associate them with request spans.
* Instruments both `resource` (legacy API) and `registerResource` (new API) if present.
* @param serverInstance - MCP server instance
*/
function wrapResourceHandlers(serverInstance) {
	if (typeof serverInstance.resource === "function") wrapMethodHandler(serverInstance, "resource");
	if (typeof serverInstance.registerResource === "function") wrapMethodHandler(serverInstance, "registerResource");
}
/**
* Wraps prompt handlers to associate them with request spans.
* Instruments both `prompt` (legacy API) and `registerPrompt` (new API) if present.
* @param serverInstance - MCP server instance
*/
function wrapPromptHandlers(serverInstance) {
	if (typeof serverInstance.prompt === "function") wrapMethodHandler(serverInstance, "prompt");
	if (typeof serverInstance.registerPrompt === "function") wrapMethodHandler(serverInstance, "registerPrompt");
}
/**
* Wraps all MCP handler types for span correlation.
* Supports both the legacy API (`tool`, `resource`, `prompt`) and the newer API
* (`registerTool`, `registerResource`, `registerPrompt`), instrumenting whichever methods are present.
* @param serverInstance - MCP server instance
*/
function wrapAllMCPHandlers(serverInstance) {
	wrapToolHandlers(serverInstance);
	wrapResourceHandlers(serverInstance);
	wrapPromptHandlers(serverInstance);
}
/**
* Retroactively wraps handlers on tools, resources, and prompts that were registered
* before `wrapMcpServerWithSentry` was called.
*
* The MCP SDK stores registered entries in private maps and invokes them via the entry's
* own property at call time — `executor` for tools, `readCallback` for resources, and
* `handler` for prompts. Replacing those properties
* in-place is therefore equivalent to having wrapped the original registration call.
*
* NOTE: This intentionally accesses private MCP SDK internals (`_registeredTools` etc.).
* The properties and their shapes are verified against @modelcontextprotocol/sdk source:
* https://github.com/modelcontextprotocol/typescript-sdk/blob/2c0c481cb9dbfd15c8613f765c940a5f5bace94d/packages/server/src/server/mcp.ts#L304
* When upgrading the MCP SDK, re-verify that these internal maps and their callable
* properties still exist and are invoked directly (not captured by closure at registration).
* All access is defensive — if a property is absent or not a function we skip silently.
* @internal
*/
function wrapExistingHandlers(serverInstance) {
	const server = serverInstance;
	const registeredTools = server["_registeredTools"];
	if (require_cacheOrigin.isObjectLike(registeredTools)) {
		for (const [name, tool] of Object.entries(registeredTools)) if (typeof tool["executor"] === "function") tool["executor"] = createWrappedHandler(tool["executor"], "registerTool", name);
	}
	const registeredResources = server["_registeredResources"];
	if (require_cacheOrigin.isObjectLike(registeredResources)) {
		for (const [name, resource] of Object.entries(registeredResources)) if (typeof resource["readCallback"] === "function") resource["readCallback"] = createWrappedHandler(resource["readCallback"], "registerResource", name);
	}
	const registeredResourceTemplates = server["_registeredResourceTemplates"];
	if (require_cacheOrigin.isObjectLike(registeredResourceTemplates)) {
		for (const [name, template] of Object.entries(registeredResourceTemplates)) if (typeof template["readCallback"] === "function") template["readCallback"] = createWrappedHandler(template["readCallback"], "registerResource", name);
	}
	const registeredPrompts = server["_registeredPrompts"];
	if (require_cacheOrigin.isObjectLike(registeredPrompts)) {
		for (const [name, prompt] of Object.entries(registeredPrompts)) if (typeof prompt["handler"] === "function") prompt["handler"] = createWrappedHandler(prompt["handler"], "registerPrompt", name);
	}
}
// src/integrations/mcp-server/validation.ts
/**
* Message validation functions for MCP server instrumentation
*
* Provides JSON-RPC 2.0 message type validation and MCP server instance validation.
*/
/**
* Validates if a message is a JSON-RPC request
* @param message - Message to validate
* @returns True if message is a JSON-RPC request
*/
function isJsonRpcRequest(message) {
	return require_cacheOrigin.isObjectLike(message) && "jsonrpc" in message && message.jsonrpc === "2.0" && "method" in message && "id" in message;
}
/**
* Validates if a message is a JSON-RPC notification
* @param message - Message to validate
* @returns True if message is a JSON-RPC notification
*/
function isJsonRpcNotification(message) {
	return require_cacheOrigin.isObjectLike(message) && "jsonrpc" in message && message.jsonrpc === "2.0" && "method" in message && !("id" in message);
}
/**
* Validates if a message is a JSON-RPC response
* @param message - Message to validate
* @returns True if message is a JSON-RPC response
*/
function isJsonRpcResponse(message) {
	return require_cacheOrigin.isObjectLike(message) && "jsonrpc" in message && message.jsonrpc === "2.0" && "id" in message && ("result" in message || "error" in message);
}
/**
* Validates MCP server instance with type checking.
* Accepts both the legacy API (`tool`, `resource`, `prompt`) used in SDK 1.x
* and the newer API (`registerTool`, `registerResource`, `registerPrompt`) introduced
* alongside the legacy API in SDK 1.x and made the only option in SDK 2.x.
* @param instance - Object to validate as MCP server instance
* @returns True if instance has required MCP server methods
*/
function validateMcpServerInstance(instance) {
	if (require_cacheOrigin.isObjectLike(instance) && "connect" in instance && ("tool" in instance && "resource" in instance && "prompt" in instance || "registerTool" in instance && "registerResource" in instance && "registerPrompt" in instance)) return true;
	require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.warn("Did not patch MCP server. Interface is incompatible.");
	return false;
}
/**
* Check if the item is a valid content item
* @param item - The item to check
* @returns True if the item is a valid content item, false otherwise
*/
function isValidContentItem(item) {
	return require_cacheOrigin.isObjectLike(item);
}
// src/integrations/mcp-server/resultExtraction.ts
/**
* Result extraction functions for MCP server instrumentation
*
* Handles extraction of attributes from tool and prompt execution results.
*/
/**
* Build attributes for tool result content items
* @param content - Array of content items from tool result
* @param includeContent - Whether to include actual content (text, URIs) or just metadata
* @returns Attributes extracted from each content item
*/
function buildAllContentItemAttributes(content, includeContent) {
	const attributes = { [_sentry_conventions_attributes.MCP_TOOL_RESULT_CONTENT_COUNT]: content.length };
	for (const [i, item] of content.entries()) {
		if (!isValidContentItem(item)) continue;
		const single = content.length === 1;
		const index = String(i);
		if (typeof item.type === "string") {
			const key = single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_CONTENT_TYPE : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_CONTENT_TYPE.replace("<key>", index);
			attributes[key] = item.type;
		}
		if (includeContent) {
			const safeSet = (key, value) => {
				if (typeof value === "string") attributes[key] = value;
			};
			safeSet(single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_MIME_TYPE : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_MIME_TYPE.replace("<key>", index), item.mimeType);
			safeSet(single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_URI : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_URI.replace("<key>", index), item.uri);
			safeSet(single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_NAME : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_NAME.replace("<key>", index), item.name);
			if (typeof item.text === "string") {
				const attrName = single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_CONTENT : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_CONTENT.replace("<key>", index);
				attributes[attrName] = item.text;
			}
			if (typeof item.data === "string") {
				const key = single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_DATA_SIZE : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_DATA_SIZE.replace("<key>", index);
				attributes[key] = item.data.length;
			}
			const resource = item.resource;
			if (isValidContentItem(resource)) {
				safeSet(single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_RESOURCE_URI : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_RESOURCE_URI.replace("<key>", index), resource.uri);
				safeSet(single ? _sentry_conventions_attributes.MCP_TOOL_RESULT_RESOURCE_MIME_TYPE : _sentry_conventions_attributes.MCP_TOOL_RESULT_KEY_RESOURCE_MIME_TYPE.replace("<key>", index), resource.mimeType);
			}
		}
	}
	return attributes;
}
/**
* Extract tool result attributes for span instrumentation
* @param result - Tool execution result
* @param recordOutputs - Whether to include actual content or just metadata (counts, error status)
* @returns Attributes extracted from tool result content
*/
function extractToolResultAttributes(result, recordOutputs) {
	if (!isValidContentItem(result)) return {};
	const attributes = Array.isArray(result.content) ? buildAllContentItemAttributes(result.content, recordOutputs) : {};
	if (typeof result.isError === "boolean") attributes[_sentry_conventions_attributes.MCP_TOOL_RESULT_IS_ERROR] = result.isError;
	return attributes;
}
/**
* Extract prompt result attributes for span instrumentation
* @param result - Prompt execution result
* @param recordOutputs - Whether to include actual content or just metadata (counts)
* @returns Attributes extracted from prompt result
*/
function extractPromptResultAttributes(result, recordOutputs) {
	const attributes = {};
	if (!isValidContentItem(result)) return attributes;
	if (recordOutputs && typeof result.description === "string") attributes[_sentry_conventions_attributes.MCP_PROMPT_RESULT_DESCRIPTION] = result.description;
	if (Array.isArray(result.messages)) {
		attributes[_sentry_conventions_attributes.MCP_PROMPT_RESULT_MESSAGE_COUNT] = result.messages.length;
		if (recordOutputs) {
			const messages = result.messages;
			for (const [i, message] of messages.entries()) {
				if (!isValidContentItem(message)) continue;
				if (typeof message.role === "string") {
					const attrName = messages.length === 1 ? _sentry_conventions_attributes.MCP_PROMPT_RESULT_MESSAGE_ROLE : _sentry_conventions_attributes.MCP_PROMPT_RESULT_KEY_ROLE.replace("<key>", String(i));
					attributes[attrName] = message.role;
				}
				if (isValidContentItem(message.content)) {
					const content = message.content;
					if (typeof content.text === "string") {
						const attrName = messages.length === 1 ? _sentry_conventions_attributes.MCP_PROMPT_RESULT_MESSAGE_CONTENT : _sentry_conventions_attributes.MCP_PROMPT_RESULT_KEY_CONTENT.replace("<key>", String(i));
						attributes[attrName] = content.text;
					}
				}
			}
		}
	}
	return attributes;
}
// src/integrations/mcp-server/sessionManagement.ts
/**
* Session-scoped data storage for stateful transports (with sessionId)
* @internal Using sessionId as key handles wrapper transport patterns
*/
const sessionToSessionData = /* @__PURE__ */ new Map();
/**
* Transport-scoped data storage fallback for stateless transports (no sessionId)
* @internal WeakMap allows automatic cleanup when transport is garbage collected
*/
const statelessSessionData = /* @__PURE__ */ new WeakMap();
/**
* Gets session data for a transport, checking sessionId first then fallback
* @internal
*/
function getSessionData(transport) {
	const sessionId = transport.sessionId;
	if (sessionId) return sessionToSessionData.get(sessionId);
	return statelessSessionData.get(transport);
}
/**
* Sets session data for a transport, using sessionId when available
* @internal
*/
function setSessionData(transport, data) {
	const sessionId = transport.sessionId;
	if (sessionId) sessionToSessionData.set(sessionId, data);
	else statelessSessionData.set(transport, data);
}
/**
* Updates session data for a transport (merges with existing data)
* @param transport - MCP transport instance
* @param partialSessionData - Partial session data to merge with existing data
*/
function updateSessionDataForTransport(transport, partialSessionData) {
	setSessionData(transport, {
		...getSessionData(transport) || {},
		...partialSessionData
	});
}
/**
* Retrieves client information for a transport
* @param transport - MCP transport instance
* @returns Client information if available
*/
function getClientInfoForTransport(transport) {
	return getSessionData(transport)?.clientInfo;
}
/**
* Retrieves protocol version for a transport
* @param transport - MCP transport instance
* @returns Protocol version if available
*/
function getProtocolVersionForTransport(transport) {
	return getSessionData(transport)?.protocolVersion;
}
/**
* Retrieves full session data for a transport
* @param transport - MCP transport instance
* @returns Complete session data if available
*/
function getSessionDataForTransport(transport) {
	return getSessionData(transport);
}
/**
* Cleans up session data for a specific transport (when that transport closes)
* @param transport - MCP transport instance
*/
function cleanupSessionDataForTransport(transport) {
	const sessionId = transport.sessionId;
	if (sessionId) sessionToSessionData.delete(sessionId);
}
// src/integrations/mcp-server/sessionExtraction.ts
/**
* Session and party info extraction functions for MCP server instrumentation
*
* Handles extraction of client/server info and session data from MCP messages.
*/
const MCP_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion";
const MCP_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
const MCP_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo";
/**
* Extracts and validates PartyInfo from an unknown object
* @param obj - Unknown object that might contain party info
* @returns Validated PartyInfo object with only string properties
*/
function extractPartyInfo(obj) {
	const partyInfo = {};
	if (isValidContentItem(obj)) {
		if (typeof obj.name === "string") partyInfo.name = obj.name;
		if (typeof obj.title === "string") partyInfo.title = obj.title;
		if (typeof obj.version === "string") partyInfo.version = obj.version;
	}
	return partyInfo;
}
/**
* Extracts session data from "initialize" requests
* @param request - JSON-RPC "initialize" request containing client info and protocol version
* @returns Session data extracted from request parameters including protocol version and client info
*/
function extractSessionDataFromInitializeRequest(request) {
	const sessionData = {};
	if (isValidContentItem(request.params)) {
		if (typeof request.params.protocolVersion === "string") sessionData.protocolVersion = request.params.protocolVersion;
		if (request.params.clientInfo) sessionData.clientInfo = extractPartyInfo(request.params.clientInfo);
	}
	return sessionData;
}
/**
* Extracts session data from an MCP 2026-07-28 request or notification envelope.
* @param message - JSON-RPC message containing modern request metadata
* @returns Session data extracted from the message
*/
function extractSessionDataFromMessage(message) {
	const sessionData = {};
	if (isValidContentItem(message.params)) {
		if (isValidContentItem(message.params._meta)) {
			const meta = message.params._meta;
			if (typeof meta[MCP_PROTOCOL_VERSION_META_KEY] === "string") sessionData.protocolVersion = meta[MCP_PROTOCOL_VERSION_META_KEY];
			if (meta[MCP_CLIENT_INFO_META_KEY]) sessionData.clientInfo = extractPartyInfo(meta[MCP_CLIENT_INFO_META_KEY]);
		}
	}
	return sessionData;
}
/**
* Extracts session data from "initialize" response
* @param result - "initialize" response result containing server info and protocol version
* @returns Partial session data extracted from response including protocol version and server info
*/
function extractSessionDataFromInitializeResponse(result) {
	const sessionData = {};
	if (isValidContentItem(result)) {
		if (typeof result.protocolVersion === "string") sessionData.protocolVersion = result.protocolVersion;
		if (result.serverInfo) sessionData.serverInfo = extractPartyInfo(result.serverInfo);
	}
	return sessionData;
}
/**
* Extracts session data from MCP 2026-07-28 result metadata.
* @param result - JSON-RPC result containing modern response metadata
* @returns Session data extracted from the result
*/
function extractSessionDataFromResponse(result) {
	const sessionData = {};
	if (isValidContentItem(result)) {
		if (isValidContentItem(result._meta) && result._meta[MCP_SERVER_INFO_META_KEY]) sessionData.serverInfo = extractPartyInfo(result._meta[MCP_SERVER_INFO_META_KEY]);
	}
	return sessionData;
}
/**
* Build client attributes from stored client info
* @param transport - MCP transport instance
* @returns Client attributes for span instrumentation
*/
function getClientAttributes(transport) {
	const clientInfo = getClientInfoForTransport(transport);
	const attributes = {};
	if (clientInfo?.name) attributes[_sentry_conventions_attributes.MCP_CLIENT_NAME] = clientInfo.name;
	if (clientInfo?.title) attributes[_sentry_conventions_attributes.MCP_CLIENT_TITLE] = clientInfo.title;
	if (clientInfo?.version) attributes[_sentry_conventions_attributes.MCP_CLIENT_VERSION] = clientInfo.version;
	return attributes;
}
/**
* Build client attributes from PartyInfo directly
* @param clientInfo - Client party info
* @returns Client attributes for span instrumentation
*/
function buildClientAttributesFromInfo(clientInfo) {
	const attributes = {};
	if (clientInfo?.name) attributes[_sentry_conventions_attributes.MCP_CLIENT_NAME] = clientInfo.name;
	if (clientInfo?.title) attributes[_sentry_conventions_attributes.MCP_CLIENT_TITLE] = clientInfo.title;
	if (clientInfo?.version) attributes[_sentry_conventions_attributes.MCP_CLIENT_VERSION] = clientInfo.version;
	return attributes;
}
/**
* Build server attributes from stored server info
* @param transport - MCP transport instance
* @returns Server attributes for span instrumentation
*/
function getServerAttributes(transport) {
	const serverInfo = getSessionDataForTransport(transport)?.serverInfo;
	const attributes = {};
	if (serverInfo?.name) attributes[_sentry_conventions_attributes.MCP_SERVER_NAME] = serverInfo.name;
	if (serverInfo?.title) attributes[_sentry_conventions_attributes.MCP_SERVER_TITLE] = serverInfo.title;
	if (serverInfo?.version) attributes[_sentry_conventions_attributes.MCP_SERVER_VERSION] = serverInfo.version;
	return attributes;
}
/**
* Build server attributes from PartyInfo directly
* @param serverInfo - Server party info
* @returns Server attributes for span instrumentation
*/
function buildServerAttributesFromInfo(serverInfo) {
	const attributes = {};
	if (serverInfo?.name) attributes[_sentry_conventions_attributes.MCP_SERVER_NAME] = serverInfo.name;
	if (serverInfo?.title) attributes[_sentry_conventions_attributes.MCP_SERVER_TITLE] = serverInfo.title;
	if (serverInfo?.version) attributes[_sentry_conventions_attributes.MCP_SERVER_VERSION] = serverInfo.version;
	return attributes;
}
/**
* Extracts client connection info from extra handler data
* @param extra - Extra handler data containing connection info
* @returns Client address and port information
*/
function extractClientInfo(extra) {
	return {
		address: extra?.requestInfo?.remoteAddress || extra?.clientAddress || extra?.request?.ip || extra?.request?.connection?.remoteAddress,
		port: extra?.requestInfo?.remotePort || extra?.clientPort || extra?.request?.connection?.remotePort
	};
}
/**
* Extracts transport types based on transport constructor name
* @param transport - MCP transport instance
* @returns Transport type mapping for span attributes
*/
function getTransportTypes(transport) {
	if (!transport?.constructor) return {
		mcpTransport: "unknown",
		networkTransport: "unknown"
	};
	const transportName = typeof transport.constructor?.name === "string" ? transport.constructor.name : "unknown";
	let networkTransport = "unknown";
	const lowerTransportName = transportName.toLowerCase();
	if (lowerTransportName.includes("stdio")) networkTransport = "pipe";
	else if (lowerTransportName.includes("http") || lowerTransportName.includes("sse")) networkTransport = "tcp";
	return {
		mcpTransport: transportName,
		networkTransport
	};
}
/**
* Build transport and network attributes
* @param transport - MCP transport instance
* @param extra - Optional extra handler data
* @param message - Current message carrying request-scoped protocol metadata
* @returns Transport attributes for span instrumentation
* @note sessionId may be undefined during initial setup - session should be established by client during initialize flow
*/
function buildTransportAttributes(transport, extra, message) {
	const messageData = message && extractSessionDataFromMessage(message);
	const hasRequestMetadata = messageData?.protocolVersion !== void 0 || messageData?.clientInfo !== void 0;
	const sessionId = !hasRequestMetadata && transport && "sessionId" in transport ? transport.sessionId : void 0;
	const clientInfo = extra ? extractClientInfo(extra) : {};
	const { mcpTransport, networkTransport } = getTransportTypes(transport);
	const clientAttributes = hasRequestMetadata ? buildClientAttributesFromInfo(messageData?.clientInfo) : getClientAttributes(transport);
	const serverAttributes = hasRequestMetadata ? {} : getServerAttributes(transport);
	const protocolVersion = hasRequestMetadata ? messageData?.protocolVersion : getProtocolVersionForTransport(transport);
	return {
		...sessionId && { [_sentry_conventions_attributes.MCP_SESSION_ID]: sessionId },
		...clientInfo.address && { [_sentry_conventions_attributes.CLIENT_ADDRESS]: clientInfo.address },
		...clientInfo.port && { [_sentry_conventions_attributes.CLIENT_PORT]: clientInfo.port },
		[_sentry_conventions_attributes.MCP_TRANSPORT]: mcpTransport,
		[_sentry_conventions_attributes.NETWORK_TRANSPORT]: networkTransport,
		[_sentry_conventions_attributes.NETWORK_PROTOCOL_VERSION]: "2.0",
		...protocolVersion && { [_sentry_conventions_attributes.MCP_PROTOCOL_VERSION]: protocolVersion },
		...clientAttributes,
		...serverAttributes
	};
}
// src/integrations/mcp-server/correlation.ts
/**
* Request-span correlation system for MCP server instrumentation
*
* Handles mapping requestId to span data for correlation with handler execution.
*
* Uses sessionId as the primary key for stateful transports. This handles the wrapper
* transport pattern (e.g., NodeStreamableHTTPServerTransport wrapping WebStandardStreamableHTTPServerTransport)
* where onmessage and send may receive different `this` values but share the same sessionId.
*
* Falls back to WeakMap by transport instance for stateless transports (no sessionId).
*/
/**
* Session-scoped correlation for stateful transports (with sessionId)
* @internal Using sessionId as key handles wrapper transport patterns where
* different transport objects share the same logical session
*/
const sessionToSpanMap = /* @__PURE__ */ new Map();
/**
* Transport-scoped correlation fallback for stateless transports (no sessionId)
* @internal WeakMap allows automatic cleanup when transport is garbage collected
*/
const statelessSpanMap = /* @__PURE__ */ new WeakMap();
/**
* Gets or creates the span map for a transport, using sessionId when available
* @internal
* @param transport - MCP transport instance
* @returns Span map for the transport/session
*/
function getOrCreateSpanMap(transport) {
	const sessionId = transport.sessionId;
	if (sessionId) {
		let spanMap = sessionToSpanMap.get(sessionId);
		if (!spanMap) {
			spanMap = /* @__PURE__ */ new Map();
			sessionToSpanMap.set(sessionId, spanMap);
		}
		return spanMap;
	}
	let spanMap = statelessSpanMap.get(transport);
	if (!spanMap) {
		spanMap = /* @__PURE__ */ new Map();
		statelessSpanMap.set(transport, spanMap);
	}
	return spanMap;
}
/**
* Stores span context for later correlation with handler execution
* @param transport - MCP transport instance
* @param requestId - Request identifier
* @param span - Active span to correlate
* @param method - MCP method name
* @param capturePolicy - Capture policy resolved when the request began
*/
function storeSpanForRequest(transport, requestId, span, method, capturePolicy) {
	getOrCreateSpanMap(transport).set(requestId, {
		span,
		method,
		capturePolicy,
		startTime: Date.now()
	});
}
/**
* Completes span with results and cleans up correlation
* @param transport - MCP transport instance
* @param requestId - Request identifier
* @param result - Execution result for attribute extraction
* @param error - The JSON-RPC error response, if any
*/
function completeSpanWithResults(transport, requestId, result, error) {
	const spanMap = getOrCreateSpanMap(transport);
	const spanData = spanMap.get(requestId);
	if (spanData) {
		const { span, method } = spanData;
		const responseSessionData = method === "initialize" ? extractSessionDataFromInitializeResponse(result) : extractSessionDataFromResponse(result);
		if (method === "initialize" && (responseSessionData.protocolVersion || responseSessionData.serverInfo)) updateSessionDataForTransport(transport, responseSessionData);
		const responseAttributes = { ...buildServerAttributesFromInfo(responseSessionData.serverInfo) };
		if (responseSessionData.protocolVersion) responseAttributes[_sentry_conventions_attributes.MCP_PROTOCOL_VERSION] = responseSessionData.protocolVersion;
		if (Object.keys(responseAttributes).length > 0) span.setAttributes(responseAttributes);
		if (error) {
			span.setAttributes({ [_sentry_conventions_attributes.RPC_RESPONSE_STATUS_CODE]: String(error.code) });
			if (isJsonRpcServerError(error.code)) {
				span.setAttributes({ [_sentry_conventions_attributes.ERROR_TYPE]: String(error.code) });
				span.setStatus({
					code: 2,
					message: error.message
				});
			}
		} else if (method === "tools/call") {
			const toolAttributes = extractToolResultAttributes(result, spanData.capturePolicy.recordOutputs);
			span.setAttributes(toolAttributes);
			if (toolAttributes[_sentry_conventions_attributes.MCP_TOOL_RESULT_IS_ERROR] === true) {
				span.setAttributes({ [_sentry_conventions_attributes.ERROR_TYPE]: "tool_error" });
				span.setStatus({
					code: 2,
					message: "internal_error"
				});
			}
		} else if (method === "prompts/get") {
			const promptAttributes = extractPromptResultAttributes(result, spanData.capturePolicy.recordOutputs);
			span.setAttributes(promptAttributes);
		}
		span.end();
		spanMap.delete(requestId);
	}
}
/**
* Cleans up pending spans for a specific transport (when that transport closes)
* @param transport - MCP transport instance
*/
function cleanupPendingSpansForTransport(transport) {
	const sessionId = transport.sessionId;
	if (sessionId) {
		const spanMap = sessionToSpanMap.get(sessionId);
		if (spanMap) {
			for (const [, spanData] of spanMap) {
				spanData.span.setStatus({
					code: 2,
					message: "cancelled"
				});
				spanData.span.end();
			}
			sessionToSpanMap.delete(sessionId);
		}
		return;
	}
	const spanMap = statelessSpanMap.get(transport);
	if (spanMap) {
		for (const [, spanData] of spanMap) {
			spanData.span.setStatus({
				code: 2,
				message: "cancelled"
			});
			spanData.span.end();
		}
		spanMap.clear();
	}
}
// src/integrations/mcp-server/methodConfig.ts
/**
* Method configuration and request processing for MCP server instrumentation
*/
/**
* Configuration for MCP methods to extract targets and arguments
* @internal Maps method names to their extraction configuration
*/
const METHOD_CONFIGS = {
	"tools/call": {
		targetField: "name",
		targetAttribute: _sentry_conventions_attributes.MCP_TOOL_NAME,
		targetIsLowCardinality: true,
		captureArguments: true,
		argumentsField: "arguments"
	},
	"resources/read": {
		targetField: "uri",
		targetAttribute: _sentry_conventions_attributes.MCP_RESOURCE_URI,
		captureUri: true
	},
	"resources/subscribe": {
		targetField: "uri",
		targetAttribute: _sentry_conventions_attributes.MCP_RESOURCE_URI
	},
	"resources/unsubscribe": {
		targetField: "uri",
		targetAttribute: _sentry_conventions_attributes.MCP_RESOURCE_URI
	},
	"prompts/get": {
		targetField: "name",
		targetAttribute: _sentry_conventions_attributes.MCP_PROMPT_NAME,
		targetIsLowCardinality: true,
		captureName: true,
		captureArguments: true,
		argumentsField: "arguments"
	}
};
/**
* Extracts target info from method and params based on method type
* @param method - MCP method name
* @param params - Method parameters
* @returns Target name and attributes for span instrumentation
*/
function extractTargetInfo(method, params) {
	const config = METHOD_CONFIGS[method];
	if (!config) return {
		targetIsLowCardinality: false,
		attributes: {}
	};
	const target = config.targetField && typeof params?.[config.targetField] === "string" ? params[config.targetField] : void 0;
	return {
		target,
		targetIsLowCardinality: !!config.targetIsLowCardinality,
		attributes: target && config.targetAttribute ? { [config.targetAttribute]: target } : {}
	};
}
/**
* Extracts request arguments based on method type
* @param method - MCP method name
* @param params - Method parameters
* @returns Arguments as span attributes with mcp.request.argument prefix
*/
function getRequestArguments(method, params) {
	const args = {};
	const config = METHOD_CONFIGS[method];
	if (!config) return args;
	if (config.captureArguments && config.argumentsField && params?.[config.argumentsField]) {
		const argumentsObj = params[config.argumentsField];
		if (require_cacheOrigin.isObjectLike(argumentsObj)) for (const [key, value] of Object.entries(argumentsObj)) args[`${_sentry_conventions_attributes.MCP_REQUEST_ARGUMENT_KEY_BASE}.${key.toLowerCase()}`] = JSON.stringify(value);
	}
	if (config.captureUri && params?.uri) args[_sentry_conventions_attributes.MCP_REQUEST_ARGUMENT_URI] = JSON.stringify(params.uri);
	if (config.captureName && params?.name) args[_sentry_conventions_attributes.MCP_REQUEST_ARGUMENT_NAME] = JSON.stringify(params.name);
	return args;
}
// src/integrations/mcp-server/attributeExtraction.ts
/**
* Core attribute extraction and building functions for MCP server instrumentation
*/
/**
* Formats logging data for span attributes
* @internal
*/
function formatLoggingData(data) {
	return typeof data === "string" ? data : JSON.stringify(data);
}
/**
* Extracts additional attributes for specific notification types
* @param method - Notification method name
* @param params - Notification parameters
* @param recordInputs - Whether to include actual content or just metadata
* @returns Method-specific attributes for span instrumentation
*/
function getNotificationAttributes(method, params, recordInputs) {
	const attributes = {};
	switch (method) {
		case "notifications/cancelled":
			if (params?.requestId) attributes[_sentry_conventions_attributes.MCP_CANCELLED_REQUEST_ID] = String(params.requestId);
			if (params?.reason) attributes[_sentry_conventions_attributes.MCP_CANCELLED_REASON] = String(params.reason);
			break;
		case "notifications/message":
			if (params?.level) attributes[_sentry_conventions_attributes.MCP_LOGGING_LEVEL] = String(params.level);
			if (params?.logger) attributes[_sentry_conventions_attributes.MCP_LOGGING_LOGGER] = String(params.logger);
			if (params?.data !== void 0) {
				attributes[_sentry_conventions_attributes.MCP_LOGGING_DATA_TYPE] = typeof params.data;
				if (recordInputs) attributes[_sentry_conventions_attributes.MCP_LOGGING_MESSAGE] = formatLoggingData(params.data);
			}
			break;
		case "notifications/progress":
			if (params?.progressToken) attributes[_sentry_conventions_attributes.MCP_PROGRESS_TOKEN] = String(params.progressToken);
			if (typeof params?.progress === "number") attributes[_sentry_conventions_attributes.MCP_PROGRESS_CURRENT] = params.progress;
			if (typeof params?.total === "number") {
				attributes[_sentry_conventions_attributes.MCP_PROGRESS_TOTAL] = params.total;
				if (typeof params?.progress === "number") attributes[_sentry_conventions_attributes.MCP_PROGRESS_PERCENTAGE] = params.progress / params.total * 100;
			}
			if (params?.message) attributes[_sentry_conventions_attributes.MCP_PROGRESS_MESSAGE] = String(params.message);
			break;
		case "notifications/resources/updated":
			if (params?.uri) {
				attributes[_sentry_conventions_attributes.MCP_RESOURCE_URI] = String(params.uri);
				const urlObject = require_fetch.parseStringToURLObject(String(params.uri));
				if (urlObject && !require_fetch.isURLObjectRelative(urlObject)) attributes[_sentry_conventions_attributes.MCP_RESOURCE_PROTOCOL] = urlObject.protocol.replace(":", "");
			}
			break;
		case "notifications/initialized":
			attributes[_sentry_conventions_attributes.MCP_LIFECYCLE_PHASE] = "initialization_complete";
			attributes[_sentry_conventions_attributes.MCP_PROTOCOL_READY] = 1;
	}
	return attributes;
}
/**
* Build type-specific attributes based on message type
* @param type - Span type (request or notification)
* @param message - JSON-RPC message
* @param params - Optional parameters for attribute extraction
* @param recordInputs - Whether to capture input arguments in spans
* @returns Type-specific attributes for span instrumentation
*/
function buildTypeSpecificAttributes(type, message, params, recordInputs) {
	if (type === "request") {
		const request = message;
		const targetInfo = extractTargetInfo(request.method, params || {});
		return {
			...request.id !== void 0 && { [_sentry_conventions_attributes.MCP_REQUEST_ID]: String(request.id) },
			...targetInfo.attributes,
			...recordInputs ? getRequestArguments(request.method, params || {}) : {}
		};
	}
	return getNotificationAttributes(message.method, params || {}, recordInputs);
}
// src/integrations/mcp-server/attributes.ts
/** Sentry origin value for MCP function spans */
const MCP_FUNCTION_ORIGIN_VALUE = "auto.function.mcp_server";
/** Sentry origin value for MCP notification spans */
const MCP_NOTIFICATION_ORIGIN_VALUE = "auto.function.mcp_server.notification";
/** Sentry source value for MCP route spans */
const MCP_ROUTE_SOURCE_VALUE = "route";
// src/integrations/mcp-server/piiFiltering.ts
/**
* PII filtering for MCP server spans
*
* Removes network-level sensitive data when dataCollection.userInfo is false.
* Input/output data (request arguments, tool/prompt results) is controlled
* separately via dataCollection.mcp and the recordInputs/recordOutputs options.
*/
/**
* Network PII attributes that should be removed when dataCollection.userInfo is false
* @internal
*/
const NETWORK_PII_ATTRIBUTES = /* @__PURE__ */ new Set([
	_sentry_conventions_attributes.CLIENT_ADDRESS,
	_sentry_conventions_attributes.CLIENT_PORT,
	_sentry_conventions_attributes.MCP_RESOURCE_URI
]);
/**
* Checks if an attribute key should be considered network PII.
*
* Returns true for:
* - client.address (IP address)
* - client.port (port number)
* - mcp.resource.uri (potentially sensitive URIs)
*
* @param key - Attribute key to evaluate
* @returns true if the attribute should be filtered out (is network PII), false if it should be preserved
* @internal
*/
function isNetworkPiiAttribute(key) {
	return NETWORK_PII_ATTRIBUTES.has(key);
}
/**
* Removes network PII attributes from span data when dataCollection.userInfo is false
* @param spanData - Raw span attributes
* @param userInfo - Whether to include user identity data (IP, port, resource URIs)
* @returns Filtered span attributes
*/
function filterMcpPiiFromSpanData(spanData, userInfo) {
	if (userInfo) return spanData;
	return Object.entries(spanData).reduce((acc, [key, value]) => {
		if (!isNetworkPiiAttribute(key)) acc[key] = value;
		return acc;
	}, {});
}
// src/integrations/mcp-server/spans.ts
/**
* Span creation and management functions for MCP server instrumentation
*
* Provides unified span creation following OpenTelemetry MCP semantic conventions and our opinitionated take on MCP.
* Handles both request and notification spans with attribute extraction.
*/
/**
* Creates a span name based on the method and target
* @internal
* @param method - MCP method name
* @param target - Optional target identifier
* @returns Formatted span name
*/
function createSpanName(method, target) {
	return target ? `${method} ${target}` : method;
}
/**
* Build Sentry-specific attributes based on span type
* @internal
* @param type - Span type configuration
* @returns Sentry-specific attributes
*/
function buildSentryAttributes(type) {
	let op;
	let origin;
	switch (type) {
		case "request":
			op = _sentry_conventions_op.MCP_SERVER;
			origin = MCP_FUNCTION_ORIGIN_VALUE;
			break;
		case "notification-incoming":
			op = _sentry_conventions_op.MCP_NOTIFICATION_CLIENT_TO_SERVER;
			origin = MCP_NOTIFICATION_ORIGIN_VALUE;
			break;
		case "notification-outgoing":
			op = _sentry_conventions_op.MCP_NOTIFICATION_SERVER_TO_CLIENT;
			origin = MCP_NOTIFICATION_ORIGIN_VALUE;
	}
	return {
		[_sentry_conventions_attributes.SENTRY_OP]: op,
		[_sentry_conventions_attributes.SENTRY_ORIGIN]: origin,
		[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: MCP_ROUTE_SOURCE_VALUE
	};
}
/**
* Unified builder for creating MCP spans
* @internal
* @param config - Span configuration
* @returns Created span
*/
function createMcpSpan(config) {
	const { type, message, transport, extra, callback, options, links } = config;
	const { method } = message;
	const params = message.params;
	const client = require_cacheOrigin.getClient();
	const spanStreamingEnabled = !!client && require_cacheOrigin.hasSpanStreamingEnabled(client);
	let spanName;
	if (type === "request") {
		const targetInfo = extractTargetInfo(method, params || {});
		const target = spanStreamingEnabled && !targetInfo.targetIsLowCardinality ? void 0 : targetInfo.target;
		spanName = method ? createSpanName(method, target) : require_fetch.MCP_SERVER_SPAN_NAME_FALLBACK;
	} else spanName = method || (spanStreamingEnabled ? "MCP notification" : method);
	const attributes = filterMcpPiiFromSpanData({
		...buildTransportAttributes(transport, extra, message),
		[_sentry_conventions_attributes.MCP_METHOD_NAME]: method,
		...buildTypeSpecificAttributes(type, message, params, options?.recordInputs),
		...buildSentryAttributes(type)
	}, Boolean(client?.getDataCollectionOptions().userInfo));
	return require_cacheOrigin.startSpan$1({
		name: spanName,
		forceTransaction: true,
		attributes,
		links
	}, callback);
}
/**
* Creates a span for incoming MCP notifications
* @param jsonRpcMessage - Notification message
* @param transport - MCP transport instance
* @param extra - Extra handler data
* @param options - Resolved MCP options
* @param callback - Span execution callback
* @param links - Links to add to the span
* @returns Span execution result
*/
function createMcpNotificationSpan(jsonRpcMessage, transport, extra, options, callback, links) {
	return createMcpSpan({
		type: "notification-incoming",
		message: jsonRpcMessage,
		transport,
		extra,
		callback,
		options,
		links
	});
}
/**
* Creates a span for outgoing MCP notifications
* @param jsonRpcMessage - Notification message
* @param transport - MCP transport instance
* @param options - Resolved MCP options
* @param callback - Span execution callback
* @returns Span execution result
*/
function createMcpOutgoingNotificationSpan(jsonRpcMessage, transport, options, callback) {
	return createMcpSpan({
		type: "notification-outgoing",
		message: jsonRpcMessage,
		transport,
		options,
		callback
	});
}
/**
* Builds span configuration for MCP server requests
* @param jsonRpcMessage - Request message
* @param transport - MCP transport instance
* @param extra - Optional extra handler data
* @param options - Resolved MCP options
* @returns Span configuration object
*/
function buildMcpServerSpanConfig(jsonRpcMessage, transport, extra, options) {
	const { method } = jsonRpcMessage;
	const params = jsonRpcMessage.params;
	const client = require_cacheOrigin.getClient();
	const spanStreamingEnabled = !!client && require_cacheOrigin.hasSpanStreamingEnabled(client);
	const targetInfo = extractTargetInfo(method, params || {});
	const target = spanStreamingEnabled && !targetInfo.targetIsLowCardinality ? void 0 : targetInfo.target;
	return {
		name: method ? createSpanName(method, target) : require_fetch.MCP_SERVER_SPAN_NAME_FALLBACK,
		forceTransaction: true,
		attributes: filterMcpPiiFromSpanData({
			...buildTransportAttributes(transport, extra, jsonRpcMessage),
			[_sentry_conventions_attributes.MCP_METHOD_NAME]: method,
			...buildTypeSpecificAttributes("request", jsonRpcMessage, params, options?.recordInputs),
			...buildSentryAttributes("request")
		}, Boolean(client?.getDataCollectionOptions().userInfo))
	};
}
// src/integrations/mcp-server/tracePropagation.ts
/**
* Trace context propagation through the MCP `params._meta` property bag.
* @see https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md#context-propagation
*/
function getSentryTraceFromMeta(meta) {
	const sentryTrace = meta["sentry-trace"];
	if (typeof sentryTrace === "string") return sentryTrace;
	const traceparent = meta.traceparent;
	return require_cacheOrigin.getClient()?.getOptions().propagateTraceparent && typeof traceparent === "string" ? require_cacheOrigin.sentryTraceFromTraceparent(traceparent) : void 0;
}
/**
* Runs `callback` in the trace carried by the message's `params._meta`, so the MCP server span becomes a child of the
* client span that sent the message. The span that was active when the message arrived (e.g. the HTTP server span of a
* Streamable HTTP request) is handed to `callback` as a link, because MCP and transport contexts are independent: one
* HTTP request can carry several MCP messages and one MCP request can be retried over several HTTP requests.
*
* Without a valid trace context in `_meta`, `callback` runs in the current context, unchanged.
*/
function continueMcpTrace(params, callback) {
	const meta = require_cacheOrigin.isObjectLike(params) && require_cacheOrigin.isObjectLike(params._meta) ? params._meta : void 0;
	const sentryTrace = meta ? getSentryTraceFromMeta(meta) : void 0;
	if (!meta || !sentryTrace || !require_cacheOrigin.extractTraceparentData(sentryTrace)?.traceId) return callback(void 0);
	const baggage = typeof meta.baggage === "string" ? meta.baggage : void 0;
	const client = require_cacheOrigin.getClient();
	if (client && !require_cacheOrigin.shouldContinueTrace(client, require_cacheOrigin.baggageHeaderToDynamicSamplingContext(baggage)?.org_id)) return callback(void 0);
	const ambientSpan = require_cacheOrigin.getActiveSpan();
	const links = ambientSpan ? [{ context: ambientSpan.spanContext() }] : void 0;
	return require_cacheOrigin.continueTrace({
		sentryTrace,
		baggage
	}, () => callback(links));
}
/**
* Returns a copy of an outgoing request or notification with the active trace context added to `params._meta`, so the
* receiving side can continue the trace. Messages that already carry trace context are returned unchanged.
*/
function injectMcpTraceContext(message) {
	const meta = message.params?._meta;
	if (meta !== void 0 && (!require_cacheOrigin.isObjectLike(meta) || meta["sentry-trace"] !== void 0 || meta.traceparent !== void 0)) return message;
	const { "sentry-trace": sentryTrace, baggage, traceparent } = require_cacheOrigin.getTraceData({ propagateTraceparent: require_cacheOrigin.getClient()?.getOptions().propagateTraceparent });
	if (!sentryTrace) return message;
	const existingBaggage = require_cacheOrigin.isObjectLike(meta) && typeof meta.baggage === "string" ? meta.baggage : void 0;
	return {
		...message,
		params: {
			...message.params,
			_meta: {
				...meta,
				"sentry-trace": sentryTrace,
				...traceparent && { traceparent },
				...baggage && { baggage: require_cacheOrigin.mergeBaggageHeaders(existingBaggage, baggage) }
			}
		}
	};
}
// src/integrations/mcp-server/transport.ts
/**
* Transport layer instrumentation for MCP server
*
* Handles message interception and response correlation.
* @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports
*/
function resolveMcpOptions(options) {
	if (options.recordInputs !== void 0 && options.recordOutputs !== void 0) return {
		recordInputs: options.recordInputs,
		recordOutputs: options.recordOutputs
	};
	const client = require_cacheOrigin.getClient();
	const userMcp = client?.getOptions().dataCollection?.mcp;
	const genAI = client?.getDataCollectionOptions().genAI;
	return {
		recordInputs: options.recordInputs ?? userMcp?.inputs ?? genAI?.inputs ?? true,
		recordOutputs: options.recordOutputs ?? userMcp?.outputs ?? genAI?.outputs ?? true
	};
}
/** Resolves only the OAuth client name; optional telemetry must not interrupt MCP dispatch. */
function resolveOAuthClientName(options, extra) {
	if (!options.getOAuthClientName) return;
	const name = require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `getOAuthClientName` callback threw an error:" : "", () => {
		const authInfo = extra?.authInfo;
		return options.getOAuthClientName?.(authInfo ? {
			clientId: authInfo.clientId,
			extra: authInfo.extra
		} : void 0);
	}, () => void 0);
	return typeof name === "string" && name ? name : void 0;
}
/**
* Wraps transport.onmessage to create spans for incoming messages.
* Stores client info and protocol version only for legacy initialize requests.
* Modern request metadata is read directly when building each message's span.
* @param transport - MCP transport instance to wrap
* @param options - MCP instrumentation options
*/
function wrapTransportOnMessage(transport, options) {
	if (transport.onmessage) require_cacheOrigin.fill(transport, "onmessage", (originalOnMessage) => {
		return function(message, extra) {
			const request = isJsonRpcRequest(message) ? message : void 0;
			const notification = isJsonRpcNotification(message) ? message : void 0;
			let messageSessionData;
			if (request?.method === "initialize") try {
				messageSessionData = extractSessionDataFromInitializeRequest(request);
				if (messageSessionData.protocolVersion || messageSessionData.clientInfo) updateSessionDataForTransport(transport, messageSessionData);
			} catch {}
			if (request) {
				const resolvedOptions = resolveMcpOptions(options);
				const isolationScope = require_cacheOrigin.getIsolationScope().clone();
				return require_cacheOrigin.withIsolationScope(isolationScope, () => continueMcpTrace(request.params, (links) => {
					const spanConfig = buildMcpServerSpanConfig(request, transport, extra, resolvedOptions);
					const oauthClientName = resolveOAuthClientName(options, extra);
					if (oauthClientName) spanConfig.attributes[_sentry_conventions_attributes.MCP_AUTH_CLIENT_NAME] = oauthClientName;
					if (request.method === "initialize" && messageSessionData) {
						Object.assign(spanConfig.attributes, buildClientAttributesFromInfo(messageSessionData.clientInfo));
						if (messageSessionData.protocolVersion) spanConfig.attributes[_sentry_conventions_attributes.MCP_PROTOCOL_VERSION] = messageSessionData.protocolVersion;
					}
					const span = require_cacheOrigin.startInactiveSpan$1({
						...spanConfig,
						links
					});
					storeSpanForRequest(transport, request.id, span, request.method, resolvedOptions);
					return require_cacheOrigin.withActiveSpan(span, () => {
						return originalOnMessage.call(this, request, extra);
					});
				}));
			}
			if (notification) {
				const resolvedOptions = resolveMcpOptions(options);
				return continueMcpTrace(notification.params, (links) => createMcpNotificationSpan(notification, transport, extra, resolvedOptions, () => {
					return originalOnMessage.call(this, notification, extra);
				}, links));
			}
			return originalOnMessage.call(this, message, extra);
		};
	});
}
/**
* Wraps transport.send to handle outgoing messages and response correlation.
* Caches legacy initialize metadata and applies modern result metadata only to
* the corresponding request span.
* @param transport - MCP transport instance to wrap
* @param options - MCP capture overrides
*/
function wrapTransportSend(transport, options) {
	if (transport.send) require_cacheOrigin.fill(transport, "send", (originalSend) => {
		return async function(...args) {
			const [message, ...restArgs] = args;
			if (isJsonRpcNotification(message)) return createMcpOutgoingNotificationSpan(message, transport, resolveMcpOptions(options), () => {
				return originalSend.call(this, injectMcpTraceContext(message), ...restArgs);
			});
			if (isJsonRpcRequest(message)) return originalSend.call(this, injectMcpTraceContext(message), ...restArgs);
			if (isJsonRpcResponse(message)) {
				if (message.id !== null && message.id !== void 0) {
					if (message.error) captureJsonRpcErrorResponse(message.error);
					completeSpanWithResults(transport, message.id, message.result, message.error);
				}
			}
			return originalSend.call(this, ...args);
		};
	});
}
/**
* Wraps transport.onclose to clean up pending spans for this transport only
* @param transport - MCP transport instance to wrap
*/
function wrapTransportOnClose(transport) {
	if (transport.onclose) require_cacheOrigin.fill(transport, "onclose", (originalOnClose) => {
		return function(...args) {
			cleanupPendingSpansForTransport(transport);
			cleanupSessionDataForTransport(transport);
			return originalOnClose.call(this, ...args);
		};
	});
}
/**
* Wraps transport error handlers to capture connection errors
* @param transport - MCP transport instance to wrap
*/
function wrapTransportError(transport) {
	if (transport.onerror) require_cacheOrigin.fill(transport, "onerror", (originalOnError) => {
		return function(error) {
			captureTransportError(error);
			return originalOnError.call(this, error);
		};
	});
}
/**
* Captures JSON-RPC error responses for server-side errors.
* @see https://www.jsonrpc.org/specification#error_object
* @internal
* @param errorResponse - JSON-RPC error response
*/
function captureJsonRpcErrorResponse(errorResponse) {
	try {
		if (require_cacheOrigin.isObjectLike(errorResponse) && "code" in errorResponse && "message" in errorResponse) {
			const jsonRpcError = errorResponse;
			if (typeof jsonRpcError.code === "number" && isJsonRpcServerError(jsonRpcError.code)) {
				const error = new Error(jsonRpcError.message);
				error.name = `JsonRpcError_${jsonRpcError.code}`;
				captureError(error, "protocol");
			}
		}
	} catch {}
}
/**
* Captures transport connection errors
* @internal
* @param error - Transport error
*/
function captureTransportError(error) {
	try {
		captureError(error, "transport");
	} catch {}
}
// src/integrations/mcp-server/index.ts
/**
* Maps each wrapped MCP server instance to the mutable instrumentation options that the transport
* instrumentation reads (per message). Prevents double-wrapping while still letting a later
* `wrapMcpServerWithSentry` fill in options left unset by an earlier wrap — e.g. an auto-wrap at
* construction installs no explicit options, so a manual override still applies.
* @internal
*/
const wrappedMcpServerOptions = /* @__PURE__ */ new WeakMap();
/**
* Fill in options not explicitly set by an earlier wrap. Only unset fields are written, so
* the first explicit value wins, but an auto-wrap that set no options still
* yields to a later manual override. Mutating the stored object updates the live transport
* instrumentation, which reads it per message.
*/
function applyMissingMcpOptions(target, source) {
	if (!source) return;
	if (target.recordInputs === void 0 && source.recordInputs !== void 0) target.recordInputs = source.recordInputs;
	if (target.recordOutputs === void 0 && source.recordOutputs !== void 0) target.recordOutputs = source.recordOutputs;
	if (target.getOAuthClientName === void 0 && source.getOAuthClientName !== void 0) target.getOAuthClientName = source.getOAuthClientName;
}
function instrumentTransport(transport, options) {
	wrapTransportOnMessage(transport, options);
	wrapTransportSend(transport, options);
	wrapTransportOnClose(transport);
	wrapTransportError(transport);
}
function interceptTransportStart(transport, beforeStart) {
	let transportStart;
	let originalDescriptor;
	try {
		transportStart = transport.start;
		originalDescriptor = Object.getOwnPropertyDescriptor(transport, "start");
	} catch {
		return () => void 0;
	}
	if (typeof transportStart !== "function") return () => void 0;
	const originalStart = transportStart;
	let isInstalled = false;
	const restoreStart = () => {
		if (!isInstalled) return;
		try {
			if (Object.getOwnPropertyDescriptor(transport, "start")?.value !== interceptedStart) {
				isInstalled = false;
				return;
			}
			if (originalDescriptor) {
				Object.defineProperty(transport, "start", originalDescriptor);
				isInstalled = false;
			} else if (Reflect.deleteProperty(transport, "start")) isInstalled = false;
		} catch {}
	};
	function interceptedStart() {
		restoreStart();
		beforeStart();
		return originalStart.call(this);
	}
	const replacementDescriptor = originalDescriptor && "value" in originalDescriptor ? {
		...originalDescriptor,
		value: interceptedStart
	} : {
		configurable: originalDescriptor?.configurable ?? true,
		enumerable: originalDescriptor?.enumerable ?? false,
		writable: true,
		value: interceptedStart
	};
	try {
		Object.defineProperty(transport, "start", replacementDescriptor);
		isInstalled = true;
	} catch {}
	return restoreStart;
}
/**
* Wraps an MCP Server instance with Sentry instrumentation.
*
* Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package (legacy `tool`/`resource`/`prompt` API)
* and `@modelcontextprotocol/server` version 2.x (`registerTool`/`registerResource`/`registerPrompt` API).
* Automatically instruments transport methods and handler functions for comprehensive monitoring.
*
* Both call orderings are supported: wrapping before or after registering tools, resources,
* and prompts. Sentry patches the registration methods for future handlers and retroactively
* wraps any already-registered ones. Wrapping at construction time is recommended by
* convention (consistent with other SDK integrations), but is not required.
*
* Calling this more than once on the same instance never patches it twice. Options behave like a
* snapshot from the first *explicit* wrap: the first value set for each option wins,
* but a field left unset can still be filled by a later call. So when the SDK auto-wraps
* the server at construction (via the `mcpServer` integration) with no explicit options, a later
* manual `wrapMcpServerWithSentry(server, { recordInputs, recordOutputs })` still applies.
*
* @example
* ```typescript
* import * as Sentry from '@sentry/core';
* import { McpServer } from '@modelcontextprotocol/server';
* import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
*
* // Wrap first, then register tools — this is the correct order
* const server = Sentry.wrapMcpServerWithSentry(
*   new McpServer({ name: "my-server", version: "1.0.0" })
* );
*
* server.registerTool('my-tool', schema, handler);
*
* // Explicitly control input/output capture
* const server = Sentry.wrapMcpServerWithSentry(
*   new McpServer({ name: "my-server", version: "1.0.0" }),
*   { recordInputs: true, recordOutputs: false }
* );
*
* const transport = new NodeStreamableHTTPServerTransport();
* await server.connect(transport);
* ```
*
* @example
* ```typescript
* // Read application-defined metadata supplied by the authentication middleware.
* const server = Sentry.wrapMcpServerWithSentry(mcpServer, {
*   getOAuthClientName: authInfo => {
*     const name = authInfo?.extra?.clientName;
*     return typeof name === 'string' ? name : undefined;
*   },
* });
* ```
*
* @param mcpServerInstance - MCP server instance to instrument
* @param options - Optional configuration for recording inputs/outputs and OAuth client attribution
* @returns Instrumented server instance (same reference)
*/
function wrapMcpServerWithSentry(mcpServerInstance, options) {
	const existingOptions = wrappedMcpServerOptions.get(mcpServerInstance);
	if (existingOptions) {
		applyMissingMcpOptions(existingOptions, options);
		return mcpServerInstance;
	}
	if (!validateMcpServerInstance(mcpServerInstance)) return mcpServerInstance;
	const serverInstance = mcpServerInstance;
	const wrapperOptions = { ...options };
	wrappedMcpServerOptions.set(mcpServerInstance, wrapperOptions);
	require_cacheOrigin.fill(serverInstance, "connect", (originalConnect) => {
		return async function(transport, ...restArgs) {
			let isTransportInstrumented = false;
			const instrumentTransportOnce = () => {
				if (isTransportInstrumented) return;
				isTransportInstrumented = true;
				instrumentTransport(transport, wrapperOptions);
			};
			const restoreStart = interceptTransportStart(transport, instrumentTransportOnce);
			try {
				const result = await originalConnect.call(this, transport, ...restArgs);
				instrumentTransportOnce();
				return result;
			} finally {
				restoreStart();
			}
		};
	});
	wrapAllMCPHandlers(serverInstance);
	wrapExistingHandlers(serverInstance);
	return mcpServerInstance;
}
// src/utils/node-stack-trace.ts
/**
* Does this filename look like it's part of the app code?
*/
function filenameIsInApp(filename, isNative = false) {
	return !(isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//)) && filename !== void 0 && !filename.includes("node_modules/");
}
/** Node Stack line parser */
function node(getModule) {
	const FILENAME_MATCH = /^\s*[-]{4,}$/;
	const FULL_MATCH = /at (?:async )?(?:(?=.*\)\s*$)(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
	const DATA_URI_MATCH = /at (?:async )?(.+?) \(data:(.*?),/;
	return (line) => {
		const dataUriMatch = line.match(DATA_URI_MATCH);
		if (dataUriMatch) return {
			filename: `<data:${dataUriMatch[2]}>`,
			function: dataUriMatch[1]
		};
		const lineMatch = line.match(FULL_MATCH);
		if (lineMatch) {
			let object;
			let method;
			let functionName;
			let typeName;
			let methodName;
			if (lineMatch[1]) {
				functionName = lineMatch[1];
				let methodStart = functionName.lastIndexOf(".");
				if (functionName[methodStart - 1] === ".") methodStart--;
				if (methodStart > 0) {
					object = functionName.slice(0, methodStart);
					method = functionName.slice(methodStart + 1);
					const objectEnd = object.indexOf(".Module");
					if (objectEnd > 0) {
						functionName = functionName.slice(objectEnd + 1);
						object = object.slice(0, objectEnd);
					}
				}
				typeName = void 0;
			}
			if (method) {
				typeName = object;
				methodName = method;
			}
			if (method === "<anonymous>") {
				methodName = void 0;
				functionName = void 0;
			}
			if (functionName === void 0) {
				methodName = methodName || "?";
				functionName = typeName ? `${typeName}.${methodName}` : methodName;
			}
			let filename = require_cacheOrigin.normalizeStackTracePath(lineMatch[2]);
			const isNative = lineMatch[5] === "native";
			if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];
			const maybeDecodedFilename = filename ? _safeDecodeURI(filename) : void 0;
			return {
				filename: maybeDecodedFilename ?? filename,
				module: maybeDecodedFilename && getModule?.(maybeDecodedFilename),
				function: functionName,
				lineno: _parseIntOrUndefined(lineMatch[3]),
				colno: _parseIntOrUndefined(lineMatch[4]),
				in_app: filenameIsInApp(filename || "", isNative)
			};
		}
		if (line.match(FILENAME_MATCH)) return { filename: line };
	};
}
/**
* Node.js stack line parser
*
* This is in @sentry/core so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.
* This allows it to be used without referencing or importing any node specific code which causes bundlers to complain
*/
function nodeStackLineParser(getModule) {
	return [90, node(getModule)];
}
function _parseIntOrUndefined(input) {
	return parseInt(input || "", 10) || void 0;
}
function _safeDecodeURI(filename) {
	try {
		return decodeURI(filename);
	} catch {
		return;
	}
}
// src/utils/vercelWaitUntil.ts
/**
* Function that delays closing of a Vercel lambda until the provided promise is resolved.
*
* Vendored from https://www.npmjs.com/package/@vercel/functions
*/
function vercelWaitUntil(task) {
	if (typeof EdgeRuntime !== "string") return;
	const ctx = require_cacheOrigin.GLOBAL_OBJ[Symbol.for("@vercel/request-context")]?.get?.();
	if (ctx?.waitUntil) ctx.waitUntil(task);
}
// src/utils/commitEnv.ts
/**
* Environment variables that CI and hosting providers set to the commit being built, in the order
* release detection checks them. The list is in approximate alpha order, separated into 3 categories:
* 1. Git providers
* 2. CI providers with specific environment variables (has the provider name in the variable name)
* 3. CI providers with generic environment variables (checked for last to prevent possible false positives)
*/
const COMMIT_ENV_VARS = [
	"GITHUB_SHA",
	"CI_MERGE_REQUEST_SOURCE_BRANCH_SHA",
	"CI_BUILD_REF",
	"CI_COMMIT_SHA",
	"BITBUCKET_COMMIT",
	"APPVEYOR_PULL_REQUEST_HEAD_COMMIT",
	"APPVEYOR_REPO_COMMIT",
	"CODEBUILD_RESOLVED_SOURCE_VERSION",
	"AWS_COMMIT_ID",
	"BUILD_SOURCEVERSION",
	"GIT_CLONE_COMMIT_HASH",
	"BUDDY_EXECUTION_REVISION",
	"BUILDKITE_COMMIT",
	"CIRCLE_SHA1",
	"CIRRUS_CHANGE_IN_REPO",
	"CF_REVISION",
	"CM_COMMIT",
	"CF_PAGES_COMMIT_SHA",
	"DRONE_COMMIT_SHA",
	"FC_GIT_COMMIT_SHA",
	"HEROKU_TEST_RUN_COMMIT_VERSION",
	"HEROKU_BUILD_COMMIT",
	"HEROKU_SLUG_COMMIT",
	"RAILWAY_GIT_COMMIT_SHA",
	"RENDER_GIT_COMMIT",
	"SEMAPHORE_GIT_SHA",
	"TRAVIS_PULL_REQUEST_SHA",
	"VERCEL_GIT_COMMIT_SHA",
	"VERCEL_GITHUB_COMMIT_SHA",
	"VERCEL_GITLAB_COMMIT_SHA",
	"VERCEL_BITBUCKET_COMMIT_SHA",
	"ZEIT_GITHUB_COMMIT_SHA",
	"ZEIT_GITLAB_COMMIT_SHA",
	"ZEIT_BITBUCKET_COMMIT_SHA",
	"CI_COMMIT_ID",
	"SOURCE_COMMIT",
	"SOURCE_VERSION",
	"GIT_COMMIT",
	"COMMIT_REF",
	"BUILD_VCS_NUMBER"
];
function warnAboutPlaceholderCommitEnvVar(name) {
	require_cacheOrigin.consoleSandbox(() => {
		console.warn(`[Sentry] Ignoring the ${name} environment variable as a release name, because its value is its own name. Set the release explicitly, or fix the variable in your build environment.`);
	});
}
/**
* Reads an environment variable that should hold a commit SHA. A value that is the variable's own
* name, such as `VERCEL_GIT_COMMIT_SHA=VERCEL_GIT_COMMIT_SHA`, is ignored: it never changes, so as
* a release name it would put every build into one release. `onPlaceholder` is called for such a
* value and warns on the console by default.
*/
function readCommitEnvVar(name, onPlaceholder = warnAboutPlaceholderCommitEnvVar) {
	if (typeof process === "undefined") return;
	const value = process.env[name];
	if (value?.trim() === name) {
		onPlaceholder(name);
		return;
	}
	return value || void 0;
}
/**
* Returns the commit that CI or the hosting provider is building, read from the first of the known
* commit environment variables that is set. Variables are read in order and only until one is
* found, so a placeholder value is only reported when it would otherwise have become the release.
*/
function getReleaseFromCommitEnv(onPlaceholder = warnAboutPlaceholderCommitEnvVar) {
	for (const name of COMMIT_ENV_VARS) {
		const value = readCommitEnvVar(name, onPlaceholder);
		if (value) return value;
	}
}
// src/utils/flushIfServerless.ts
/**
* Marks a request's isolation scope whose events a runtime wrapper flushes once the response is sent. A shared symbol,
* so `flushIfServerless()` sees it without depending on the wrapper's package.
*/
const FLUSHED_BY_RUNTIME = Symbol.for("sentry.flushedByRuntime");
/**
* Tells `flushIfServerless()` to skip the flush for the request that owns `scope`, because a runtime wrapper (such as
* the Cloudflare `withSentry` wrap) flushes its events once the response is sent. Forked scopes keep the mark.
*
* The default isolation scope is shared by every request, so it is never marked.
*
* @internal
*/
function setScopeFlushedByRuntime(scope) {
	if (scope === require_cacheOrigin.getDefaultIsolationScope()) return;
	scope.refs[FLUSHED_BY_RUNTIME] = true;
}
async function flushWithTimeout(timeout) {
	try {
		require_cacheOrigin.debug.log("Flushing events...");
		await require_cacheOrigin.flush(timeout);
		require_cacheOrigin.debug.log("Done flushing events");
	} catch (e) {
		require_cacheOrigin.debug.log("Error while flushing events:\n", e);
	}
}
/**
*  Flushes the event queue with a timeout in serverless environments to ensure that events are sent to Sentry before the
*  serverless function execution ends.
*
* The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.
*
* This function is aware of the following serverless platforms:
* - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).
*               If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).
* - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.
* - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables
*   and uses a regular `await flush()`.
*
* It does nothing for a request whose scope is marked with `setScopeFlushedByRuntime()`.
*
*  @internal This function is supposed for internal Sentry SDK usage only.
*  @hidden
*/
async function flushIfServerless(params = {}) {
	const { timeout = 2e3 } = params;
	if (require_cacheOrigin.getIsolationScope().refs[FLUSHED_BY_RUNTIME]) return;
	if ("cloudflareWaitUntil" in params && typeof params?.cloudflareWaitUntil === "function") {
		params.cloudflareWaitUntil(flushWithTimeout(timeout));
		return;
	}
	if ("cloudflareCtx" in params && typeof params.cloudflareCtx?.waitUntil === "function") {
		params.cloudflareCtx.waitUntil(flushWithTimeout(timeout));
		return;
	}
	if (require_cacheOrigin.GLOBAL_OBJ[Symbol.for("@vercel/request-context")]) {
		vercelWaitUntil(flushWithTimeout(timeout));
		return;
	}
	if (typeof process === "undefined") return;
	if (!!process.env.FUNCTIONS_WORKER_RUNTIME || !!process.env.LAMBDA_TASK_ROOT || !!process.env.K_SERVICE || !!process.env.CF_PAGES || !!process.env.VERCEL || !!process.env.NETLIFY) await flushWithTimeout(timeout);
}
// src/utils/anr.ts
/**
* A node.js watchdog timer
* @param pollInterval The interval that we expect to get polled at
* @param anrThreshold The threshold for when we consider ANR
* @param callback The callback to call for ANR
* @returns An object with `poll` and `enabled` functions {@link WatchdogReturn}
*/
function watchdogTimer(createTimer, pollInterval, anrThreshold, callback) {
	const timer = createTimer();
	let triggered = false;
	let enabled = true;
	setInterval(() => {
		const diffMs = timer.getTimeMs();
		if (triggered === false && diffMs > pollInterval + anrThreshold) {
			triggered = true;
			if (enabled) callback();
		}
		if (diffMs < pollInterval + anrThreshold) triggered = false;
	}, 20);
	return {
		poll: () => {
			timer.reset();
		},
		enabled: (state) => {
			enabled = state;
		}
	};
}
/**
* Converts Debugger.CallFrame to Sentry StackFrame
*/
function callFrameToStackFrame(frame, url, getModuleFromFilename) {
	const filename = url ? url.replace(/^file:\/\//, "") : void 0;
	const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : void 0;
	const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : void 0;
	return {
		filename,
		module: getModuleFromFilename(filename),
		function: frame.functionName || "?",
		colno,
		lineno,
		in_app: filename ? filenameIsInApp(filename) : void 0
	};
}
// src/utils/get-default-export.ts
/**
* Often we patch a module's default export, but we want to be able to do
* something like this:
*
* ```ts
* patchTheThing(await import('the-thing'));
* ```
*
* Or like this:
*
* ```ts
* import theThing from 'the-thing';
* patchTheThing(theThing);
* ```
*
* Note: this does not support modules with a falsey default export. However,
* presumably in those cases, there's no default export to patch anyway.
*/
function getDefaultExport(moduleExport) {
	return !!moduleExport && typeof moduleExport === "object" && "default" in moduleExport && moduleExport.default || moduleExport;
}
const HTTP_ON_CLIENT_REQUEST = "http.client.request.created";
const HTTP_ON_SERVER_REQUEST = "http.server.request.start";
const HTTP2_ON_SERVER_STREAM = "http2.server.stream.start";
// src/integrations/http/get-request-url.ts
/** Convert an outgoing request to request options. */
function getRequestOptions(request) {
	const hostWithPort = request.host || "";
	const portInHost = /^(.*):(\d+)$/.exec(hostWithPort);
	const hostname = portInHost ? portInHost[1] : hostWithPort;
	const port = request.port ?? (portInHost ? Number(portInHost[2]) : void 0);
	return {
		method: request.method,
		port,
		protocol: request.protocol,
		host: request.host,
		hostname,
		path: request.path,
		headers: request.getHeaders()
	};
}
function getRequestUrl(requestOptions) {
	try {
		return String(getRequestUrlObject(requestOptions));
	} catch {
		return "";
	}
}
function getRequestUrlObject(requestOptions) {
	const protocol = requestOptions.protocol || "http:";
	const hostname = requestOptions.headers?.host && String(requestOptions.headers?.host) || requestOptions.hostname || requestOptions.host || "";
	const port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\d+)$/.test(hostname) ? "" : `:${requestOptions.port}`;
	const path = requestOptions.path ? requestOptions.path : "/";
	const base = `${protocol}//${hostname}${port}`;
	return new URL(path.startsWith("//") ? `${base}${path}` : path, base);
}
/**
* Build the full URL string from a Node.js ClientRequest.
*/
function getRequestUrlFromClientRequest(request) {
	return String(getRequestUrl(getRequestOptions(request)));
}
// src/integrations/http/add-outgoing-request-breadcrumb.ts
/**
* Create a breadcrumb for a finished outgoing HTTP request.
*/
function addOutgoingRequestBreadcrumb(request, response) {
	const url = getRequestUrlFromClientRequest(request);
	const parsedUrl = require_fetch.parseUrl(url);
	const statusCode = response?.statusCode;
	const level = require_fetch.getBreadcrumbLogLevelFromHttpStatusCode(statusCode);
	require_fetch.addBreadcrumb({
		category: "http",
		data: {
			status_code: statusCode,
			url: require_fetch.getSanitizedUrlString(parsedUrl),
			[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: request.method || "GET",
			[_sentry_conventions_attributes.URL_QUERY]: require_fetch.filterCollectedUrlQuery(require_fetch.getUrlQuery(parsedUrl.search)),
			[_sentry_conventions_attributes.URL_FRAGMENT]: require_fetch.getUrlFragment(parsedUrl.hash)
		},
		type: "http",
		level
	}, {
		event: "response",
		request,
		response
	});
}
// src/integrations/http/get-outgoing-span-data.ts
/**
* Build the initial span name and attributes for an outgoing HTTP request.
* This is called before the span is created, to get the initial details.
*/
function getOutgoingRequestSpanData(request) {
	const url = getRequestUrlFromClientRequest(request);
	const urlObject = require_fetch.parseStringToURLObject(url);
	const [name, attributes] = require_fetch.getHttpSpanDetailsFromUrlObject(urlObject, "client", "auto.http.client", request);
	const userAgent = request.getHeader("user-agent");
	const client = require_cacheOrigin.getClient();
	const method = request.method?.toUpperCase();
	const domain = urlObject && !require_fetch.isURLObjectRelative(urlObject) ? urlObject.hostname : void 0;
	const streamedName = method ? domain ? `${method} ${domain}` : method : require_fetch.HTTP_SPAN_NAME_FALLBACK;
	return {
		name: !!client && require_cacheOrigin.hasSpanStreamingEnabled(client) ? streamedName : name,
		attributes: {
			[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_CLIENT,
			[_sentry_conventions_attributes.SENTRY_KIND]: "client",
			[_sentry_conventions_attributes.URL_FULL]: require_fetch.filterCollectedUrl(url),
			[_sentry_conventions_attributes.SERVER_ADDRESS]: request.host,
			[_sentry_conventions_attributes.SERVER_PORT]: typeof request.port === "number" && !isNaN(request.port) ? request.port : void 0,
			[_sentry_conventions_attributes.USER_AGENT_ORIGINAL]: userAgent || void 0,
			...attributes
		},
		onlyIfParent: true
	};
}
/**
* Add span attributes once the response is received.
*/
function setIncomingResponseSpanData(response, span) {
	const { statusCode, statusMessage, httpVersion, socket } = response;
	const transport = httpVersion?.toUpperCase() !== "QUIC" ? "tcp" : "udp";
	span.setAttributes({
		[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE]: statusCode,
		[_sentry_conventions_attributes.NETWORK_PROTOCOL_NAME]: "http",
		[_sentry_conventions_attributes.NETWORK_PROTOCOL_VERSION]: httpVersion,
		[_sentry_conventions_attributes.NETWORK_TRANSPORT]: transport,
		[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_TEXT]: statusMessage?.toUpperCase(),
		[_sentry_conventions_attributes.HTTP_RESPONSE_BODY_SIZE]: require_fetch.getContentLengthFromHeaders(response.headers),
		...getSocketAttrs(socket)
	});
}
function getSocketAttrs(socket) {
	if (!socket) return {};
	const { localAddress, localPort, remoteAddress, remotePort } = socket;
	return {
		[_sentry_conventions_attributes.NETWORK_LOCAL_ADDRESS]: localAddress,
		[_sentry_conventions_attributes.NETWORK_LOCAL_PORT]: localPort,
		[_sentry_conventions_attributes.NETWORK_PEER_ADDRESS]: remoteAddress,
		[_sentry_conventions_attributes.NETWORK_PEER_PORT]: remotePort
	};
}
// src/integrations/http/inject-trace-propagation-headers.ts
/**
* Inject Sentry trace-propagation headers into an outgoing request if the
* target URL matches the configured `tracePropagationTargets`.
*
* Note: this must be called *before* calling `request.end()` (or firing the
* `http.client.request.start` diagnostics channel), because at that point,
* the headers have already been sent, and cannot be modified.
*/
function injectTracePropagationHeaders(request, propagationDecisionMap) {
	const url = getRequestUrlFromClientRequest(request);
	const { tracePropagationTargets, propagateTraceparent } = require_cacheOrigin.getClient()?.getOptions() ?? {};
	if (!require_fetch.shouldPropagateTraceForUrl(url, tracePropagationTargets, propagationDecisionMap)) return;
	if (!!request.getHeader("sentry-trace")) return;
	const traceData = require_cacheOrigin.getTraceData({ propagateTraceparent });
	if (!traceData) return;
	const { "sentry-trace": sentryTrace, baggage, traceparent } = traceData;
	if (sentryTrace) try {
		request.setHeader("sentry-trace", sentryTrace);
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("@sentry/instrumentation-http", "Added sentry-trace header");
	} catch (e) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("@sentry/instrumentation-http", "Failed to set sentry-trace header:", require_cacheOrigin.isError(e) ? e.message : "Unknown error");
	}
	if (traceparent && !request.getHeader("traceparent")) try {
		request.setHeader("traceparent", traceparent);
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("@sentry/instrumentation-http", "Added traceparent header");
	} catch (e) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("@sentry/instrumentation-http", "Failed to set traceparent header:", require_cacheOrigin.isError(e) ? e.message : "Unknown error");
	}
	if (baggage) {
		const merged = require_cacheOrigin.mergeBaggageHeaders(request.getHeader("baggage"), baggage);
		if (merged) try {
			request.setHeader("baggage", merged);
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("@sentry/instrumentation-http", "Added baggage header");
		} catch (e) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error("@sentry/instrumentation-http", "Failed to set baggage header:", require_cacheOrigin.isError(e) ? e.message : "Unknown error");
		}
	}
}
// src/integrations/http/double-wrap-warning.ts
const isOtelWrapped = (fn) => typeof fn.__unwrap === "function";
const warning = "Double-wrapped http.client detected. Either disable spans in Sentry.httpIntegration, or disable the OpenTelemetry HTTP instrumentation. See: https://docs.sentry.io/platforms/javascript/guides/express/opentelemetry/custom-setup/#custom-http-instrumentation";
let didDoubleWrapWarning = false;
const doubleWrapWarning = require_cacheOrigin.DEBUG_BUILD ? (http) => {
	if (!didDoubleWrapWarning) {
		if (isOtelWrapped(http.request) || isOtelWrapped(http.get)) {
			didDoubleWrapWarning = true;
			require_cacheOrigin.debug.warn(warning);
		}
	}
} : () => {};
// src/integrations/http/client-subscriptions.ts
function getHttpClientSubscriptions(options) {
	const propagationDecisionMap = new require_fetch.LRUMap(100);
	const getConfig = () => require_cacheOrigin.getClient()?.getOptions();
	const onHttpClientRequestCreated = (data) => {
		if (require_cacheOrigin.isTracingSuppressed()) return;
		const clientOptions = getConfig();
		const { errorMonitor = "error", spans: createSpans = clientOptions ? require_cacheOrigin.hasSpansEnabled(clientOptions) : true, tracePropagation = false, breadcrumbs = true, http, https, suppressOtelWarning = false } = options;
		const { request } = data;
		const url = getRequestUrlFromClientRequest(request);
		if (require_fetch.isSentryRequestUrl(url, require_cacheOrigin.getClient()) || options.ignoreOutgoingRequests?.(url, request)) return;
		let addedBreadcrumbs = false;
		function addBreadcrumbs(request, response) {
			if (!addedBreadcrumbs) {
				addedBreadcrumbs = true;
				addOutgoingRequestBreadcrumb(request, response);
			}
		}
		function breadcrumbsOnly(request) {
			request.on(errorMonitor, () => addBreadcrumbs(request, void 0));
			request.prependListener("response", (response) => {
				if (request.listenerCount("response") <= 1) response.resume();
				response.on("end", () => addBreadcrumbs(request, response));
				response.on(errorMonitor, () => addBreadcrumbs(request, response));
			});
		}
		if (!createSpans) {
			if (breadcrumbs) breadcrumbsOnly(request);
			if (tracePropagation) injectTracePropagationHeaders(request, propagationDecisionMap);
			return;
		}
		if (!suppressOtelWarning) {
			if (http) doubleWrapWarning(http);
			if (https) doubleWrapWarning(https);
		}
		const span = require_cacheOrigin.startInactiveSpan$1(getOutgoingRequestSpanData(request));
		options.outgoingRequestHook?.(span, request);
		if (tracePropagation) {
			if (span.isRecording()) require_cacheOrigin.withActiveSpan(span, () => {
				injectTracePropagationHeaders(request, propagationDecisionMap);
			});
			else injectTracePropagationHeaders(request, propagationDecisionMap);
		}
		let spanEnded = false;
		function endSpan(status) {
			if (!spanEnded) {
				spanEnded = true;
				span.setStatus(status);
				span.end();
			}
		}
		const requestOnClose = () => endSpan({ code: 0 });
		request.on("close", requestOnClose);
		let responseStatusCode;
		request.on(errorMonitor, (error) => {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("@sentry/instrumentation-http", "outgoingRequest on request error()", error);
			if (breadcrumbs) addBreadcrumbs(request, void 0);
			if (require_cacheOrigin.isError(error) && error.name === "AbortError") endSpan(typeof responseStatusCode === "number" ? require_cacheOrigin.getSpanStatusFromHttpCode(responseStatusCode) : { code: 0 });
			else endSpan({ code: 2 });
		});
		request.prependListener("response", (response) => {
			request.removeListener("close", requestOnClose);
			responseStatusCode = response.statusCode;
			if (request.listenerCount("response") <= 1) response.resume();
			setIncomingResponseSpanData(response, span);
			require_cacheOrigin.bindScopeToEmitter(response);
			options.outgoingResponseHook?.(span, response);
			let finished = false;
			function finishWithResponse(error) {
				if (!finished) {
					finished = true;
					if (error) require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("@sentry/instrumentation-http", "outgoingRequest on response error()", error);
					if (breadcrumbs) addBreadcrumbs(request, response);
					const status = error || typeof response.statusCode !== "number" ? { code: 2 } : require_cacheOrigin.getSpanStatusFromHttpCode(response.statusCode);
					options.applyCustomAttributesOnSpan?.(span, request, response);
					endSpan(status);
				}
			}
			response.on("end", () => finishWithResponse());
			response.on(errorMonitor, finishWithResponse);
			response.on("close", () => finishWithResponse(response.errored));
		});
	};
	return { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated };
}
// src/integrations/http/client-patch.ts
/**
* Platform-portable HTTP(S) outgoing-request patching integration
*
* Patches the `http` and `https` Node.js built-in module exports to create
* Sentry spans for outgoing requests and optionally inject distributed trace
* propagation headers.
*
* @module
*
* This Sentry integration is a derivative work based on the OpenTelemetry
* HTTP instrumentation.
*
* <https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http>
*
* Extended under the terms of the Apache 2.0 license linked below:
*
* ----
*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
let onHttpClientRequestCreated;
/**
* Patch `ClientRequest.prototype._storeHeader` so that every outgoing request
* is routed through our instrumentation.
*
* We deliberately patch the shared `ClientRequest` prototype rather than the
* module's `request`/`get` exports. Every outgoing request — no matter how the
* module was imported (`require('node:http')`, `import http from 'node:http'`,
* or `import * as http from 'node:http'`) — ultimately constructs a
* `ClientRequest` and serializes its headers through `_storeHeader` on this one
* prototype. ES module namespace bindings (`import * as http` / `import
* { request }`) are immutable snapshots that cannot be monkey-patched at all,
* but the prototype is a shared, mutable object, so patching it reaches those
* consumers too.
*
* `_storeHeader` is the method that renders the outgoing header block into
* `request._header`. We run *before* the original, which is the last moment a
* header can still be added via `setHeader` (afterwards `request._header` is
* set and any `setHeader` call throws `ERR_HTTP_HEADERS_SENT`). It runs
* synchronously in the caller's async context — during `request.end()` /
* `request.write()` — so spans are parented correctly, and is invoked exactly
* once per request whether the headers are being sent immediately or buffered
* while a socket is assigned.
*
* We intentionally do *not* hook `onSocket`: it does not fire until a socket is
* assigned to the request, which for an `Agent` with all sockets busy (e.g.
* `maxSockets: 1`) happens only *after* the request's headers have already been
* serialized — far too late to inject trace-propagation headers.
*
* `https` requests reuse `http`'s `ClientRequest`, so patching `http` covers
* both; the `https` module does not expose its own `ClientRequest` and is a
* no-op here.
*/
function patchClientRequest(httpModule, options) {
	const proto = httpModule.ClientRequest?.prototype;
	if (typeof proto?._storeHeader !== "function") return;
	onHttpClientRequestCreated = getHttpClientSubscriptions({
		...options,
		http: httpModule
	})[HTTP_ON_CLIENT_REQUEST];
	if (require_cacheOrigin.getOriginalFunction(proto._storeHeader)) return;
	const originalStoreHeader = proto._storeHeader;
	require_cacheOrigin.wrapMethod(proto, "_storeHeader", function patchedStoreHeader(...args) {
		try {
			onHttpClientRequestCreated({ request: this }, HTTP_ON_CLIENT_REQUEST);
		} catch {}
		return originalStoreHeader.apply(this, args);
	});
}
function patchModule(httpModuleExport, options = {}) {
	patchClientRequest(getDefaultExport(httpModuleExport), options);
	return httpModuleExport;
}
/**
* Patch `node:http`. This also covers `node:https` as it reuses the same `ClientRequest` class.
*
* @example
* ```javascript
* import http from 'http';
* import { patchHttpModuleClient } from '@sentry/core';
* patchHttpModuleClient(http, { tracePropagation: true });
* ```
*/
const patchHttpModuleClient = (httpModuleExport, options = {}) => patchModule(httpModuleExport, options);
// src/integrations/http/patch-request-to-capture-body.ts
/**
* This method patches the request object to capture the body.
* Instead of actually consuming the streamed body ourselves, which has
* potential side effects, we monkey patch `req.on('data')` to intercept
* the body chunks. This way, we only read the body if the user also consumes
* the body, ensuring we do not change any behavior in unexpected ways.
*/
function patchRequestToCaptureBody(req, isolationScope, maxIncomingRequestBodySize, integrationName) {
	let bodyByteLength = 0;
	const chunks = [];
	require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(integrationName, "Patching request.on");
	const callbackMap = /* @__PURE__ */ new WeakMap();
	const maxBodySize = require_fetch.getMaxBodyByteLength(maxIncomingRequestBodySize);
	try {
		req.on = req.addListener = new Proxy(req.on, { apply: (target, thisArg, args) => {
			const [event, listener, ...restArgs] = args;
			if (event === "data") {
				require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(integrationName, `Handling request.on("data") with maximum body size of ${maxBodySize}b`);
				const callback = new Proxy(listener, { apply: (target, thisArg, args) => {
					try {
						const chunk = args[0];
						const bufferifiedChunk = Buffer.from(chunk);
						if (bodyByteLength < maxBodySize) {
							chunks.push(bufferifiedChunk);
							bodyByteLength += bufferifiedChunk.byteLength;
						} else if (require_cacheOrigin.DEBUG_BUILD) require_cacheOrigin.debug.log(integrationName, `Dropping request body chunk because maximum body length of ${maxBodySize}b is exceeded.`);
					} catch {
						require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.error(integrationName, "Encountered error while storing body chunk.");
					}
					return Reflect.apply(target, thisArg, args);
				} });
				callbackMap.set(listener, callback);
				return Reflect.apply(target, thisArg, [
					event,
					callback,
					...restArgs
				]);
			}
			return Reflect.apply(target, thisArg, args);
		} });
		req.off = req.removeListener = new Proxy(req.off, { apply: (target, thisArg, args) => {
			const [, listener] = args;
			const callback = callbackMap.get(listener);
			if (callback) {
				callbackMap.delete(listener);
				const modifiedArgs = args.slice();
				modifiedArgs[1] = callback;
				return Reflect.apply(target, thisArg, modifiedArgs);
			}
			return Reflect.apply(target, thisArg, args);
		} });
		req.on("end", () => {
			try {
				const body = Buffer.concat(chunks).toString("utf-8");
				if (body) {
					const truncatedBody = Buffer.byteLength(body, "utf-8") > maxBodySize ? `${Buffer.from(body).subarray(0, maxBodySize - 3).toString("utf-8")}...` : body;
					isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: truncatedBody } });
				}
			} catch (error) {
				if (require_cacheOrigin.DEBUG_BUILD) require_cacheOrigin.debug.error(integrationName, "Error building captured request body", error);
			}
		});
	} catch (error) {
		if (require_cacheOrigin.DEBUG_BUILD) require_cacheOrigin.debug.error(integrationName, "Error patching request to capture body", error);
	}
}
// src/integrations/http/record-request-session.ts
const clientToRequestSessionAggregatesMap = /* @__PURE__ */ new WeakMap();
/**
* Starts a session and tracks it in the context of a given isolation scope.
* When the passed response is finished, the session is put into a task and
* is aggregated with other sessions that may happen in a certain time window
* (sessionFlushingDelayMs).
*
* The sessions are always aggregated by the client that is on the current
* scope at the time of ending the response (if there is one).
*/
function recordRequestSession(client, { requestIsolationScope, response, sessionFlushingDelayMS }) {
	response.once("close", startRequestSession(client, {
		requestIsolationScope,
		sessionFlushingDelayMS
	}));
}
/**
* Starts a session and tracks it in the context of a given isolation scope.
* Returns a function to call when the request ends. It puts the session into
* a task, which aggregates it with other sessions in a certain time window
* (sessionFlushingDelayMs, 60 seconds by default). Calls after the first
* one do nothing.
*
* Use this when the server has no `node:http` response to pass to
* {@link recordRequestSession}.
*/
function startRequestSession(client, { requestIsolationScope, sessionFlushingDelayMS = 6e4 }) {
	requestIsolationScope.setSession();
	requestIsolationScope.setSDKProcessingMetadata({ requestSession: { status: "ok" } });
	client.emit("startRequestSession");
	let ended = false;
	return () => {
		if (ended) return;
		ended = true;
		const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;
		if (client && requestSession) {
			require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(`Recorded request session with status: ${requestSession.status}`);
			const roundedDate = new Date(require_cacheOrigin.safeDateNow());
			roundedDate.setSeconds(0, 0);
			const dateBucketKey = roundedDate.toISOString();
			const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client);
			const bucket = existingClientAggregate?.[dateBucketKey] || {
				exited: 0,
				crashed: 0,
				errored: 0
			};
			bucket[{
				ok: "exited",
				crashed: "crashed",
				errored: "errored"
			}[requestSession.status]]++;
			if (existingClientAggregate) existingClientAggregate[dateBucketKey] = bucket;
			else {
				require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Opened new request session aggregate.");
				const newClientAggregate = { [dateBucketKey]: bucket };
				clientToRequestSessionAggregatesMap.set(client, newClientAggregate);
				const flushPendingClientAggregates = () => {
					clearTimeout(timeout);
					unregisterClientFlushHook();
					clientToRequestSessionAggregatesMap.delete(client);
					const aggregatePayload = Object.entries(newClientAggregate).map(([timestamp, value]) => ({
						started: timestamp,
						exited: value.exited,
						errored: value.errored,
						crashed: value.crashed
					}));
					client.sendSession({ aggregates: aggregatePayload });
				};
				const unregisterClientFlushHook = client.on("flush", () => {
					require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Sending request session aggregate due to client flush");
					flushPendingClientAggregates();
				});
				const timeout = setTimeout(() => {
					require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Sending request session aggregate due to flushing schedule");
					flushPendingClientAggregates();
				}, sessionFlushingDelayMS);
				require_cacheOrigin.safeUnref(timeout);
			}
		}
	};
}
// src/integrations/http/server-subscription.ts
const INTEGRATION_NAME = "Http.Server";
const SPANS_INTEGRATION_NAME = "Http.SentryServerSpans";
const lastSentryEmitMap = /* @__PURE__ */ new WeakMap();
const kRequestMark = Symbol.for("sentry_http_server_instrumented");
/** return true if it is NOT already marked */
function markRequest(request) {
	return !request[kRequestMark] && (request[kRequestMark] = true);
}
function instrumentServer(options, server) {
	const currentEmit = server.emit;
	if (currentEmit === lastSentryEmitMap.get(server)) return;
	const newEmit = new Proxy(currentEmit, { apply(target, thisArg, args) {
		const [event, ...data] = args;
		if (event !== "request") return target.apply(thisArg, args);
		const client = require_cacheOrigin.getClient();
		const [request, response] = data;
		if (!client || !markRequest(request)) return target.apply(thisArg, args);
		if (require_fetch.isServedTunnelRequest(request)) {
			if (require_fetch.getNodeTunnelHandler()?.(request, response)) return true;
			const tunnelIsolationScope = require_cacheOrigin.getIsolationScope().clone();
			tunnelIsolationScope.setClient(client);
			return require_cacheOrigin.withIsolationScope(tunnelIsolationScope, () => target.apply(thisArg, args));
		}
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(INTEGRATION_NAME, "Handling incoming request");
		const isolationScope = require_cacheOrigin.getIsolationScope().clone();
		isolationScope.setClient(client);
		const ipAddress = request.socket?.remoteAddress;
		const url = request.url || "/";
		const normalizedRequest = require_fetch.httpRequestToRequestData(request);
		const { maxRequestBodySize: configuredBodySize, ignoreRequestBody, sessions = true, sessionFlushingDelayMS = 6e4 } = options;
		const effectiveBodySize = configuredBodySize ?? (client.getDataCollectionOptions().httpBodies.includes("incomingRequest") ? "medium" : "none");
		if (effectiveBodySize !== "none" && !require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `ignoreRequestBody` callback threw an error, ignoring the request body:" : "", () => !!ignoreRequestBody?.(url, request), () => true)) patchRequestToCaptureBody(request, isolationScope, effectiveBodySize, INTEGRATION_NAME);
		isolationScope.setSDKProcessingMetadata({
			normalizedRequest,
			ipAddress
		});
		const bestEffortTransactionName = `${(request.method || "GET").toUpperCase()} ${require_fetch.stripUrlQueryAndFragment(url)}`;
		isolationScope.setTransactionName(bestEffortTransactionName);
		if (sessions) recordRequestSession(client, {
			requestIsolationScope: isolationScope,
			response,
			sessionFlushingDelayMS: sessionFlushingDelayMS ?? 6e4
		});
		return require_cacheOrigin.withIsolationScope(isolationScope, () => {
			const sentryTrace = normalizedRequest.headers?.["sentry-trace"];
			const baggage = normalizedRequest.headers?.["baggage"];
			const sentryTraceValue = Array.isArray(sentryTrace) ? sentryTrace[0] : sentryTrace;
			return require_cacheOrigin.continueTrace({
				sentryTrace: sentryTraceValue,
				baggage: Array.isArray(baggage) ? baggage[0] : baggage
			}, () => {
				const propagationContext = require_cacheOrigin.getCurrentScope().getPropagationContext();
				propagationContext.propagationSpanId = require_cacheOrigin.generateSpanId();
				if (!sentryTraceValue) {
					propagationContext.traceId = require_cacheOrigin.generateTraceId();
					propagationContext.sampleRand = require_cacheOrigin.safeMathRandom();
				}
				response.once("close", () => {
					isolationScope.setContext("response", { status_code: response.statusCode });
				});
				const wrap = options.wrapServerEmitRequest;
				let emitResult = false;
				if (wrap) wrap(request, response, normalizedRequest, () => {
					emitResult = target.apply(thisArg, args);
				});
				else emitResult = target.apply(thisArg, args);
				return emitResult;
			});
		});
	} });
	lastSentryEmitMap.set(server, newEmit);
	server.emit = newEmit;
}
function getHttpServerSubscriptions(options) {
	const userWrap = options.wrapServerEmitRequest;
	const spanWrap = buildServerSpanWrap(options);
	require_fetch.setHttpServerHandlesTunnel();
	const effectiveOptions = {
		...options,
		wrapServerEmitRequest(request, response, normalizedRequest, next) {
			const clientOptions = require_cacheOrigin.getClient()?.getOptions();
			if (options.spans ?? (clientOptions ? require_cacheOrigin.hasSpansEnabled(clientOptions) : false)) spanWrap(request, response, normalizedRequest, next);
			else if (userWrap) userWrap(request, response, normalizedRequest, next);
			else next();
		}
	};
	const onHttpServerRequest = (data) => {
		const { server } = data;
		instrumentServer(effectiveOptions, server);
	};
	const onHttp2ServerStream = (data) => {
		const server = data.stream?.session?.server;
		if (server) instrumentServer(effectiveOptions, server);
	};
	return {
		[HTTP_ON_SERVER_REQUEST]: onHttpServerRequest,
		[HTTP2_ON_SERVER_STREAM]: onHttp2ServerStream
	};
}
function buildServerSpanWrap(options) {
	const { wrapServerEmitRequest: userWrap, ignoreIncomingRequests, ignoreStaticAssets = true, onSpanCreated, errorMonitor = "error", onSpanEnd } = options;
	return (request, response, normalizedRequest, next) => {
		if (typeof __SENTRY_TRACING__ !== "undefined" && !__SENTRY_TRACING__) return next();
		return userWrap ? userWrap(request, response, normalizedRequest, createSpan) : createSpan();
		function createSpan() {
			const client = require_cacheOrigin.getIsolationScope().getClient();
			if (!client) return next();
			const dataCollectionOptions = client.getDataCollectionOptions();
			if (shouldIgnoreSpansForIncomingRequest(request, {
				ignoreStaticAssets,
				ignoreIncomingRequests
			})) {
				require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log(SPANS_INTEGRATION_NAME, "Skipping span creation for incoming request", request.url);
				return next();
			}
			const fullUrl = normalizedRequest.url || request.url || "/";
			const urlObj = require_fetch.parseStringToURLObject(fullUrl);
			const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : require_fetch.stripUrlQueryAndFragment(fullUrl);
			const method = (request.method || "GET").toUpperCase();
			const name = require_cacheOrigin.hasSpanStreamingEnabled(client) ? request.method?.toUpperCase() || "HTTP" : `${method} ${httpTargetWithoutQueryFragment}`;
			const headers = request.headers;
			const userAgent = headers["user-agent"];
			const httpVersion = request.httpVersion;
			const hostname = require_fetch.getHostFromHeaders(headers)?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
			const scheme = fullUrl.startsWith("https") ? "https" : "http";
			const { socket } = request;
			const { localAddress, localPort, remoteAddress, remotePort } = socket ?? {};
			const collectClientAddress = client.getDataCollectionOptions().userInfo;
			const forwardedAddress = require_fetch.getClientIPAddress(headers);
			const clientAddress = forwardedAddress || remoteAddress;
			return require_cacheOrigin.startSpanManual$1({
				name,
				attributes: {
					[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_SERVER,
					[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.http.http_server",
					[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
					[_sentry_conventions_attributes.SENTRY_KIND]: "server",
					[_sentry_conventions_attributes.SERVER_ADDRESS]: hostname,
					[_sentry_conventions_attributes.SERVER_PORT]: localPort,
					[_sentry_conventions_attributes.NETWORK_LOCAL_ADDRESS]: localAddress,
					[_sentry_conventions_attributes.NETWORK_LOCAL_PORT]: localPort,
					[_sentry_conventions_attributes.CLIENT_ADDRESS]: collectClientAddress ? clientAddress : void 0,
					[_sentry_conventions_attributes.CLIENT_PORT]: forwardedAddress ? void 0 : remotePort,
					[_sentry_conventions_attributes.NETWORK_PEER_ADDRESS]: collectClientAddress ? remoteAddress : void 0,
					[_sentry_conventions_attributes.NETWORK_PEER_PORT]: remotePort,
					[_sentry_conventions_attributes.SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || void 0,
					[_sentry_conventions_attributes.URL_FULL]: require_fetch.filterCollectedUrl(fullUrl, client),
					[_sentry_conventions_attributes.URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,
					[_sentry_conventions_attributes.URL_QUERY]: require_fetch.filterCollectedUrlQuery(require_fetch.getUrlQuery(urlObj?.search), client),
					[_sentry_conventions_attributes.URL_FRAGMENT]: require_fetch.getUrlFragment(urlObj?.hash),
					[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: method,
					[_sentry_conventions_attributes.NETWORK_PROTOCOL_NAME]: "http",
					[_sentry_conventions_attributes.NETWORK_PROTOCOL_VERSION]: httpVersion,
					[_sentry_conventions_attributes.USER_AGENT_ORIGINAL]: userAgent,
					[_sentry_conventions_attributes.URL_SCHEME]: scheme,
					[_sentry_conventions_attributes.NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === "QUIC" ? "udp" : "tcp",
					[_sentry_conventions_attributes.HTTP_REQUEST_BODY_SIZE]: require_fetch.getContentLengthFromHeaders(request.headers),
					...require_fetch.httpHeadersToSpanAttributes(normalizedRequest.headers || {}, dataCollectionOptions)
				}
			}, (span) => {
				require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `onSpanCreated` callback threw an error:" : "", () => onSpanCreated?.(span, request, response), () => void 0);
				let isEnded = false;
				function endSpan(status) {
					if (isEnded) return;
					isEnded = true;
					span.setAttributes({
						[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_TEXT]: request.httpVersion === "2.0" ? void 0 : response.statusMessage?.toUpperCase(),
						[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE]: response.statusCode,
						...require_fetch.httpHeadersToSpanAttributes(require_fetch.headersToDict(response.headers), dataCollectionOptions, "response")
					});
					span.setStatus(status);
					require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `onSpanEnd` callback threw an error:" : "", () => onSpanEnd?.(span, request, response), () => void 0);
					span.end();
				}
				response.once("close", () => {
					endSpan(require_cacheOrigin.getSpanStatusFromHttpCode(response.statusCode));
				});
				response.once(errorMonitor, () => {
					const httpStatus = require_cacheOrigin.getSpanStatusFromHttpCode(response.statusCode);
					endSpan(httpStatus.code === 2 ? httpStatus : { code: 2 });
				});
				next();
			});
		}
	};
}
function shouldIgnoreSpansForIncomingRequest(request, { ignoreStaticAssets, ignoreIncomingRequests }) {
	const urlPath = request.url;
	const method = request.method?.toUpperCase();
	if (method === "OPTIONS" || method === "HEAD" || !urlPath) return true;
	if (ignoreStaticAssets && method === "GET" && isStaticAssetRequest(urlPath)) return true;
	if (require_cacheOrigin.safeCallback(require_cacheOrigin.DEBUG_BUILD ? "The `ignoreIncomingRequests` callback threw an error, not ignoring the request:" : "", () => !!ignoreIncomingRequests?.(urlPath, request), () => false)) return true;
	return false;
}
function isStaticAssetRequest(urlPath) {
	const path = require_fetch.stripUrlQueryAndFragment(urlPath);
	if (path.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) return true;
	if (path.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/)) return true;
	return false;
}
function isKnownPrefetchRequest(req) {
	return req.headers["next-router-prefetch"] === "1";
}
// src/integrations/http/server-transaction-event.ts
/**
* Shared post-processing for transaction events produced by server span instrumentation.
*
* Node's `httpServerSpansIntegration` and Deno's `denoHttpIntegration` both create their
* server spans outside of the OTel SDK span exporter, so neither gets the exporter's
* status code handling for free. Both run this from their `processEvent` hook instead.
*/
/**
* Status codes for which server transactions are dropped unless `ignoreStatusCodes` says otherwise.
*
* 300 and 304 are possibly valid status codes we do not want to filter, hence the split ranges.
*/
const DEFAULT_IGNORE_STATUS_CODES = [
	[401, 404],
	[301, 303],
	[305, 399]
];
/**
* If the given status code should be filtered for the given list of status codes/ranges.
*/
function shouldFilterStatusCode(statusCode, dropForStatusCodes) {
	return dropForStatusCodes.some((code) => {
		if (typeof code === "number") return code === statusCode;
		const [min, max] = code;
		return statusCode >= min && statusCode <= max;
	});
}
/**
* Drop transaction events whose HTTP status code matches `ignoreStatusCodes`, and surface the
* status as the top-level `response` context on the ones that are kept.
*
* Pass `spanOrigin` to only act on transactions produced by a specific instrumentation, so that
* an integration owning this option does not filter transactions created by a different one.
* When omitted, every transaction carrying an HTTP status code is considered.
*
* Returns `null` when the event should be dropped, otherwise the (possibly updated) event.
*/
function processHttpServerTransactionEvent(event, ignoreStatusCodes, spanOrigin) {
	if (event.type !== "transaction") return event;
	if (spanOrigin !== void 0 && event.contexts?.trace?.origin !== spanOrigin) return event;
	const statusCode = event.contexts?.trace?.data?.[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE];
	if (typeof statusCode !== "number") return event;
	if (shouldFilterStatusCode(statusCode, ignoreStatusCodes)) {
		require_cacheOrigin.DEBUG_BUILD && require_cacheOrigin.debug.log("Dropping transaction due to status code", statusCode);
		return null;
	}
	event.contexts = {
		...event.contexts,
		response: {
			...event.contexts?.response,
			status_code: statusCode
		}
	};
	return event;
}
// src/utils/responseStreaming.ts
/**
* Classifies a Response as streaming or non-streaming.
*
* Heuristics:
* - No body → not streaming
* - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)
* - text/plain or text/x-component without Content-Length → streaming (some AI APIs, streamed RSC)
* - Otherwise → not streaming (conservative default, including HTML/SSR)
*
* We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)
* or SSR streams that may not have data ready immediately.
*/
function classifyResponseStreaming(res) {
	if (!res.body) return { isStreaming: false };
	const contentType = res.headers.get("content-type") ?? "";
	const contentLength = res.headers.get("content-length");
	if (/^text\/event-stream\b/i.test(contentType) || /^application\/(x-)?ndjson\b/i.test(contentType) || /^application\/stream\+json\b/i.test(contentType) || /^text\/(plain|x-component)\b/i.test(contentType) && !contentLength) return { isStreaming: true };
	return { isStreaming: false };
}
exports.DEFAULT_IGNORE_STATUS_CODES = DEFAULT_IGNORE_STATUS_CODES;
exports.HTTP2_ON_SERVER_STREAM = HTTP2_ON_SERVER_STREAM;
exports.HTTP_ON_CLIENT_REQUEST = HTTP_ON_CLIENT_REQUEST;
exports.HTTP_ON_SERVER_REQUEST = HTTP_ON_SERVER_REQUEST;
exports.ServerRuntimeClient = ServerRuntimeClient;
exports._INTERNAL_forwardTunnelRequest = require_fetch.forwardTunnelRequest;
exports._INTERNAL_getCacheOriginMetaTags = require_cacheOrigin._INTERNAL_getCacheOriginMetaTags;
exports._INTERNAL_getReleaseFromCommitEnv = getReleaseFromCommitEnv;
exports._INTERNAL_getReleaseMetaTag = require_fetch.getReleaseMetaTag;
exports._INTERNAL_getRenderStart = require_cacheOrigin._INTERNAL_getRenderStart;
exports._INTERNAL_getRootSpanSentryTrace = require_cacheOrigin._INTERNAL_getRootSpanSentryTrace;
exports._INTERNAL_getServedTunnel = require_fetch.getServedTunnel;
exports._INTERNAL_getTunnelPaths = require_fetch.getTunnelPaths;
exports._INTERNAL_handleServedNodeTunnelRequest = require_fetch.handleServedNodeTunnelRequest;
exports._INTERNAL_handleServedTunnelRequest = require_fetch.handleServedTunnelRequest;
exports._INTERNAL_httpServerHandlesTunnel = require_fetch.httpServerHandlesTunnel;
exports._INTERNAL_isServedTunnelRequest = require_fetch.isServedTunnelRequest;
exports._INTERNAL_pickForwardedHeaders = require_fetch.pickForwardedHeaders;
exports._INTERNAL_readCommitEnvVar = readCommitEnvVar;
exports._INTERNAL_resetTunnelDefaults = _INTERNAL_resetTunnelDefaults;
exports._INTERNAL_safeUnref = require_cacheOrigin.safeUnref;
exports._INTERNAL_setNodeTunnelHandler = require_fetch.setNodeTunnelHandler;
exports._INTERNAL_setScopeFlushedByRuntime = setScopeFlushedByRuntime;
exports._INTERNAL_setTunnelDefaults = setTunnelDefaults;
exports.addOutgoingRequestBreadcrumb = addOutgoingRequestBreadcrumb;
exports.callFrameToStackFrame = callFrameToStackFrame;
exports.classifyResponseStreaming = classifyResponseStreaming;
exports.createFetchIntegration = require_fetch.createFetchIntegration;
exports.filenameIsInApp = filenameIsInApp;
exports.flushIfServerless = flushIfServerless;
exports.getClientIPAddress = require_fetch.getClientIPAddress;
exports.getHttpClientSubscriptions = getHttpClientSubscriptions;
exports.getHttpServerSubscriptions = getHttpServerSubscriptions;
exports.getRequestOptions = getRequestOptions;
exports.getRequestUrl = getRequestUrl;
exports.getRequestUrlFromClientRequest = getRequestUrlFromClientRequest;
exports.getRequestUrlObject = getRequestUrlObject;
exports.handleTunnelRequestIfMatched = require_fetch.handleTunnelRequestIfMatched;
exports.isNodeEnv = require_cacheOrigin.isNodeEnv;
exports.isStaticAssetRequest = isStaticAssetRequest;
exports.isTunnelRequest = require_fetch.isTunnelRequest;
exports.loadModule = require_cacheOrigin.loadModule;
exports.node = node;
exports.nodeStackLineParser = nodeStackLineParser;
exports.patchHttpModuleClient = patchHttpModuleClient;
exports.processHttpServerTransactionEvent = processHttpServerTransactionEvent;
exports.recordRequestSession = recordRequestSession;
exports.serveTunnelIntegration = serveTunnelIntegration;
exports.startRequestSession = startRequestSession;
exports.trpcMiddleware = trpcMiddleware;
exports.vercelWaitUntil = vercelWaitUntil;
exports.watchdogTimer = watchdogTimer;
exports.wrapMcpServerWithSentry = wrapMcpServerWithSentry;

//# sourceMappingURL=server.js.map