UNPKG

@sentry/core

Version:
8,712 lines • 292 kB
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
// src/debug-build.ts
/**
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
*
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
*/
const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
// src/utils/worldwide.ts
/** Get's the global object for the current JavaScript runtime */
const GLOBAL_OBJ = globalThis;
// src/utils/version.ts
const SDK_VERSION = "11.16.0";
// src/carrier.ts
/**
* Returns the global shim registry.
*
* FIXME: This function is problematic, because despite always returning a valid Carrier,
* it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check
* at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.
**/
function getMainCarrier() {
	getSentryCarrier(GLOBAL_OBJ);
	return GLOBAL_OBJ;
}
/** Will either get the existing sentry carrier, or create a new one. */
function getSentryCarrier(carrier) {
	const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
	__SENTRY__.version = __SENTRY__.version || "11.16.0";
	return __SENTRY__[SDK_VERSION] = __SENTRY__["11.16.0"] || {};
}
/**
* Returns a global singleton contained in the global `__SENTRY__[]` object.
*
* If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
* function and added to the `__SENTRY__` object.
*
* @param name name of the global singleton on __SENTRY__
* @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
* @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
* @returns the singleton
*/
function getGlobalSingleton(name, creator, obj = GLOBAL_OBJ) {
	const __SENTRY__ = obj.__SENTRY__ = obj.__SENTRY__ || {};
	const carrier = __SENTRY__[SDK_VERSION] = __SENTRY__["11.16.0"] || {};
	return carrier[name] || (carrier[name] = creator());
}
// src/utils/debug-logger.ts
const CONSOLE_LEVELS = [
	"debug",
	"info",
	"warn",
	"error",
	"log",
	"assert",
	"trace"
];
/** Prefix for logging strings */
const PREFIX = "Sentry Logger ";
/** This may be mutated by the console instrumentation. */
const originalConsoleMethods = {};
/**
* Temporarily disable sentry console instrumentations.
*
* @param callback The function to run against the original `console` messages
* @returns The results of the callback
*/
function consoleSandbox(callback) {
	if (!("console" in GLOBAL_OBJ)) return callback();
	const console = GLOBAL_OBJ.console;
	const wrappedFuncs = {};
	const wrappedLevels = Object.keys(originalConsoleMethods);
	wrappedLevels.forEach((level) => {
		const originalConsoleMethod = originalConsoleMethods[level];
		wrappedFuncs[level] = console[level];
		console[level] = originalConsoleMethod;
	});
	try {
		return callback();
	} finally {
		wrappedLevels.forEach((level) => {
			console[level] = wrappedFuncs[level];
		});
	}
}
function enable() {
	_getLoggerSettings().enabled = true;
}
function disable() {
	_getLoggerSettings().enabled = false;
}
function isEnabled$1() {
	return _getLoggerSettings().enabled;
}
function log(...args) {
	_maybeLog("log", ...args);
}
function warn(...args) {
	_maybeLog("warn", ...args);
}
function error(...args) {
	_maybeLog("error", ...args);
}
function _maybeLog(level, ...args) {
	if (!DEBUG_BUILD) return;
	if (isEnabled$1()) consoleSandbox(() => {
		GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);
	});
}
function _getLoggerSettings() {
	if (!DEBUG_BUILD) return { enabled: false };
	return getGlobalSingleton("loggerSettings", () => ({ enabled: false }));
}
/**
* This is a logger singleton which either logs things or no-ops if logging is not enabled.
*/
const debug = {
	/** Enable logging. */
	enable,
	/** Disable logging. */
	disable,
	/** Check if logging is enabled. */
	isEnabled: isEnabled$1,
	/** Log a message. */
	log,
	/** Log a warning. */
	warn,
	/** Log an error. */
	error
};
// src/utils/stacktrace.ts
const STACKTRACE_FRAME_LIMIT = 50;
const UNKNOWN_FUNCTION = "?";
const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
/**
* Creates a stack parser with the supplied line parsers
*
* StackFrames are returned in the correct order for Sentry Exception
* frames and with Sentry SDK internal frames removed from the top and bottom
*
*/
function createStackParser(...parsers) {
	const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map((p) => p[1]);
	return (stack, skipFirstLines = 0, framesToPop = 0) => {
		const frames = [];
		const lines = stack.split("\n");
		for (let i = skipFirstLines; i < lines.length; i++) {
			let line = lines[i];
			if (line.length > 1024) line = line.slice(0, 1024);
			const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
			if (cleanedLine.includes("Error: ")) continue;
			for (const parser of sortedParsers) {
				const frame = parser(cleanedLine);
				if (frame) {
					frames.push(frame);
					break;
				}
			}
			if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) break;
		}
		return stripSentryFramesAndReverse(frames.slice(framesToPop));
	};
}
/**
* Gets a stack parser implementation from Options.stackParser
* @see Options
*
* If options contains an array of line parsers, it is converted into a parser
*/
function stackParserFromStackParserOptions(stackParser) {
	if (Array.isArray(stackParser)) return createStackParser(...stackParser);
	return stackParser;
}
/**
* Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.
* Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the
* function that caused the crash is the last frame in the array.
* @hidden
*/
function stripSentryFramesAndReverse(stack) {
	if (!stack.length) return [];
	const localStack = Array.from(stack);
	if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) localStack.pop();
	localStack.reverse();
	if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
		localStack.pop();
		if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) localStack.pop();
	}
	return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
		...frame,
		filename: frame.filename || getLastStackFrame(localStack).filename,
		function: frame.function || "?"
	}));
}
function getLastStackFrame(arr) {
	return arr[arr.length - 1] || {};
}
const defaultFunctionName = "<anonymous>";
/**
* Safely extract function name from itself
*/
function getFunctionName(fn) {
	try {
		if (!fn || typeof fn !== "function") return defaultFunctionName;
		return fn.name || defaultFunctionName;
	} catch {
		return defaultFunctionName;
	}
}
/**
* Get's stack frames from an event without needing to check for undefined properties.
*/
function getFramesFromEvent(event) {
	const exception = event.exception;
	if (exception) {
		const frames = [];
		try {
			exception.values.forEach((value) => {
				if (value.stacktrace.frames) frames.push(...value.stacktrace.frames);
			});
			return frames;
		} catch {
			return;
		}
	}
}
/**
* Normalizes stack line paths by removing file:// prefix and leading slashes for Windows paths
*/
function normalizeStackTracePath(path) {
	let filename = path?.startsWith("file://") ? path.slice(7) : path;
	if (filename?.match(/\/[A-Z]:/)) filename = filename.slice(1);
	return filename;
}
// src/instrument/handlers.ts
const handlers = {};
const instrumented = {};
/** Add a handler function. Returns a function to remove the handler. */
function addHandler(type, handler) {
	handlers[type] = handlers[type] || [];
	handlers[type].push(handler);
	return () => {
		const typeHandlers = handlers[type];
		if (typeHandlers) {
			const index = typeHandlers.indexOf(handler);
			if (index !== -1) typeHandlers.splice(index, 1);
		}
	};
}
/**
* Reset all instrumentation handlers.
* This can be used by tests to ensure we have a clean slate of instrumentation handlers.
*/
function resetInstrumentationHandlers() {
	Object.keys(handlers).forEach((key) => {
		handlers[key] = void 0;
	});
}
/** Maybe run an instrumentation function, unless it was already called. */
function maybeInstrument(type, instrumentFn) {
	if (!instrumented[type]) {
		instrumented[type] = true;
		try {
			instrumentFn();
		} catch (e) {
			DEBUG_BUILD && debug.error(`Error while instrumenting ${type}`, e);
		}
	}
}
/** Trigger handlers for a given instrumentation type. */
function triggerHandlers(type, data) {
	const typeHandlers = type && handlers[type];
	if (!typeHandlers) return;
	for (const handler of typeHandlers) try {
		handler(data);
	} catch (e) {
		DEBUG_BUILD && debug.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e);
	}
}
// src/instrument/globalError.ts
let _oldOnErrorHandler = null;
/**
* Add an instrumentation handler for when an error is captured by the global error handler.
*
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
function addGlobalErrorInstrumentationHandler(handler) {
	const type = "error";
	addHandler(type, handler);
	maybeInstrument(type, instrumentError);
}
function instrumentError() {
	_oldOnErrorHandler = GLOBAL_OBJ.onerror;
	GLOBAL_OBJ.onerror = function(msg, url, line, column, error) {
		triggerHandlers("error", {
			column,
			error,
			line,
			msg,
			url
		});
		if (_oldOnErrorHandler) return _oldOnErrorHandler.apply(this, arguments);
		return false;
	};
	GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
}
// src/instrument/globalUnhandledRejection.ts
let _oldOnUnhandledRejectionHandler = null;
/**
* Add an instrumentation handler for when an unhandled promise rejection is captured.
*
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
function addGlobalUnhandledRejectionInstrumentationHandler(handler) {
	const type = "unhandledrejection";
	addHandler(type, handler);
	maybeInstrument(type, instrumentUnhandledRejection);
}
function instrumentUnhandledRejection() {
	_oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;
	GLOBAL_OBJ.onunhandledrejection = function(e) {
		triggerHandlers("unhandledrejection", e);
		if (_oldOnUnhandledRejectionHandler) return _oldOnUnhandledRejectionHandler.apply(this, arguments);
		return true;
	};
	GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
}
// src/utils/is.ts
const objectToString = Object.prototype.toString;
/**
* Checks whether given value's type is one of a few Error or Error-like
* {@link isError}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isError(wat) {
	switch (objectToString.call(wat)) {
		case "[object Error]":
		case "[object Exception]":
		case "[object DOMException]":
		case "[object WebAssembly.Exception]": return true;
		default: return isInstanceOf(wat, Error);
	}
}
/**
* Checks whether given value is an instance of the given built-in class.
*
* @param wat The value to be checked
* @param className
* @returns A boolean representing the result.
*/
function isBuiltin(wat, className) {
	return objectToString.call(wat) === `[object ${className}]`;
}
/**
* Checks whether given value's type is ErrorEvent
* {@link isErrorEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isErrorEvent(wat) {
	return isBuiltin(wat, "ErrorEvent");
}
/**
* Checks whether given value's type is DOMError
* {@link isDOMError}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isDOMError(wat) {
	return isBuiltin(wat, "DOMError");
}
/**
* Checks whether given value's type is DOMException
* {@link isDOMException}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isDOMException(wat) {
	return isBuiltin(wat, "DOMException");
}
/**
* Checks whether given value's type is a string
* {@link isString}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isString(wat) {
	return isBuiltin(wat, "String");
}
/**
* Checks whether given string is parameterized
* {@link isParameterizedString}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isParameterizedString(wat) {
	return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
}
/**
* Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
* {@link isPrimitive}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isPrimitive(wat) {
	return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
}
/**
* Checks whether given value's type is an object literal, or a class instance.
* {@link isPlainObject}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isPlainObject(wat) {
	return isBuiltin(wat, "Object");
}
/**
* Checks whether given value is a non-null object (i.e. `typeof` is `'object'` and it is not `null`).
* Unlike {@link isPlainObject}, this also accepts arrays and class instances - it only rules out
* `null`, primitives, and functions.
* {@link isObjectLike}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isObjectLike(wat) {
	return typeof wat === "object" && wat !== null;
}
/**
* Checks whether given value's type is an Event instance
* {@link isEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isEvent(wat) {
	return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
/**
* Checks whether given value's type is an Element instance
* {@link isElement}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
* @deprecated This is browser-specific and will be removed from `@sentry/core` in a future major version.
* Import `isElement` from `@sentry/browser-utils` instead.
*/
function isElement(wat) {
	return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
/**
* Checks whether given value's type is an regexp
* {@link isRegExp}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isRegExp(wat) {
	return isBuiltin(wat, "RegExp");
}
/**
* Checks whether given value has a then function.
* @param wat A value to be checked.
*/
function isThenable(wat) {
	return Boolean(wat?.then && typeof wat.then === "function");
}
/**
* Checks whether given value's type is a React SyntheticEvent
* {@link isSyntheticEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
* @deprecated This is React-specific and will be removed from `@sentry/core` in a future major version.
* Use the equivalent helper that ships with `@sentry/react` instead.
*/
function isSyntheticEvent(wat) {
	return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
function isInstanceOf(wat, base) {
	try {
		return wat instanceof base;
	} catch {
		return false;
	}
}
/**
* Checks whether given value's type is a Vue ViewModel or a VNode.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
* @deprecated This is Vue-specific and will be removed from `@sentry/core` in a future major version.
* Use the equivalent helper that ships with `@sentry/vue` instead.
*/
function isVueViewModel(wat) {
	return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue || wat.__v_isVNode));
}
/**
* Checks whether the given parameter is a Standard Web API Request instance.
*
* Returns false if Request is not available in the current runtime.
*/
function isRequest(request) {
	return typeof Request !== "undefined" && isInstanceOf(request, Request);
}
// src/utils/object.ts
/**
* Replace a method in an object with a wrapped version of itself.
*
* If the method on the passed object is not a function, the wrapper will not be applied.
*
* @param source An object that contains a method to be wrapped.
* @param name The name of the method to be wrapped.
* @param replacementFactory A higher-order function that takes the original version of the given method and returns a
* wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to
* preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other
* args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.
* @returns void
*/
function fill(source, name, replacementFactory) {
	if (!(name in source)) return;
	const original = source[name];
	if (typeof original !== "function") return;
	const wrapped = replacementFactory(original);
	if (typeof wrapped === "function") markFunctionWrapped(wrapped, original);
	try {
		source[name] = wrapped;
	} catch {
		DEBUG_BUILD && debug.log(`Failed to replace method "${String(name)}" in object`, source);
	}
}
/**
* Defines a non-enumerable property on the given object.
*
* @param obj The object on which to set the property
* @param name The name of the property to be set
* @param value The value to which to set the property
*/
function addNonEnumerableProperty(obj, name, value) {
	try {
		Object.defineProperty(obj, name, {
			value,
			writable: true,
			configurable: true
		});
	} catch {
		DEBUG_BUILD && debug.log(`Failed to add non-enumerable property "${String(name)}" to object`, obj);
	}
}
/**
* Remembers the original function on the wrapped function and
* patches up the prototype.
*
* @param wrapped the wrapper function
* @param original the original function that gets wrapped
*/
function markFunctionWrapped(wrapped, original) {
	try {
		wrapped.prototype = original.prototype = original.prototype || {};
		addNonEnumerableProperty(wrapped, "__sentry_original__", original);
	} catch {}
}
/**
* Wrap a method on an object by name, only if it is not already wrapped.
*
* Note: to set the wrapped method as a non-enumerable property, pass
* false as the `enumerable` argument. This could be detected, but only
* by either walking up the prototype chain, or iterating over all fields
* in a `for(in)` loop. Neither are an acceptable performance impact for
* the rare case where we might patch a non-enumerable method.
*/
function wrapMethod(obj, field, wrapped, enumerable = true) {
	const original = obj[field];
	if (typeof original !== "function") throw new Error(`Cannot wrap method: ${field} is not a function`);
	if (getOriginalFunction(original)) throw new Error(`Attempting to wrap method ${field} multiple times`);
	markFunctionWrapped(wrapped, original);
	Object.defineProperty(obj, field, {
		writable: true,
		configurable: true,
		enumerable,
		value: wrapped
	});
}
/**
* This extracts the original function if available.  See
* `markFunctionWrapped` for more information.
*
* @param func the function to unwrap
* @returns the unwrapped version of the function if available.
*/
function getOriginalFunction(func) {
	return func.__sentry_original__;
}
/**
* Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
* non-enumerable properties attached.
*
* @param value Initial source that we have to transform in order for it to be usable by the serializer
* @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
*  an Error.
*/
function convertToPlainObject(value) {
	if (isError(value)) return {
		message: value.message,
		name: value.name,
		stack: value.stack,
		...getOwnProperties(value)
	};
	if (isEvent(value)) {
		const { type, target, currentTarget, detail } = value;
		return {
			type,
			target,
			currentTarget,
			...detail ? { detail } : {},
			...getOwnProperties(value)
		};
	}
	return value;
}
/** Filters out all but an object's own properties */
function getOwnProperties(obj) {
	if (isObjectLike(obj)) return Object.fromEntries(Object.entries(obj));
	return {};
}
/**
* Given any captured exception, extract its keys and create a sorted
* and truncated list that will be used inside the event message.
* eg. `Non-error exception captured with keys: foo, bar, baz`
*/
function extractExceptionKeysForMessage(exception) {
	const keys = Object.keys(convertToPlainObject(exception));
	keys.sort();
	return !keys[0] ? "[object has no keys]" : keys.join(", ");
}
/**
* Given any object, return a new object having removed all fields whose value was `undefined`.
* Works recursively on objects and arrays.
*
* Attention: This function keeps circular references in the returned object.
*
* @deprecated This function is no longer used by the SDK and will be removed in a future major version.
*/
function dropUndefinedKeys(inputValue) {
	return _dropUndefinedKeys(inputValue, /* @__PURE__ */ new Map());
}
function _dropUndefinedKeys(inputValue, memoizationMap) {
	if (inputValue === null || typeof inputValue !== "object") return inputValue;
	const memoVal = memoizationMap.get(inputValue);
	if (memoVal !== void 0) return memoVal;
	if (Array.isArray(inputValue)) {
		const returnValue = [];
		memoizationMap.set(inputValue, returnValue);
		inputValue.forEach((value) => {
			returnValue.push(_dropUndefinedKeys(value, memoizationMap));
		});
		return returnValue;
	}
	if (isPojo(inputValue)) {
		const returnValue = {};
		memoizationMap.set(inputValue, returnValue);
		Object.keys(inputValue).forEach((key) => {
			const val = inputValue[key];
			if (val !== void 0) returnValue[key] = _dropUndefinedKeys(val, memoizationMap);
		});
		return returnValue;
	}
	return inputValue;
}
function isPojo(input) {
	const constructor = input.constructor;
	return constructor === Object || constructor === void 0;
}
/**
* Ensure that something is an object.
*
* Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper
* classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.
*
* @param wat The subject of the objectification
* @returns A version of `wat` which can safely be used with `Object` class methods
*/
function objectify(wat) {
	let objectified;
	switch (true) {
		case wat == void 0:
			objectified = new String(wat);
			break;
		case typeof wat === "symbol" || typeof wat === "bigint":
			objectified = Object(wat);
			break;
		case isPrimitive(wat):
			objectified = new wat.constructor(wat);
			break;
		default: objectified = wat;
	}
	return objectified;
}
// src/utils/randomSafeContext.ts
let RESOLVED_RUNNER;
/**
* Simple wrapper that allows SDKs to *secretly* set context wrapper to generate safe random IDs in cache components contexts
*/
function withRandomSafeContext(cb) {
	if (RESOLVED_RUNNER !== void 0) return RESOLVED_RUNNER ? RESOLVED_RUNNER(cb) : cb();
	const sym = Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__");
	const globalWithSymbol = GLOBAL_OBJ;
	if (sym in globalWithSymbol && typeof globalWithSymbol[sym] === "function") {
		RESOLVED_RUNNER = globalWithSymbol[sym];
		return RESOLVED_RUNNER(cb);
	}
	RESOLVED_RUNNER = null;
	return cb();
}
/**
* Identical to Math.random() but wrapped in withRandomSafeContext
* to ensure safe random number generation in certain contexts (e.g., Next.js Cache Components).
*/
function safeMathRandom() {
	return withRandomSafeContext(() => Math.random());
}
/**
* Identical to Date.now() but wrapped in withRandomSafeContext
* to ensure safe time value generation in certain contexts (e.g., Next.js Cache Components).
*/
function safeDateNow() {
	return withRandomSafeContext(() => Date.now());
}
// src/utils/normalizationHints.ts
/**
* Internal symbols for normalization behavior. JSON and other structured user payloads cannot
* carry these keys, so they cannot spoof SDK-only normalization hints.
* We use Symbol.for to ensure that the symbols are the same across different modules/files.
*/
const SENTRY_SKIP_NORMALIZATION = Symbol.for("sentry.skipNormalization");
const SENTRY_OVERRIDE_NORMALIZATION_DEPTH = Symbol.for("sentry.overrideNormalizationDepth");
/** Marks an object so `normalize` returns it unchanged (already-normalized SDK data). */
function setSkipNormalizationHint(obj) {
	addNonEnumerableProperty(obj, SENTRY_SKIP_NORMALIZATION, true);
}
/** Overrides remaining normalization depth from this object downward (e.g. Redux / Pinia state). */
function setNormalizationDepthOverrideHint(obj, depth) {
	addNonEnumerableProperty(obj, SENTRY_OVERRIDE_NORMALIZATION_DEPTH, depth);
}
/** @internal */
function hasSkipNormalizationHint(value) {
	return Boolean(value[SENTRY_SKIP_NORMALIZATION]);
}
/** @internal */
function getNormalizationDepthOverrideHint(value) {
	const v = value[SENTRY_OVERRIDE_NORMALIZATION_DEPTH];
	return typeof v === "number" ? v : void 0;
}
// src/utils/normalize.ts
let stringifier;
/**
* Set a custom stringifier for the normalize function.
* If this returns a non-empty string, it will be used instead of the default stringification.
* Return undefined to fall back to the generic behavior.
*/
function setNormalizeStringifier(newStringifier) {
	stringifier = newStringifier;
}
/**
* Recursively normalizes the given object.
*
* - Creates a copy to prevent original input mutation
* - Skips non-enumerable properties
* - When stringifying, calls `toJSON` if implemented
* - Removes circular references
* - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format
* - Translates known global objects/classes to a string representations
* - Takes care of `Error` object serialization
* - Optionally limits depth of final output
* - Optionally limits number of properties/elements included in any single object/array
*
* @param input The object to be normalized.
* @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)
* @param maxProperties The max number of elements or properties to be included in any single array or
* object in the normalized output.
* @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization.
*/
function normalize(input, depth = 100, maxProperties = 1e400) {
	try {
		return visit("", input, depth, maxProperties);
	} catch (err) {
		return { ERROR: `**non-serializable** (${stringifyCaughtValue(err)})` };
	}
}
/**
* Stringify a caught value for an error message. Template literals and other implicit
* conversions throw on symbols and on objects with no usable `toString`, which is how
* the values that end up here tend to be broken in the first place, so fall back to
* fixed text instead of throwing again.
*/
function stringifyCaughtValue(err) {
	try {
		return String(err);
	} catch {
		return "unknown error";
	}
}
/** JSDoc */
function normalizeToSize(object, depth = 3, maxSize = 102400) {
	const normalized = normalize(object, depth);
	if (jsonSize(normalized) > maxSize) return normalizeToSize(object, depth - 1, maxSize);
	return normalized;
}
/**
* Visits a node to perform normalization on it
*
* @param key The key corresponding to the given node
* @param value The node to be visited
* @param depth Optional number indicating the maximum recursion depth
* @param maxProperties Optional maximum number of properties/elements included in any single object/array
* @param memo Optional Memo class handling decycling
*/
function visit(key, value, depth = 1e400, maxProperties = 1e400, memo = memoBuilder()) {
	const [memoize, unmemoize] = memo;
	if (value == null || ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) return value;
	const stringified = stringifyValue(key, value);
	if (!stringified.startsWith("[object ")) return stringified;
	if (hasSkipNormalizationHint(value)) return value;
	const overrideDepth = getNormalizationDepthOverrideHint(value);
	const remainingDepth = overrideDepth !== void 0 ? overrideDepth : depth;
	if (remainingDepth === 0) return stringified.replace("object ", "");
	if (memoize(value)) return "[Circular ~]";
	const valueWithToJSON = value;
	if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") try {
		return visit("", valueWithToJSON.toJSON(), remainingDepth - 1, maxProperties, memo);
	} catch {}
	const normalized = Array.isArray(value) ? [] : {};
	let numAdded = 0;
	const visitable = convertToPlainObject(value);
	for (const visitKey in visitable) {
		if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) continue;
		if (numAdded >= maxProperties) {
			normalized[visitKey] = "[MaxProperties ~]";
			break;
		}
		const visitValue = visitable[visitKey];
		normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
		numAdded++;
	}
	unmemoize(value);
	return normalized;
}
/**
* Stringify the given value. Handles various known special values and types.
*
* Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn
* the number 1231 into "[Object Number]", nor on `null`, as it will throw.
*
* @param value The value to stringify
* @returns A stringified representation of the given value
*/
function stringifyValue(key, value) {
	try {
		if (stringifier) {
			const stringified = stringifier(value);
			if (stringified) return stringified;
		}
		if (typeof global !== "undefined" && value === global) return "[Global]";
		if (typeof value === "number" && !Number.isFinite(value)) return `[${value}]`;
		if (typeof value === "function") return `[Function: ${getFunctionName(value)}]`;
		if (typeof value === "symbol") return `[${String(value)}]`;
		if (typeof value === "bigint") return `[BigInt: ${String(value)}]`;
		return `[object ${getConstructorName(value)}]`;
	} catch (err) {
		return `**non-serializable** (${stringifyCaughtValue(err)})`;
	}
}
function getConstructorName(value) {
	const prototype = Object.getPrototypeOf(value);
	return prototype?.constructor ? prototype.constructor.name : "null prototype";
}
/** Calculates bytes size of input string */
function utf8Length(value) {
	return ~-encodeURI(value).split(/%..|./).length;
}
/** Calculates bytes size of input object */
function jsonSize(value) {
	return utf8Length(JSON.stringify(value));
}
/**
* Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint
* across platforms and working directory.
*
* @param url The URL to be normalized.
* @param basePath The application base path.
* @returns The normalized URL.
*/
function normalizeUrlToBase(url, basePath) {
	const escapedBase = basePath.replace(/\\/g, "/").replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
	let newUrl = url;
	try {
		newUrl = decodeURI(url);
	} catch {}
	return newUrl.replace(/\\/g, "/").replace(/webpack:\/?/g, "").replace(new RegExp(`(file://)?/*${escapedBase}/*`, "ig"), "app:///");
}
/**
* Helper to decycle json objects
*/
function memoBuilder() {
	const inner = /* @__PURE__ */ new WeakSet();
	function memoize(obj) {
		if (inner.has(obj)) return true;
		inner.add(obj);
		return false;
	}
	function unmemoize(obj) {
		inner.delete(obj);
	}
	return [memoize, unmemoize];
}
// src/vendor/escapeStringForRegex.ts
/**
* Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to
* `new RegExp()`.
*
* @param regexString The string to escape
* @returns An version of the string with all special regex characters escaped
*/
function escapeStringForRegex(regexString) {
	return regexString.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}
// src/utils/string.ts
/**
* Coerce a value to a string without ever throwing. Strings pass through unchanged (so an
* already-serialized value isn't double-encoded and a plain string isn't wrapped in quotes);
* anything else is `JSON.stringify`-ed, falling back to `fallback` if that throws (e.g. on
* circular references or `BigInt`). Returns `undefined` for values `JSON.stringify` itself drops
* (top-level `undefined`, functions, symbols), matching `JSON.stringify`'s own runtime behavior.
*
* @param value the value to stringify
* @param fallback returned when serialization throws, or, if a function, called with `value` to
*   produce the fallback. Defaults to `'[unserializable]'`.
*/
function stringify(value, fallback = "[unserializable]") {
	if (typeof value === "string") return value;
	try {
		return JSON.stringify(value);
	} catch {
		return typeof fallback === "function" ? fallback(value) : fallback;
	}
}
/**
* Truncates given string to the maximum characters count
*
* @param str An object that contains serializable values
* @param max Maximum number of characters in truncated string (0 = unlimited)
* @returns string Encoded
*/
function truncate(str, max = 0) {
	if (typeof str !== "string" || max === 0) return str;
	return str.length <= max ? str : `${str.slice(0, max)}...`;
}
/**
* This is basically just `trim_line` from
* https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67
*
* @param str An object that contains serializable values
* @param max Maximum number of characters in truncated string
* @returns string Encoded
*/
function snipLine(line, colno) {
	let newLine = line;
	const lineLength = newLine.length;
	if (lineLength <= 150) return newLine;
	if (colno > lineLength) colno = lineLength;
	let start = Math.max(colno - 60, 0);
	if (start < 5) start = 0;
	let end = Math.min(start + 140, lineLength);
	if (end > lineLength - 5) end = lineLength;
	if (end === lineLength) start = Math.max(end - 140, 0);
	newLine = newLine.slice(start, end);
	if (start > 0) newLine = `'{snip} ${newLine}`;
	if (end < lineLength) newLine += " {snip}";
	return newLine;
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns Joined values
*/
function safeJoin(input, delimiter) {
	if (!Array.isArray(input)) return "";
	const output = [];
	for (let i = 0; i < input.length; i++) {
		const value = input[i];
		if (isPrimitive(value)) output.push(String(value));
		else if (value instanceof Error) output.push(value.message ? `${value.name}: ${value.message}` : value.name);
		else output.push(stringifyValue(void 0, value));
	}
	return output.join(delimiter);
}
/**
* Checks if the given value matches a regex or string
*
* @param value The string to test
* @param pattern Either a regex or a string against which `value` will be matched
* @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match
* `pattern` if it contains `pattern`. Only applies to string-type patterns.
*/
function isMatchingPattern(value, pattern, requireExactStringMatch = false) {
	if (!isString(value)) return false;
	if (isRegExp(pattern)) return pattern.test(value);
	if (isString(pattern)) return requireExactStringMatch ? value === pattern : value.includes(pattern);
	if (typeof pattern === "function") return pattern(value);
	return false;
}
/**
* Test the given string against an array of strings and regexes. By default, string matching is done on a
* substring-inclusion basis rather than a strict equality basis
*
* @param testString The string to test
* @param patterns The patterns against which to test the string
* @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to
* count. If false, `testString` will match a string pattern if it contains that pattern.
* @returns
*/
function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
	for (const pattern of patterns) if (isMatchingPattern(testString, pattern, requireExactStringMatch)) return true;
	return false;
}
// src/utils/misc.ts
function getCrypto() {
	const gbl = GLOBAL_OBJ;
	return gbl.crypto || gbl.msCrypto;
}
let emptyUuid;
function getRandomByte() {
	return safeMathRandom() * 16;
}
/**
* UUID4 generator
* @param crypto Object that provides the crypto API.
* @returns string Generated UUID4.
*/
function uuid4(crypto = getCrypto()) {
	try {
		if (crypto?.randomUUID) return withRandomSafeContext(() => crypto.randomUUID()).replace(/-/g, "");
	} catch {}
	if (!emptyUuid) emptyUuid = "10000000100040008000100000000000";
	return emptyUuid.replace(/[018]/g, (c) => (c ^ (getRandomByte() & 15) >> c / 4).toString(16));
}
function getFirstException(event) {
	return event.exception?.values?.[0];
}
/**
* Extracts either message or type+value from an event that can be used for user-facing logs
* @returns event's description
*/
function getEventDescription(event) {
	const { message, event_id: eventId } = event;
	if (message) return message;
	const firstException = getFirstException(event);
	if (firstException) {
		if (firstException.type && firstException.value) return `${firstException.type}: ${firstException.value}`;
		return firstException.type || firstException.value || eventId || "<unknown>";
	}
	return eventId || "<unknown>";
}
/**
* Adds exception values, type and value to an synthetic Exception.
* @param event The event to modify.
* @param value Value of the exception.
* @param type Type of the exception.
* @hidden
*/
function addExceptionTypeValue(event, value, type) {
	const exception = event.exception = event.exception || {};
	const values = exception.values = exception.values || [];
	const firstException = values[0] = values[0] || {};
	if (!firstException.value) firstException.value = value || "";
	if (!firstException.type) firstException.type = type || "Error";
}
/**
* Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
*
* @param event The event to modify.
* @param newMechanism Mechanism data to add to the event.
* @hidden
*/
function addExceptionMechanism(event, newMechanism) {
	const firstException = getFirstException(event);
	if (!firstException) return;
	applyExceptionMechanism(firstException, newMechanism);
}
/**
* Adds exception mechanism data to the originally captured (root) exception of a given event.
*
* @hidden
*/
function addExceptionMechanismToCapturedException(event, newMechanism) {
	const exceptions = event.exception?.values;
	const capturedException = exceptions?.find((exception) => exception.mechanism?.exception_id === 0) ?? exceptions?.[0];
	if (!capturedException) return;
	applyExceptionMechanism(capturedException, newMechanism);
}
function applyExceptionMechanism(exception, newMechanism) {
	const defaultMechanism = {
		type: "generic",
		handled: true
	};
	const currentMechanism = exception.mechanism;
	exception.mechanism = {
		...defaultMechanism,
		...currentMechanism,
		...newMechanism
	};
	if (newMechanism && "data" in newMechanism) exception.mechanism.data = {
		...currentMechanism?.data,
		...newMechanism.data
	};
}
const SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
function _parseInt(input) {
	return parseInt(input || "", 10);
}
/**
* Parses input into a SemVer interface
* @param input string representation of a semver version
*/
function parseSemver(input) {
	const match = input.match(SEMVER_REGEXP) || [];
	const major = _parseInt(match[1]);
	const minor = _parseInt(match[2]);
	const patch = _parseInt(match[3]);
	return {
		buildmetadata: match[5],
		major: isNaN(major) ? void 0 : major,
		minor: isNaN(minor) ? void 0 : minor,
		patch: isNaN(patch) ? void 0 : patch,
		prerelease: match[4]
	};
}
/**
* This function adds context (pre/post/line) lines to the provided frame
*
* @param lines string[] containing all lines
* @param frame StackFrame that will be mutated
* @param linesOfContext number of context lines we want to add pre/post
*/
function addContextToFrame(lines, frame, linesOfContext = 5) {
	if (frame.lineno === void 0) return;
	const maxLines = lines.length;
	const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);
	frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0));
	frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
	frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0));
}
/**
* Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
* in question), and marks it captured if not.
*
* This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
* record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
* that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
* the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
* caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
* function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
* see it.
*
* The client runs this check for every captured exception, also when `dedupeIntegration` is not active.
* `dedupeIntegration` drops equal events that come from different error objects.
*
* Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
* them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
* object wrapper forms so that this check will always work. However, because we need to flag the exact object which
* will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
* must be done before the exception captured.
*
* @param A thrown exception to check or flag as having been seen
* @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
*/
function checkOrSetAlreadyCaught(exception) {
	if (isAlreadyCaptured(exception)) return true;
	try {
		addNonEnumerableProperty(exception, "__sentry_captured__", true);
	} catch {}
	return false;
}
/**
* Checks whether we've already captured the given exception (note: not an identical exception - the very object).
* It is considered already captured if it has the `__sentry_captured__` property set to `true`.
*
* @internal Only considered for internal usage
*/
function isAlreadyCaptured(exception) {
	try {
		return exception.__sentry_captured__;
	} catch {}
}
// src/utils/time.ts
const ONE_SECOND_IN_MS = 1e3;
/**
* If `performance.timeOrigin + performance.now()` and `Date.now()` differ by more than this, we correct the time origin.
*/
const CLOCK_DRIFT_THRESHOLD_MS = 1e3;
/**
* Max number of time origins we store. When we hit it, we drop the oldest one, except the page load origin, which
* the pageload span uses.
*/
const MAX_TIME_ORIGIN_SEGMENTS = 100;
/**
* Returns a timestamp in seconds since the UNIX epoch using the Date API.
*/
function dateTimestampInSeconds() {
	return safeDateNow() / ONE_SECOND_IN_MS;
}
/**
* All time origins of the page, oldest first. Empty until the first `timestampInSeconds` call, or if the Performance
* API is unavailable.
*/
let _timeOriginSegments = [];
/**
* Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
* support the API.
*
* Wrapping the native API works around differences in behavior from different browsers.
*/
function createUnixTimestampInSecondsFunc() {
	const { performance } = GLOBAL_OBJ;
	if (!performance?.now || !performance.timeOrigin) {
		if (performance?.now) _timeOriginSegments = [{
			from: 0,
			origin: safeDateNow() - withRandomSafeContext(() => performance.now())
		}];
		return dateTimestampInSeconds;
	}
	let correctedTimeOrigin = performance.timeOrigin;
	_timeOriginSegments = [{
		from: 0,
		origin: correctedTimeOrigin
	}];
	let isFirstCall = true;
	let lastCheckedPerformanceNow = 0;
	return () => {
		return withRandomSafeContext(() => {
			const performanceNow = performance.now();
			const dateNow = Date.now();
			if (Math.abs(correctedTimeOrigin + performanceNow - dateNow) > CLOCK_DRIFT_THRESHOLD_MS) {
				correctedTimeOrigin = dateNow - performanceNow;
				if (isFirstCall) _timeOriginSegments = [{
					from: 0,
					origin: correctedTimeOrigin
				}];
				else {
					_timeOriginSegments.push({
						from: lastCheckedPerformanceNow,
						origin: correctedTimeOrigin
					});
					if (_timeOriginSegments.length > MAX_TIME_ORIGIN_SEGMENTS) _timeOriginSegments.splice(1, 1);
				}
			}
			isFirstCall = false;
			lastCheckedPerformanceNow = performanceNow;
			return (correctedTimeOrigin + performanceNow) / ONE_SECOND_IN_MS;
		});
	};
}
/**
* Returns `performance.now()` in milliseconds, or `undefined` if the Performance API is unavailable.
*/
function safePerformanceNow() {
	const { performance } = GLOBAL_OBJ;
	return performance?.now ? withRandomSafeContext(() => performance.now()) : void 0;
}
let _cachedTimestampInSecondsFn;
let _checkedForDriftInThisTask = false;
/**
* Converts a `performance.now()` based, relative time in milliseconds (e.g. a `PerformanceEntry`'s `startTime`)
* to a UNIX timestamp in seconds, matching {@link timestampInSeconds}.
*
* Corrects for clock drift via browserPerformanceTimeOrigin().
*
* Pass `entryStartTimeInMs` (also a `performance.now()` based time) to use the time origin that was valid at the entry's
* start. Use it for all timings of one entry, so its duration stays correct.
*
* Returns `undefined` if the Performance API is unavailable.
*/
function performanceTimeToSeconds(monotonicTimeInMs, entryStartTimeInMs = monotonicTimeInMs) {
	const origin = browserPerformanceTimeOrigin(entryStartTimeInMs);
	return origin == null ? void 0 : (origin + monotonicTimeInMs) / ONE_SECOND_IN_MS;
}
/**
* Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
* availability of the Performance API.
*
* If the Performance API time and `Date.now()` differ by more than {@link CLOCK_DRIFT_THRESHOLD_MS} (e.g. after the
* device slept), the time origin is corrected based on `Date.now()`.
* See https://github.com/getsentry/sentry-javascript/issues/2590.
*/
function timestampInSeconds() {
	return (_cachedTimestampInSecondsFn ?? (_cachedTimestampInSecondsFn = createUnixTimestampInSecondsFunc()))();
}
/**
* Returns the time origin in milliseconds that was valid at the given `performance.now()` time. Defaults to the page
* load origin.
*
* Pass the time you want to convert, so entries that are reported late (e.g. INP on pagehide) are not shifted by a
* drift that happened after they were recorded. Use the same time for all timings of one entry to keep its duration.
*
* Returns `undefined` if the Performance API is unavailable.
*/
function browserPerformanceTimeOrigin(monotonicTimeInMs = 0) {
	if (!_checkedForDriftInThisTask) {
		_checkedForDriftInThisTask = true;
		Promise.resolve().then(() => {
			_checkedForDriftInThisTask = false;
		});
		timestampInSeconds();
	}
	let segment;
	for (const candidate of _timeOriginSegments) {
		if (segment && candidate.from > monotonicTimeInMs) break;
		segment = candidate;
	}
	return segment?.origin;
}
// src/session.ts
/**
* Creates a new `Session` object by setting certain default parameters. If optional @param context
* is passed, the passed properties are applied to the session object.
*
* @param context (optional) additional properties to be applied to the returned session object
*
* @returns a new `Session` object
*/
function makeSession(context) {
	const startingTime = timestampInSeconds();
	const session = {
		sid: uuid4(),
		init: true,
		timestamp: startingTime,
		started: startingTime,
		duration: 0,
		status: "ok",
		errors: 0,
		ignoreDuration: false,
		toJSON: () => sessionToJSON(session)
	};
	if (context) updateSession(session, context);
	return session;
}
/**
* Updates a session object with the properties passed in the context.
*
* Note that this function mutates the passed object and returns void.
* (Had to do this instead of returning a new and updated session because closing and sending a session
* makes an update to the session after it was passed to the sending logic.
* @see Client.captureSession )
*
* @param session the `Session` to update
* @param context the `SessionContext` holding the properties that should be updated in @param session
*/
function updateSession(session, context = {}) {
	if (context.user) {
		if (!session.ipAddress && context.user.ip_address) session.ipAddress = context.user.ip_address;
		if (!session.did && !context.did) session.did = context.user.id || context.user.email || context.user.username;
	}
	session.timestamp = context.timestamp || timestampInSeconds();
	if (context.abnormal_mechanism) session.abnormal_mechanism = context.abnormal_mechanism;
	if (context.ignoreDuration) session.ignoreDuration = context.ignoreDuration;
	if (context.sid) session.sid = context.sid.length === 32 ? context.sid : uuid4();
	if (context.init !== void 0) session.init = context.init;
	if (!session.did && context.did) session.did = `${context.did}`;
	if (typeof context.started === "number") session.started = context.started;
	if (session.ignoreDuration) session.duration = void 0;
	else if (typeof context.duration === "number") session.duration = context.duration;
	else {
		const duration = session.timestamp - session.started;
		session.duration = duration >= 0 ? duration : 0;
	}
	if (context.release) session.release = context.release;
	if (context.environment) session.environment = context.environment;
	if (!session.ipAddress && context.ipAddress) session.ipAddress = context.ipAddress;
	if (!session.userAgent && context.userAgent) session.userAgent = context.userAgent;
	if (typeof context.errors === "number") session.errors = context.errors;
	if (context.status) session.status = context.status;
}
/**
* Closes a session by setting its status and updating the session object with it.
* Internally calls `updateSession` to update the passed session object.
*
* Note that this function mutates the passed session (@see updateSession for explanation).
*
* @param session the `Session` object to be closed
* @param status the `SessionStatus` with which the session was closed. If you don't pass a status,
*               this function will keep the previously set status, unless it was `'ok'` in which case
*               it is changed to `'exited'`.
*/
function closeSession(session, status) {
	let context = {};
	if (status) context = { status };
	else if (session.status === "ok") context = { status: "exited" };
	updateSession(session, context);
}
/**
* Serializes a passed session object to a JSON object with a slightly different structure.
* This is necessary because the Sentry backend requires a slightly different schema of a session
* than the one the JS SDKs use internally.
*
* @param session the session to be converted
*
* @returns a JSON object of the passed session
*/
function sessionToJSON(session) {
	return {
		sid: `${session.sid}`,
		init: session.init,
		started: (/* @__PURE__ */ new Date(session.started * 1e3)).toISOString(),
		timestamp: (/* @__PURE__ */ new Date(session.timestamp * 1e3)).toISOString(),
		status: session.status,
		errors: session.errors,
		did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
		duration: session.duration,
		abnormal_mechanism: session.abnormal_mechanism,
		attrs: {
			release: session.release,
			environment: session.environment,
			ip_address: session.ipAddress,
			user_agent: session.userAgent
		}
	};
}
// src/utils/merge.ts
/**
* Shallow merge two objects.
* Does not mutate the passed in objects.
* Undefined/empty values in the merge object will overwrite existing values.
*
* By default, this merges 2 levels deep.
*/
function merge(initialObj, mergeObj, levels = 2) {
	if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) return mergeObj;
	if (initialObj && Object.keys(mergeObj).length === 0) return initialObj;
	const output = { ...initialObj };
	for (const key in mergeObj) if (Object.prototype.hasOwnProperty.call(mergeObj, key)) output[key] = merge(output[key], mergeObj[key], levels - 1);
	return output;
}
// src/utils/propagationContext.ts
/**
* Generate a random, valid trace ID.
*/
function generateTraceId() {
	return uuid4();
}
/**
* Generate a random, valid span ID.
*/
function generateSpanId() {
	return uuid4().substring(16);
}
// src/scope.ts
/**
* Default value for maximum number of breadcrumbs added to an event.
*/
const DEFAULT_MAX_BREADCRUMBS = 100;
/**
* Holds additional event information.
*/
var Scope = class Scope {
	constructor() {
		this._notifyingListeners = false;
		this._scopeListeners = [];
		this._eventProcessors = [];
		this._breadcrumbs = [];
		this._attachments = [];
		this._user = {};
		this._tags = {};
		this._attributes = {};
		this._extra = {};
		this._contexts = {};
		this._sdkProcessingMetadata = {};
		addNonEnumerableProperty(this, "refs", {});
		this._propagationContext = {
			traceId: generateTraceId(),
			sampleRand: safeMathRandom()
		};
	}
	/**
	* Clone all data from this scope into a new scope.
	*/
	clone() {
		const newScope = new Scope();
		newScope._breadcrumbs = [...this._breadcrumbs];
		newScope._tags = { ...this._tags };
		newScope._attributes = { ...this._attributes };
		newScope._extra = { ...this._extra };
		newScope._contexts = { ...this._contexts };
		if (this._contexts.flags) newScope._contexts.flags = { values: [...this._contexts.flags.values] };
		newScope._user = this._user;
		newScope._level = this._level;
		newScope._session = this._session;
		newScope._transactionName = this._transactionName;
		newScope._fingerprint = this._fingerprint;
		newScope._eventProcessors = [...this._eventProcessors];
		newScope._attachments = [...this._attachments];
		newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
		newScope._propagationContext = { ...this._propagationContext };
		newScope._client = this._client;
		newScope._lastEventId = this._lastEventId;
		newScope._conversationId = this._conversationId;
		newScope.refs = { ...this.refs };
		return newScope;
	}
	/**
	* Update the client assigned to this scope.
	* Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,
	* as well as manually created scopes.
	*/
	setClient(client) {
		this._client = client;
	}
	/**
	* Set the ID of the last captured error event.
	* This is generally only captured on the isolation scope.
	*/
	setLastEventId(lastEventId) {
		this._lastEventId = lastEventId;
	}
	/**
	* Get the client assigned to this scope.
	*/
	getClient() {
		return this._client;
	}
	/**
	* Get the ID of the last captured error event.
	* This is generally only available on the isolation scope.
	*/
	lastEventId() {
		return this._lastEventId;
	}
	/**
	* @inheritDoc
	*/
	addScopeListener(callback) {
		this._scopeListeners.push(callback);
	}
	/**
	* Add an event processor that will be called before an event is sent.
	*/
	addEventProcessor(callback) {
		this._eventProcessors.push(callback);
		return this;
	}
	/**
	* Set the user for this scope.
	* Set to `null` to unset the user.
	*/
	setUser(user) {
		this._user = user || {
			email: void 0,
			id: void 0,
			ip_address: void 0,
			username: void 0
		};
		if (this._session) updateSession(this._session, { user });
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Get the user from this scope.
	*/
	getUser() {
		return this._user;
	}
	/**
	* Set the conversation ID for this scope.
	* Set to `null` to unset the conversation ID.
	*/
	setConversationId(conversationId) {
		this._conversationId = conversationId || void 0;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Set an object that will be merged into existing tags on the scope,
	* and will be sent as tags data with the event.
	*/
	setTags(tags) {
		this._tags = {
			...this._tags,
			...tags
		};
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Set a single tag that will be sent as tags data with the event.
	*/
	setTag(key, value) {
		return this.setTags({ [key]: value });
	}
	/**
	* Sets attributes onto the scope.
	*
	* These attributes are applied to logs, metrics and streamed spans.
	*
	* Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.
	*
	* @param newAttributes - The attributes to set on the scope, as key-value pairs.
	*
	* @example
	* ```typescript
	* scope.setAttributes({
	*   is_admin: true,
	*   payment_selection: 'credit_card',
	*   render_duration: 150,
	* });
	* ```
	*/
	setAttributes(newAttributes) {
		this._attributes = {
			...this._attributes,
			...newAttributes
		};
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Sets an attribute onto the scope.
	*
	* These attributes are applied to logs, metrics and streamed spans.
	*
	* Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.
	*
	* @param key - The attribute key.
	* @param value - The attribute value.
	*
	* @example
	* ```typescript
	* scope.setAttribute('is_admin', true);
	* scope.setAttribute('render_duration', 150);
	* ```
	*/
	setAttribute(key, value) {
		return this.setAttributes({ [key]: value });
	}
	/**
	* Removes the attribute with the given key from the scope.
	*
	* @param key - The attribute key.
	*
	* @example
	* ```typescript
	* scope.removeAttribute('is_admin');
	* ```
	*/
	removeAttribute(key) {
		if (key in this._attributes) {
			delete this._attributes[key];
			this._notifyScopeListeners();
		}
		return this;
	}
	/**
	* Set an object that will be merged into existing extra on the scope,
	* and will be sent as extra data with the event.
	*/
	setExtras(extras) {
		this._extra = {
			...this._extra,
			...extras
		};
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Set a single key:value extra entry that will be sent as extra data with the event.
	*/
	setExtra(key, extra) {
		this._extra = {
			...this._extra,
			[key]: extra
		};
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Sets the fingerprint on the scope to send with the events.
	* @param {string[]} fingerprint Fingerprint to group events in Sentry.
	*/
	setFingerprint(fingerprint) {
		this._fingerprint = fingerprint;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Sets the level on the scope for future events.
	*/
	setLevel(level) {
		this._level = level;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Sets the transaction name on the scope so that the name of e.g. taken server route or
	* the page location is attached to future events.
	*
	* IMPORTANT: Calling this function does NOT change the name of the currently active
	* root span. If you want to change the name of the active root span, use
	* `Sentry.updateSpanName(rootSpan, 'new name')` instead.
	*
	* By default, the SDK updates the scope's transaction name automatically on sensible
	* occasions, such as a page navigation or when handling a new request on the server.
	*/
	setTransactionName(name) {
		this._transactionName = name;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Sets context data with the given name.
	* Data passed as context will be normalized. You can also pass `null` to unset the context.
	* Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.
	*/
	setContext(key, context) {
		if (context === null) delete this._contexts[key];
		else this._contexts[key] = context;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Set the session for the scope.
	*/
	setSession(session) {
		if (!session) delete this._session;
		else this._session = session;
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Get the session from the scope.
	*/
	getSession() {
		return this._session;
	}
	/**
	* Updates the scope with provided data. Can work in three variations:
	* - plain object containing updatable attributes
	* - Scope instance that'll extract the attributes from
	* - callback function that'll receive the current scope as an argument and allow for modifications
	*/
	update(captureContext) {
		if (!captureContext) return this;
		const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
		const { tags, attributes, extra, user, contexts, level, fingerprint = [], propagationContext, conversationId } = (scopeToMerge instanceof Scope ? scopeToMerge.getScopeData() : isPlainObject(scopeToMerge) ? captureContext : void 0) || {};
		this._tags = {
			...this._tags,
			...tags
		};
		this._attributes = {
			...this._attributes,
			...attributes
		};
		this._extra = {
			...this._extra,
			...extra
		};
		this._contexts = {
			...this._contexts,
			...contexts
		};
		if (user && Object.keys(user).length) this._user = user;
		if (level) this._level = level;
		if (fingerprint.length) this._fingerprint = fingerprint;
		if (propagationContext) this._propagationContext = propagationContext;
		if (conversationId) this._conversationId = conversationId;
		return this;
	}
	/**
	* Adds a breadcrumb to the scope.
	* By default, the last 100 breadcrumbs are kept.
	*/
	addBreadcrumb(breadcrumb, maxBreadcrumbs) {
		const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
		if (maxCrumbs <= 0) return this;
		const mergedBreadcrumb = {
			timestamp: dateTimestampInSeconds(),
			...breadcrumb,
			message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message
		};
		this._breadcrumbs.push(mergedBreadcrumb);
		if (this._breadcrumbs.length > maxCrumbs) this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Get the last breadcrumb of the scope.
	*/
	getLastBreadcrumb() {
		return this._breadcrumbs[this._breadcrumbs.length - 1];
	}
	/**
	* Clear all breadcrumbs from the scope.
	*/
	clearBreadcrumbs() {
		this._breadcrumbs = [];
		this._notifyScopeListeners();
		return this;
	}
	/**
	* Add an attachment to the scope.
	*/
	addAttachment(attachment) {
		this._attachments.push(attachment);
		return this;
	}
	/**
	* Clear all attachments from the scope.
	*/
	clearAttachments() {
		this._attachments = [];
		return this;
	}
	/**
	* Get the data of this scope, which should be applied to an event during processing.
	*/
	getScopeData() {
		return {
			breadcrumbs: this._breadcrumbs,
			attachments: this._attachments,
			contexts: this._contexts,
			tags: this._tags,
			attributes: this._attributes,
			extra: this._extra,
			user: this._user,
			level: this._level,
			fingerprint: this._fingerprint || [],
			eventProcessors: this._eventProcessors,
			propagationContext: this._propagationContext,
			sdkProcessingMetadata: this._sdkProcessingMetadata,
			transactionName: this._transactionName,
			conversationId: this._conversationId
		};
	}
	/**
	* Add data which will be accessible during event processing but won't get sent to Sentry.
	*/
	setSDKProcessingMetadata(newData) {
		this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);
		return this;
	}
	/**
	* Add propagation context to the scope, used for distributed tracing
	*/
	setPropagationContext(context) {
		this._propagationContext = context;
		return this;
	}
	/**
	* Get propagation context from the scope, used for distributed tracing
	*/
	getPropagationContext() {
		return this._propagationContext;
	}
	/**
	* Capture an exception for this scope.
	*
	* @returns {string} The id of the captured Sentry event.
	*/
	captureException(exception, hint) {
		const eventId = hint?.event_id || uuid4();
		if (!this._client) {
			DEBUG_BUILD && debug.warn("No client configured on scope - will not capture exception!");
			return eventId;
		}
		const syntheticException = /* @__PURE__ */ new Error("Sentry syntheticException");
		this._client.captureException(exception, {
			originalException: exception,
			syntheticException,
			...hint,
			event_id: eventId
		}, this);
		return eventId;
	}
	/**
	* Capture a message for this scope.
	*
	* @returns {string} The id of the captured message.
	*/
	captureMessage(message, level, hint) {
		const eventId = hint?.event_id || uuid4();
		if (!this._client) {
			DEBUG_BUILD && debug.warn("No client configured on scope - will not capture message!");
			return eventId;
		}
		const syntheticException = hint?.syntheticException ?? new Error(message);
		this._client.captureMessage(message, level, {
			originalException: message,
			syntheticException,
			...hint,
			event_id: eventId
		}, this);
		return eventId;
	}
	/**
	* Capture a Sentry event for this scope.
	*
	* @returns {string} The id of the captured event.
	*/
	captureEvent(event, hint) {
		const eventId = event.event_id || hint?.event_id || uuid4();
		if (!this._client) {
			DEBUG_BUILD && debug.warn("No client configured on scope - will not capture event!");
			return eventId;
		}
		this._client.captureEvent(event, {
			...hint,
			event_id: eventId
		}, this);
		return eventId;
	}
	/**
	* This will be called on every set call.
	*/
	_notifyScopeListeners() {
		if (!this._notifyingListeners) {
			this._notifyingListeners = true;
			this._scopeListeners.forEach((callback) => {
				callback(this);
			});
			this._notifyingListeners = false;
		}
	}
};
// src/defaultScopes.ts
/** Get the default current scope. */
function getDefaultCurrentScope() {
	return getGlobalSingleton("defaultCurrentScope", () => new Scope());
}
/** Get the default isolation scope. */
function getDefaultIsolationScope() {
	return getGlobalSingleton("defaultIsolationScope", () => new Scope());
}
// src/tracing/constants.ts
const SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__";
// src/utils/chain-and-copy-promiselike.ts
const isActualPromise = (p) => p instanceof Promise && !p[kChainedCopy];
const kChainedCopy = Symbol("chained PromiseLike");
/**
* Copy the properties from a decorated promiselike object onto its chained
* actual promise.
*/
const chainAndCopyPromiseLike = (original, onSuccess, onError) => {
	const chained = original.then((value) => {
		onSuccess(value);
		return value;
	}, (err) => {
		onError(err);
		throw err;
	});
	return isActualPromise(chained) && isActualPromise(original) ? chained : copyProps(original, chained);
};
const copyProps = (original, chained) => {
	if (!chained) return original;
	let mutated = false;
	for (const key in original) {
		if (key in chained) continue;
		mutated = true;
		const value = original[key];
		if (typeof value === "function") Object.defineProperty(chained, key, {
			value: (...args) => value.apply(original, args),
			enumerable: true,
			configurable: true,
			writable: true
		});
		else chained[key] = value;
	}
	if (mutated) Object.assign(chained, { [kChainedCopy]: true });
	return chained;
};
// src/asyncContext/stackStrategy.ts
/**
* This is an object that holds a stack of scopes.
*/
var AsyncContextStack = class {
	constructor(scope, isolationScope) {
		let assignedScope;
		if (!scope) assignedScope = new Scope();
		else assignedScope = scope;
		let assignedIsolationScope;
		if (!isolationScope) assignedIsolationScope = new Scope();
		else assignedIsolationScope = isolationScope;
		this._stack = [{ scope: assignedScope }];
		this._isolationScope = assignedIsolationScope;
	}
	/**
	* Fork a scope for the stack.
	*/
	withScope(callback) {
		const scope = this._pushScope();
		let maybePromiseResult;
		try {
			maybePromiseResult = callback(scope);
		} catch (e) {
			this._popScope();
			throw e;
		}
		if (isThenable(maybePromiseResult)) return chainAndCopyPromiseLike(maybePromiseResult, () => this._popScope(), () => this._popScope());
		this._popScope();
		return maybePromiseResult;
	}
	/**
	* Get the client of the stack.
	*/
	getClient() {
		return this.getStackTop().client;
	}
	/**
	* Returns the scope of the top stack.
	*/
	getScope() {
		return this.getStackTop().scope;
	}
	/**
	* Get the isolation scope for the stack.
	*/
	getIsolationScope() {
		return this._isolationScope;
	}
	/**
	* Returns the topmost scope layer in the order domain > local > process.
	*/
	getStackTop() {
		return this._stack[this._stack.length - 1];
	}
	/**
	* Push a scope to the stack.
	*/
	_pushScope() {
		const scope = this.getScope().clone();
		this._stack.push({
			client: this.getClient(),
			scope
		});
		return scope;
	}
	/**
	* Pop a scope from the stack.
	*/
	_popScope() {
		if (this._stack.length <= 1) return false;
		return !!this._stack.pop();
	}
};
/**
* Get the global async context stack.
* This will be removed during the v8 cycle and is only here to make migration easier.
*/
function getAsyncContextStack() {
	const sentry = getSentryCarrier(getMainCarrier());
	return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());
}
function withScope$1(callback) {
	return getAsyncContextStack().withScope(callback);
}
function withSetScope(scope, callback) {
	const stack = getAsyncContextStack();
	return stack.withScope(() => {
		stack.getStackTop().scope = scope;
		return callback(scope);
	});
}
function withIsolationScope$1(callback) {
	return getAsyncContextStack().withScope(() => {
		return callback(getAsyncContextStack().getIsolationScope());
	});
}
/**
* Get the stack-based async context strategy.
*/
function getStackAsyncContextStrategy() {
	return {
		suppressTracing: suppressTracingInStack,
		withIsolationScope: withIsolationScope$1,
		withScope: withScope$1,
		withSetScope,
		withSetIsolationScope: (_isolationScope, callback) => {
			return withIsolationScope$1(callback);
		},
		getCurrentScope: () => getAsyncContextStack().getScope(),
		getIsolationScope: () => getAsyncContextStack().getIsolationScope()
	};
}
/**
* In stack-based ACS, we do not wait for the callback to finish before we reset the metadata
* the reason for this is that otherwise, in the stack this can lead to very weird behavior
* as there is only a single top scope, if the callback takes longer to finish,
* other, unrelated spans may also be suppressed, which we do not want
* so instead, we only suppress tracing synchronoysly in the stack.
*/
function suppressTracingInStack(callback) {
	return withScope$1((scope) => {
		scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });
		const res = callback();
		scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: void 0 });
		return res;
	});
}
// src/asyncContext/index.ts
/**
* @private Private API with no semver guarantees!
*
* Sets the global async context strategy
*/
function setAsyncContextStrategy(strategy) {
	const sentry = getSentryCarrier(getMainCarrier());
	sentry.acs = strategy;
}
/**
* Get the current async context strategy.
* If none has been setup, the default will be used.
*/
function getAsyncContextStrategy(carrier) {
	const sentry = getSentryCarrier(carrier);
	if (sentry.acs) return sentry.acs;
	return getStackAsyncContextStrategy();
}
// src/attributes.ts
/**
* Type-guard: The attribute object has the shape the official attribute object (value, type, unit).
* https://develop.sentry.dev/sdk/telemetry/scopes/#setting-attributes
*/
function isAttributeObject(maybeObj) {
	return typeof maybeObj === "object" && maybeObj != null && !Array.isArray(maybeObj) && Object.keys(maybeObj).includes("value");
}
/**
* Converts an attribute value to a typed attribute value.
*
* For now, we support primitive values and arrays, either raw or inside attribute objects.
* If @param useFallback is true, we stringify other non-primitive values to a string attribute
* value. Otherwise we return `undefined` for unsupported values.
*
* @param value - The value of the passed attribute.
* @param useFallback - If true, unsupported values will be stringified to a string attribute value.
*                      Defaults to false. In this case, `undefined` is returned for unsupported values.
* @returns The typed attribute.
*/
function attributeValueToTypedAttributeValue(rawValue, useFallback) {
	const { value, unit } = isAttributeObject(rawValue) ? rawValue : {
		value: rawValue,
		unit: void 0
	};
	const attributeValue = getTypedAttributeValue(value);
	const checkedUnit = unit && typeof unit === "string" ? { unit } : {};
	if (attributeValue) return {
		...attributeValue,
		...checkedUnit
	};
	if (!useFallback || useFallback === "skip-undefined" && value === void 0) return;
	let stringValue = "";
	try {
		stringValue = JSON.stringify(value) ?? "";
	} catch {}
	return {
		value: stringValue,
		type: "string",
		...checkedUnit
	};
}
/**
* Serializes raw attributes to typed attributes as expected in our envelopes.
*
* @param attributes The raw attributes to serialize.
* @param fallback   If true, unsupported values will be stringified to a string attribute value.
*                   Defaults to false. In this case, `undefined` is returned for unsupported values.
*
* @returns The serialized attributes.
*/
function serializeAttributes(attributes, fallback = false) {
	const serializedAttributes = {};
	for (const [key, value] of Object.entries(attributes ?? {})) {
		const typedValue = attributeValueToTypedAttributeValue(value, fallback);
		if (typedValue) serializedAttributes[key] = typedValue;
	}
	return serializedAttributes;
}
/**
* Estimates the serialized byte size of {@link Attributes},
* with a couple of heuristics for performance.
*/
function estimateTypedAttributesSizeInBytes(attributes) {
	if (!attributes) return 0;
	let weight = 0;
	for (const [key, attr] of Object.entries(attributes)) {
		weight += key.length * 2;
		weight += attr.type.length * 2;
		weight += (attr.unit?.length ?? 0) * 2;
		const val = attr.value;
		if (Array.isArray(val)) weight += estimatePrimitiveSizeInBytes(val[0]) * val.length;
		else if (isPrimitive(val)) weight += estimatePrimitiveSizeInBytes(val);
		else weight += 100;
	}
	return weight;
}
function estimatePrimitiveSizeInBytes(value) {
	if (typeof value === "string") return value.length * 2;
	else if (typeof value === "boolean") return 4;
	else if (typeof value === "number") return 8;
	return 0;
}
/**
* NOTE: We return typed attributes for primitives and arrays:
*  - Relay currently only supports arrays consisting of primitive values. Attributes with non-conforming arrays are dropped by Relay, so runtime type validation in the SDK is unnecessary.
*  - Objects are not supported yet and product support is still TBD.
*/
function getTypedAttributeValue(value) {
	if (Array.isArray(value)) return {
		value,
		type: "array"
	};
	const primitiveType = typeof value === "string" ? "string" : typeof value === "boolean" ? "boolean" : typeof value === "number" && !Number.isNaN(value) ? Number.isInteger(value) ? "integer" : "double" : null;
	if (primitiveType) return {
		value,
		type: primitiveType
	};
}
// src/currentScopes.ts
/**
* Register an external propagation context provider function.
* When registered, trace context will be read from the external source (e.g. OpenTelemetry)
* instead of from the Sentry scope's propagation context.
*/
function registerExternalPropagationContext(fn) {
	getSentryCarrier(getMainCarrier()).externalPropagationContextProvider = fn;
}
/**
* Get the external propagation context, if a provider has been registered.
*/
function getExternalPropagationContext() {
	return getSentryCarrier(getMainCarrier()).externalPropagationContextProvider?.();
}
/**
* Check if an external propagation context provider has been registered.
*/
function hasExternalPropagationContext() {
	return getSentryCarrier(getMainCarrier()).externalPropagationContextProvider !== void 0;
}
/**
* Get the currently active scope.
*/
function getCurrentScope() {
	return getAsyncContextStrategy(getMainCarrier()).getCurrentScope();
}
/**
* Get the currently active isolation scope.
* The isolation scope is active for the current execution context.
*/
function getIsolationScope() {
	return getAsyncContextStrategy(getMainCarrier()).getIsolationScope();
}
/**
* Get the global scope.
* This scope is applied to _all_ events.
*/
function getGlobalScope() {
	return getGlobalSingleton("globalScope", () => new Scope());
}
/**
* Either creates a new active scope, or sets the given scope as active scope in the given callback.
*/
function withScope(...rest) {
	const acs = getAsyncContextStrategy(getMainCarrier());
	if (rest.length === 2) {
		const [scope, callback] = rest;
		if (!scope) return acs.withScope(callback);
		return acs.withSetScope(scope, callback);
	}
	return acs.withScope(rest[0]);
}
/**
* Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.
*/
function withIsolationScope(...rest) {
	const acs = getAsyncContextStrategy(getMainCarrier());
	if (rest.length === 2) {
		const [isolationScope, callback] = rest;
		if (!isolationScope) return acs.withIsolationScope(callback);
		return acs.withSetIsolationScope(isolationScope, callback);
	}
	return acs.withIsolationScope(rest[0]);
}
/**
* Get the currently active client.
*/
function getClient() {
	return getCurrentScope().getClient();
}
/**
* Get a trace context for the given scope.
*/
function getTraceContextFromScope(scope) {
	const externalContext = getExternalPropagationContext();
	if (externalContext) return {
		trace_id: externalContext.traceId,
		span_id: externalContext.spanId
	};
	const { traceId, parentSpanId, propagationSpanId } = scope.getPropagationContext();
	const traceContext = {
		trace_id: traceId,
		span_id: propagationSpanId || generateSpanId()
	};
	if (parentSpanId) traceContext.parent_span_id = parentSpanId;
	return traceContext;
}
// src/semanticAttributes.ts
/**
* Attributes that holds the sample rate that was locally applied to a span.
* If this attribute is not defined, it means that the span inherited a sampling decision.
*
* NOTE: Is only defined on root spans.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate";
/**
* Attribute holding the sample rate of the previous trace.
* This is used to sample consistently across subsequent traces in the browser SDK.
*
* Note: Only defined on root spans, if opted into consistent sampling
*/
const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = "sentry.previous_trace_sample_rate";
/**
* Use this attribute to represent the operation of a span.
* @deprecated Use `SENTRY_OP` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op";
/**
* Use this attribute to represent the origin of a span.
* @deprecated Use `SENTRY_ORIGIN` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin";
/**
* Holds the human-readable span status message (e.g. set via
* `span.setStatus({ code, message })`).
*
* Streamed (v2) span statuses are reduced to `ok`/`error`, so we preserve the
* message as an attribute instead of dropping it. This mirrors the attribute
* Sentry's OTLP ingestion uses for the same purpose.
* @deprecated Use `SENTRY_STATUS_MESSAGE` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE = "sentry.status.message";
/**
* The reason why an idle span finished.
* @deprecated Use `SENTRY_IDLE_SPAN_FINISH_REASON` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = "sentry.idle_span_finish_reason";
/** The unit of a measurement, which may be stored as a TimedEvent. */
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit";
/** The value of a measurement, which may be stored as a TimedEvent. */
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value";
/**
* The release version of the application
* @deprecated Use `SENTRY_RELEASE` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_RELEASE = "sentry.release";
/**
* The environment name (e.g., "production", "staging", "development")
* @deprecated Use `SENTRY_ENVIRONMENT` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT = "sentry.environment";
/**
* The segment name (e.g., "GET /users")
* @deprecated Use `SENTRY_SEGMENT_NAME` `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME = "sentry.segment.name";
/**
* The id of the segment that this span belongs to.
* @deprecated Use `SENTRY_SEGMENT_ID` `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID = "sentry.segment.id";
/**
* The name of the Sentry SDK (e.g., "sentry.php", "sentry.javascript")
* @deprecated Use `SENTRY_SDK_NAME` `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME = "sentry.sdk.name";
/**
* The version of the Sentry SDK
* @deprecated Use `SENTRY_SDK_VERSION` `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION = "sentry.sdk.version";
/**
* The list of integrations enabled in the Sentry SDK (e.g., ["EventFilters", "BrowserTracing"])
* @deprecated Use `SENTRY_SDK_INTEGRATIONS` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS = "sentry.sdk.integrations";
/**
* The user ID
* @deprecated Use `USER_ID` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_USER_ID = "user.id";
/**
* The user email
* @deprecated Use `USER_EMAIL` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_USER_EMAIL = "user.email";
/**
* The user IP address
* @deprecated Use `USER_IP_ADDRESS` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS = "user.ip_address";
/**
* The user username
* @deprecated Use `USER_NAME` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_USER_USERNAME = "user.name";
/**
* A custom span name set by users guaranteed to be taken over any automatically
* inferred name. This attribute is removed before the span is sent.
*
* @internal only meant for internal SDK usage
* @hidden
*/
const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name";
/**
* The id of the profile that this span occurred in.
* @deprecated Use `SENTRY_PROFILE_ID` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id";
/**
* @deprecated Use `SENTRY_EXCLUSIVE_TIME` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time";
/**
* @deprecated Use `CACHE_HIT` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_CACHE_HIT = "cache.hit";
/**
* @deprecated Use `CACHE_KEY` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_CACHE_KEY = "cache.key";
/**
* @deprecated Use `CACHE_ITEM_SIZE` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = "cache.item_size";
/**
* @deprecated Use `HTTP_REQUEST_METHOD` from `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = "http.request.method";
/**
* @deprecated Use `URL_FULL` `@sentry/conventions/attributes` instead.
*/
const SEMANTIC_ATTRIBUTE_URL_FULL = "url.full";
/**
* A span link attribute to mark the link as a special span link.
*
* Known values:
* - `previous_trace`: The span links to the frontend root span of the previous trace.
* - `next_trace`: The span links to the frontend root span of the next trace. (Not set by the SDK)
*
* Other values may be set as appropriate.
* @deprecated Use `SENTRY_LINK_TYPE` from `@sentry/conventions/attributes` instead.
* @see https://develop.sentry.dev/sdk/telemetry/traces/span-links/#link-types
*/
const SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = "sentry.link.type";
/**
* =============================================================================
* GEN AI ATTRIBUTES
* Based on OpenTelemetry Semantic Conventions for Generative AI
* @see https://opentelemetry.io/docs/specs/semconv/gen-ai/
* =============================================================================
*/
/**
* The conversation ID for linking messages across API calls.
* For OpenAI Assistants API: thread_id
* For LangGraph: configurable.thread_id
* @deprecated Use `GEN_AI_CONVERSATION_ID` from `@sentry/conventions/attributes` instead.
*/
const GEN_AI_CONVERSATION_ID_ATTRIBUTE = "gen_ai.conversation.id";
// src/types/spanStatus.ts
const SPAN_STATUS_TYPES = [
	"ok",
	"deadline_exceeded",
	"unauthenticated",
	"permission_denied",
	"not_found",
	"resource_exhausted",
	"invalid_argument",
	"unimplemented",
	"unavailable",
	"internal_error",
	"unknown_error",
	"cancelled",
	"already_exists",
	"failed_precondition",
	"aborted",
	"out_of_range",
	"data_loss"
];
// src/tracing/spanstatus.ts
const SPAN_STATUS_UNSET = 0;
const SPAN_STATUS_OK = 1;
const SPAN_STATUS_ERROR = 2;
function isStatusErrorMessageValid(message) {
	return message !== "ok" && SPAN_STATUS_TYPES.includes(message);
}
/**
* Converts a HTTP status code into a sentry status with a message.
*
* @param httpStatus The HTTP response status code.
* @returns The span status or internal_error.
*/
function getSpanStatusFromHttpCode(httpStatus) {
	if (httpStatus < 400 && httpStatus >= 100) return { code: 1 };
	if (httpStatus >= 400 && httpStatus < 500) switch (httpStatus) {
		case 401: return {
			code: 2,
			message: "unauthenticated"
		};
		case 403: return {
			code: 2,
			message: "permission_denied"
		};
		case 404: return {
			code: 2,
			message: "not_found"
		};
		case 409: return {
			code: 2,
			message: "already_exists"
		};
		case 413: return {
			code: 2,
			message: "failed_precondition"
		};
		case 429: return {
			code: 2,
			message: "resource_exhausted"
		};
		case 499: return {
			code: 2,
			message: "cancelled"
		};
		default: return {
			code: 2,
			message: "invalid_argument"
		};
	}
	if (httpStatus >= 500 && httpStatus < 600) switch (httpStatus) {
		case 501: return {
			code: 2,
			message: "unimplemented"
		};
		case 503: return {
			code: 2,
			message: "unavailable"
		};
		case 504: return {
			code: 2,
			message: "deadline_exceeded"
		};
		default: return {
			code: 2,
			message: "internal_error"
		};
	}
	return {
		code: 2,
		message: "internal_error"
	};
}
/**
* Sets the Http status attributes on the current span based on the http code.
* Additionally, the span's status is updated, depending on the http code.
*/
function setHttpStatus(span, httpStatus) {
	span.setAttribute(_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE, httpStatus);
	const spanStatus = getSpanStatusFromHttpCode(httpStatus);
	if (spanStatus.message !== "unknown_error") span.setStatus(spanStatus);
}
// src/utils/weakRef.ts
/**
* Creates a weak reference to an object if WeakRef is available,
* otherwise returns the object directly.
*
* This is useful for breaking circular references while maintaining
* compatibility with environments that don't support WeakRef (e.g., older browsers).
*
* @param value - The object to create a weak reference to
* @returns A WeakRef wrapper if available, or the original object as fallback
*/
function makeWeakRef(value) {
	try {
		const WeakRefImpl = GLOBAL_OBJ.WeakRef;
		if (typeof WeakRefImpl === "function") return new WeakRefImpl(value);
	} catch {}
	return value;
}
/**
* Resolves a potentially weak reference, returning the underlying object
* or undefined if the reference has been garbage collected.
*
* @param ref - A MaybeWeakRef or undefined
* @returns The referenced object, or undefined if GC'd or ref was undefined
*/
function derefWeakRef(ref) {
	if (!ref) return;
	if (typeof ref === "object" && "deref" in ref && typeof ref.deref === "function") try {
		return ref.deref();
	} catch {
		return;
	}
	return ref;
}
// src/tracing/utils.ts
const SCOPE_ON_START_SPAN_FIELD = "_sentryScope";
const ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope";
const TRACER_PROVIDER_SPAN_FIELD = Symbol.for("sentry.tracerProviderSpan");
/** Store the scope & isolation scope for a span, which can the be used when it is finished. */
function setCapturedScopesOnSpan(span, scope, isolationScope) {
	if (span) {
		addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, makeWeakRef(isolationScope));
		addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
	}
}
/**
* Grabs the scope and isolation scope off a span that were active when the span was started.
* If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.
*/
function getCapturedScopesOnSpan(span) {
	const spanWithScopes = span;
	return {
		scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],
		isolationScope: derefWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD])
	};
}
/**
* Mark a span as created by the `SentryTracerProvider` (via the OTel tracer). Set by `SentryTracer`
* on every span it creates; read by `SentrySpan.end()` to seal the span against further writes once
* it has ended, mirroring OTel SDK spans (which are immutable after `end()`).
*/
function markSpanAsTracerProviderSpan(span) {
	addNonEnumerableProperty(span, TRACER_PROVIDER_SPAN_FIELD, true);
}
/** Whether a span was created by the `SentryTracerProvider` (see {@link markSpanAsTracerProviderSpan}). */
function spanIsTracerProviderSpan(span) {
	return span[TRACER_PROVIDER_SPAN_FIELD] === true;
}
// src/utils/baggage.ts
const SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
/**
* Max length of a serialized baggage string
*
* https://www.w3.org/TR/baggage/#limits
*/
const MAX_BAGGAGE_STRING_LENGTH = 8192;
/**
* Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values
* from it.
*
* @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.
* @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.
*/
function baggageHeaderToDynamicSamplingContext(baggageHeader) {
	const baggageObject = parseBaggageHeader(baggageHeader);
	if (!baggageObject) return;
	const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
		if (key.startsWith("sentry-")) {
			const nonPrefixedKey = key.slice(7);
			acc[nonPrefixedKey] = value;
		}
		return acc;
	}, {});
	if (Object.keys(dynamicSamplingContext).length > 0) return dynamicSamplingContext;
	else return;
}
/**
* Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-".
*
* @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility
* with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is
* `undefined` the function will return `undefined`.
* @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`
* was `undefined`, or if `dynamicSamplingContext` didn't contain any values.
*/
function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {
	if (!dynamicSamplingContext) return;
	return objectToBaggageHeader(Object.entries(dynamicSamplingContext).reduce((acc, [dscKey, dscValue]) => {
		if (dscValue) acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;
		return acc;
	}, {}));
}
/**
* Take a baggage header and parse it into an object.
*/
function parseBaggageHeader(baggageHeader) {
	if (!baggageHeader || !isString(baggageHeader) && !Array.isArray(baggageHeader)) return;
	if (Array.isArray(baggageHeader)) return baggageHeader.reduce((acc, curr) => {
		const currBaggageObject = baggageHeaderToObject(curr);
		Object.entries(currBaggageObject).forEach(([key, value]) => {
			acc[key] = value;
		});
		return acc;
	}, {});
	return baggageHeaderToObject(baggageHeader);
}
/**
* Will parse a baggage header, which is a simple key-value map, into a flat object.
*
* @param baggageHeader The baggage header to parse.
* @returns a flat object containing all the key-value pairs from `baggageHeader`.
*/
function baggageHeaderToObject(baggageHeader) {
	return baggageHeader.split(",").map((baggageEntry) => {
		const eqIdx = baggageEntry.indexOf("=");
		if (eqIdx === -1) return [];
		return [baggageEntry.slice(0, eqIdx), baggageEntry.slice(eqIdx + 1)].map((keyOrValue) => {
			try {
				return decodeURIComponent(keyOrValue.trim());
			} catch {
				return;
			}
		});
	}).reduce((acc, [key, value]) => {
		if (key && value) acc[key] = value;
		return acc;
	}, {});
}
/**
* Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.
*
* @param object The object to turn into a baggage header.
* @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header
* is not spec compliant.
*/
function objectToBaggageHeader(object) {
	if (Object.keys(object).length === 0) return;
	return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {
		const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;
		const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;
		if (newBaggageHeader.length > 8192) {
			DEBUG_BUILD && debug.warn(`Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`);
			return baggageHeader;
		} else return newBaggageHeader;
	}, "");
}
/**
* Merge two baggage headers into one.
* - Sentry-specific entries (keys starting with "sentry-") from the new
*   baggage take precedence
* - Non-Sentry entries from existing baggage take precedence
*
* The order of the existing baggage will be preserved, and new entries will
* be added to the end.
*
* This matches the behavior of OTEL's propagation.inject() which uses
* `baggage.setEntry()`  to overwrite existing entries with the same key.
*/
function mergeBaggageHeaders(existing, incoming) {
	if (!existing) return incoming;
	const existingEntries = parseBaggageHeader(existing);
	const incomingEntries = parseBaggageHeader(incoming);
	if (!incomingEntries) return existing;
	const merged = {};
	let hasNewSentryEntries = false;
	const newSentryEntries = {};
	const newNonSentryEntries = {};
	for (const [key, value] of Object.entries(incomingEntries)) if (key.startsWith("sentry-")) {
		newSentryEntries[key] = value;
		hasNewSentryEntries = true;
	} else newNonSentryEntries[key] = value;
	if (existingEntries) {
		for (const [key, value] of Object.entries(existingEntries)) if (!hasNewSentryEntries || !key.startsWith("sentry-")) merged[key] = value;
	}
	if (hasNewSentryEntries) Object.assign(merged, newSentryEntries);
	for (const [key, value] of Object.entries(newNonSentryEntries)) merged[key] ?? (merged[key] = value);
	return objectToBaggageHeader(merged);
}
// src/utils/dsn.ts
/** Regular expression used to extract org ID from a DSN host. */
const ORG_ID_REGEX = /^o(\d+)\./;
/** Regular expression used to parse a Dsn. */
const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) {
	return protocol === "http" || protocol === "https";
}
/**
* Renders the string representation of this Dsn.
*
* By default, this will render the public representation without the password
* component. To get the deprecated private representation, set `withPassword`
* to true.
*
* @param withPassword When set to true, the password will be included.
*/
function dsnToString(dsn, withPassword = false) {
	const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
	return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`;
}
/**
* Parses a Dsn from a given string.
*
* @param str A Dsn as string
* @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string
*/
function dsnFromString(str) {
	const match = DSN_REGEX.exec(str);
	if (!match) {
		consoleSandbox(() => {
			console.error(`Invalid Sentry Dsn: ${str}`);
		});
		return;
	}
	const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match.slice(1);
	let path = "";
	let projectId = lastPath;
	const split = projectId.split("/");
	if (split.length > 1) {
		path = split.slice(0, -1).join("/");
		projectId = split.pop();
	}
	if (projectId) {
		const projectMatch = projectId.match(/^\d+/);
		if (projectMatch) projectId = projectMatch[0];
	}
	return dsnFromComponents({
		host,
		pass,
		path,
		projectId,
		port,
		protocol,
		publicKey
	});
}
function dsnFromComponents(components) {
	return {
		protocol: components.protocol,
		publicKey: components.publicKey || "",
		pass: components.pass || "",
		host: components.host,
		port: components.port || "",
		path: components.path || "",
		projectId: components.projectId
	};
}
function validateDsn(dsn) {
	if (!DEBUG_BUILD) return true;
	const { port, projectId, protocol } = dsn;
	if ([
		"protocol",
		"publicKey",
		"host",
		"projectId"
	].find((component) => {
		if (!dsn[component]) {
			debug.error(`Invalid Sentry Dsn: ${component} missing`);
			return true;
		}
		return false;
	})) return false;
	if (!projectId.match(/^\d+$/)) {
		debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
		return false;
	}
	if (!isValidProtocol(protocol)) {
		debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
		return false;
	}
	if (port && isNaN(parseInt(port, 10))) {
		debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);
		return false;
	}
	return true;
}
/**
* Extract the org ID from a DSN host.
*
* @param host The host from a DSN
* @returns The org ID if found, undefined otherwise
*/
function extractOrgIdFromDsnHost(host) {
	return host.match(ORG_ID_REGEX)?.[1];
}
/**
*  Returns the organization ID of the client.
*
*  The organization ID is extracted from the DSN. If the client options include a `orgId`, this will always take precedence.
*/
function extractOrgIdFromClient(client) {
	const options = client.getOptions();
	const { host } = client.getDsn() || {};
	let org_id;
	if (options.orgId) org_id = String(options.orgId);
	else if (host) org_id = extractOrgIdFromDsnHost(host);
	return org_id;
}
/**
* Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
* @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source
*/
function makeDsn(from) {
	const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
	if (!components || !validateDsn(components)) return;
	return components;
}
// src/utils/parseSampleRate.ts
/**
* Parse a sample rate from a given value.
* This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).
* If a string is passed, we try to convert it to a number.
*
* Any invalid sample rate will return `undefined`.
*/
function parseSampleRate(sampleRate) {
	if (typeof sampleRate === "boolean") return Number(sampleRate);
	const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate;
	if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) return;
	return rate;
}
// src/utils/tracing.ts
const TRACEPARENT_REGEXP = /* @__PURE__ */ new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");
/**
* Extract transaction context data from a `sentry-trace` header.
*
* This is terrible naming but the function has nothing to do with the W3C traceparent header.
* It can only parse the `sentry-trace` header and extract the "trace parent" data.
*
* @param traceparent Traceparent string
*
* @returns Object containing data from the header, or undefined if traceparent string is malformed
*/
function extractTraceparentData(traceparent) {
	if (!traceparent) return;
	const matches = traceparent.match(TRACEPARENT_REGEXP);
	if (!matches) return;
	let parentSampled;
	if (matches[3] === "1") parentSampled = true;
	else if (matches[3] === "0") parentSampled = false;
	return {
		traceId: matches[1],
		parentSampled,
		parentSpanId: matches[2]
	};
}
/**
* Whether a propagation context continues an incoming trace, rather than being the head of a new one.
*
* Both fields have to be checked. `parentSpanId` is unset when the incoming `sentry-trace` header
* carried no span id, which the header format allows. `dsc` is unset when a remote parent arrived
* without any incoming baggage. Either one on its own therefore misses a continued trace.
*/
function isContinuingTrace(propagationContext) {
	return !!propagationContext.parentSpanId || !!propagationContext.dsc;
}
/**
* Create a propagation context from incoming headers or
* creates a minimal new one if the headers are undefined.
*/
function propagationContextFromHeaders(sentryTrace, baggage) {
	const traceparentData = extractTraceparentData(sentryTrace);
	const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);
	if (!traceparentData?.traceId) return {
		traceId: generateTraceId(),
		sampleRand: safeMathRandom()
	};
	const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);
	if (dynamicSamplingContext) dynamicSamplingContext.sample_rand = sampleRand.toString();
	const { traceId, parentSpanId, parentSampled } = traceparentData;
	return {
		traceId,
		parentSpanId,
		sampled: parentSampled,
		dsc: dynamicSamplingContext || {},
		sampleRand
	};
}
/**
* Converts a W3C `traceparent` value to the `sentry-trace` format, so carriers that only hold W3C
* Trace Context can be passed to `continueTrace`.
*/
function sentryTraceFromTraceparent(traceparent) {
	const [version, traceId, spanId, flags] = traceparent.split("-");
	if (version !== "00" || !traceId || !spanId || !flags) return;
	return `${traceId}-${spanId}-${parseInt(flags, 16) % 2 === 1 ? "1" : "0"}`;
}
/**
* Create sentry-trace header from span context values.
*/
function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) {
	let sampledString = "";
	if (sampled !== void 0) sampledString = sampled ? "-1" : "-0";
	return `${traceId}-${spanId}${sampledString}`;
}
/**
* Creates a W3C traceparent header from the given trace and span ids.
*/
function generateTraceparentHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) {
	return `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`;
}
/**
* Given any combination of an incoming trace, generate a sample rand based on its defined semantics.
*
* Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value
*/
function getSampleRandFromTraceparentAndDsc(traceparentData, dsc) {
	const parsedSampleRand = parseSampleRate(dsc?.sample_rand);
	if (parsedSampleRand !== void 0) return parsedSampleRand;
	const parsedSampleRate = parseSampleRate(dsc?.sample_rate);
	if (parsedSampleRate && traceparentData?.parentSampled !== void 0) return traceparentData.parentSampled ? safeMathRandom() * parsedSampleRate : parsedSampleRate + safeMathRandom() * (1 - parsedSampleRate);
	else return safeMathRandom();
}
/**
* Determines whether a new trace should be continued based on the provided baggage org ID and the client's `strictTraceContinuation` option.
* If the trace should not be continued, a new trace will be started.
*
* The result is dependent on the `strictTraceContinuation` option in the client.
* See https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation
*/
function shouldContinueTrace(client, baggageOrgId) {
	const clientOrgId = extractOrgIdFromClient(client);
	if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) {
		debug.log(`Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`);
		return false;
	}
	if (client.getOptions().strictTraceContinuation || false) {
		if (baggageOrgId && !clientOrgId || !baggageOrgId && clientOrgId) {
			debug.log(`Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`);
			return false;
		}
	}
	return true;
}
// src/utils/spanOnScope.ts
const SCOPE_SPAN_FIELD = "span";
/**
* Set the active span for a given scope.
* NOTE: This should NOT be used directly, but is only used internally by the trace methods.
*/
function _setSpanForScope(scope, span) {
	if (span) scope.refs[SCOPE_SPAN_FIELD] = makeWeakRef(span);
	else delete scope.refs[SCOPE_SPAN_FIELD];
}
/**
* Get the active span for a given scope.
* NOTE: This should NOT be used directly, but is only used internally by the trace methods.
*/
function _getSpanForScope(scope) {
	return derefWeakRef(scope.refs[SCOPE_SPAN_FIELD]);
}
/**
* Convert a span to a trace context, which can be sent as the `trace` context in an event.
* By default, this will only include trace_id, span_id & parent_span_id.
* If `includeAllData` is true, it will also include data, op, status & origin.
*/
function spanToTransactionTraceContext(span) {
	const { spanId: span_id, traceId: trace_id } = span.spanContext();
	const { data, op, parent_span_id, status, origin, links } = spanToStaticSpanJSON(span);
	return {
		parent_span_id,
		span_id,
		trace_id,
		data,
		op,
		status,
		origin,
		links
	};
}
/**
* Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.
*/
function spanToTraceContext(span) {
	const { spanId, traceId: trace_id, isRemote } = span.spanContext();
	const parent_span_id = isRemote ? spanId : spanToStaticSpanJSON(span).parent_span_id;
	const scope = getCapturedScopesOnSpan(span).scope;
	return {
		parent_span_id,
		span_id: isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId,
		trace_id
	};
}
/**
* Convert a Span to a Sentry trace header.
*/
function spanToTraceHeader(span) {
	const { traceId, spanId } = span.spanContext();
	return generateSentryTraceHeader(traceId, spanId, spanIsSampled(span));
}
/**
* Convert a Span to a W3C traceparent header.
*/
function spanToTraceparentHeader(span) {
	const { traceId, spanId } = span.spanContext();
	return generateTraceparentHeader(traceId, spanId, spanIsSampled(span));
}
/**
*  Converts the span links array to a flattened version to be sent within an envelope.
*
*  If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.
*/
function convertSpanLinksForEnvelope(links) {
	if (links && links.length > 0) return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({
		span_id: spanId,
		trace_id: traceId,
		sampled: traceFlags === 1,
		attributes,
		...restContext
	}));
	else return;
}
/**
* Converts the span links array to a flattened version with serialized attributes for V2 spans.
*
* If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.
*/
function getStreamedSpanLinks(links) {
	if (links?.length) return links.map(({ context: { spanId, traceId, traceFlags }, attributes }) => ({
		span_id: spanId,
		trace_id: traceId,
		sampled: traceFlags === 1,
		attributes
	}));
	else return;
}
/**
* Convert a span time input into a timestamp in seconds.
*/
function spanTimeInputToSeconds(input) {
	if (typeof input === "number") return ensureTimestampInSeconds(input);
	if (Array.isArray(input)) return input[0] + input[1] / 1e9;
	if (input instanceof Date) return ensureTimestampInSeconds(input.getTime());
	return timestampInSeconds();
}
/**
* Converts a timestamp to second, if it was in milliseconds, or keeps it as second.
*/
function ensureTimestampInSeconds(timestamp) {
	return timestamp > 9999999999 ? timestamp / 1e3 : timestamp;
}
/**
* Convert an OpenTelemetry time input into a timestamp in seconds.
*
* OpenTelemetry numbers are always milliseconds, either since the epoch or since the performance time origin
* (`performance.now()`).
*/
function otelTimeInputToSeconds(input) {
	if (typeof input !== "number") return spanTimeInputToSeconds(input);
	if (input < 0xe8d4a51000) return performanceTimeToSeconds(input) ?? timestampInSeconds();
	return input / 1e3;
}
/**
* Convert a span to a static JSON representation.
*/
function spanToStaticSpanJSON(span) {
	if (spanIsSentrySpan(span)) return span.getStaticSpanJSON();
	const { spanId: span_id, traceId: trace_id } = span.spanContext();
	if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
		const { attributes, startTime, name, endTime, status, links } = span;
		return {
			span_id,
			trace_id,
			data: attributes,
			description: name,
			parent_span_id: getOtelParentSpanId(span),
			start_timestamp: spanTimeInputToSeconds(startTime),
			timestamp: spanTimeInputToSeconds(endTime) || void 0,
			status: getStatusMessage(status),
			op: attributes[_sentry_conventions_attributes.SENTRY_OP],
			origin: attributes[_sentry_conventions_attributes.SENTRY_ORIGIN],
			links: convertSpanLinksForEnvelope(links)
		};
	}
	return {
		span_id,
		trace_id,
		start_timestamp: 0,
		status: "ok",
		data: {}
	};
}
/**
* Convert a span to a JSON representation.
*/
function spanToJSON(span) {
	if (spanIsSentrySpan(span)) return span.getSpanJSON();
	const { spanId: span_id, traceId: trace_id } = span.spanContext();
	if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
		const { attributes, startTime, name, endTime, status, links } = span;
		return {
			name,
			span_id,
			trace_id,
			parent_span_id: getOtelParentSpanId(span),
			start_timestamp: spanTimeInputToSeconds(startTime),
			end_timestamp: spanTimeInputToSeconds(endTime) || void 0,
			is_segment: spanIsSegment(span),
			status: getSimpleStatus(status),
			attributes: addStatusMessageAttribute(attributes, status),
			links: getStreamedSpanLinks(links)
		};
	}
	return {
		span_id,
		trace_id,
		start_timestamp: 0,
		name: "",
		status: "ok",
		is_segment: spanIsSegment(span),
		attributes: {}
	};
}
/**
* In preparation for the next major of OpenTelemetry, we want to support
* looking up the parent span id according to the new API
* In OTel v1, the parent span id is accessed as `parentSpanId`
* In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`
*/
function getOtelParentSpanId(span) {
	return "parentSpanId" in span ? span.parentSpanId : "parentSpanContext" in span ? span.parentSpanContext?.spanId : void 0;
}
/**
* Converts a {@link StreamedSpanJSON} to a {@link SerializedSpan}.
* This is the final serialized span format that is sent to Sentry.
* The returned serilaized spans must not be consumed by users or SDK integrations.
*/
function streamedSpanJsonToSerializedSpan(spanJson) {
	return {
		...spanJson,
		end_timestamp: spanJson.end_timestamp ?? spanJson.start_timestamp,
		attributes: serializeAttributes(spanJson.attributes),
		links: spanJson.links?.map((link) => ({
			...link,
			attributes: serializeAttributes(link.attributes)
		}))
	};
}
function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
	const castSpan = span;
	return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
}
/**
* Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.
* :( So instead we approximate this by checking if it has the `getSpanJSON` method.
*/
function spanIsSentrySpan(span) {
	return typeof span.getSpanJSON === "function";
}
/**
* Returns true if a span is sampled.
* In most cases, you should just use `span.isRecording()` instead.
* However, this has a slightly different semantic, as it also returns false if the span is finished.
* So in the case where this distinction is important, use this method.
*/
function spanIsSampled(span) {
	const { traceFlags } = span.spanContext();
	return traceFlags === 1;
}
/** Get the status message to use for a JSON representation of a span. */
function getStatusMessage(status) {
	if (!status || status.code === 0) return "ok";
	if (status.code === 1) return "ok";
	return status.message && isStatusErrorMessageValid(status.message) ? status.message : "internal_error";
}
/**
* Convert the various statuses to the simple ones expected by Sentry for streamed spans ('ok' is default).
*/
function getSimpleStatus(status) {
	return !status || status.code === 1 || status.code === 0 || status.message === "cancelled" ? "ok" : "error";
}
/**
* Returns the span's attributes with the SENTRY_STATUS_MESSAGE attribute added
* if the span has an error status message worth preserving.
*
* An explicitly set attribute is never overwritten.
*/
function addStatusMessageAttribute(attributes, status) {
	const statusMessage = getSimpleStatus(status) === "error" ? status?.message : void 0;
	return {
		...statusMessage && { [_sentry_conventions_attributes.SENTRY_STATUS_MESSAGE]: statusMessage },
		...attributes
	};
}
const CHILD_SPANS_FIELD = "_sentryChildSpans";
const ROOT_SPAN_FIELD = "_sentryRootSpan";
/**
* Adds an opaque child span reference to a span.
*/
function addChildSpanToSpan(span, childSpan) {
	const rootSpan = span[ROOT_SPAN_FIELD] || span;
	addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan);
	childSpan.setAttribute(_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE, void 0);
	if (!spanIsSampled(span)) return;
	if (!span.isRecording() && !rootSpan.isRecording()) return;
	if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].add(childSpan);
	else addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan]));
}
/** This is only used internally by Idle Spans. */
function removeChildSpanFromSpan(span, childSpan) {
	if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].delete(childSpan);
}
/**
* Returns an array of the given span and all of its descendants.
*/
function getSpanDescendants(span) {
	const resultSet = /* @__PURE__ */ new Set();
	function addSpanChildren(span) {
		if (resultSet.has(span)) return;
		else if (spanIsSampled(span)) {
			resultSet.add(span);
			const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];
			for (const childSpan of childSpans) addSpanChildren(childSpan);
		}
	}
	addSpanChildren(span);
	return Array.from(resultSet);
}
/**
* Returns the root span of a given span.
*/
const getRootSpan = INTERNAL_getSegmentSpan;
/**
* Returns the segment span of a given span.
*/
function INTERNAL_getSegmentSpan(span) {
	return span[ROOT_SPAN_FIELD] || span;
}
/**
* Whether the given span is the segment span, i.e. it has no parent within its trace.
*/
function spanIsSegment(span) {
	return span === INTERNAL_getSegmentSpan(span);
}
/**
* Returns the currently active span.
*/
function getActiveSpan(scope) {
	const acs = getAsyncContextStrategy(getMainCarrier());
	if (acs.getActiveSpan) return acs.getActiveSpan(scope);
	return _getSpanForScope(scope || getCurrentScope());
}
/**
* Updates the name of the given span and ensures that the span name is not
* overwritten by the Sentry SDK.
*
* Use this function instead of `span.updateName()` if you want to make sure that
* your name is kept. For some spans, for example root `http.server` spans the
* Sentry SDK would otherwise overwrite the span name with a high-quality name
* it infers when the span ends.
*
* Use this function in server code or when your span is started on the server
* and on the client (browser). If you only update a span name on the client,
* you can also use `span.updateName()` the SDK does not overwrite the name.
*
* @param span - The span to update the name of.
* @param name - The name to set on the span.
*/
function updateSpanName(span, name) {
	span.updateName(name);
	span.setAttributes({ [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name });
	INTERNAL_setSegmentNameSourceIfSegment(span, "custom");
}
/**
* Sets `sentry.segment.name.source` only when `span` is the segment span.
* No-op for child spans — the attribute must exclusively live on the segment.
*/
function INTERNAL_setSegmentNameSourceIfSegment(span, source) {
	if (spanIsSegment(span)) span.setAttribute(_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE, source);
}
// src/tracing/errors.ts
let errorsInstrumented = false;
/**
* Ensure that global errors automatically set the active span status.
*/
function registerSpanErrorInstrumentation() {
	if (errorsInstrumented) return;
	/**
	* If an error or unhandled promise occurs, we mark the active root span as failed
	*/
	function errorCallback() {
		const activeSpan = getActiveSpan();
		const rootSpan = activeSpan && getRootSpan(activeSpan);
		if (rootSpan) {
			const message = "internal_error";
			DEBUG_BUILD && debug.log(`[Tracing] Root span: ${message} -> Global error occurred`);
			rootSpan.setStatus({
				code: 2,
				message
			});
		}
	}
	errorsInstrumented = true;
	addGlobalErrorInstrumentationHandler(errorCallback);
	addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);
}
// src/utils/hasSpansEnabled.ts
/**
* Determines if span recording is currently enabled.
*
* Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`
* is defined in the SDK config. This function does not make any assumption about
* sampling decisions, it only checks if the SDK is configured to record spans.
*
* Important: This function only determines if span recording is enabled. Trace
* continuation and propagation is separately controlled and not covered by this function.
* If this function returns `false`, traces can still be propagated (which is what
* we refer to by "Tracing without Performance")
* @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/
*
* @param maybeOptions An SDK options object to be passed to this function.
* If this option is not provided, the function will use the current client's options.
*/
function hasSpansEnabled(maybeOptions) {
	if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) return false;
	const options = maybeOptions || getClient()?.getOptions();
	return !!options && (options.tracesSampleRate != null || !!options.tracesSampler);
}
// src/utils/should-ignore-span.ts
function logIgnoredSpan(droppedSpan) {
	debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \`ignoreSpans\`.`);
}
/**
* Check if a span should be ignored based on the ignoreSpans configuration.
*/
function shouldIgnoreSpan(span, ignoreSpans) {
	if (!ignoreSpans?.length) return false;
	for (const pattern of ignoreSpans) {
		if (isStringOrRegExp(pattern)) {
			if (span.description && isMatchingPattern(span.description, pattern)) {
				DEBUG_BUILD && logIgnoredSpan(span);
				return true;
			}
			continue;
		}
		const hasAttributes = !!pattern.attributes && Object.keys(pattern.attributes).length > 0;
		if (!pattern.name && !pattern.op && !hasAttributes) continue;
		const nameMatches = pattern.name ? span.description && isMatchingPattern(span.description, pattern.name) : true;
		const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true;
		const attrsMatch = pattern.attributes ? Object.entries(pattern.attributes).every(([key, valuePattern]) => _matchesAttributeValue(span.attributes?.[key], valuePattern)) : true;
		if (nameMatches && opMatches && attrsMatch) {
			DEBUG_BUILD && logIgnoredSpan(span);
			return true;
		}
	}
	return false;
}
function _matchesAttributeValue(actual, pat) {
	if (typeof actual === "string" && (typeof pat === "string" || pat instanceof RegExp)) return isMatchingPattern(actual, pat);
	if (Array.isArray(actual) && Array.isArray(pat)) return actual.length === pat.length && actual.every((v, i) => v === pat[i]);
	return actual === pat;
}
/**
* Takes a list of spans, and a span that was dropped, and re-parents the child spans of the dropped span to the parent of the dropped span, if possible.
* This mutates the spans array in place!
*/
function reparentChildSpans(spans, dropSpan) {
	const droppedSpanParentId = dropSpan.parent_span_id;
	const droppedSpanId = dropSpan.span_id;
	if (!droppedSpanParentId) return;
	for (const span of spans) if (span.parent_span_id === droppedSpanId) span.parent_span_id = droppedSpanParentId;
}
function isStringOrRegExp(value) {
	return typeof value === "string" || value instanceof RegExp;
}
// src/integration.ts
const installedIntegrations = [];
/**
* Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to
* preserve the order of integrations in the array.
*
* @private
*/
function filterDuplicates(integrations) {
	const integrationsByName = {};
	integrations.forEach((currentInstance) => {
		const { name } = currentInstance;
		const existingInstance = integrationsByName[name];
		if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) return;
		integrationsByName[name] = currentInstance;
	});
	return Object.values(integrationsByName);
}
/** Gets integrations to install */
function getIntegrationsToSetup(options) {
	const defaultIntegrations = options.defaultIntegrations || [];
	const userIntegrations = options.integrations;
	defaultIntegrations.forEach((integration) => {
		integration.isDefaultInstance = true;
	});
	let integrations;
	if (Array.isArray(userIntegrations)) integrations = [...defaultIntegrations, ...userIntegrations];
	else if (typeof userIntegrations === "function") {
		const resolvedUserIntegrations = userIntegrations(defaultIntegrations);
		integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];
	} else integrations = defaultIntegrations;
	return filterDuplicates(integrations);
}
/**
* Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default
* integrations are added unless they were already provided before.
* @param integrations array of integration instances
* @param withDefault should enable default integrations
*/
function setupIntegrations(client, integrations) {
	const integrationIndex = {};
	integrations.forEach((integration) => {
		if (integration?.beforeSetup) integration.beforeSetup(client);
	});
	integrations.forEach((integration) => {
		if (integration) setupIntegration(client, integration, integrationIndex);
	});
	return integrationIndex;
}
/**
* Execute the `afterAllSetup` hooks of the given integrations.
*/
function afterSetupIntegrations(client, integrations) {
	for (const integration of integrations) if (integration?.afterAllSetup) integration.afterAllSetup(client);
}
/** Setup a single integration.  */
function setupIntegration(client, integration, integrationIndex) {
	if (integrationIndex[integration.name]) {
		DEBUG_BUILD && debug.log(`Integration skipped because it was already installed: ${integration.name}`);
		return;
	}
	integrationIndex[integration.name] = integration;
	if (!installedIntegrations.includes(integration.name) && typeof integration.setupOnce === "function") {
		integration.setupOnce();
		installedIntegrations.push(integration.name);
	}
	if (integration.setup && typeof integration.setup === "function") integration.setup(client);
	if (typeof integration.preprocessEvent === "function") {
		const callback = integration.preprocessEvent.bind(integration);
		client.on("preprocessEvent", (event, hint) => callback(event, hint, client));
	}
	if (typeof integration.processEvent === "function") {
		const callback = integration.processEvent.bind(integration);
		const processor = Object.assign((event, hint) => callback(event, hint, client), { id: integration.name });
		client.addEventProcessor(processor);
	}
	["processSpan", "processSegmentSpan"].forEach((hook) => {
		const callback = integration[hook];
		if (typeof callback === "function") client.on(hook, (span) => callback.call(integration, span, client));
	});
	DEBUG_BUILD && debug.log(`Integration installed: ${integration.name}`);
}
/** Add an integration to the current scope's client. */
function addIntegration(integration) {
	const client = getClient();
	if (!client) {
		DEBUG_BUILD && debug.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`);
		return;
	}
	client.addIntegration(integration);
}
/**
* Define an integration function that can be used to create an integration instance.
* Note that this by design hides the implementation details of the integration, as they are considered internal.
*/
function defineIntegration(fn) {
	return fn;
}
/**
* Wrap a parent integration with an extended integration.
* Any passed integration function will call the parent integration function first, if it exists.
*
* Example usage:
*
* @example
* ```typescript
* const parentIntegration = defineIntegration(() => ({
*   name: 'ParentIntegration',
*   setupOnce: () => {
*     console.log('ParentIntegration setupOnce');
*   },
* }));
*
* const extendedIntegration = extendIntegration(parentIntegration, {
*   setupOnce: () => {
*     console.log('ExtendedIntegration setupOnce');
*   },
* });
* ```
*/
function extendIntegration(integration, extendedIntegration) {
	const wrappedIntegration = {
		...integration,
		...extendedIntegration
	};
	for (const key in extendedIntegration) {
		const baseValue = integration[key];
		const extendedValue = extendedIntegration[key];
		if (typeof baseValue === "function" && typeof extendedValue === "function") wrappedIntegration[key] = new Proxy(baseValue, { apply: (target, thisArg, args) => {
			Reflect.apply(target, thisArg, args);
			return Reflect.apply(extendedValue, thisArg, args);
		} });
	}
	return wrappedIntegration;
}
// src/constants.ts
const DEFAULT_ENVIRONMENT = "production";
const DEV_ENVIRONMENT = "development";
// src/tracing/sentryNonRecordingSpan.ts
const NON_RECORDING_SPAN_FIELD = Symbol.for("sentry.nonRecordingSpan");
/**
* A Sentry Span that is non-recording, meaning it will not be sent to Sentry.
*/
var SentryNonRecordingSpan = class {
	constructor(spanContext = {}) {
		this._traceId = spanContext.traceId || generateTraceId();
		this._spanId = spanContext.spanId || generateSpanId();
		this.dropReason = spanContext.dropReason;
		addNonEnumerableProperty(this, NON_RECORDING_SPAN_FIELD, true);
	}
	/** @inheritdoc */
	spanContext() {
		return {
			spanId: this._spanId,
			traceId: this._traceId,
			traceFlags: 0
		};
	}
	/** @inheritdoc */
	end(_timestamp) {}
	/** @inheritdoc */
	setAttribute(_key, _value) {
		return this;
	}
	/** @inheritdoc */
	setAttributes(_values) {
		return this;
	}
	/** @inheritdoc */
	setStatus(_status) {
		return this;
	}
	/** @inheritdoc */
	updateName(_name) {
		return this;
	}
	/** @inheritdoc */
	isRecording() {
		return false;
	}
	/** @inheritdoc */
	addEvent(_name, _attributesOrStartTime, _startTime) {
		return this;
	}
	/** @inheritDoc */
	addLink(_link) {
		return this;
	}
	/** @inheritDoc */
	addLinks(_links) {
		return this;
	}
	/**
	* This should generally not be used,
	* but we need it for being compliant with the OTEL Span interface.
	*
	* @hidden
	* @internal
	*/
	recordException(_exception, _time) {}
};
/**
* Whether the given span is a {@link SentryNonRecordingSpan}.
*/
function spanIsNonRecordingSpan(span) {
	return !!span && span[NON_RECORDING_SPAN_FIELD] === true;
}
// src/tracing/dynamicSamplingContext.ts
/**
* If you change this value, also update the terser plugin config to
* avoid minification of the object property!
*/
const FROZEN_DSC_FIELD = "_frozenDsc";
/**
* Freeze the given DSC on the given span.
*/
function freezeDscOnSpan(span, dsc) {
	addNonEnumerableProperty(span, FROZEN_DSC_FIELD, dsc);
}
/**
* Creates a dynamic sampling context from a client.
*
* Dispatches the `createDsc` lifecycle hook as a side effect.
*/
function getDynamicSamplingContextFromClient(trace_id, client) {
	const options = client.getOptions();
	const { publicKey: public_key } = client.getDsn() || {};
	const dsc = {
		environment: options.environment || "production",
		release: options.release,
		public_key,
		trace_id,
		org_id: extractOrgIdFromClient(client)
	};
	client.emit("createDsc", dsc);
	return dsc;
}
/**
* Get the dynamic sampling context for the currently active scopes.
*/
function getDynamicSamplingContextFromScope(client, scope) {
	if (getExternalPropagationContext()) return;
	const propagationContext = scope.getPropagationContext();
	return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
}
/**
* Creates a dynamic sampling context from a span (and client and scope)
*
* @param span the span from which a few values like the root span name and sample rate are extracted.
*
* @returns a dynamic sampling context
*/
function getDynamicSamplingContextFromSpan(span) {
	const client = getClient();
	if (!client) return {};
	const rootSpan = getRootSpan(span);
	const rootSpanJson = spanToStaticSpanJSON(rootSpan);
	const rootSpanAttributes = rootSpanJson.data;
	const traceState = rootSpan.spanContext().traceState;
	const rootSpanSampleRate = traceState?.get("sentry.sample_rate") ?? rootSpanAttributes["sentry.sample_rate"] ?? rootSpanAttributes["sentry.previous_trace_sample_rate"];
	function applyLocalSampleRateToDsc(dsc) {
		if (typeof rootSpanSampleRate === "number" || typeof rootSpanSampleRate === "string") dsc.sample_rate = `${rootSpanSampleRate}`;
		return dsc;
	}
	const frozenDsc = rootSpan[FROZEN_DSC_FIELD];
	if (frozenDsc) return applyLocalSampleRateToDsc(frozenDsc);
	const isNonRecordingRoot = spanIsNonRecordingSpan(rootSpan);
	const isIgnoredRoot = isNonRecordingRoot && rootSpan.dropReason === "ignored";
	if (isNonRecordingRoot && (!hasSpansEnabled(client.getOptions()) || isIgnoredRoot)) {
		const capturedScope = getCapturedScopesOnSpan(rootSpan).scope;
		const scopeDsc = capturedScope && getDynamicSamplingContextFromScope(client, capturedScope);
		if (scopeDsc) {
			const dsc = { ...scopeDsc };
			if (isIgnoredRoot) dsc.sampled = "false";
			return applyLocalSampleRateToDsc(dsc);
		}
	}
	const traceStateDsc = traceState?.get("sentry.dsc");
	const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
	if (dscOnTraceState) return applyLocalSampleRateToDsc(dscOnTraceState);
	const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
	const source = rootSpanAttributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE];
	const name = rootSpanJson.description;
	if (source !== "url" && name) dsc.transaction = name;
	if (hasSpansEnabled()) {
		dsc.sampled = String(spanIsSampled(rootSpan));
		dsc.sample_rand = traceState?.get("sentry.sample_rand") ?? getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();
	}
	applyLocalSampleRateToDsc(dsc);
	client.emit("createDsc", dsc, rootSpan);
	return dsc;
}
/**
* Convert a Span to a baggage header.
*/
function spanToBaggageHeader(span) {
	return dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(span));
}
// src/utils/scopeData.ts
/**
* Applies data from the scope to the event and runs all event processors on it.
*/
function applyScopeDataToEvent(event, data) {
	const { fingerprint, breadcrumbs, sdkProcessingMetadata } = data;
	applyDataToEvent(event, data);
	applyFingerprintToEvent(event, fingerprint);
	applyBreadcrumbsToEvent(event, breadcrumbs);
	applySdkMetadataToEvent(event, sdkProcessingMetadata);
}
/** Merge data of two scopes together. */
function mergeScopeData(data, mergeData) {
	const { extra, tags, attributes, user, contexts, level, sdkProcessingMetadata, breadcrumbs, fingerprint, eventProcessors, attachments, propagationContext, transactionName } = mergeData;
	mergeAndOverwriteScopeData(data, "extra", extra);
	mergeAndOverwriteScopeData(data, "tags", tags);
	mergeAndOverwriteScopeData(data, "attributes", attributes);
	mergeAndOverwriteScopeData(data, "user", user);
	mergeAndOverwriteScopeData(data, "contexts", contexts);
	data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);
	if (level) data.level = level;
	if (transactionName) data.transactionName = transactionName;
	if (breadcrumbs.length) data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
	if (fingerprint.length) data.fingerprint = [...data.fingerprint, ...fingerprint];
	if (eventProcessors.length) data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
	if (attachments.length) data.attachments = [...data.attachments, ...attachments];
	data.propagationContext = {
		...data.propagationContext,
		...propagationContext
	};
}
/**
* Merges certain scope data. Undefined values will overwrite any existing values.
* Exported only for tests.
*/
function mergeAndOverwriteScopeData(data, prop, mergeVal) {
	data[prop] = merge(data[prop], mergeVal, 1);
}
/**
* Get the scope data for the current scope after merging with the
* global scope and isolation scope.
*
* @param currentScope - The current scope.
* @returns The scope data.
*/
function getCombinedScopeData(isolationScope, currentScope) {
	const scopeData = getGlobalScope().getScopeData();
	isolationScope && mergeScopeData(scopeData, isolationScope.getScopeData());
	currentScope && mergeScopeData(scopeData, currentScope.getScopeData());
	return scopeData;
}
function applyDataToEvent(event, data) {
	const { extra, tags, user, contexts, level, transactionName } = data;
	if (Object.keys(extra).length) event.extra = {
		...extra,
		...event.extra
	};
	if (Object.keys(tags).length) event.tags = {
		...tags,
		...event.tags
	};
	if (Object.keys(user).length) event.user = {
		...user,
		...event.user
	};
	if (Object.keys(contexts).length) event.contexts = {
		...contexts,
		...event.contexts
	};
	if (level) event.level = level;
	if (transactionName && event.type !== "transaction") event.transaction = transactionName;
}
function applyBreadcrumbsToEvent(event, breadcrumbs) {
	const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs];
	event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0;
}
function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
	event.sdkProcessingMetadata = {
		...event.sdkProcessingMetadata,
		...sdkProcessingMetadata
	};
}
/** Apply a given span to the event. */
function applySpanToEvent(event, span) {
	event.contexts = {
		trace: spanToTraceContext(span),
		...event.contexts
	};
	event.sdkProcessingMetadata = {
		dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
		...event.sdkProcessingMetadata
	};
	const transactionName = spanToStaticSpanJSON(getRootSpan(span)).description;
	if (transactionName && !event.transaction && event.type === "transaction") event.transaction = transactionName;
}
/**
* Applies fingerprint from the scope to the event if there's one,
* uses message if there's one instead or get rid of empty fingerprint
*/
function applyFingerprintToEvent(event, fingerprint) {
	event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : [];
	if (fingerprint) event.fingerprint = event.fingerprint.concat(fingerprint);
	if (!event.fingerprint.length) delete event.fingerprint;
}
// src/utils/safeCallback.ts
/**
* Lets a `safeCallback` fallback signal "the callback failed" as opposed to "the callback returned `null`",
* so the call site can report the drop as `callback_error`. Always return it, never throw it: a thrown
* sentinel would have to be caught at every boundary, and some of those (e.g. `prepareEvent`) are public.
*/
const CALLBACK_ERROR = Symbol.for("SentryCallbackError");
/**
* Invokes a user-provided callback (e.g. `beforeSend`, `tracesSampler`, an integration hook) so that
* neither a synchronous throw nor a rejected promise escapes into the caller. On failure the error is
* logged and `fallback(error)` supplies the result instead.
*
* Not for `startSpan` bodies: those must re-throw and are handled by `handleCallbackErrors`.
*
* @param message - Logged via `debug.error` together with the error. Pass it as `DEBUG_BUILD ? '...' : ''`
*   so the string is tree-shaken from non-debug bundles.
* @param fn - Invokes the callback.
* @param fallback - Produces the result to use when the callback throws or rejects.
*/
function safeCallback(message, fn, fallback) {
	let result;
	try {
		result = fn();
	} catch (error) {
		return recover(message, error, fallback);
	}
	if (isThenable(result)) return result.then(void 0, (error) => recover(message, error, fallback));
	return result;
}
function recover(message, error, fallback) {
	DEBUG_BUILD && debug.error(message, error);
	return fallback(error);
}
// src/tracing/spans/beforeSendSpan.ts
/**
* A wrapper to use the static, transaction-based span format in your `beforeSendSpan` callback.
*
* When using `traceLifecycle: 'static'`, wrap your callback with this function
* to receive and return a static span instead of a {@link StreamedSpanJSON}.
*
* @example
*
* Sentry.init({
*   traceLifecycle: 'static',
*   beforeSendSpan: withStaticSpan((span) => {
*     // span is of type SpanJSON
*     return span;
*   }),
* });
*
* @param callback - A {@link BeforeSendStaticSpanCallback} that receives and returns a static span.
* @returns A callback that is compatible with the `beforeSendSpan` option when using `traceLifecycle: 'static'`.
*/
function withStaticSpan(callback) {
	addNonEnumerableProperty(callback, "_static", true);
	return callback;
}
/**
* A wrapper to explicitly use the streamed span format in your `beforeSendSpan` callback.
*
* @deprecated `beforeSendSpan` callbacks receive {@link StreamedSpanJSON} by default.
* This function returns the callback unchanged and will be removed in SDK version 12.
*
* @param callback - The callback function that receives and returns a {@link StreamedSpanJSON}.
* @returns The provided callback.
*/
function withStreamedSpan(callback) {
	return callback;
}
/**
* Typesafe check to identify if a `beforeSendSpan` callback expects the static span JSON format.
*
* @param callback - The `beforeSendSpan` callback to check.
* @returns `true` if the callback was wrapped with {@link withStaticSpan}.
*/
function isStaticBeforeSendSpanCallback(callback) {
	return !!callback && typeof callback === "function" && "_static" in callback && !!callback._static;
}
/**
* Apply a user-provided beforeSendSpan callback to a span JSON.
*/
function applyBeforeSendSpanCallback(span, beforeSendSpan) {
	return safeCallback(DEBUG_BUILD ? "The `beforeSendSpan` callback threw an error, sending the span unmodified:" : "", () => beforeSendSpan(span), () => span) || span;
}
// src/tracing/spans/spanJsonToStreamedSpan.ts
/**
* Converts a v1 SpanJSON (from a legacy transaction) to a serialized v2 StreamedSpan.
*/
function spanJsonToSerializedStreamedSpan(span) {
	return streamedSpanJsonToSerializedSpan({
		trace_id: span.trace_id,
		span_id: span.span_id,
		parent_span_id: span.parent_span_id,
		name: span.description || "",
		start_timestamp: span.start_timestamp,
		end_timestamp: span.timestamp,
		status: !span.status || span.status === "ok" || span.status === "cancelled" ? "ok" : "error",
		is_segment: false,
		attributes: { ...span.data },
		links: span.links
	});
}
// src/tracing/spans/scopeContextAttributes.ts
/**
* Convert known scope contexts set by SDK integrations to span attributes.
* Only maps context keys that are relevant to browser SDKs.
* Server-only contexts (aws, gcp, trpc) are handled
* by processSegmentSpan hooks in their respective packages.
*/
function scopeContextsToSpanAttributes(contexts) {
	const attrs = {};
	const { response, profile, cloud_resource, culture, state } = contexts;
	if (response) {
		if (response.status_code != null) attrs[_sentry_conventions_attributes.HTTP_RESPONSE_STATUS_CODE] = response.status_code;
		if (response.body_size != null) attrs[_sentry_conventions_attributes.HTTP_RESPONSE_BODY_SIZE] = response.body_size;
	}
	if (profile) {
		if (profile.profile_id) attrs[_sentry_conventions_attributes.SENTRY_PROFILE_ID] = profile.profile_id;
		if (profile.profiler_id) attrs[_sentry_conventions_attributes.SENTRY_PROFILER_ID] = profile.profiler_id;
	}
	if (cloud_resource) {
		for (const [key, value] of Object.entries(cloud_resource)) if (value != null) attrs[key] = value;
	}
	if (culture) {
		if (culture.locale) attrs[_sentry_conventions_attributes.CULTURE_LOCALE] = culture.locale;
		if (culture.timezone) attrs[_sentry_conventions_attributes.CULTURE_TIMEZONE] = culture.timezone;
	}
	if (state?.state && typeof state.state.type === "string") attrs[_sentry_conventions_attributes.STATE_TYPE] = state.state.type;
	const angular = contexts["angular"];
	if (angular) {
		const version = angular["version"];
		if (typeof version === "string" || typeof version === "number") attrs[_sentry_conventions_attributes.ANGULAR_VERSION] = version;
	}
	const react = contexts["react"];
	if (react) {
		const version = react["version"];
		if (typeof version === "string" || typeof version === "number") attrs[_sentry_conventions_attributes.REACT_VERSION] = version;
	}
	return attrs;
}
// src/tracing/spans/captureSpan.ts
/**
* Captures a span and returns a JSON representation to be enqueued for sending.
*
* IMPORTANT: This function converts the span to JSON immediately to avoid writing
* to an already-ended OTel span instance (which is blocked by the OTel Span class).
*
* @returns the final serialized span with a reference to its segment span. This reference
* is needed later on to compute the DSC and the final segment name for the span envelope.
*/
function captureSpan(span, client) {
	const spanJSON = spanToJSON(span);
	if (spanJSON.attributes) delete spanJSON.attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
	const segmentSpan = INTERNAL_getSegmentSpan(span);
	const serializedSegmentSpan = spanToJSON(segmentSpan);
	const { isolationScope: spanIsolationScope, scope: spanScope } = getCapturedScopesOnSpan(span);
	const finalScopeData = getCombinedScopeData(spanIsolationScope, spanScope);
	applyCommonSpanAttributes(spanJSON, serializedSegmentSpan, client, finalScopeData);
	client.emit("preprocessSpan", spanJSON);
	if (spanJSON.is_segment) {
		freezeDscOnSpan(segmentSpan, getDynamicSamplingContextFromSpan(segmentSpan));
		applyScopeToSegmentSpan(spanJSON, finalScopeData);
		applySdkMetadataToSegmentSpan(spanJSON, client);
		client.emit("processSegmentSpan", spanJSON);
	}
	client.emit("processSpan", spanJSON);
	const { beforeSendSpan, traceLifecycle } = client.getOptions();
	return {
		...streamedSpanJsonToSerializedSpan(traceLifecycle !== "static" && beforeSendSpan && !isStaticBeforeSendSpanCallback(beforeSendSpan) ? applyBeforeSendSpanCallback(spanJSON, beforeSendSpan) : spanJSON),
		_segmentSpan: segmentSpan,
		_segmentNameAtCapture: serializedSegmentSpan.name
	};
}
function applyScopeToSegmentSpan(segmentSpanJSON, scopeData) {
	safeSetSpanJSONAttributes(segmentSpanJSON, scopeContextsToSpanAttributes(scopeData.contexts));
}
/**
* Safely set attributes on a span JSON.
* If an attribute already exists, it will not be overwritten.
*/
function safeSetSpanJSONAttributes(spanJSON, newAttributes) {
	const originalAttributes = spanJSON.attributes ?? (spanJSON.attributes = {});
	Object.entries(newAttributes).forEach(([key, value]) => {
		if (value != null && !(key in originalAttributes)) originalAttributes[key] = value;
	});
}
function applySdkMetadataToSegmentSpan(segmentSpanJSON, client) {
	const integrationNames = client.getIntegrationNames();
	if (!integrationNames.length) return;
	safeSetSpanJSONAttributes(segmentSpanJSON, { [_sentry_conventions_attributes.SENTRY_SDK_INTEGRATIONS]: integrationNames });
}
function commonSpanAttributes(serializedSegmentSpan, client, scopeData, includeScopeAttributes = true) {
	const sdk = client.getSdkMetadata();
	const { release, environment } = client.getOptions();
	return {
		[_sentry_conventions_attributes.SENTRY_TRACE_LIFECYCLE]: "stream",
		[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME]: serializedSegmentSpan.name,
		[_sentry_conventions_attributes.SENTRY_SEGMENT_ID]: serializedSegmentSpan.span_id,
		[_sentry_conventions_attributes.SENTRY_SDK_NAME]: sdk?.sdk?.name,
		[_sentry_conventions_attributes.SENTRY_SDK_VERSION]: sdk?.sdk?.version,
		[_sentry_conventions_attributes.SENTRY_RELEASE]: release,
		[_sentry_conventions_attributes.SENTRY_ENVIRONMENT]: environment || "production",
		[_sentry_conventions_attributes.USER_ID]: scopeData.user?.id,
		[_sentry_conventions_attributes.USER_EMAIL]: scopeData.user?.email,
		[_sentry_conventions_attributes.USER_IP_ADDRESS]: scopeData.user?.ip_address,
		[_sentry_conventions_attributes.USER_NAME]: scopeData.user?.username,
		...includeScopeAttributes ? scopeData.attributes : void 0
	};
}
function applyCommonSpanAttributes(spanJSON, serializedSegmentSpan, client, scopeData) {
	safeSetSpanJSONAttributes(spanJSON, commonSpanAttributes(serializedSegmentSpan, client, scopeData));
}
/**
* Captures a standalone span whose `beforeSendSpan` callback expects the v1 {@link SpanJSON} format
* (i.e. the user opted out of span streaming). The span is serialized to v1, the common attributes are
* applied, the callback runs in its native format, and the result is converted forward to a serialized
* v2 span. This mirrors how gen_ai spans reach the v2 span path from a static transaction (a plain
* conversion, no `processSpan` hooks), so there is never a reverse v2 -> v1 conversion.
*
* TODO(standalone): remove once the static (transaction) trace lifecycle is dropped.
*/
function captureStandaloneSpanWithStaticCallback(span, client, beforeSendSpan) {
	const spanJSON = spanToStaticSpanJSON(span);
	const serializedSegmentSpan = spanToJSON(INTERNAL_getSegmentSpan(span));
	const { isolationScope: spanIsolationScope, scope: spanScope } = getCapturedScopesOnSpan(span);
	const commonAttributes = commonSpanAttributes(serializedSegmentSpan, client, getCombinedScopeData(spanIsolationScope, spanScope), false);
	Object.entries(commonAttributes).forEach(([key, value]) => {
		if (value != null && !(key in spanJSON.data)) spanJSON.data[key] = value;
	});
	return spanJsonToSerializedStreamedSpan(applyBeforeSendSpanCallback(spanJSON, beforeSendSpan));
}
// src/tracing/spans/hasSpanStreamingEnabled.ts
/**
* Determines if span streaming is enabled for the given client
*/
function hasSpanStreamingEnabled(client) {
	return client.getOptions().traceLifecycle === "stream";
}
// src/utils/timer.ts
/**
* Calls `unref` on a timer, if the method is available on @param timer.
*
* `unref()` is used to allow processes to exit immediately, even if the timer
* is still running and hasn't resolved yet.
*
* Use this in places where code can run on browser or server, since browsers
* do not support `unref`.
*/
function safeUnref(timer) {
	if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
	return timer;
}
// src/utils/envelope.ts
/**
* Creates an envelope.
* Make sure to always explicitly provide the generic to this function
* so that the envelope types resolve correctly.
*/
function createEnvelope(headers, items = []) {
	return [headers, items];
}
/**
* Add an item to an envelope.
* Make sure to always explicitly provide the generic to this function
* so that the envelope types resolve correctly.
*/
function addItemToEnvelope(envelope, newItem) {
	const [headers, items] = envelope;
	return [headers, [...items, newItem]];
}
/**
* Convenience function to loop through the items and item types of an envelope.
* (This function was mostly created because working with envelope types is painful at the moment)
*
* If the callback returns true, the rest of the items will be skipped.
*/
function forEachEnvelopeItem(envelope, callback) {
	const envelopeItems = envelope[1];
	for (const envelopeItem of envelopeItems) {
		const envelopeItemType = envelopeItem[0].type;
		if (callback(envelopeItem, envelopeItemType)) return true;
	}
	return false;
}
/**
* Returns true if the envelope contains any of the given envelope item types
*/
function envelopeContainsItemType(envelope, types) {
	return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));
}
/**
* Encode a string to UTF8 array.
*/
function encodeUTF8(input) {
	const carrier = getSentryCarrier(GLOBAL_OBJ);
	return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);
}
/**
* Decode a UTF8 array to string.
*/
function decodeUTF8(input) {
	const carrier = getSentryCarrier(GLOBAL_OBJ);
	return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);
}
/**
* Serializes an envelope.
*/
function serializeEnvelope(envelope) {
	const [envHeaders, items] = envelope;
	let parts = JSON.stringify(envHeaders);
	function append(next) {
		if (typeof parts === "string") parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next];
		else parts.push(typeof next === "string" ? encodeUTF8(next) : next);
	}
	for (const item of items) {
		const [itemHeaders, payload] = item;
		append(`\n${JSON.stringify(itemHeaders)}\n`);
		if (typeof payload === "string" || payload instanceof Uint8Array) append(payload);
		else {
			let stringifiedPayload;
			try {
				stringifiedPayload = JSON.stringify(payload);
			} catch {
				stringifiedPayload = JSON.stringify(normalize(payload));
			}
			append(stringifiedPayload);
		}
	}
	return typeof parts === "string" ? parts : concatBuffers(parts);
}
function concatBuffers(buffers) {
	const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
	const merged = new Uint8Array(totalLength);
	let offset = 0;
	for (const buffer of buffers) {
		merged.set(buffer, offset);
		offset += buffer.length;
	}
	return merged;
}
/**
* Parses an envelope
*/
function parseEnvelope(env) {
	let buffer = typeof env === "string" ? encodeUTF8(env) : env;
	function readBinary(length) {
		const bin = buffer.subarray(0, length);
		buffer = buffer.subarray(length + 1);
		return bin;
	}
	function readJson() {
		let i = buffer.indexOf(10);
		if (i < 0) i = buffer.length;
		return JSON.parse(decodeUTF8(readBinary(i)));
	}
	const envelopeHeader = readJson();
	const items = [];
	while (buffer.length) {
		const itemHeader = readJson();
		const binaryLength = typeof itemHeader.length === "number" ? itemHeader.length : void 0;
		items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);
	}
	return [envelopeHeader, items];
}
/**
* Creates attachment envelope items
*/
function createAttachmentEnvelopeItem(attachment) {
	const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data;
	return [{
		type: "attachment",
		length: buffer.length,
		filename: attachment.filename,
		content_type: attachment.contentType,
		attachment_type: attachment.attachmentType
	}, buffer];
}
const DATA_CATEGORY_OVERRIDES = {
	sessions: "session",
	event: "error",
	client_report: "internal",
	user_report: "default",
	profile_chunk: "profile",
	replay_event: "replay",
	replay_recording: "replay",
	check_in: "monitor",
	raw_security: "security",
	log: "log_item",
	metric: "trace_metric"
};
function _isOverriddenType(type) {
	return type in DATA_CATEGORY_OVERRIDES;
}
/**
* Maps the type of an envelope item to a data category.
*/
function envelopeItemTypeToDataCategory(type) {
	return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type;
}
/** Extracts the minimal SDK info from the metadata or an events */
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
	if (!metadataOrEvent?.sdk) return;
	const { name, version } = metadataOrEvent.sdk;
	return {
		name,
		version
	};
}
/**
* Creates event envelope headers, based on event, sdk info and tunnel
* Note: This function was extracted from the core package to make it available in Replay
*/
function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
	const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;
	return {
		event_id: event.event_id,
		sent_at: new Date(safeDateNow()).toISOString(),
		...sdkInfo && { sdk: sdkInfo },
		...!!tunnel && dsn && { dsn: dsnToString(dsn) },
		...dynamicSamplingContext && { trace: dynamicSamplingContext }
	};
}
/**
* Maps an event type to the data category used for client reports.
*/
function getDataCategoryByType(type) {
	return type === "replay_event" ? "replay" : type || "error";
}
// src/utils/env.ts
/**
* Figures out if we're building a browser bundle.
*
* @returns true if this is a browser bundle build.
*/
function isBrowserBundle() {
	return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
}
/**
* Get source of SDK.
*/
function getSDKSource() {
	/*! __SENTRY_SDK_SOURCE__ */ return "npm";
}
// src/utils/node.ts
/**
* NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
* you must either a) use `console.log` rather than the `debug` singleton, or b) put your function elsewhere.
*/
/**
* Checks whether we're in the Node.js or Browser environment
*
* @returns Answer to given question
*/
function isNodeEnv() {
	return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
}
/**
* Requires a module which is protected against bundler minification.
*
* @param request The module path to resolve
*/
function dynamicRequire(mod, request) {
	return mod.require(request);
}
/**
* Helper for dynamically loading module that should work with linked dependencies.
* The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`
* However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during
* build time. `require.resolve` is also not available in any other way, so we cannot create,
* a fake helper like we do with `dynamicRequire`.
*
* We always prefer to use local package, thus the value is not returned early from each `try/catch` block.
* That is to mimic the behavior of `require.resolve` exactly.
*
* @param moduleName module name to require
* @param existingModule module to use for requiring
* @returns possibly required module
*/
function loadModule(moduleName, existingModule = typeof module !== "undefined" ? module : void 0) {
	let mod;
	try {
		mod = dynamicRequire(existingModule, moduleName);
	} catch {}
	if (!mod) try {
		const { cwd } = dynamicRequire(existingModule, "process");
		mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`);
	} catch {}
	return mod;
}
// src/utils/isBrowser.ts
/**
* Returns true if we are in the browser.
*/
function isBrowser() {
	return typeof window !== "undefined" && (!isNodeEnv() || isElectronNodeRenderer());
}
function isElectronNodeRenderer() {
	return GLOBAL_OBJ.process?.type === "renderer";
}
// src/tracing/spans/envelope.ts
/**
* Creates a span v2 span streaming envelope
*/
function createStreamedSpanEnvelope(serializedSpans, dsc, client) {
	const options = client.getOptions();
	const dsn = client.getDsn();
	const tunnel = options.tunnel;
	const sdk = getSdkMetadataForEnvelopeHeader(options._metadata);
	return createEnvelope({
		sent_at: new Date(safeDateNow()).toISOString(),
		...dscHasRequiredProps(dsc) && { trace: dsc },
		...sdk && { sdk },
		...!!tunnel && dsn && { dsn: dsnToString(dsn) }
	}, [createSpanContainerItem(serializedSpans, client)]);
}
/**
* Builds a span v2 container envelope item from already-serialized streamed spans.
*/
function createSpanContainerItem(serializedSpans, client) {
	const inferSetting = client.getDataCollectionOptions().userInfo ? "auto" : "never";
	return [{
		type: "span",
		item_count: serializedSpans.length,
		content_type: "application/vnd.sentry.items.span.v2+json"
	}, {
		version: 2,
		ingest_settings: isBrowser() ? {
			infer_ip: inferSetting,
			infer_user_agent: inferSetting
		} : void 0,
		items: serializedSpans
	}];
}
function dscHasRequiredProps(dsc) {
	return !!dsc.trace_id && !!dsc.public_key;
}
// src/tracing/spans/estimateSize.ts
/**
* Estimates the serialized byte size of a {@link SerializedStreamedSpan}.
*
* Uses 2 bytes per character as a UTF-16 approximation, and 8 bytes per number.
* The estimate is intentionally conservative and may be slightly lower than the
* actual byte size on the wire.
* We compensate for this by setting the span buffers internal limit well below the limit
* of how large an actual span v2 envelope may be.
*/
function estimateSerializedSpanSizeInBytes(span) {
	let weight = 156;
	weight += span.name.length * 2;
	weight += estimateTypedAttributesSizeInBytes(span.attributes);
	if (span.links && span.links.length > 0) {
		const attributes = span.links[0]?.attributes;
		const linkWeight = 100 + (attributes ? estimateTypedAttributesSizeInBytes(attributes) : 0);
		weight += linkWeight * span.links.length;
	}
	return weight;
}
// src/tracing/spans/spanBuffer.ts
/**
* We must not send more than 1000 spans in one envelope.
* Otherwise the envelope is dropped by Relay.
*/
const MAX_SPANS_PER_ENVELOPE = 1e3;
const MAX_TRACE_WEIGHT_IN_BYTES = 5e6;
/**
* A buffer for serialized streamed span JSON objects that flushes them to Sentry in Span v2 envelopes.
* Handles per-trace timeout-based flushing, size thresholds, and graceful shutdown.
* Also handles computation of the Dynamic Sampling Context (DSC) for the trace, if it wasn't yet
* frozen onto the segment span.
*
* For this, we need the reference to the segment span instance, from
* which we compute the DSC. Doing this in the buffer ensures that we compute the DSC as late as possible,
* allowing span name and data updates up to this point. Worth noting here that the segment span is likely
* still active and modifyable when child spans are added to the buffer.
*/
var SpanBuffer = class {
	constructor(client, options) {
		this._traceBuckets = /* @__PURE__ */ new Map();
		this._client = client;
		const { maxSpanLimit, flushInterval, maxTraceWeightInBytes } = options ?? {};
		this._maxSpanLimit = maxSpanLimit && maxSpanLimit > 0 && maxSpanLimit <= MAX_SPANS_PER_ENVELOPE ? maxSpanLimit : MAX_SPANS_PER_ENVELOPE;
		this._flushInterval = flushInterval && flushInterval > 0 ? flushInterval : 5e3;
		this._maxTraceWeight = maxTraceWeightInBytes && maxTraceWeightInBytes > 0 ? maxTraceWeightInBytes : MAX_TRACE_WEIGHT_IN_BYTES;
		this._client.on("flush", () => {
			this.drain();
		});
		this._client.on("close", () => {
			this._traceBuckets.forEach((bucket) => {
				clearTimeout(bucket.timeout);
			});
			this._traceBuckets.clear();
		});
	}
	/**
	* Add a span to the buffer.
	*/
	add(spanJSON) {
		const traceId = spanJSON.trace_id;
		let bucket = this._traceBuckets.get(traceId);
		if (!bucket) {
			bucket = {
				spans: /* @__PURE__ */ new Set(),
				size: 0,
				timeout: safeUnref(setTimeout(() => {
					this.flush(traceId);
				}, this._flushInterval))
			};
			this._traceBuckets.set(traceId, bucket);
		}
		bucket.spans.add(spanJSON);
		bucket.size += estimateSerializedSpanSizeInBytes(spanJSON);
		if (bucket.spans.size >= this._maxSpanLimit || bucket.size >= this._maxTraceWeight) this.flush(traceId);
	}
	/**
	* Drain and flush all buffered traces.
	*/
	drain() {
		if (!this._traceBuckets.size) return;
		DEBUG_BUILD && debug.log(`Flushing span tree map with ${this._traceBuckets.size} traces`);
		this._traceBuckets.forEach((_, traceId) => {
			this.flush(traceId);
		});
	}
	/**
	* Flush spans of a specific trace.
	* In contrast to {@link SpanBuffer.drain}, this method does not flush all traces, but only the one with the given traceId.
	*/
	flush(traceId) {
		const bucket = this._traceBuckets.get(traceId);
		if (!bucket) return;
		if (!bucket.spans.size) {
			this._removeTrace(traceId);
			return;
		}
		const spans = Array.from(bucket.spans);
		const segmentSpan = spans[0]?._segmentSpan;
		if (!segmentSpan) {
			DEBUG_BUILD && debug.warn("No segment span reference found on span JSON, cannot compute DSC");
			this._removeTrace(traceId);
			return;
		}
		const dsc = getDynamicSamplingContextFromSpan(segmentSpan);
		freezeDscOnSpan(segmentSpan, dsc);
		const currentSegmentNames = /* @__PURE__ */ new Map();
		const getCurrentSegmentName = (span) => {
			let name = currentSegmentNames.get(span);
			if (name === void 0) {
				name = spanToJSON(span).name;
				currentSegmentNames.set(span, name);
			}
			return name;
		};
		const cleanedSpans = spans.map((spanJSON) => {
			const { _segmentSpan, _segmentNameAtCapture, ...cleanSpanJSON } = spanJSON;
			refreshSegmentName(cleanSpanJSON, _segmentNameAtCapture, () => getCurrentSegmentName(_segmentSpan));
			return cleanSpanJSON;
		});
		const envelope = createStreamedSpanEnvelope(cleanedSpans, dsc, this._client);
		DEBUG_BUILD && debug.log(`Sending span envelope for trace ${traceId} with ${cleanedSpans.length} spans`);
		this._client.sendEnvelope(envelope).then(null, (reason) => {
			DEBUG_BUILD && debug.error("Error while sending streamed span envelope:", reason);
		});
		this._removeTrace(traceId);
	}
	_removeTrace(traceId) {
		const bucket = this._traceBuckets.get(traceId);
		if (bucket) clearTimeout(bucket.timeout);
		this._traceBuckets.delete(traceId);
	}
};
/**
* Spans are captured when they end, but the segment span can still be renamed afterwards
* (e.g. once the route is known). Only replace the value we set at capture time, so that
* values set by users or `beforeSendSpan` are kept.
*/
function refreshSegmentName(spanJSON, segmentNameAtCapture, getCurrentSegmentName) {
	const segmentNameAttribute = spanJSON.attributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME];
	if (segmentNameAtCapture === void 0 || segmentNameAttribute?.value !== segmentNameAtCapture) return;
	const currentSegmentName = getCurrentSegmentName();
	if (currentSegmentName !== segmentNameAtCapture) spanJSON.attributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME] = {
		...segmentNameAttribute,
		value: currentSegmentName
	};
}
// src/integrations/spanStreaming.ts
const INTEGRATION_NAME = "SpanStreaming";
const spanStreamingIntegration = defineIntegration((options = {}) => {
	const flushOnSegmentEnd = options.flushOnSegmentEnd ?? true;
	return {
		name: INTEGRATION_NAME,
		setup(client) {
			if (!hasSpanStreamingEnabled(client)) {
				DEBUG_BUILD && debug.log(`[SpanStreaming] \`traceLifecycle\` is "static", skipping setup.`);
				return;
			}
			const buffer = new SpanBuffer(client);
			client.on("afterSpanEnd", (span) => {
				if (!spanIsSampled(span)) return;
				buffer.add(captureSpan(span, client));
			});
			client.on("flushTraceSpans", (traceId) => {
				buffer.flush(traceId);
			});
			if (flushOnSegmentEnd) client.on("afterSegmentSpanEnd", (segmentSpan) => {
				const traceId = segmentSpan.spanContext().traceId;
				safeUnref(setTimeout(() => {
					buffer.flush(traceId);
				}, 500));
			});
		}
	};
});
// src/utils/handleCallbackErrors.ts
/**
* Wrap a callback function with error handling.
* If an error is thrown, it will be passed to the `onError` callback and re-thrown.
*
* If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.
*
* If an `onFinally` callback is provided, this will be called when the callback has finished
* - so if it returns a promise, once the promise resolved/rejected,
* else once the callback has finished executing.
* The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.
*/
function handleCallbackErrors(fn, onError, onFinally = () => {}, onSuccess = () => {}) {
	let maybePromiseResult;
	try {
		maybePromiseResult = fn();
	} catch (e) {
		onError(e);
		onFinally();
		throw e;
	}
	return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);
}
/**
* Maybe handle a promise rejection.
* This expects to be given a value that _may_ be a promise, or any other value.
* If it is a promise, and it rejects, it will call the `onError` callback.
*
* For thenable objects with extra methods (like jQuery's jqXHR),
* this function preserves those methods by wrapping the original thenable in a Proxy
* that intercepts .then() calls to apply error handling while forwarding all other
* properties to the original object.
* This allows code like `startSpan(() => $.ajax(...)).abort()` to work correctly.
*/
function maybeHandlePromiseRejection(value, onError, onFinally, onSuccess) {
	if (isThenable(value)) return chainAndCopyPromiseLike(value, (result) => {
		onFinally();
		onSuccess(result);
	}, (err) => {
		onError(err);
		onFinally();
	});
	onFinally();
	onSuccess(value);
	return value;
}
// src/utils/errorSpanAttribution.ts
/**
* The trace context of the span an error escaped, keyed by the error itself.
*
* We store the trace context rather than the span because that is the shape we apply to the event
* later, and it snapshots the span as it failed instead of reading it back once it has ended.
*/
const escapedSpanTraceContexts = /* @__PURE__ */ new WeakMap();
/**
* A `WeakMap` can only be keyed by an object, so an error thrown as a primitive (`throw 'boom'`)
* has nothing we can hang the span on and is left unattributed.
*/
function toWeakMapKey(error) {
	return isPrimitive(error) ? void 0 : error;
}
/**
* Remember which span an error escaped, so a later `captureException` can attribute the error to
* the span that actually failed instead of whichever span happens to be active at capture time.
*
* The first span to see the error wins: as an error unwinds through nested spans, the innermost
* one is the one that failed. Unsampled spans are skipped because they are never sent, so their
* span id would point at a span that does not exist. Sampling rather than `isRecording()` is what
* matters here: a span ended before the error escaped it, which is the norm for `startSpanManual`,
* has stopped recording but is still sent.
*/
function recordEscapedErrorSpan(error, span) {
	const key = toWeakMapKey(error);
	if (!key || !spanIsSampled(span) || escapedSpanTraceContexts.has(key)) return;
	escapedSpanTraceContexts.set(key, spanToTraceContext(span));
}
/**
* Attribute an error event to the span the error escaped, if we recorded one.
*
* This only applies within the error's own trace. The stored span id is meaningless in another
* trace, and the event's dynamic sampling context (which the envelope header is built from) is
* derived from the root span of the trace the event is already on. Rewriting the trace id here
* would leave the envelope header and body naming different traces.
*/
function applyEscapedErrorSpanToEvent(event, hint, scope) {
	const key = toWeakMapKey(hint.originalException);
	const traceContext = key && escapedSpanTraceContexts.get(key);
	if (!traceContext) return;
	const eventTraceContext = event.contexts?.trace;
	if ((eventTraceContext?.trace_id ?? (scope && getTraceContextFromScope(scope).trace_id)) !== traceContext.trace_id) return;
	event.contexts = {
		...event.contexts,
		trace: {
			...eventTraceContext,
			...traceContext
		}
	};
}
// src/tracing/logSpans.ts
/**
* Print a log message for a started span.
*/
function logSpanStart(span) {
	if (!DEBUG_BUILD) return;
	const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToStaticSpanJSON(span);
	const { spanId } = span.spanContext();
	const sampled = spanIsSampled(span);
	const rootSpan = getRootSpan(span);
	const isRootSpan = rootSpan === span;
	const header = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`;
	const infoParts = [
		`op: ${op}`,
		`name: ${description}`,
		`ID: ${spanId}`
	];
	if (parentSpanId) infoParts.push(`parent ID: ${parentSpanId}`);
	if (!isRootSpan) {
		const { op, description } = spanToStaticSpanJSON(rootSpan);
		infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);
		if (op) infoParts.push(`root op: ${op}`);
		if (description) infoParts.push(`root description: ${description}`);
	}
	debug.log(`${header}
  ${infoParts.join("\n  ")}`);
}
/**
* Print a log message for an ended span.
*/
function logSpanEnd(span) {
	if (!DEBUG_BUILD) return;
	const { description = "< unknown name >", op = "< unknown op >" } = spanToStaticSpanJSON(span);
	const { spanId } = span.spanContext();
	const msg = `[Tracing] Finishing "${op}" ${getRootSpan(span) === span ? "root " : ""}span "${description}" with ID ${spanId}`;
	debug.log(msg);
}
// src/tracing/sampling.ts
/**
* Makes a sampling decision for the given options.
*
* Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be
* sent to Sentry.
*/
function sampleSpan(options, samplingContext, sampleRand) {
	if (!hasSpansEnabled(options)) return [false];
	const resolved = resolveSampleRate(options, samplingContext);
	if (!resolved) return [
		false,
		void 0,
		void 0,
		"callback_error"
	];
	const [sampleRate, localSampleRateWasApplied] = resolved;
	const parsedSampleRate = parseSampleRate(sampleRate);
	if (parsedSampleRate === void 0) {
		DEBUG_BUILD && debug.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(sampleRate)} of type ${JSON.stringify(typeof sampleRate)}.`);
		return [false];
	}
	if (!parsedSampleRate) {
		DEBUG_BUILD && debug.log(`[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`);
		return [
			false,
			parsedSampleRate,
			localSampleRateWasApplied
		];
	}
	const shouldSample = sampleRand < parsedSampleRate;
	if (!shouldSample) DEBUG_BUILD && debug.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(sampleRate)})`);
	return [
		shouldSample,
		parsedSampleRate,
		localSampleRateWasApplied
	];
}
/**
* Prefers `tracesSampler`. If it throws, falls back to the parent decision, then `tracesSampleRate`.
* Returns `undefined` when there is nothing to fall back to.
*/
function resolveSampleRate(options, samplingContext) {
	const { tracesSampler, tracesSampleRate } = options;
	if (typeof tracesSampler === "function") {
		const samplerResult = safeCallback(DEBUG_BUILD ? "The `tracesSampler` callback threw an error, falling back to the parent sampling decision or `tracesSampleRate`:" : "", () => [tracesSampler({
			...samplingContext,
			inheritOrSampleWith: (fallbackSampleRate) => {
				if (typeof samplingContext.parentSampleRate === "number") return samplingContext.parentSampleRate;
				if (typeof samplingContext.parentSampled === "boolean") return Number(samplingContext.parentSampled);
				return fallbackSampleRate;
			}
		}), true], () => void 0);
		if (samplerResult) return samplerResult;
	}
	if (samplingContext.parentSampled !== void 0) return [samplingContext.parentSampled];
	if (typeof tracesSampleRate !== "undefined") return [tracesSampleRate, true];
}
// src/tracing/measurement.ts
/**
* Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span
* as the 4th parameter.
*/
function setMeasurement(name, value, unit, activeSpan = getActiveSpan()) {
	const rootSpan = activeSpan && getRootSpan(activeSpan);
	if (rootSpan) {
		DEBUG_BUILD && debug.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);
		rootSpan.addEvent(name, {
			[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,
			[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit
		});
	}
}
/**
* Convert timed events to measurements.
*/
function timedEventsToMeasurements(events) {
	if (!events || events.length === 0) return;
	const measurements = {};
	events.forEach((event) => {
		const attributes = event.attributes || {};
		const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT];
		const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];
		if (typeof unit === "string" && typeof value === "number") measurements[event.name] = {
			value,
			unit
		};
	});
	return measurements;
}
// src/tracing/segmentSpanCaptureStrategy.ts
/**
* @private Private API with no semver guarantees!
*
* Set the global segment-span capture strategy (or clear it with `undefined`).
*/
function setSegmentSpanCaptureStrategy(strategy) {
	getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy = strategy;
}
/** Get the global segment-span capture strategy, or `undefined` when none is registered. */
function getSegmentSpanCaptureStrategy() {
	return getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy;
}
// src/tracing/sentrySpan.ts
const MAX_SPAN_COUNT = 1e3;
/**
* Span contains all data about a span
*/
var SentrySpan = class {
	/**
	* You should never call the constructor manually, always use `Sentry.startSpan()`
	* or other span methods.
	* @internal
	* @hideconstructor
	* @hidden
	*/
	constructor(spanContext = {}) {
		this._traceId = spanContext.traceId || generateTraceId();
		this._spanId = spanContext.spanId || generateSpanId();
		if (spanContext.startTimestamp) this._startTime = spanContext.startTimestamp;
		else {
			this._startTime = timestampInSeconds();
			this._startPerformanceNow = safePerformanceNow();
		}
		this._links = spanContext.links;
		this._attributes = {};
		this.setAttributes({
			[_sentry_conventions_attributes.SENTRY_ORIGIN]: "manual",
			[_sentry_conventions_attributes.SENTRY_OP]: spanContext.op,
			...spanContext.attributes
		});
		this._name = spanContext.name;
		if (spanContext.parentSpanId) this._parentSpanId = spanContext.parentSpanId;
		if ("sampled" in spanContext) this._sampled = spanContext.sampled;
		this._events = [];
		this._isStandaloneSpan = spanContext.isStandalone;
	}
	/** @inheritDoc */
	addLink(link) {
		if (this._frozen) return this;
		if (this._links) this._links.push(link);
		else this._links = [link];
		return this;
	}
	/** @inheritDoc */
	addLinks(links) {
		if (this._frozen) return this;
		if (this._links) this._links.push(...links);
		else this._links = links;
		return this;
	}
	/**
	* This should generally not be used,
	* but it is needed for being compliant with the OTEL Span interface.
	*
	* @hidden
	* @internal
	*/
	recordException(_exception, _time) {}
	/** @inheritdoc */
	spanContext() {
		const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
		return {
			spanId,
			traceId,
			traceFlags: sampled ? 1 : 0
		};
	}
	/** @inheritdoc */
	setAttribute(key, value) {
		if (this._frozen) return this;
		if (key === _sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE && value !== void 0 && !spanIsSegment(this)) {
			DEBUG_BUILD && debug.warn("[Tracing] Ignoring name source on a child span: this attribute is only valid on the root span.");
			return this;
		}
		if (value === void 0) delete this._attributes[key];
		else this._attributes[key] = value;
		return this;
	}
	/** @inheritdoc */
	setAttributes(attributes) {
		Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));
		return this;
	}
	/**
	* This should generally not be used,
	* but we need it for browser tracing where we want to adjust the start time afterwards.
	* USE THIS WITH CAUTION!
	*
	* @hidden
	* @internal
	*/
	updateStartTime(timeInput) {
		if (this._frozen) return;
		this._startTime = timeInputToSeconds(this, timeInput);
		this._startPerformanceNow = void 0;
	}
	/**
	* @inheritDoc
	*/
	setStatus(value) {
		if (this._frozen) return this;
		this._status = value;
		return this;
	}
	/**
	* @inheritDoc
	*/
	updateName(name) {
		if (this._frozen) return this;
		this._name = name;
		INTERNAL_setSegmentNameSourceIfSegment(this, "custom");
		return this;
	}
	/** @inheritdoc */
	end(endTimestamp) {
		if (this._endTime) return;
		this._endTime = endTimestamp == null ? this._getEndTimeFromDuration() : timeInputToSeconds(this, endTimestamp);
		logSpanEnd(this);
		this._onSpanEnded();
		this._frozen = spanIsTracerProviderSpan(this);
	}
	/**
	* Get JSON representation of this span.
	*
	* @hidden
	* @internal This method is purely for internal purposes and should not be used outside
	* of SDK code. If you need to get a JSON representation of a span,
	* use `spanToJSON(span)` instead.
	*/
	getStaticSpanJSON() {
		return {
			data: this._attributes,
			description: this._name,
			op: this._attributes[_sentry_conventions_attributes.SENTRY_OP],
			parent_span_id: this._parentSpanId,
			span_id: this._spanId,
			start_timestamp: this._startTime,
			status: getStatusMessage(this._status),
			timestamp: this._endTime,
			trace_id: this._traceId,
			origin: this._attributes[_sentry_conventions_attributes.SENTRY_ORIGIN],
			profile_id: this._attributes[_sentry_conventions_attributes.SENTRY_PROFILE_ID],
			exclusive_time: this._attributes[_sentry_conventions_attributes.SENTRY_EXCLUSIVE_TIME],
			measurements: timedEventsToMeasurements(this._events),
			links: convertSpanLinksForEnvelope(this._links)
		};
	}
	/**
	* Get {@link StreamedSpanJSON} representation of this span.
	*
	* @hidden
	* @internal This method is purely for internal purposes and should not be used outside
	* of SDK code. If you need to get a JSON representation of a span,
	* use `spanToJSON(span)` instead.
	*/
	getSpanJSON() {
		return {
			name: this._name ?? "",
			span_id: this._spanId,
			trace_id: this._traceId,
			parent_span_id: this._parentSpanId,
			start_timestamp: this._startTime,
			end_timestamp: this._endTime,
			is_segment: spanIsSegment(this),
			status: getSimpleStatus(this._status),
			attributes: addStatusMessageAttribute(this._attributes, this._status),
			links: getStreamedSpanLinks(this._links)
		};
	}
	/** @inheritdoc */
	isRecording() {
		return !this._endTime && !!this._sampled;
	}
	/**
	* @inheritdoc
	*/
	addEvent(name, attributesOrStartTime, startTime) {
		if (this._frozen) return this;
		DEBUG_BUILD && debug.log("[Tracing] Adding an event to span:", name);
		const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || void 0;
		const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};
		const event = {
			name,
			time: timeInputToSeconds(this, time),
			attributes
		};
		this._events.push(event);
		return this;
	}
	/**
	* Whether this span is sent on its own (as a v2 streamed span) rather than as part of a
	* transaction. Used internally; see `_isStandaloneSpan`.
	* @internal
	*/
	isStandaloneSpan() {
		return !!this._isStandaloneSpan;
	}
	/**
	* Returns the start time plus the `performance.now()` time since the span started.
	*
	* This way, the duration is correct even if the time origin was corrected while the span was running (e.g. after the
	* device slept), and it can never be negative.
	*/
	_getEndTimeFromDuration() {
		const performanceNow = safePerformanceNow();
		if (this._startPerformanceNow == null || performanceNow == null) return timestampInSeconds();
		return this._startTime + (performanceNow - this._startPerformanceNow) / 1e3;
	}
	/** Emit `spanEnd` when the span is ended. */
	_onSpanEnded() {
		const client = getClient();
		client?.emit("spanEnd", this);
		if (this._isStandaloneSpan) {
			if (!client) return;
			if (this._sampled) {
				sendStandaloneSpan(this, client);
				return;
			}
			DEBUG_BUILD && debug.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled.");
			return;
		}
		client?.emit("afterSpanEnd", this);
		const rootSpan = getRootSpan(this);
		if (rootSpan !== this) {
			const strategy = getSegmentSpanCaptureStrategy();
			if (strategy) {
				const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
				strategy.onChildSpanEnded(this, rootSpan, (options) => this._convertSpanToTransaction(options), scope);
			}
			return;
		}
		if (client && hasSpanStreamingEnabled(client)) {
			client.emit("afterSegmentSpanEnd", this);
			return;
		}
		const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
		const strategy = getSegmentSpanCaptureStrategy();
		if (strategy) strategy.onSegmentSpanEnded((options) => this._convertSpanToTransaction(options), scope);
		else {
			const transactionEvent = this._convertSpanToTransaction();
			if (transactionEvent) scope.captureEvent(transactionEvent);
		}
	}
	/**
	* Finish the transaction & prepare the event to send to Sentry.
	*/
	_convertSpanToTransaction(options = {}) {
		if (!isFullFinishedSpan(spanToStaticSpanJSON(this))) return;
		if (!this._name) {
			DEBUG_BUILD && debug.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
			this._name = "<unlabeled transaction>";
		}
		const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);
		const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;
		if (this._sampled !== true) return;
		options.onSpanCaptured?.(this);
		const spans = [];
		let droppedUnfinishedSpanCount = 0;
		for (const descendant of getSpanDescendants(this)) {
			if (descendant === this || isStandaloneSpan(descendant) || options.isSpanAlreadyCaptured?.(descendant)) continue;
			const spanJSON = spanToStaticSpanJSON(descendant);
			if (!isFullFinishedSpan(spanJSON)) {
				if (!options.onSpanCaptured) droppedUnfinishedSpanCount++;
				continue;
			}
			options.onSpanCaptured?.(descendant);
			spans.push(spanJSON);
		}
		const client = capturedSpanScope?.getClient() || getClient();
		if (droppedUnfinishedSpanCount) client?.recordDroppedEvent("invalid", "span", droppedUnfinishedSpanCount);
		if (spans.length > MAX_SPAN_COUNT) client?.recordDroppedEvent("buffer_overflow", "span", spans.length - MAX_SPAN_COUNT);
		const source = this._attributes[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE];
		delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
		let hasGenAiSpans = false;
		spans.forEach((span) => {
			delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
			if (span.op?.startsWith("gen_ai.")) hasGenAiSpans = true;
		});
		const transaction = {
			contexts: { trace: spanToTransactionTraceContext(this) },
			spans: spans.length > MAX_SPAN_COUNT ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans,
			start_timestamp: this._startTime,
			timestamp: this._endTime,
			transaction: this._name,
			type: "transaction",
			sdkProcessingMetadata: {
				capturedSpanScope,
				capturedSpanIsolationScope,
				dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),
				hasGenAiSpans
			},
			request: normalizedRequest,
			...source && { transaction_info: { source } }
		};
		const measurements = timedEventsToMeasurements(this._events);
		if (measurements && Object.keys(measurements).length) {
			DEBUG_BUILD && debug.log("[Measurements] Adding measurements to transaction event", JSON.stringify(measurements, void 0, 2));
			transaction.measurements = measurements;
		}
		return transaction;
	}
};
function timeInputToSeconds(span, input) {
	return spanIsTracerProviderSpan(span) ? otelTimeInputToSeconds(input) : spanTimeInputToSeconds(input);
}
function isSpanTimeInput(value) {
	return value && typeof value === "number" || value instanceof Date || Array.isArray(value);
}
function isFullFinishedSpan(input) {
	return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
}
/**
* `SentrySpan`s can be sent on their own (as a v2 streamed span) rather than as part of a transaction.
*
* TODO(standalone): remove once the static (transaction) trace lifecycle is dropped.
*/
function isStandaloneSpan(span) {
	return span instanceof SentrySpan && span.isStandaloneSpan();
}
/**
* Sends a single span on its own, as a v2 streamed span envelope.
*
* Used for standalone spans (e.g. a late INP web vital when span streaming is disabled): they are
* not part of a transaction and are not handled by the span streaming buffer, so we serialize and
* send them here directly.
*
* TODO(standalone): remove once the static (transaction) trace lifecycle is dropped.
*/
function sendStandaloneSpan(span, client) {
	const { beforeSendSpan, traceLifecycle } = client.getOptions();
	if (traceLifecycle === "static" && isStaticBeforeSendSpanCallback(beforeSendSpan)) {
		const serializedSpan = captureStandaloneSpanWithStaticCallback(span, client, beforeSendSpan);
		const dsc = getDynamicSamplingContextFromSpan(span);
		client.sendEnvelope(createStreamedSpanEnvelope([serializedSpan], dsc, client));
		return;
	}
	const { _segmentSpan, _segmentNameAtCapture, ...serializedSpan } = captureSpan(span, client);
	const dsc = getDynamicSamplingContextFromSpan(_segmentSpan);
	client.sendEnvelope(createStreamedSpanEnvelope([serializedSpan], dsc, client));
}
// src/tracing/trace.ts
/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
*
* If you want to create a span that is not set as active, use {@link startInactiveSpan}.
*
* You'll always get a span passed to the callback,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
function startSpan$1(options, callback) {
	const spanArguments = parseSentrySpanArguments(options);
	const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
	const customForkedScope = customScope?.clone();
	return withScope(customForkedScope, () => {
		return getActiveSpanWrapper(customParentSpan)(() => {
			const scope = getCurrentScope();
			const parentSpan = getParentSpan(customScope ?? scope, customParentSpan);
			const client = getClient();
			const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, client) : createChildOrRootSpan({
				parentSpan,
				spanArguments,
				forceTransaction,
				scope
			});
			return runCallback(activeSpan, !spanIsIgnored(activeSpan) || !parentSpan, () => callback(activeSpan), () => activeSpan.end());
		});
	});
}
/**
* Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span
* after the function is done automatically. Use `span.end()` to end the span.
*
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
*
* You'll always get a span passed to the callback,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
function startSpanManual$1(options, callback) {
	const spanArguments = parseSentrySpanArguments(options);
	const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
	const customForkedScope = customScope?.clone();
	return withScope(customForkedScope, () => {
		return getActiveSpanWrapper(customParentSpan)(() => {
			const scope = getCurrentScope();
			const parentSpan = getParentSpan(customScope ?? scope, customParentSpan);
			const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, getClient()) : createChildOrRootSpan({
				parentSpan,
				spanArguments,
				forceTransaction,
				scope
			});
			return runCallback(activeSpan, !spanIsIgnored(activeSpan) || !parentSpan, () => callback(activeSpan, () => activeSpan.end()));
		});
	});
}
/**
* Creates a span. This span is not set as active, so will not get automatic instrumentation spans
* as children or be able to be accessed via `Sentry.getActiveSpan()`.
*
* If you want to create a span that is set as active, use {@link startSpan}.
*
* This function will always return a span,
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
*/
function startInactiveSpan$1(options) {
	const spanArguments = parseSentrySpanArguments(options);
	const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
	return (customScope ? (callback) => withScope(customScope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback())(() => {
		const scope = getCurrentScope();
		const parentSpan = getParentSpan(customScope ?? scope, customParentSpan);
		const client = getClient();
		if (options.onlyIfParent && !parentSpan) return startMissingRequiredParentSpan(scope, client);
		return createChildOrRootSpan({
			parentSpan,
			spanArguments,
			forceTransaction,
			scope
		});
	});
}
/**
* Continue a trace from `sentry-trace` and `baggage` values.
* These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">`
* and `<meta name="baggage">` HTML tags.
*
* Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically
* be attached to the incoming trace.
*/
const continueTrace = (options, callback) => {
	const acs = getAsyncContextStrategy(getMainCarrier());
	if (acs.continueTrace) return acs.continueTrace(options, callback);
	const { sentryTrace, baggage } = options;
	const client = getClient();
	const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);
	if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) return startNewTrace(callback);
	return withScope((scope) => {
		const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
		scope.setPropagationContext(propagationContext);
		return withActiveSpan(null, callback);
	});
};
/**
* Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
* passed `null` to start an entirely new span tree.
*
* @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
* spans started within the callback will not be attached to a parent span.
* @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
* @returns the value returned from the provided callback function.
*/
function withActiveSpan(span, callback) {
	const acs = getAcs();
	if (acs.withActiveSpan) return acs.withActiveSpan(span, callback);
	return withScope((scope) => {
		_setSpanForScope(scope, span || void 0);
		return callback(scope);
	});
}
/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */
function suppressTracing(callback) {
	const acs = getAcs();
	if (acs.suppressTracing) return acs.suppressTracing(callback);
	return withScope((scope) => {
		scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });
		return callback();
	});
}
/** Check if tracing is suppressed. */
function isTracingSuppressed(scope = getCurrentScope()) {
	const acs = getAcs();
	if (acs.isTracingSuppressed) return acs.isTracingSuppressed(scope);
	return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true;
}
/**
* Starts a new trace for the duration of the provided callback. Spans started within the
* callback will be part of the new trace instead of a potentially previously started trace.
*
* Important: Only use this function if you want to override the default trace lifetime and
* propagation mechanism of the SDK for the duration and scope of the provided callback.
* The newly created trace will also be the root of a new distributed trace, for example if
* you make http requests within the callback.
* This function might be useful if the operation you want to instrument should not be part
* of a potentially ongoing trace.
*
* Default behavior:
* - Server-side: A new trace is started for each incoming request.
* - Browser: A new trace is started for each page our route. Navigating to a new route
*            or page will automatically create a new trace.
*/
function startNewTrace(callback) {
	const acs = getAcs();
	if (acs.startNewTrace) return acs.startNewTrace(callback);
	return withActiveSpan(null, () => {
		return withScope((scope) => {
			scope.setPropagationContext({
				traceId: generateTraceId(),
				sampleRand: safeMathRandom()
			});
			DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);
			return callback();
		});
	});
}
/**
* The placeholder returned from `startSpan*` when `onlyIfParent` is set but there is no parent span.
* It carries the current trace id and captured scopes so the trace data it propagates (and any nested
* span that resolves it as its root via `getRootSpan`) reads its DSC from the scope, preserving a
* continued trace's DSC instead of fabricating a fresh client one. Also records the dropped-span outcome.
*/
function startMissingRequiredParentSpan(scope, client) {
	client?.recordDroppedEvent("no_parent_span", "span");
	const span = new SentryNonRecordingSpan({
		dropReason: "no_parent_span",
		traceId: scope.getPropagationContext().traceId
	});
	setCapturedScopesOnSpan(span, scope, getIsolationScope());
	return span;
}
function createChildOrRootSpan({ parentSpan: resolvedParentSpan, spanArguments, forceTransaction, scope: currentScope }) {
	const isolationScope = getIsolationScope();
	const spanScope = {
		scope: currentScope,
		parentSpan: resolvedParentSpan
	};
	getClient()?.emit("prepareSpanScope", spanScope);
	const { scope, parentSpan } = spanScope;
	if (!hasSpansEnabled()) {
		const scopePropagationContext = scope.getPropagationContext();
		const span = new SentryNonRecordingSpan({ traceId: parentSpan ? parentSpan.spanContext().traceId : scopePropagationContext.traceId });
		if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, span);
		setCapturedScopesOnSpan(span, scope, isolationScope);
		return span;
	}
	const client = getClient();
	if (_shouldIgnoreStreamedSpan(client, spanArguments)) {
		if (!isTracingSuppressed(scope)) client?.recordDroppedEvent("ignored", "span");
		const ignoredSpan = new SentryNonRecordingSpan({
			dropReason: "ignored",
			traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId
		});
		if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, ignoredSpan);
		setCapturedScopesOnSpan(ignoredSpan, scope, isolationScope);
		return ignoredSpan;
	}
	let span;
	if (parentSpan && !forceTransaction) {
		span = _startChildSpan(parentSpan, scope, spanArguments, isolationScope);
		addChildSpanToSpan(parentSpan, span);
	} else if (parentSpan) {
		const dsc = getDynamicSamplingContextFromSpan(parentSpan);
		const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
		const parentSampled = spanIsSampled(parentSpan);
		span = _startRootSpan({
			traceId,
			parentSpanId,
			...spanArguments
		}, scope, isolationScope, parentSampled);
		freezeDscOnSpan(span, dsc);
	} else {
		const { traceId, dsc, parentSpanId, sampled: parentSampled, sampleRand } = scope.getPropagationContext();
		span = _startRootSpan({
			traceId,
			parentSpanId,
			...spanArguments
		}, scope, isolationScope, parentSampled);
		if (dsc) {
			const dscWithSampleRand = Object.keys(dsc).length === 0 && sampleRand !== void 0 ? { sample_rand: sampleRand.toString() } : dsc;
			freezeDscOnSpan(span, dscWithSampleRand);
		}
	}
	logSpanStart(span);
	return span;
}
/**
* This converts StartSpanOptions to SentrySpanArguments.
* For the most part (for now) we accept the same options,
* but some of them need to be transformed.
*/
function parseSentrySpanArguments(options) {
	const initialCtx = {
		isStandalone: options.experimental?.standalone,
		...options
	};
	if (options.op) initialCtx.attributes = {
		[_sentry_conventions_attributes.SENTRY_OP]: options.op,
		...options.attributes
	};
	if (options.startTime) {
		const ctx = { ...initialCtx };
		ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);
		delete ctx.startTime;
		return ctx;
	}
	return initialCtx;
}
function getAcs() {
	return getAsyncContextStrategy(getMainCarrier());
}
/**
* Runs the callback with the span active. When the async context strategy bridges to an ambient
* context (OTel), activation must go through it so the span lands on that context and
* instrumentation-created child spans nest under it; the scope alone is not consulted there.
*/
function _startRootSpan(spanArguments, scope, isolationScope, parentSampled) {
	const client = getClient();
	const options = client?.getOptions() || {};
	const { name = "" } = spanArguments;
	const mutableSpanSamplingData = {
		spanAttributes: { ...spanArguments.attributes },
		spanName: name,
		parentSampled
	};
	client?.emit("beforeSampling", mutableSpanSamplingData, { decision: false });
	const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;
	const finalAttributes = mutableSpanSamplingData.spanAttributes;
	const currentPropagationContext = scope.getPropagationContext();
	const _isTracingSuppressed = isTracingSuppressed(scope);
	const [sampled, sampleRate, localSampleRateWasApplied, dropReason] = _isTracingSuppressed ? [false] : sampleSpan(options, {
		name,
		parentSampled: finalParentSampled,
		attributes: finalAttributes,
		normalizedRequest: isolationScope.getScopeData().sdkProcessingMetadata.normalizedRequest,
		parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate)
	}, currentPropagationContext.sampleRand);
	const rootSpan = new SentrySpan({
		...spanArguments,
		attributes: {
			[_sentry_conventions_attributes.SENTRY_SEGMENT_NAME_SOURCE]: "custom",
			[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate !== void 0 && localSampleRateWasApplied ? sampleRate : void 0,
			...finalAttributes
		},
		sampled
	});
	if (!sampled && client && !_isTracingSuppressed) {
		DEBUG_BUILD && debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled.");
		const outcomeReason = dropReason || "sample_rate";
		if (!hasSpanStreamingEnabled(client) && !spanArguments.isStandalone) client.recordDroppedEvent(outcomeReason, "transaction");
		client.recordDroppedEvent(outcomeReason, "span");
	}
	setCapturedScopesOnSpan(rootSpan, scope, isolationScope);
	if (client) client.emit("spanStart", rootSpan);
	return rootSpan;
}
/**
* Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.
* This inherits the sampling decision from the parent span.
*/
function _startChildSpan(parentSpan, scope, spanArguments, isolationScope) {
	const { spanId, traceId } = parentSpan.spanContext();
	const _isTracingSuppressed = isTracingSuppressed(scope);
	const sampled = _isTracingSuppressed ? false : spanIsSampled(parentSpan);
	const childSpan = sampled ? new SentrySpan({
		...spanArguments,
		parentSpanId: spanId,
		traceId,
		sampled
	}) : new SentryNonRecordingSpan({ traceId });
	addChildSpanToSpan(parentSpan, childSpan);
	setCapturedScopesOnSpan(childSpan, scope, isolationScope);
	const client = getClient();
	if (!client) return childSpan;
	if (spanIsNonRecordingSpan(childSpan)) {
		if (spanIsNonRecordingSpan(parentSpan) && parentSpan.dropReason) {
			childSpan.dropReason = parentSpan.dropReason;
			client.recordDroppedEvent(parentSpan.dropReason, "span");
		} else if (!_isTracingSuppressed) {
			childSpan.dropReason = "sample_rate";
			client.recordDroppedEvent("sample_rate", "span");
		}
	}
	client.emit("spanStart", childSpan);
	return childSpan;
}
function getParentSpan(scope, customParentSpan) {
	if (customParentSpan) return customParentSpan;
	if (customParentSpan === null) return;
	const span = getActiveSpan(scope);
	if (!span) return;
	const client = getClient();
	if ((client ? client.getOptions() : {}).parentSpanIsAlwaysRootSpan) return getRootSpan(span);
	return span;
}
function getActiveSpanWrapper(parentSpan) {
	return parentSpan !== void 0 ? (callback) => {
		return withActiveSpan(parentSpan, callback);
	} : (callback) => callback();
}
function _shouldIgnoreStreamedSpan(client, spanArguments) {
	const ignoreSpans = client?.getOptions().ignoreSpans;
	if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) return false;
	return shouldIgnoreSpan({
		description: spanArguments.name || "",
		op: spanArguments.attributes?.[_sentry_conventions_attributes.SENTRY_OP] || spanArguments.op,
		attributes: spanArguments.attributes
	}, ignoreSpans);
}
/**
* Whether a span is an ignored (`ignoreSpans`) placeholder. Such a span must not be set as the active
* span when it has a parent, so its children attach to that parent and get re-parented rather than
* dropped with it. Shared with the OTel-based provider so both span pipelines apply the same rule.
*/
function spanIsIgnored(span) {
	return spanIsNonRecordingSpan(span) && span.dropReason === "ignored";
}
function runCallback(span, makeSpanActive, callback, finallyCallback) {
	return (makeSpanActive ? (callback) => {
		return withActiveSpan(span, () => {
			const scope = getCurrentScope();
			const creationScope = getCapturedScopesOnSpan(span).scope;
			if (creationScope) scope.setPropagationContext(creationScope.getPropagationContext());
			setCapturedScopesOnSpan(span, scope, getIsolationScope());
			return callback();
		});
	} : (callback) => callback())(() => handleCallbackErrors(() => callback(), (error) => {
		recordEscapedErrorSpan(error, span);
		const { status } = spanToStaticSpanJSON(span);
		if (span.isRecording() && status === "ok") span.setStatus({
			code: 2,
			message: "internal_error"
		});
	}, finallyCallback));
}
// src/tracing/browserSpanApi.ts
/**
* Browser variants of the span-start APIs.
*
* These exist purely so that the span streaming integration is only reachable from code that can
* actually start a span. `@sentry/browser`'s `init()` deliberately doesn't reference spanStreamingIntegration,
* so error-only apps tree-shake the entire span streaming graph away without needing
* the `__SENTRY_TRACING__` flag.
*/
const clientsWithIntegration = /* @__PURE__ */ new WeakSet();
/**
* Lazily install the browser span streaming integration.
*
* Defaults to the current client; pass one explicitly from integration hooks, where the client being
* set up isn't necessarily the current one.
*
* @internal
*/
function _INTERNAL_ensureBrowserSpanStreaming(client = getClient()) {
	if (!client || clientsWithIntegration.has(client) || !hasSpanStreamingEnabled(client)) return;
	clientsWithIntegration.add(client);
	client.addIntegration(spanStreamingIntegration());
}
/**
* Wraps a function with a span and finishes the span after the function is done.
*
* See {@link startSpan} in `@sentry/core` for details.
*/
function startSpan(options, callback) {
	_INTERNAL_ensureBrowserSpanStreaming();
	return startSpan$1(options, callback);
}
/**
* Similar to `startSpan`, but forces the span to be ended manually.
*
* See {@link startSpanManual} in `@sentry/core` for details.
*/
function startSpanManual(options, callback) {
	_INTERNAL_ensureBrowserSpanStreaming();
	return startSpanManual$1(options, callback);
}
/**
* Creates a span that is not set as active.
*
* See {@link startInactiveSpan} in `@sentry/core` for details.
*/
function startInactiveSpan(options) {
	_INTERNAL_ensureBrowserSpanStreaming();
	return startInactiveSpan$1(options);
}
// src/tracing/idleSpan.ts
const TRACING_DEFAULTS = {
	idleTimeout: 1e3,
	finalTimeout: 3e4,
	childSpanTimeout: 15e3
};
const FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed";
const FINISH_REASON_IDLE_TIMEOUT = "idleTimeout";
const FINISH_REASON_FINAL_TIMEOUT = "finalTimeout";
const FINISH_REASON_EXTERNAL_FINISH = "externalFinish";
/**
* An idle span is a span that automatically finishes. It does this by tracking child spans as activities.
* An idle span is always the active span.
*/
function startIdleSpan(startSpanOptions, options = {}) {
	const client = getClient();
	_INTERNAL_ensureBrowserSpanStreaming(client);
	const activities = /* @__PURE__ */ new Map();
	let _finished = false;
	let _idleTimeoutID;
	let _childSpanTimeoutID;
	let _finishReason = FINISH_REASON_EXTERNAL_FINISH;
	let _autoFinishAllowed = !options.disableAutoFinish;
	const _cleanupHooks = [];
	const { idleTimeout = TRACING_DEFAULTS.idleTimeout, finalTimeout = TRACING_DEFAULTS.finalTimeout, childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout, trimIdleSpanEndTimestamp = true } = options;
	const scope = getCurrentScope();
	if (!client || !hasSpansEnabled()) {
		const span = new SentryNonRecordingSpan({ traceId: scope.getPropagationContext().traceId });
		setCapturedScopesOnSpan(span, scope, getIsolationScope());
		return span;
	}
	const previousActiveSpan = getActiveSpan();
	const span = startInactiveSpan$1(startSpanOptions);
	_setSpanForScope(getCurrentScope(), span);
	DEBUG_BUILD && debug.log("[Tracing] Started span is an idle span");
	span.end = new Proxy(span.end, { apply(target, thisArg, args) {
		client.emit("beforeIdleSpanEnd", span);
		if (spanIsNonRecordingSpan(thisArg)) return;
		const [definedEndTimestamp, ...rest] = args;
		const spanEndTimestamp = spanTimeInputToSeconds(definedEndTimestamp || timestampInSeconds());
		const spans = getSpanDescendants(span).filter((child) => child !== span);
		const spanJson = spanToStaticSpanJSON(span);
		if (!spans.length || !trimIdleSpanEndTimestamp) {
			onIdleSpanEnded(spanEndTimestamp);
			return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);
		}
		const ignoreSpans = client.getOptions().ignoreSpans;
		const latestSpanEndTimestamp = spans?.reduce((acc, current) => {
			const currentSpanJson = spanToStaticSpanJSON(current);
			if (!currentSpanJson.timestamp) return acc;
			if (ignoreSpans && shouldIgnoreSpan({
				description: currentSpanJson.description,
				op: currentSpanJson.op,
				attributes: currentSpanJson.data
			}, ignoreSpans)) return acc;
			return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;
		}, void 0);
		const spanStartTimestamp = spanJson.start_timestamp;
		const endTimestamp = Math.min(spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1e3 : 1e400, Math.max(spanStartTimestamp || -1e400, Math.min(spanEndTimestamp, latestSpanEndTimestamp || 1e400)));
		onIdleSpanEnded(endTimestamp);
		return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);
	} });
	/**
	* Cancels the existing idle timeout, if there is one.
	*/
	function _cancelIdleTimeout() {
		if (_idleTimeoutID) {
			clearTimeout(_idleTimeoutID);
			_idleTimeoutID = void 0;
		}
	}
	/**
	* Cancels the existing child span timeout, if there is one.
	*/
	function _cancelChildSpanTimeout() {
		if (_childSpanTimeoutID) {
			clearTimeout(_childSpanTimeoutID);
			_childSpanTimeoutID = void 0;
		}
	}
	/**
	* Restarts idle timeout, if there is no running idle timeout it will start one.
	*/
	function _restartIdleTimeout(endTimestamp) {
		_cancelIdleTimeout();
		_idleTimeoutID = setTimeout(() => {
			if (!_finished && activities.size === 0 && _autoFinishAllowed) {
				_finishReason = FINISH_REASON_IDLE_TIMEOUT;
				span.end(endTimestamp);
			}
		}, idleTimeout);
	}
	/**
	* Restarts child span timeout, if there is none running it will start one.
	*/
	function _restartChildSpanTimeout(endTimestamp) {
		_cancelChildSpanTimeout();
		_childSpanTimeoutID = setTimeout(() => {
			if (!_finished && _autoFinishAllowed) {
				_finishReason = FINISH_REASON_HEARTBEAT_FAILED;
				span.end(endTimestamp);
			}
		}, childSpanTimeout);
	}
	/**
	* Start tracking a specific activity.
	* @param spanId The span id that represents the activity
	*/
	function _pushActivity(spanId) {
		_cancelIdleTimeout();
		activities.set(spanId, true);
		_restartChildSpanTimeout(timestampInSeconds() + childSpanTimeout / 1e3);
	}
	/**
	* Remove an activity from usage
	* @param spanId The span id that represents the activity
	*/
	function _popActivity(spanId) {
		if (activities.has(spanId)) activities.delete(spanId);
		if (activities.size === 0) {
			_restartIdleTimeout(timestampInSeconds() + idleTimeout / 1e3);
			_cancelChildSpanTimeout();
		}
	}
	function onIdleSpanEnded(endTimestamp) {
		_finished = true;
		activities.clear();
		_cleanupHooks.forEach((cleanup) => cleanup());
		_setSpanForScope(scope, previousActiveSpan);
		const spanJSON = spanToStaticSpanJSON(span);
		const { start_timestamp: startTimestamp } = spanJSON;
		if (!startTimestamp) return;
		if (!spanJSON.data[_sentry_conventions_attributes.SENTRY_IDLE_SPAN_FINISH_REASON]) span.setAttribute(_sentry_conventions_attributes.SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);
		const currentStatus = spanJSON.status;
		if (!currentStatus || currentStatus === "unknown") span.setStatus({ code: 1 });
		debug.log(`[Tracing] Idle span "${spanJSON.op}" finished`);
		const childSpans = getSpanDescendants(span).filter((child) => child !== span);
		let discardedSpans = 0;
		childSpans.forEach((childSpan) => {
			if (childSpan.isRecording()) {
				childSpan.setStatus({
					code: 2,
					message: "cancelled"
				});
				childSpan.end(endTimestamp);
				DEBUG_BUILD && debug.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2));
			}
			const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = spanToStaticSpanJSON(childSpan);
			const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;
			const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3;
			const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;
			if (DEBUG_BUILD) {
				const stringifiedSpan = JSON.stringify(childSpan, void 0, 2);
				if (!spanStartedBeforeIdleSpanEnd) debug.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan);
				else if (!spanEndedBeforeFinalTimeout) debug.log("[Tracing] Discarding span since it finished after idle span final timeout", stringifiedSpan);
			}
			if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {
				removeChildSpanFromSpan(span, childSpan);
				discardedSpans++;
			}
		});
		if (discardedSpans > 0) span.setAttribute("sentry.idle_span_discarded_spans", discardedSpans);
	}
	_cleanupHooks.push(client.on("spanStart", (startedSpan) => {
		if (_finished || startedSpan === span || !!spanToJSON(startedSpan).end_timestamp || startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan()) return;
		if (getSpanDescendants(span).includes(startedSpan)) _pushActivity(startedSpan.spanContext().spanId);
	}));
	_cleanupHooks.push(client.on("spanEnd", (endedSpan) => {
		if (_finished) return;
		_popActivity(endedSpan.spanContext().spanId);
	}));
	_cleanupHooks.push(client.on("idleSpanEnableAutoFinish", (spanToAllowAutoFinish) => {
		if (spanToAllowAutoFinish === span) {
			_autoFinishAllowed = true;
			_restartIdleTimeout();
			if (activities.size) _restartChildSpanTimeout();
		}
	}));
	if (!options.disableAutoFinish) _restartIdleTimeout();
	setTimeout(() => {
		if (!_finished) {
			span.setStatus({
				code: 2,
				message: "deadline_exceeded"
			});
			_finishReason = FINISH_REASON_FINAL_TIMEOUT;
			span.end();
		}
	}, finalTimeout);
	return span;
}
// src/utils/debounce.ts
/**
* Heavily simplified debounce function based on lodash.debounce.
*
* This function takes a callback function (@param fun) and delays its invocation
* by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,
* which ensures that the callback is invoked at least once after the specified max. wait time.
*
* @param func the function whose invocation is to be debounced
* @param wait the minimum time until the function is invoked after it was called once
* @param options the options object, which can contain the `maxWait` property
*
* @returns the debounced version of the function, which needs to be called at least once to start the
*          debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc
*          was already invoked in the meantime, return @param func's return value.
*          The debounced function has two additional properties:
*          - `flush`: Invokes the debounced function immediately and returns its return value
*          - `cancel`: Cancels the debouncing process and resets the debouncing timer
*/
function debounce(func, wait, options) {
	let callbackReturnValue;
	let timerId;
	let maxTimerId;
	const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0;
	const setTimeoutImpl = options?.setTimeoutImpl || setTimeout;
	function invokeFunc() {
		cancelTimers();
		callbackReturnValue = func();
		return callbackReturnValue;
	}
	function cancelTimers() {
		timerId !== void 0 && clearTimeout(timerId);
		maxTimerId !== void 0 && clearTimeout(maxTimerId);
		timerId = maxTimerId = void 0;
	}
	function flush() {
		if (timerId !== void 0 || maxTimerId !== void 0) return invokeFunc();
		return callbackReturnValue;
	}
	function debounced() {
		if (timerId) clearTimeout(timerId);
		timerId = setTimeoutImpl(invokeFunc, wait);
		if (maxWait && maxTimerId === void 0) maxTimerId = setTimeoutImpl(invokeFunc, maxWait);
		return callbackReturnValue;
	}
	debounced.cancel = cancelTimers;
	debounced.flush = flush;
	return debounced;
}
// src/tracing/deferSegmentSpanCapture.ts
const CAPTURED_SPANS = /* @__PURE__ */ new WeakSet();
const isSpanAlreadyCaptured = (span) => CAPTURED_SPANS.has(span);
const markSpanCaptured = (span) => {
	CAPTURED_SPANS.add(span);
};
const CLIENT_QUEUES = /* @__PURE__ */ new WeakMap();
/**
* @private Private API with no semver guarantees!
*
* Enable deferred segment-span transaction capture for a client: create its debounced queue and
* register the strategy (idempotent).
*
* `SentrySpan` otherwise assembles the transaction synchronously the instant a segment span ends, which
* drops children whose async instrumentation closes them later (a diagnostics-channel `asyncEnd`
* callback in the same tick, or engine spans replayed on a later tick). The debounced snapshot delays
* capture just enough for those later span ends to land first; a child that still ends after it is
* emitted as its own orphan transaction. Pending captures drain on the client's `flush` hook, so
* `Sentry.flush()` / `client.close()` cannot resolve before they run.
*/
function _INTERNAL_setDeferSegmentSpanCapture(client) {
	if (!getSegmentSpanCaptureStrategy()) setSegmentSpanCaptureStrategy(deferredSegmentSpanCaptureStrategy);
	if (CLIENT_QUEUES.has(client)) return;
	const pendingCaptures = /* @__PURE__ */ new Set();
	const debouncedDrain = debounce(() => {
		const captures = [...pendingCaptures];
		pendingCaptures.clear();
		for (const capture of captures) capture();
	}, 1, { maxWait: 100 });
	client.on("flush", () => {
		debouncedDrain.flush();
	});
	CLIENT_QUEUES.set(client, (capture) => {
		pendingCaptures.add(capture);
		debouncedDrain();
	});
}
const deferredSegmentSpanCaptureStrategy = {
	onSegmentSpanEnded(convert, scope) {
		const client = scope.getClient();
		const enqueue = client && CLIENT_QUEUES.get(client);
		if (!enqueue) {
			const transactionEvent = convert();
			if (transactionEvent) client?.captureEvent(transactionEvent);
			return;
		}
		enqueue(() => {
			const transactionEvent = convert({
				isSpanAlreadyCaptured,
				onSpanCaptured: markSpanCaptured
			});
			if (transactionEvent) client.captureEvent(transactionEvent);
		});
	},
	onChildSpanEnded(span, rootSpan, convert, scope) {
		if (CAPTURED_SPANS.has(span) || !CAPTURED_SPANS.has(rootSpan)) return;
		const client = scope.getClient();
		const enqueue = client && CLIENT_QUEUES.get(client);
		const captureOrphan = () => {
			const transactionEvent = convert({
				isSpanAlreadyCaptured,
				onSpanCaptured: markSpanCaptured
			});
			if (transactionEvent?.contexts?.trace?.data) transactionEvent.contexts.trace.data["sentry.parent_span_already_sent"] = true;
			if (transactionEvent) client?.captureEvent(transactionEvent);
		};
		if (enqueue) enqueue(captureOrphan);
		else captureOrphan();
	}
};
// src/tracing/bindScopeToEmitter.ts
/** Listener-registration methods we patch so listeners inherit the bound scope. */
const ADD_LISTENER_METHODS = [
	"addListener",
	"on",
	"once",
	"prependListener",
	"prependOnceListener",
	"addEventListener"
];
/** Listener-removal methods we patch so removals find the scope-bound wrapper. */
const REMOVE_LISTENER_METHODS = [
	"removeListener",
	"off",
	"removeEventListener"
];
/** Symbol under which the patch map is stashed on a bound emitter. */
const SCOPE_BOUND_LISTENERS = Symbol("SentryScopeBoundListeners");
let registeringWrapper;
function isReentrantWrapperRegistration(listener) {
	return registeringWrapper !== void 0 && (listener === registeringWrapper || listener.listener === registeringWrapper);
}
/**
* Binds a scope to the given event emitter, so that any listener added to it runs with that scope
* (and therefore the active span) active — even if the listener fires later, in a different async
* context.
*
* By default the currently active scope is bound, captured at the time this function is called.
* Pass an explicit `scope` to bind a different one.
*
* This is useful when instrumenting APIs that hand back an event emitter (e.g. a streamed database
* query) whose `'data'` / `'error'` / `'end'` listeners would otherwise lose the trace context.
*
* Works with both Node.js `EventEmitter`s (`on`, `addListener`, ...) and DOM `EventTarget`s
* (`addEventListener`). Objects exposing none of these methods are returned untouched.
*
* The isolation scope is intentionally not captured — it is carried along by the active async
* context. This mirrors the event-emitter behavior of OpenTelemetry's `ContextManager.bind`.
*/
function bindScopeToEmitter(emitter, scope = getCurrentScope()) {
	const ee = emitter;
	if (getPatchMap(ee)) return emitter;
	createPatchMap(ee);
	for (const methodName of ADD_LISTENER_METHODS) {
		if (typeof ee[methodName] !== "function") continue;
		ee[methodName] = patchAddListener(ee, ee[methodName], scope);
	}
	for (const methodName of REMOVE_LISTENER_METHODS) {
		if (typeof ee[methodName] !== "function") continue;
		ee[methodName] = patchRemoveListener(ee, ee[methodName]);
	}
	if (typeof ee.removeAllListeners === "function") ee.removeAllListeners = patchRemoveAllListeners(ee, ee.removeAllListeners);
	return emitter;
}
/** Wraps a listener so it runs with the given scope active. */
function bindListenerToScope(listener, scope) {
	return function(...args) {
		return withScope(scope, () => listener.apply(this, args));
	};
}
function isBoundListener(listener) {
	return typeof listener === "function";
}
function patchAddListener(ee, original, scope) {
	return function(...args) {
		const event = args[0];
		const listener = args[1];
		const rest = args.slice(2);
		if (!isBoundListener(listener) || isReentrantWrapperRegistration(listener)) return original.apply(this, args);
		const map = getPatchMap(ee) || createPatchMap(ee);
		let listeners = map.get(event);
		if (!listeners) {
			listeners = /* @__PURE__ */ new WeakMap();
			map.set(event, listeners);
		}
		let boundListener = listeners.get(listener);
		if (!boundListener) {
			boundListener = bindListenerToScope(listener, scope);
			listeners.set(listener, boundListener);
		}
		const previous = registeringWrapper;
		registeringWrapper = boundListener;
		try {
			return original.call(this, event, boundListener, ...rest);
		} finally {
			registeringWrapper = previous;
		}
	};
}
function patchRemoveListener(ee, original) {
	return function(...args) {
		const event = args[0];
		const listener = args[1];
		const rest = args.slice(2);
		const boundListener = isBoundListener(listener) ? getPatchMap(ee)?.get(event)?.get(listener) : void 0;
		if (!boundListener) return original.apply(this, args);
		return original.call(this, event, boundListener, ...rest);
	};
}
function patchRemoveAllListeners(ee, original) {
	return function(...args) {
		const map = getPatchMap(ee);
		if (map) {
			if (args.length === 0) createPatchMap(ee);
			else {
				const event = args[0];
				map.delete(event);
			}
		}
		return original.apply(this, args);
	};
}
function createPatchMap(ee) {
	const map = /* @__PURE__ */ new Map();
	ee[SCOPE_BOUND_LISTENERS] = map;
	return map;
}
function getPatchMap(ee) {
	return ee[SCOPE_BOUND_LISTENERS];
}
// src/utils/data-collection/filtering-snippets.ts
const FILTERED_VALUE = "[Filtered]";
const SENSITIVE_KEY_SNIPPETS = [
	"auth",
	"token",
	"secret",
	"session",
	"password",
	"passwd",
	"pwd",
	"key",
	"jwt",
	"bearer",
	"sso",
	"saml",
	"csrf",
	"xsrf",
	"credentials",
	"sid",
	"identity",
	"set-cookie",
	"cookie"
];
/**
* Extra substrings matched only against individual Cookie / Set-Cookie **names** (not header names),
* so we can cover common session secrets that do not match {@link SENSITIVE_KEY_SNIPPETS}
* (e.g. `connect.sid` does not contain `session`) without false positives on arbitrary HTTP headers.
*
* Cookie names are checked with the same `includes()` list as headers plus these entries; omit redundant
* cookie-only snippets that are already implied by a header match (e.g. `oauth` → `auth`, `id_token` → `token`,
* `next-auth` → `auth`).
*/
const SENSITIVE_COOKIE_NAME_SNIPPETS = [
	".sid",
	"sessid",
	"remember",
	"oidc",
	"pkce",
	"nonce",
	"__secure-",
	"__host-",
	"awsalb",
	"awselb",
	"akamai",
	"__stripe",
	"cognito",
	"firebase",
	"supabase",
	"sb-",
	"mfa",
	"2fa"
];
// src/utils/data-collection/filterKeyValueData.ts
function isSensitiveKey(lower, denySnippets) {
	return denySnippets.some((snippet) => lower.includes(snippet));
}
function shouldFilterDataKey(key, behavior, additionalDenyTerms) {
	if (behavior === false) return true;
	const lowerKey = key.toLowerCase();
	if (isSensitiveKey(lowerKey, additionalDenyTerms != null ? [...SENSITIVE_KEY_SNIPPETS, ...additionalDenyTerms] : SENSITIVE_KEY_SNIPPETS)) return true;
	if (behavior === true) return false;
	const matchesConfiguredTerm = ("deny" in behavior ? behavior.deny : behavior.allow).some((term) => lowerKey.includes(term.toLowerCase()));
	return "deny" in behavior ? matchesConfiguredTerm : !matchesConfiguredTerm;
}
/**
* Filters a key-value record according to a `CollectBehavior`.
*
* Key names are always preserved. Values are either kept, replaced with
* `[Filtered]`, or the entire record is dropped (off mode).
*
* @param additionalDenyTerms - Additional sensitive snippets to check beyond the built-in denylist.
*/
function filterKeyValueData(data, behavior, additionalDenyTerms) {
	if (behavior === false) return {};
	const result = {};
	for (const key of Object.keys(data)) result[key] = shouldFilterDataKey(key, behavior, additionalDenyTerms) ? FILTERED_VALUE : data[key];
	return result;
}
// src/utils/syncpromise.ts
/** SyncPromise internal states */
const STATE_PENDING = 0;
const STATE_RESOLVED = 1;
const STATE_REJECTED = 2;
/**
* Creates a resolved sync promise.
*
* @param value the value to resolve the promise with
* @returns the resolved sync promise
*/
function resolvedSyncPromise(value) {
	return new SyncPromise((resolve) => {
		resolve(value);
	});
}
/**
* Creates a rejected sync promise.
*
* @param value the value to reject the promise with
* @returns the rejected sync promise
*/
function rejectedSyncPromise(reason) {
	return new SyncPromise((_, reject) => {
		reject(reason);
	});
}
/**
* Thenable class that behaves like a Promise and follows it's interface
* but is not async internally
*/
var SyncPromise = class SyncPromise {
	constructor(executor) {
		this._state = STATE_PENDING;
		this._handlers = [];
		this._runExecutor(executor);
	}
	/** @inheritdoc */
	then(onfulfilled, onrejected) {
		return new SyncPromise((resolve, reject) => {
			this._handlers.push([
				false,
				(result) => {
					if (!onfulfilled) resolve(result);
					else try {
						resolve(onfulfilled(result));
					} catch (e) {
						reject(e);
					}
				},
				(reason) => {
					if (!onrejected) reject(reason);
					else try {
						resolve(onrejected(reason));
					} catch (e) {
						reject(e);
					}
				}
			]);
			this._executeHandlers();
		});
	}
	/** @inheritdoc */
	catch(onrejected) {
		return this.then((val) => val, onrejected);
	}
	/** @inheritdoc */
	finally(onfinally) {
		return new SyncPromise((resolve, reject) => {
			let val;
			let isRejected;
			return this.then((value) => {
				isRejected = false;
				val = value;
				if (onfinally) onfinally();
			}, (reason) => {
				isRejected = true;
				val = reason;
				if (onfinally) onfinally();
			}).then(() => {
				if (isRejected) {
					reject(val);
					return;
				}
				resolve(val);
			});
		});
	}
	/** Excute the resolve/reject handlers. */
	_executeHandlers() {
		if (this._state === STATE_PENDING) return;
		const cachedHandlers = this._handlers.slice();
		this._handlers = [];
		cachedHandlers.forEach((handler) => {
			if (handler[0]) return;
			if (this._state === STATE_RESOLVED) handler[1](this._value);
			if (this._state === STATE_REJECTED) handler[2](this._value);
			handler[0] = true;
		});
	}
	/** Run the executor for the SyncPromise. */
	_runExecutor(executor) {
		const setResult = (state, value) => {
			if (this._state !== STATE_PENDING) return;
			if (isThenable(value)) {
				value.then(resolve, reject);
				return;
			}
			this._state = state;
			this._value = value;
			this._executeHandlers();
		};
		const resolve = (value) => {
			setResult(STATE_RESOLVED, value);
		};
		const reject = (reason) => {
			setResult(STATE_REJECTED, reason);
		};
		try {
			executor(resolve, reject);
		} catch (e) {
			reject(e);
		}
	}
};
// src/eventProcessors.ts
/**
* Process an array of event processors, returning the processed event (or `null` if the event was dropped).
*/
function notifyEventProcessors(processors, event, hint, index = 0, onDrop) {
	try {
		const result = _notifyEventProcessors(event, hint, processors, index, onDrop);
		return isThenable(result) ? result : resolvedSyncPromise(result);
	} catch (error) {
		return rejectedSyncPromise(error);
	}
}
function _notifyEventProcessors(event, hint, processors, index, onDrop) {
	const processor = processors[index];
	if (!event || !processor) return event;
	const processorName = `Event processor "${processor.id || "?"}"`;
	let callbackError = false;
	const result = safeCallback(DEBUG_BUILD ? `${processorName} threw an error, dropping event:` : "", () => processor({ ...event }, hint), () => {
		callbackError = true;
		return null;
	});
	DEBUG_BUILD && result === null && debug.log(`${processorName} dropped event`);
	if (isThenable(result)) return result.then((final) => {
		if (!final) {
			onDrop?.(callbackError ? "callback_error" : "event_processor");
			return null;
		}
		return _notifyEventProcessors(final, hint, processors, index + 1, onDrop);
	});
	if (!result) {
		onDrop?.(callbackError ? "callback_error" : "event_processor");
		return null;
	}
	return _notifyEventProcessors(result, hint, processors, index + 1, onDrop);
}
// src/utils/debug-ids.ts
let parsedStackResults;
let lastSentryKeysCount;
let lastNativeKeysCount;
let cachedFilenameDebugIds;
/**
* Returns a map of filenames to debug identifiers.
* Supports both proprietary _sentryDebugIds and native _debugIds (e.g., from Vercel) formats.
*/
function getFilenameToDebugIdMap(stackParser) {
	const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds;
	const nativeDebugIdMap = GLOBAL_OBJ._debugIds;
	if (!sentryDebugIdMap && !nativeDebugIdMap) return {};
	const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : [];
	const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : [];
	if (cachedFilenameDebugIds && sentryDebugIdKeys.length === lastSentryKeysCount && nativeDebugIdKeys.length === lastNativeKeysCount) return cachedFilenameDebugIds;
	lastSentryKeysCount = sentryDebugIdKeys.length;
	lastNativeKeysCount = nativeDebugIdKeys.length;
	cachedFilenameDebugIds = {};
	if (!parsedStackResults) parsedStackResults = {};
	const processDebugIds = (debugIdKeys, debugIdMap) => {
		for (const key of debugIdKeys) {
			const debugId = debugIdMap[key];
			const result = parsedStackResults?.[key];
			if (result && cachedFilenameDebugIds && debugId) {
				cachedFilenameDebugIds[result[0]] = debugId;
				if (parsedStackResults) parsedStackResults[key] = [result[0], debugId];
			} else if (debugId) {
				const parsedStack = stackParser(key);
				for (let i = parsedStack.length - 1; i >= 0; i--) {
					const filename = parsedStack[i]?.filename;
					if (filename && cachedFilenameDebugIds && parsedStackResults) {
						cachedFilenameDebugIds[filename] = debugId;
						parsedStackResults[key] = [filename, debugId];
						break;
					}
				}
			}
		}
	};
	if (sentryDebugIdMap) processDebugIds(sentryDebugIdKeys, sentryDebugIdMap);
	if (nativeDebugIdMap) processDebugIds(nativeDebugIdKeys, nativeDebugIdMap);
	return cachedFilenameDebugIds;
}
/**
* Returns a list of debug images for the given resources.
*/
function getDebugImagesForResources(stackParser, resource_paths) {
	const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
	if (!filenameDebugIdMap) return [];
	const images = [];
	for (const path of resource_paths) {
		const normalizedPath = normalizeStackTracePath(path);
		if (normalizedPath && filenameDebugIdMap[normalizedPath]) images.push({
			type: "sourcemap",
			code_file: path,
			debug_id: filenameDebugIdMap[normalizedPath]
		});
	}
	return images;
}
// src/utils/eventUtils.ts
function isInternalException(hint) {
	return hint.data?.__sentry__ === true;
}
/**
* Get a list of possible event messages from a Sentry event.
*/
function getPossibleEventMessages(event) {
	const possibleMessages = [];
	if (event.message) possibleMessages.push(event.message);
	try {
		const lastException = event.exception.values[event.exception.values.length - 1];
		if (lastException?.value) {
			possibleMessages.push(lastException.value);
			if (lastException.type) possibleMessages.push(`${lastException.type}: ${lastException.value}`);
		}
	} catch {}
	return possibleMessages;
}
// src/utils/prepareEvent.ts
/**
* Adds common information to events.
*
* The information includes release and environment from `options`,
* breadcrumbs and context (extra, tags and user) from the scope.
*
* Information that is already present in the event is never overwritten. For
* nested objects, such as the context, keys are merged.
*
* @param event The original event.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A new event with more information, or `null` if an event processor dropped it (or threw). In that case the
*   drop has already been recorded on the client, so callers must not record it again.
* @hidden
*/
function prepareEvent(options, event, hint, scope, client, isolationScope) {
	const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;
	const prepared = {
		...event,
		event_id: event.event_id || hint.event_id || uuid4(),
		timestamp: event.timestamp || dateTimestampInSeconds()
	};
	const integrations = hint.integrations || options.integrations.map((i) => i.name);
	applyClientOptions(prepared, options);
	applyIntegrationsMetadata(prepared, integrations);
	if (client) client.emit("applyFrameMetadata", event);
	if (event.type === void 0) applyDebugIds(prepared, options.stackParser);
	const finalScope = getFinalScope(scope, hint.captureContext);
	if (hint.mechanism) addExceptionMechanismToCapturedException(prepared, hint.mechanism);
	const clientEventProcessors = client ? client.getEventProcessors() : [];
	const data = getCombinedScopeData(isolationScope, finalScope);
	const attachments = [...hint.attachments || [], ...data.attachments];
	if (attachments.length) hint.attachments = attachments;
	applyScopeDataToEvent(prepared, data);
	const span = getActiveSpan(finalScope);
	if (span) applySpanToEvent(prepared, span);
	applyEscapedErrorSpanToEvent(prepared, hint, finalScope);
	const eventProcessors = [...clientEventProcessors, ...data.eventProcessors];
	const isTransaction = event.type === "transaction";
	const spanCountBeforeProcessing = event.spans?.length || 0;
	return (isInternalException(hint) ? resolvedSyncPromise(prepared) : notifyEventProcessors(eventProcessors, prepared, hint, 0, (reason) => {
		if (!client) return;
		client.recordDroppedEvent(reason, getDataCategoryByType(event.type));
		if (isTransaction) client.recordDroppedEvent(reason, "span", 1 + spanCountBeforeProcessing);
	})).then((evt) => {
		if (!evt) return null;
		if (isTransaction && client) {
			const droppedSpanCount = spanCountBeforeProcessing - (evt.spans?.length || 0);
			if (droppedSpanCount > 0) client.recordDroppedEvent("event_processor", "span", droppedSpanCount);
		}
		applyDebugMeta(evt);
		if (typeof normalizeDepth === "number" && normalizeDepth > 0) return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
		return evt;
	});
}
/**
* Enhances event using the client configuration.
* It takes care of all "static" values like environment, release and `dist`,
* as well as truncating overly long values.
*
* Only exported for tests.
*
* @param event event instance to be enhanced
*/
function applyClientOptions(event, options) {
	const { environment, release, dist, maxValueLength } = options;
	event.environment = event.environment || environment || "production";
	if (!event.release && release) event.release = release;
	if (!event.dist && dist) event.dist = dist;
	const request = event.request;
	if (request?.url && maxValueLength) request.url = truncate(request.url, maxValueLength);
	if (maxValueLength) event.exception?.values?.forEach((exception) => {
		if (exception.value) exception.value = truncate(exception.value, maxValueLength);
	});
}
/**
* Puts debug IDs into the stack frames of an error event.
*/
function applyDebugIds(event, stackParser) {
	const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
	event.exception?.values?.forEach((exception) => {
		exception.stacktrace?.frames?.forEach((frame) => {
			if (frame.filename) frame.debug_id = filenameDebugIdMap[frame.filename];
		});
	});
}
/**
* Moves debug IDs from the stack frames of an error event into the debug_meta field.
*/
function applyDebugMeta(event) {
	const filenameDebugIdMap = {};
	event.exception?.values?.forEach((exception) => {
		exception.stacktrace?.frames?.forEach((frame) => {
			if (frame.debug_id) {
				if (frame.abs_path) filenameDebugIdMap[frame.abs_path] = frame.debug_id;
				else if (frame.filename) filenameDebugIdMap[frame.filename] = frame.debug_id;
				delete frame.debug_id;
			}
		});
	});
	if (Object.keys(filenameDebugIdMap).length === 0) return;
	event.debug_meta = event.debug_meta || {};
	event.debug_meta.images = event.debug_meta.images || [];
	const images = event.debug_meta.images;
	Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
		images.push({
			type: "sourcemap",
			code_file: filename,
			debug_id
		});
	});
}
/**
* This function adds all used integrations to the SDK info in the event.
* @param event The event that will be filled with all integrations.
*/
function applyIntegrationsMetadata(event, integrationNames) {
	if (integrationNames.length > 0) {
		event.sdk = event.sdk || {};
		event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];
	}
}
/**
* Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
* Normalized keys:
* - `breadcrumbs.data`
* - `user`
* - `contexts`
* - `extra`
* @param event Event
* @returns Normalized event
*/
function normalizeEvent(event, depth, maxBreadth) {
	if (!event) return null;
	const normalized = {
		...event,
		...event.breadcrumbs && { breadcrumbs: event.breadcrumbs.map((b) => ({
			...b,
			...b.data && { data: normalize(b.data, depth, maxBreadth) }
		})) },
		...event.user && { user: normalize(event.user, depth, maxBreadth) },
		...event.contexts && { contexts: normalize(event.contexts, depth, maxBreadth) },
		...event.extra && { extra: normalize(event.extra, depth, maxBreadth) }
	};
	if (event.contexts?.trace && normalized.contexts) {
		normalized.contexts.trace = event.contexts.trace;
		if (event.contexts.trace.data) normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);
	}
	if (event.spans) normalized.spans = event.spans.map((span) => {
		return {
			...span,
			...span.data && { data: normalize(span.data, depth, maxBreadth) }
		};
	});
	if (event.contexts?.flags && normalized.contexts) normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);
	return normalized;
}
function getFinalScope(scope, captureContext) {
	if (!captureContext) return scope;
	const finalScope = scope ? scope.clone() : new Scope();
	finalScope.update(captureContext);
	return finalScope;
}
/**
* Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.
* This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.
*/
function parseEventHintOrCaptureContext(hint) {
	if (!hint) return;
	if (hintIsScopeOrFunction(hint)) return { captureContext: hint };
	if (hintIsScopeContext(hint)) return { captureContext: hint };
	return hint;
}
function hintIsScopeOrFunction(hint) {
	return hint instanceof Scope || typeof hint === "function";
}
const captureContextKeys = [
	"user",
	"level",
	"extra",
	"contexts",
	"tags",
	"fingerprint",
	"propagationContext"
];
function hintIsScopeContext(hint) {
	return Object.keys(hint).some((key) => captureContextKeys.includes(key));
}
// src/exports.ts
/**
* Captures an exception event and sends it to Sentry.
*
* @param exception The exception to capture.
* @param hint Optional additional data to attach to the Sentry event.
* @returns the id of the captured Sentry event.
*/
function captureException(exception, hint) {
	return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));
}
/**
* Captures a message event and sends it to Sentry.
*
* @param message The message to send to Sentry.
* @param captureContext Define the level of the message or pass in additional data to attach to the message.
* @returns the id of the captured message.
*/
function captureMessage(message, captureContext) {
	const level = typeof captureContext === "string" ? captureContext : void 0;
	const hint = typeof captureContext !== "string" ? { captureContext } : void 0;
	return getCurrentScope().captureMessage(message, level, hint);
}
/**
* Captures a manually created event and sends it to Sentry.
*
* @param event The event to send to Sentry.
* @param hint Optional additional data to attach to the Sentry event.
* @returns the id of the captured event.
*/
function captureEvent(event, hint) {
	return getCurrentScope().captureEvent(event, hint);
}
/**
* Sets context data with the given name.
* @param name of the context
* @param context Any kind of data. This data will be normalized.
*/
function setContext(name, context) {
	getIsolationScope().setContext(name, context);
}
/**
* Set an object that will be merged sent as extra data with the event.
* @param extras Extras object to merge into current context.
*/
function setExtras(extras) {
	getIsolationScope().setExtras(extras);
}
/**
* Set key:value that will be sent as extra data with the event.
* @param key String of extra
* @param extra Any kind of data. This data will be normalized.
*/
function setExtra(key, extra) {
	getIsolationScope().setExtra(key, extra);
}
/**
* Set an object that will be merged sent as tags data with the event.
* @param tags Tags context object to merge into current context.
*/
function setTags(tags) {
	getIsolationScope().setTags(tags);
}
/**
* Set key:value that will be sent as tags data with the event.
*
* Can also be used to unset a tag, by passing `undefined`.
*
* @param key String key of tag
* @param value Value of tag
*/
function setTag(key, value) {
	getIsolationScope().setTag(key, value);
}
/**
* Sets attributes on the isolation scope.
*
* These attributes are applied to logs, metrics and streamed spans.
*
* Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.
*
* @param attributes - The attributes to set on the scope, as key-value pairs.
*
* @example
* ```typescript
* Sentry.setAttributes({
*   is_admin: true,
*   payment_selection: 'credit_card',
*   render_duration: 150,
* });
* ```
*/
function setAttributes(attributes) {
	getIsolationScope().setAttributes(attributes);
}
/**
* Sets an attribute on the isolation scope.
*
* These attributes are applied to logs, metrics and streamed spans.
*
* Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.
*
* @param key - The attribute key.
* @param value - The attribute value.
*
* @example
* ```typescript
* Sentry.setAttribute('is_admin', true);
* Sentry.setAttribute('render_duration', 150);
* ```
*/
function setAttribute(key, value) {
	getIsolationScope().setAttribute(key, value);
}
/**
* Updates user context information for future events.
*
* @param user User context object to be set in the current context. Pass `null` to unset the user.
*/
function setUser(user) {
	getIsolationScope().setUser(user);
}
/**
* Sets the conversation ID for the current isolation scope.
*
* @param conversationId The conversation ID to set. Pass `null` or `undefined` to unset the conversation ID.
*/
function setConversationId(conversationId) {
	getIsolationScope().setConversationId(conversationId);
}
/**
* The last error event id of the isolation scope.
*
* Warning: This function really returns the last recorded error event id on the current
* isolation scope. If you call this function after handling a certain error and another error
* is captured in between, the last one is returned instead of the one you might expect.
* Also, ids of events that were never sent to Sentry (for example because
* they were dropped by sampling or `beforeSend`) could be returned.
*
* @returns The last event id of the isolation scope.
*/
function lastEventId() {
	return getIsolationScope().lastEventId();
}
/**
* Call `flush()` on the current client, if there is one. See {@link Client.flush}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
* the client to wait until all events are sent before resolving the promise.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
async function flush(timeout) {
	const client = getClient();
	if (client) return client.flush(timeout);
	DEBUG_BUILD && debug.warn("Cannot flush events. No client defined.");
	return Promise.resolve(false);
}
/**
* Call `close()` on the current client, if there is one, and unbind it from the current scope.
* See {@link Client.close}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
* parameter will cause the client to wait until all events are sent before disabling itself.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
async function close(timeout) {
	const scope = getCurrentScope();
	const client = scope.getClient();
	if (client) {
		const result = await client.close(timeout);
		if (scope.getClient() === client) scope.setClient(void 0);
		return result;
	}
	DEBUG_BUILD && debug.warn("Cannot flush events and disable SDK. No client defined.");
	return Promise.resolve(false);
}
/**
* Returns true if Sentry has been properly initialized.
*/
function isInitialized() {
	return !!getClient();
}
/** If the SDK is initialized & enabled. */
function isEnabled() {
	const client = getClient();
	return client?.getOptions().enabled !== false && !!client?.getTransport();
}
/**
* Add an event processor.
* This will be added to the current isolation scope, ensuring any event that is processed in the current execution
* context will have the processor applied.
*/
function addEventProcessor(callback) {
	getIsolationScope().addEventProcessor(callback);
}
/**
* Start a session on the current isolation scope.
*
* @param context (optional) additional properties to be applied to the returned session object
*
* @returns the new active session
*/
function startSession(context) {
	const isolationScope = getIsolationScope();
	const { user } = getCombinedScopeData(isolationScope, getCurrentScope());
	let userAgent = GLOBAL_OBJ.navigator?.userAgent;
	if (userAgent) {
		const headerCollection = getClient()?.getDataCollectionOptions().httpHeaders.request ?? true;
		userAgent = filterKeyValueData({ "User-Agent": userAgent }, headerCollection)["User-Agent"];
	}
	const session = makeSession({
		user,
		userAgent,
		...context
	});
	const currentSession = isolationScope.getSession();
	if (currentSession?.status === "ok") updateSession(currentSession, { status: "exited" });
	endSession();
	isolationScope.setSession(session);
	return session;
}
/**
* End the session on the current isolation scope.
*/
function endSession() {
	const isolationScope = getIsolationScope();
	const session = getCurrentScope().getSession() || isolationScope.getSession();
	if (session) closeSession(session);
	_sendSessionUpdate();
	isolationScope.setSession();
}
/**
* Sends the current Session on the scope
*/
function _sendSessionUpdate() {
	const isolationScope = getIsolationScope();
	const client = getClient();
	const session = isolationScope.getSession();
	if (session && client) client.captureSession(session);
}
/**
* Sends the current session on the scope to Sentry
*
* @param end If set the session will be marked as exited and removed from the scope.
*            Defaults to `false`.
*/
function captureSession(end = false) {
	if (end) {
		endSession();
		return;
	}
	_sendSessionUpdate();
}
// src/utils/traceData.ts
/**
* Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation
* context) and serializes it to `sentry-trace` and `baggage` values. These values can be used to propagate
* a trace via our tracing Http headers or Html `<meta>` tags.
*
* This function also applies some validation to the generated sentry-trace and baggage values to ensure that
* only valid strings are returned.
*
* When an external propagation context is registered (e.g. via the OTLP integration) and there is no active
* Sentry span, this function returns an empty object to defer outgoing request propagation to the external
* propagator (e.g. an OpenTelemetry propagator).
*
* If (@param options.propagateTraceparent) is `true`, the function will also generate a `traceparent` value,
* following the W3C traceparent header format.
*
* @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header
* or meta tag name.
*/
function getTraceData(options = {}) {
	const client = options.client || getClient();
	if (!isEnabled() || !client) return {};
	const acs = getAsyncContextStrategy(getMainCarrier());
	if (acs.getTraceData) return acs.getTraceData(options);
	const scope = options.scope || getCurrentScope();
	const span = options.span || getActiveSpan();
	const isTwpPlaceholder = spanIsNonRecordingSpan(span) && !hasSpansEnabled(client.getOptions());
	if (!span && hasExternalPropagationContext()) return {};
	const sentryTrace = span && !isTwpPlaceholder ? spanToTraceHeader(span) : scopeToTraceHeader(scope);
	const baggage = dynamicSamplingContextToSentryBaggageHeader(span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope));
	if (!TRACEPARENT_REGEXP.test(sentryTrace)) {
		debug.warn("Invalid sentry-trace data. Cannot generate trace data");
		return {};
	}
	const traceData = {
		"sentry-trace": sentryTrace,
		baggage
	};
	if (options.propagateTraceparent) traceData.traceparent = span && !isTwpPlaceholder ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope);
	return traceData;
}
/**
* Get a sentry-trace header value for the given scope.
*/
function scopeToTraceHeader(scope) {
	const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();
	return generateSentryTraceHeader(traceId, propagationSpanId, sampled);
}
function scopeToTraceparentHeader(scope) {
	const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();
	return generateTraceparentHeader(traceId, propagationSpanId, sampled);
}
// src/utils/cacheOrigin.ts
/**
* Replaces `sentry-trace` and `baggage` in a cached or prerendered page, so that no visitor continues the
* trace of the render.
*
* - No tag: the server rendered the page for this request, or rendered no content (a client-side shell)
* - Empty `content`: there is no trace of the render to link, for example for a page prerendered in the build
* - A `sentry-trace` value: the client links the render
*/
const _INTERNAL_CACHE_ORIGIN_META_TAG_NAME = "sentry-cache-origin";
/**
* Holds the start of the render of a cached or prerendered page, as UNIX time in whole seconds. The server writes it
* next to `sentry-cache-origin`, also when that tag is empty. The client turns it into `page.server_rendering.age`.
*/
const _INTERNAL_RENDER_START_META_TAG_NAME = "sentry-render-start";
/**
* Returns the `sentry-cache-origin` meta tag and the `sentry-render-start` meta tag for the request that rendered the
* page. Without `renderTrace`, the `sentry-cache-origin` tag is empty. `requestStart` is in seconds.
*/
function _INTERNAL_getCacheOriginMetaTags(renderTrace, requestStart) {
	const renderStart = _INTERNAL_getRenderStart(getActiveRootSpan(), requestStart);
	return [`<meta name="${_INTERNAL_CACHE_ORIGIN_META_TAG_NAME}" content="${renderTrace ?? ""}"/>`, `<meta name="${_INTERNAL_RENDER_START_META_TAG_NAME}" content="${renderStart}"/>`].join("\n");
}
/**
* Returns the `sentry-trace` of the request's root span, which a cached page links as its render. Unlike
* `getTraceData()`, it ignores an active child span, such as SvelteKit's `sveltekit.resolve`.
*/
function _INTERNAL_getRootSpanSentryTrace() {
	return getTraceData({ span: getActiveRootSpan() })["sentry-trace"];
}
/**
* Returns the start of a render as UNIX time in whole seconds: the start of `span` if it records, because the
* `cache_origin` link points to it, else `startWithoutSpan` (in seconds), for example in the build or in an unsampled
* request. The age needs no more precision, and whole seconds make the server clock harder to fingerprint.
*/
function _INTERNAL_getRenderStart(span, startWithoutSpan) {
	return Math.floor(span?.isRecording() ? spanToJSON(span).start_timestamp : startWithoutSpan);
}
function getActiveRootSpan() {
	const activeSpan = getActiveSpan();
	return activeSpan && getRootSpan(activeSpan);
}
/**
* Sets `page.server_rendering.type` on a pageload whose document has a `sentry-cache-origin` tag, even an
* empty one. Links the render if the tag holds the `sentry-trace` of a sampled render, and sets
* `page.server_rendering.age` if the document has a `sentry-render-start` tag. Pass `undefined` as
* `serverRenderingType` while the type is not known.
*
* Call it before the span starts, so `tracesSampler` and `ignoreSpans` see the attribute.
*/
function _INTERNAL_withCacheOrigin(spanOptions, serverRenderingType) {
	const renderTrace = getMetaTagContent(_INTERNAL_CACHE_ORIGIN_META_TAG_NAME);
	if (renderTrace == null) return spanOptions;
	const link = getSampledRenderLink(renderTrace);
	const renderAge = getRenderAge(getMetaTagContent(_INTERNAL_RENDER_START_META_TAG_NAME));
	return {
		...spanOptions,
		attributes: {
			...spanOptions.attributes,
			...serverRenderingType && { [_sentry_conventions_attributes.PAGE_SERVER_RENDERING_TYPE]: serverRenderingType },
			...renderAge !== void 0 && { [_sentry_conventions_attributes.PAGE_SERVER_RENDERING_AGE]: renderAge }
		},
		...link && { links: [...spanOptions.links ?? [], link] }
	};
}
function getMetaTagContent(name) {
	return GLOBAL_OBJ.document?.querySelector(`meta[name="${name}"]`)?.getAttribute("content");
}
const MAX_RENDER_AGE = 31536e3;
function getRenderAge(renderStart) {
	const timeOrigin = browserPerformanceTimeOrigin();
	if (!renderStart || !/^\d+$/.test(renderStart) || !timeOrigin) return;
	const age = Math.max(0, Math.floor(timeOrigin / 1e3 - Number(renderStart)));
	return age <= MAX_RENDER_AGE ? age : void 0;
}
function getSampledRenderLink(renderTrace) {
	const traceparent = extractTraceparentData(renderTrace);
	if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) return;
	return {
		context: {
			traceId: traceparent.traceId,
			spanId: traceparent.parentSpanId,
			traceFlags: 1
		},
		attributes: { [_sentry_conventions_attributes.SENTRY_LINK_TYPE]: "cache_origin" }
	};
}
Object.defineProperty(exports, "CALLBACK_ERROR", {
	enumerable: true,
	get: function() {
		return CALLBACK_ERROR;
	}
});
Object.defineProperty(exports, "CONSOLE_LEVELS", {
	enumerable: true,
	get: function() {
		return CONSOLE_LEVELS;
	}
});
Object.defineProperty(exports, "DEBUG_BUILD", {
	enumerable: true,
	get: function() {
		return DEBUG_BUILD;
	}
});
Object.defineProperty(exports, "DEFAULT_ENVIRONMENT", {
	enumerable: true,
	get: function() {
		return DEFAULT_ENVIRONMENT;
	}
});
Object.defineProperty(exports, "DEV_ENVIRONMENT", {
	enumerable: true,
	get: function() {
		return DEV_ENVIRONMENT;
	}
});
Object.defineProperty(exports, "FILTERED_VALUE", {
	enumerable: true,
	get: function() {
		return FILTERED_VALUE;
	}
});
Object.defineProperty(exports, "GEN_AI_CONVERSATION_ID_ATTRIBUTE", {
	enumerable: true,
	get: function() {
		return GEN_AI_CONVERSATION_ID_ATTRIBUTE;
	}
});
Object.defineProperty(exports, "GLOBAL_OBJ", {
	enumerable: true,
	get: function() {
		return GLOBAL_OBJ;
	}
});
Object.defineProperty(exports, "INTEGRATION_NAME", {
	enumerable: true,
	get: function() {
		return INTEGRATION_NAME;
	}
});
Object.defineProperty(exports, "INTERNAL_getSegmentSpan", {
	enumerable: true,
	get: function() {
		return INTERNAL_getSegmentSpan;
	}
});
Object.defineProperty(exports, "INTERNAL_setSegmentNameSourceIfSegment", {
	enumerable: true,
	get: function() {
		return INTERNAL_setSegmentNameSourceIfSegment;
	}
});
Object.defineProperty(exports, "MAX_BAGGAGE_STRING_LENGTH", {
	enumerable: true,
	get: function() {
		return MAX_BAGGAGE_STRING_LENGTH;
	}
});
Object.defineProperty(exports, "SDK_VERSION", {
	enumerable: true,
	get: function() {
		return SDK_VERSION;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_CACHE_HIT", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_CACHE_HIT;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_CACHE_KEY", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_CACHE_KEY;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_PROFILE_ID", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_PROFILE_ID;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_OP", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_OP;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_RELEASE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_RELEASE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_URL_FULL", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_URL_FULL;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_USER_EMAIL", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_USER_EMAIL;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_USER_ID", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_USER_ID;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS;
	}
});
Object.defineProperty(exports, "SEMANTIC_ATTRIBUTE_USER_USERNAME", {
	enumerable: true,
	get: function() {
		return SEMANTIC_ATTRIBUTE_USER_USERNAME;
	}
});
Object.defineProperty(exports, "SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE", {
	enumerable: true,
	get: function() {
		return SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE;
	}
});
Object.defineProperty(exports, "SENSITIVE_COOKIE_NAME_SNIPPETS", {
	enumerable: true,
	get: function() {
		return SENSITIVE_COOKIE_NAME_SNIPPETS;
	}
});
Object.defineProperty(exports, "SENTRY_BAGGAGE_KEY_PREFIX", {
	enumerable: true,
	get: function() {
		return SENTRY_BAGGAGE_KEY_PREFIX;
	}
});
Object.defineProperty(exports, "SENTRY_BAGGAGE_KEY_PREFIX_REGEX", {
	enumerable: true,
	get: function() {
		return SENTRY_BAGGAGE_KEY_PREFIX_REGEX;
	}
});
Object.defineProperty(exports, "SPAN_STATUS_ERROR", {
	enumerable: true,
	get: function() {
		return SPAN_STATUS_ERROR;
	}
});
Object.defineProperty(exports, "SPAN_STATUS_OK", {
	enumerable: true,
	get: function() {
		return SPAN_STATUS_OK;
	}
});
Object.defineProperty(exports, "SPAN_STATUS_UNSET", {
	enumerable: true,
	get: function() {
		return SPAN_STATUS_UNSET;
	}
});
Object.defineProperty(exports, "Scope", {
	enumerable: true,
	get: function() {
		return Scope;
	}
});
Object.defineProperty(exports, "SentryNonRecordingSpan", {
	enumerable: true,
	get: function() {
		return SentryNonRecordingSpan;
	}
});
Object.defineProperty(exports, "SentrySpan", {
	enumerable: true,
	get: function() {
		return SentrySpan;
	}
});
Object.defineProperty(exports, "SpanBuffer", {
	enumerable: true,
	get: function() {
		return SpanBuffer;
	}
});
Object.defineProperty(exports, "SyncPromise", {
	enumerable: true,
	get: function() {
		return SyncPromise;
	}
});
Object.defineProperty(exports, "TRACEPARENT_REGEXP", {
	enumerable: true,
	get: function() {
		return TRACEPARENT_REGEXP;
	}
});
Object.defineProperty(exports, "TRACING_DEFAULTS", {
	enumerable: true,
	get: function() {
		return TRACING_DEFAULTS;
	}
});
Object.defineProperty(exports, "UNKNOWN_FUNCTION", {
	enumerable: true,
	get: function() {
		return UNKNOWN_FUNCTION;
	}
});
Object.defineProperty(exports, "_INTERNAL_CACHE_ORIGIN_META_TAG_NAME", {
	enumerable: true,
	get: function() {
		return _INTERNAL_CACHE_ORIGIN_META_TAG_NAME;
	}
});
Object.defineProperty(exports, "_INTERNAL_RENDER_START_META_TAG_NAME", {
	enumerable: true,
	get: function() {
		return _INTERNAL_RENDER_START_META_TAG_NAME;
	}
});
Object.defineProperty(exports, "_INTERNAL_ensureBrowserSpanStreaming", {
	enumerable: true,
	get: function() {
		return _INTERNAL_ensureBrowserSpanStreaming;
	}
});
Object.defineProperty(exports, "_INTERNAL_getCacheOriginMetaTags", {
	enumerable: true,
	get: function() {
		return _INTERNAL_getCacheOriginMetaTags;
	}
});
Object.defineProperty(exports, "_INTERNAL_getRenderStart", {
	enumerable: true,
	get: function() {
		return _INTERNAL_getRenderStart;
	}
});
Object.defineProperty(exports, "_INTERNAL_getRootSpanSentryTrace", {
	enumerable: true,
	get: function() {
		return _INTERNAL_getRootSpanSentryTrace;
	}
});
Object.defineProperty(exports, "_INTERNAL_setDeferSegmentSpanCapture", {
	enumerable: true,
	get: function() {
		return _INTERNAL_setDeferSegmentSpanCapture;
	}
});
Object.defineProperty(exports, "_INTERNAL_withCacheOrigin", {
	enumerable: true,
	get: function() {
		return _INTERNAL_withCacheOrigin;
	}
});
Object.defineProperty(exports, "_setSpanForScope", {
	enumerable: true,
	get: function() {
		return _setSpanForScope;
	}
});
Object.defineProperty(exports, "addChildSpanToSpan", {
	enumerable: true,
	get: function() {
		return addChildSpanToSpan;
	}
});
Object.defineProperty(exports, "addContextToFrame", {
	enumerable: true,
	get: function() {
		return addContextToFrame;
	}
});
Object.defineProperty(exports, "addEventProcessor", {
	enumerable: true,
	get: function() {
		return addEventProcessor;
	}
});
Object.defineProperty(exports, "addExceptionMechanism", {
	enumerable: true,
	get: function() {
		return addExceptionMechanism;
	}
});
Object.defineProperty(exports, "addExceptionTypeValue", {
	enumerable: true,
	get: function() {
		return addExceptionTypeValue;
	}
});
Object.defineProperty(exports, "addGlobalErrorInstrumentationHandler", {
	enumerable: true,
	get: function() {
		return addGlobalErrorInstrumentationHandler;
	}
});
Object.defineProperty(exports, "addGlobalUnhandledRejectionInstrumentationHandler", {
	enumerable: true,
	get: function() {
		return addGlobalUnhandledRejectionInstrumentationHandler;
	}
});
Object.defineProperty(exports, "addHandler", {
	enumerable: true,
	get: function() {
		return addHandler;
	}
});
Object.defineProperty(exports, "addIntegration", {
	enumerable: true,
	get: function() {
		return addIntegration;
	}
});
Object.defineProperty(exports, "addItemToEnvelope", {
	enumerable: true,
	get: function() {
		return addItemToEnvelope;
	}
});
Object.defineProperty(exports, "addNonEnumerableProperty", {
	enumerable: true,
	get: function() {
		return addNonEnumerableProperty;
	}
});
Object.defineProperty(exports, "afterSetupIntegrations", {
	enumerable: true,
	get: function() {
		return afterSetupIntegrations;
	}
});
Object.defineProperty(exports, "applyBeforeSendSpanCallback", {
	enumerable: true,
	get: function() {
		return applyBeforeSendSpanCallback;
	}
});
Object.defineProperty(exports, "applyScopeDataToEvent", {
	enumerable: true,
	get: function() {
		return applyScopeDataToEvent;
	}
});
Object.defineProperty(exports, "baggageHeaderToDynamicSamplingContext", {
	enumerable: true,
	get: function() {
		return baggageHeaderToDynamicSamplingContext;
	}
});
Object.defineProperty(exports, "bindScopeToEmitter", {
	enumerable: true,
	get: function() {
		return bindScopeToEmitter;
	}
});
Object.defineProperty(exports, "browserPerformanceTimeOrigin", {
	enumerable: true,
	get: function() {
		return browserPerformanceTimeOrigin;
	}
});
Object.defineProperty(exports, "captureEvent", {
	enumerable: true,
	get: function() {
		return captureEvent;
	}
});
Object.defineProperty(exports, "captureException", {
	enumerable: true,
	get: function() {
		return captureException;
	}
});
Object.defineProperty(exports, "captureMessage", {
	enumerable: true,
	get: function() {
		return captureMessage;
	}
});
Object.defineProperty(exports, "captureSession", {
	enumerable: true,
	get: function() {
		return captureSession;
	}
});
Object.defineProperty(exports, "captureSpan", {
	enumerable: true,
	get: function() {
		return captureSpan;
	}
});
Object.defineProperty(exports, "checkOrSetAlreadyCaught", {
	enumerable: true,
	get: function() {
		return checkOrSetAlreadyCaught;
	}
});
Object.defineProperty(exports, "close", {
	enumerable: true,
	get: function() {
		return close;
	}
});
Object.defineProperty(exports, "closeSession", {
	enumerable: true,
	get: function() {
		return closeSession;
	}
});
Object.defineProperty(exports, "consoleSandbox", {
	enumerable: true,
	get: function() {
		return consoleSandbox;
	}
});
Object.defineProperty(exports, "continueTrace", {
	enumerable: true,
	get: function() {
		return continueTrace;
	}
});
Object.defineProperty(exports, "convertSpanLinksForEnvelope", {
	enumerable: true,
	get: function() {
		return convertSpanLinksForEnvelope;
	}
});
Object.defineProperty(exports, "convertToPlainObject", {
	enumerable: true,
	get: function() {
		return convertToPlainObject;
	}
});
Object.defineProperty(exports, "createAttachmentEnvelopeItem", {
	enumerable: true,
	get: function() {
		return createAttachmentEnvelopeItem;
	}
});
Object.defineProperty(exports, "createEnvelope", {
	enumerable: true,
	get: function() {
		return createEnvelope;
	}
});
Object.defineProperty(exports, "createEventEnvelopeHeaders", {
	enumerable: true,
	get: function() {
		return createEventEnvelopeHeaders;
	}
});
Object.defineProperty(exports, "createSpanContainerItem", {
	enumerable: true,
	get: function() {
		return createSpanContainerItem;
	}
});
Object.defineProperty(exports, "createStackParser", {
	enumerable: true,
	get: function() {
		return createStackParser;
	}
});
Object.defineProperty(exports, "dateTimestampInSeconds", {
	enumerable: true,
	get: function() {
		return dateTimestampInSeconds;
	}
});
Object.defineProperty(exports, "debounce", {
	enumerable: true,
	get: function() {
		return debounce;
	}
});
Object.defineProperty(exports, "debug", {
	enumerable: true,
	get: function() {
		return debug;
	}
});
Object.defineProperty(exports, "defineIntegration", {
	enumerable: true,
	get: function() {
		return defineIntegration;
	}
});
Object.defineProperty(exports, "derefWeakRef", {
	enumerable: true,
	get: function() {
		return derefWeakRef;
	}
});
Object.defineProperty(exports, "dropUndefinedKeys", {
	enumerable: true,
	get: function() {
		return dropUndefinedKeys;
	}
});
Object.defineProperty(exports, "dsnFromString", {
	enumerable: true,
	get: function() {
		return dsnFromString;
	}
});
Object.defineProperty(exports, "dsnToString", {
	enumerable: true,
	get: function() {
		return dsnToString;
	}
});
Object.defineProperty(exports, "dynamicSamplingContextToSentryBaggageHeader", {
	enumerable: true,
	get: function() {
		return dynamicSamplingContextToSentryBaggageHeader;
	}
});
Object.defineProperty(exports, "endSession", {
	enumerable: true,
	get: function() {
		return endSession;
	}
});
Object.defineProperty(exports, "envelopeContainsItemType", {
	enumerable: true,
	get: function() {
		return envelopeContainsItemType;
	}
});
Object.defineProperty(exports, "envelopeItemTypeToDataCategory", {
	enumerable: true,
	get: function() {
		return envelopeItemTypeToDataCategory;
	}
});
Object.defineProperty(exports, "escapeStringForRegex", {
	enumerable: true,
	get: function() {
		return escapeStringForRegex;
	}
});
Object.defineProperty(exports, "extendIntegration", {
	enumerable: true,
	get: function() {
		return extendIntegration;
	}
});
Object.defineProperty(exports, "extractExceptionKeysForMessage", {
	enumerable: true,
	get: function() {
		return extractExceptionKeysForMessage;
	}
});
Object.defineProperty(exports, "extractTraceparentData", {
	enumerable: true,
	get: function() {
		return extractTraceparentData;
	}
});
Object.defineProperty(exports, "fill", {
	enumerable: true,
	get: function() {
		return fill;
	}
});
Object.defineProperty(exports, "filterKeyValueData", {
	enumerable: true,
	get: function() {
		return filterKeyValueData;
	}
});
Object.defineProperty(exports, "flush", {
	enumerable: true,
	get: function() {
		return flush;
	}
});
Object.defineProperty(exports, "forEachEnvelopeItem", {
	enumerable: true,
	get: function() {
		return forEachEnvelopeItem;
	}
});
Object.defineProperty(exports, "generateSentryTraceHeader", {
	enumerable: true,
	get: function() {
		return generateSentryTraceHeader;
	}
});
Object.defineProperty(exports, "generateSpanId", {
	enumerable: true,
	get: function() {
		return generateSpanId;
	}
});
Object.defineProperty(exports, "generateTraceId", {
	enumerable: true,
	get: function() {
		return generateTraceId;
	}
});
Object.defineProperty(exports, "generateTraceparentHeader", {
	enumerable: true,
	get: function() {
		return generateTraceparentHeader;
	}
});
Object.defineProperty(exports, "getActiveSpan", {
	enumerable: true,
	get: function() {
		return getActiveSpan;
	}
});
Object.defineProperty(exports, "getAsyncContextStrategy", {
	enumerable: true,
	get: function() {
		return getAsyncContextStrategy;
	}
});
Object.defineProperty(exports, "getCapturedScopesOnSpan", {
	enumerable: true,
	get: function() {
		return getCapturedScopesOnSpan;
	}
});
Object.defineProperty(exports, "getClient", {
	enumerable: true,
	get: function() {
		return getClient;
	}
});
Object.defineProperty(exports, "getCombinedScopeData", {
	enumerable: true,
	get: function() {
		return getCombinedScopeData;
	}
});
Object.defineProperty(exports, "getCurrentScope", {
	enumerable: true,
	get: function() {
		return getCurrentScope;
	}
});
Object.defineProperty(exports, "getDataCategoryByType", {
	enumerable: true,
	get: function() {
		return getDataCategoryByType;
	}
});
Object.defineProperty(exports, "getDebugImagesForResources", {
	enumerable: true,
	get: function() {
		return getDebugImagesForResources;
	}
});
Object.defineProperty(exports, "getDefaultCurrentScope", {
	enumerable: true,
	get: function() {
		return getDefaultCurrentScope;
	}
});
Object.defineProperty(exports, "getDefaultIsolationScope", {
	enumerable: true,
	get: function() {
		return getDefaultIsolationScope;
	}
});
Object.defineProperty(exports, "getDynamicSamplingContextFromClient", {
	enumerable: true,
	get: function() {
		return getDynamicSamplingContextFromClient;
	}
});
Object.defineProperty(exports, "getDynamicSamplingContextFromScope", {
	enumerable: true,
	get: function() {
		return getDynamicSamplingContextFromScope;
	}
});
Object.defineProperty(exports, "getDynamicSamplingContextFromSpan", {
	enumerable: true,
	get: function() {
		return getDynamicSamplingContextFromSpan;
	}
});
Object.defineProperty(exports, "getEventDescription", {
	enumerable: true,
	get: function() {
		return getEventDescription;
	}
});
Object.defineProperty(exports, "getExternalPropagationContext", {
	enumerable: true,
	get: function() {
		return getExternalPropagationContext;
	}
});
Object.defineProperty(exports, "getFilenameToDebugIdMap", {
	enumerable: true,
	get: function() {
		return getFilenameToDebugIdMap;
	}
});
Object.defineProperty(exports, "getFramesFromEvent", {
	enumerable: true,
	get: function() {
		return getFramesFromEvent;
	}
});
Object.defineProperty(exports, "getFunctionName", {
	enumerable: true,
	get: function() {
		return getFunctionName;
	}
});
Object.defineProperty(exports, "getGlobalScope", {
	enumerable: true,
	get: function() {
		return getGlobalScope;
	}
});
Object.defineProperty(exports, "getGlobalSingleton", {
	enumerable: true,
	get: function() {
		return getGlobalSingleton;
	}
});
Object.defineProperty(exports, "getIntegrationsToSetup", {
	enumerable: true,
	get: function() {
		return getIntegrationsToSetup;
	}
});
Object.defineProperty(exports, "getIsolationScope", {
	enumerable: true,
	get: function() {
		return getIsolationScope;
	}
});
Object.defineProperty(exports, "getMainCarrier", {
	enumerable: true,
	get: function() {
		return getMainCarrier;
	}
});
Object.defineProperty(exports, "getOriginalFunction", {
	enumerable: true,
	get: function() {
		return getOriginalFunction;
	}
});
Object.defineProperty(exports, "getPossibleEventMessages", {
	enumerable: true,
	get: function() {
		return getPossibleEventMessages;
	}
});
Object.defineProperty(exports, "getRootSpan", {
	enumerable: true,
	get: function() {
		return getRootSpan;
	}
});
Object.defineProperty(exports, "getSDKSource", {
	enumerable: true,
	get: function() {
		return getSDKSource;
	}
});
Object.defineProperty(exports, "getSdkMetadataForEnvelopeHeader", {
	enumerable: true,
	get: function() {
		return getSdkMetadataForEnvelopeHeader;
	}
});
Object.defineProperty(exports, "getSpanDescendants", {
	enumerable: true,
	get: function() {
		return getSpanDescendants;
	}
});
Object.defineProperty(exports, "getSpanStatusFromHttpCode", {
	enumerable: true,
	get: function() {
		return getSpanStatusFromHttpCode;
	}
});
Object.defineProperty(exports, "getStatusMessage", {
	enumerable: true,
	get: function() {
		return getStatusMessage;
	}
});
Object.defineProperty(exports, "getTraceContextFromScope", {
	enumerable: true,
	get: function() {
		return getTraceContextFromScope;
	}
});
Object.defineProperty(exports, "getTraceData", {
	enumerable: true,
	get: function() {
		return getTraceData;
	}
});
Object.defineProperty(exports, "handleCallbackErrors", {
	enumerable: true,
	get: function() {
		return handleCallbackErrors;
	}
});
Object.defineProperty(exports, "hasExternalPropagationContext", {
	enumerable: true,
	get: function() {
		return hasExternalPropagationContext;
	}
});
Object.defineProperty(exports, "hasSpanStreamingEnabled", {
	enumerable: true,
	get: function() {
		return hasSpanStreamingEnabled;
	}
});
Object.defineProperty(exports, "hasSpansEnabled", {
	enumerable: true,
	get: function() {
		return hasSpansEnabled;
	}
});
Object.defineProperty(exports, "installedIntegrations", {
	enumerable: true,
	get: function() {
		return installedIntegrations;
	}
});
Object.defineProperty(exports, "isAlreadyCaptured", {
	enumerable: true,
	get: function() {
		return isAlreadyCaptured;
	}
});
Object.defineProperty(exports, "isBrowser", {
	enumerable: true,
	get: function() {
		return isBrowser;
	}
});
Object.defineProperty(exports, "isBrowserBundle", {
	enumerable: true,
	get: function() {
		return isBrowserBundle;
	}
});
Object.defineProperty(exports, "isContinuingTrace", {
	enumerable: true,
	get: function() {
		return isContinuingTrace;
	}
});
Object.defineProperty(exports, "isDOMError", {
	enumerable: true,
	get: function() {
		return isDOMError;
	}
});
Object.defineProperty(exports, "isDOMException", {
	enumerable: true,
	get: function() {
		return isDOMException;
	}
});
Object.defineProperty(exports, "isElement", {
	enumerable: true,
	get: function() {
		return isElement;
	}
});
Object.defineProperty(exports, "isEnabled", {
	enumerable: true,
	get: function() {
		return isEnabled;
	}
});
Object.defineProperty(exports, "isError", {
	enumerable: true,
	get: function() {
		return isError;
	}
});
Object.defineProperty(exports, "isErrorEvent", {
	enumerable: true,
	get: function() {
		return isErrorEvent;
	}
});
Object.defineProperty(exports, "isEvent", {
	enumerable: true,
	get: function() {
		return isEvent;
	}
});
Object.defineProperty(exports, "isInitialized", {
	enumerable: true,
	get: function() {
		return isInitialized;
	}
});
Object.defineProperty(exports, "isInstanceOf", {
	enumerable: true,
	get: function() {
		return isInstanceOf;
	}
});
Object.defineProperty(exports, "isInternalException", {
	enumerable: true,
	get: function() {
		return isInternalException;
	}
});
Object.defineProperty(exports, "isMatchingPattern", {
	enumerable: true,
	get: function() {
		return isMatchingPattern;
	}
});
Object.defineProperty(exports, "isNodeEnv", {
	enumerable: true,
	get: function() {
		return isNodeEnv;
	}
});
Object.defineProperty(exports, "isObjectLike", {
	enumerable: true,
	get: function() {
		return isObjectLike;
	}
});
Object.defineProperty(exports, "isParameterizedString", {
	enumerable: true,
	get: function() {
		return isParameterizedString;
	}
});
Object.defineProperty(exports, "isPlainObject", {
	enumerable: true,
	get: function() {
		return isPlainObject;
	}
});
Object.defineProperty(exports, "isPrimitive", {
	enumerable: true,
	get: function() {
		return isPrimitive;
	}
});
Object.defineProperty(exports, "isRegExp", {
	enumerable: true,
	get: function() {
		return isRegExp;
	}
});
Object.defineProperty(exports, "isRequest", {
	enumerable: true,
	get: function() {
		return isRequest;
	}
});
Object.defineProperty(exports, "isStaticBeforeSendSpanCallback", {
	enumerable: true,
	get: function() {
		return isStaticBeforeSendSpanCallback;
	}
});
Object.defineProperty(exports, "isStatusErrorMessageValid", {
	enumerable: true,
	get: function() {
		return isStatusErrorMessageValid;
	}
});
Object.defineProperty(exports, "isString", {
	enumerable: true,
	get: function() {
		return isString;
	}
});
Object.defineProperty(exports, "isSyntheticEvent", {
	enumerable: true,
	get: function() {
		return isSyntheticEvent;
	}
});
Object.defineProperty(exports, "isThenable", {
	enumerable: true,
	get: function() {
		return isThenable;
	}
});
Object.defineProperty(exports, "isTracingSuppressed", {
	enumerable: true,
	get: function() {
		return isTracingSuppressed;
	}
});
Object.defineProperty(exports, "isVueViewModel", {
	enumerable: true,
	get: function() {
		return isVueViewModel;
	}
});
Object.defineProperty(exports, "lastEventId", {
	enumerable: true,
	get: function() {
		return lastEventId;
	}
});
Object.defineProperty(exports, "loadModule", {
	enumerable: true,
	get: function() {
		return loadModule;
	}
});
Object.defineProperty(exports, "logSpanEnd", {
	enumerable: true,
	get: function() {
		return logSpanEnd;
	}
});
Object.defineProperty(exports, "logSpanStart", {
	enumerable: true,
	get: function() {
		return logSpanStart;
	}
});
Object.defineProperty(exports, "makeDsn", {
	enumerable: true,
	get: function() {
		return makeDsn;
	}
});
Object.defineProperty(exports, "makeSession", {
	enumerable: true,
	get: function() {
		return makeSession;
	}
});
Object.defineProperty(exports, "makeWeakRef", {
	enumerable: true,
	get: function() {
		return makeWeakRef;
	}
});
Object.defineProperty(exports, "markFunctionWrapped", {
	enumerable: true,
	get: function() {
		return markFunctionWrapped;
	}
});
Object.defineProperty(exports, "markSpanAsTracerProviderSpan", {
	enumerable: true,
	get: function() {
		return markSpanAsTracerProviderSpan;
	}
});
Object.defineProperty(exports, "maybeInstrument", {
	enumerable: true,
	get: function() {
		return maybeInstrument;
	}
});
Object.defineProperty(exports, "merge", {
	enumerable: true,
	get: function() {
		return merge;
	}
});
Object.defineProperty(exports, "mergeBaggageHeaders", {
	enumerable: true,
	get: function() {
		return mergeBaggageHeaders;
	}
});
Object.defineProperty(exports, "mergeScopeData", {
	enumerable: true,
	get: function() {
		return mergeScopeData;
	}
});
Object.defineProperty(exports, "normalize", {
	enumerable: true,
	get: function() {
		return normalize;
	}
});
Object.defineProperty(exports, "normalizeStackTracePath", {
	enumerable: true,
	get: function() {
		return normalizeStackTracePath;
	}
});
Object.defineProperty(exports, "normalizeToSize", {
	enumerable: true,
	get: function() {
		return normalizeToSize;
	}
});
Object.defineProperty(exports, "normalizeUrlToBase", {
	enumerable: true,
	get: function() {
		return normalizeUrlToBase;
	}
});
Object.defineProperty(exports, "notifyEventProcessors", {
	enumerable: true,
	get: function() {
		return notifyEventProcessors;
	}
});
Object.defineProperty(exports, "objectToBaggageHeader", {
	enumerable: true,
	get: function() {
		return objectToBaggageHeader;
	}
});
Object.defineProperty(exports, "objectify", {
	enumerable: true,
	get: function() {
		return objectify;
	}
});
Object.defineProperty(exports, "originalConsoleMethods", {
	enumerable: true,
	get: function() {
		return originalConsoleMethods;
	}
});
Object.defineProperty(exports, "otelTimeInputToSeconds", {
	enumerable: true,
	get: function() {
		return otelTimeInputToSeconds;
	}
});
Object.defineProperty(exports, "parseBaggageHeader", {
	enumerable: true,
	get: function() {
		return parseBaggageHeader;
	}
});
Object.defineProperty(exports, "parseEnvelope", {
	enumerable: true,
	get: function() {
		return parseEnvelope;
	}
});
Object.defineProperty(exports, "parseSampleRate", {
	enumerable: true,
	get: function() {
		return parseSampleRate;
	}
});
Object.defineProperty(exports, "parseSemver", {
	enumerable: true,
	get: function() {
		return parseSemver;
	}
});
Object.defineProperty(exports, "performanceTimeToSeconds", {
	enumerable: true,
	get: function() {
		return performanceTimeToSeconds;
	}
});
Object.defineProperty(exports, "prepareEvent", {
	enumerable: true,
	get: function() {
		return prepareEvent;
	}
});
Object.defineProperty(exports, "propagationContextFromHeaders", {
	enumerable: true,
	get: function() {
		return propagationContextFromHeaders;
	}
});
Object.defineProperty(exports, "registerExternalPropagationContext", {
	enumerable: true,
	get: function() {
		return registerExternalPropagationContext;
	}
});
Object.defineProperty(exports, "registerSpanErrorInstrumentation", {
	enumerable: true,
	get: function() {
		return registerSpanErrorInstrumentation;
	}
});
Object.defineProperty(exports, "rejectedSyncPromise", {
	enumerable: true,
	get: function() {
		return rejectedSyncPromise;
	}
});
Object.defineProperty(exports, "reparentChildSpans", {
	enumerable: true,
	get: function() {
		return reparentChildSpans;
	}
});
Object.defineProperty(exports, "resetInstrumentationHandlers", {
	enumerable: true,
	get: function() {
		return resetInstrumentationHandlers;
	}
});
Object.defineProperty(exports, "resolvedSyncPromise", {
	enumerable: true,
	get: function() {
		return resolvedSyncPromise;
	}
});
Object.defineProperty(exports, "safeCallback", {
	enumerable: true,
	get: function() {
		return safeCallback;
	}
});
Object.defineProperty(exports, "safeDateNow", {
	enumerable: true,
	get: function() {
		return safeDateNow;
	}
});
Object.defineProperty(exports, "safeJoin", {
	enumerable: true,
	get: function() {
		return safeJoin;
	}
});
Object.defineProperty(exports, "safeMathRandom", {
	enumerable: true,
	get: function() {
		return safeMathRandom;
	}
});
Object.defineProperty(exports, "safeSetSpanJSONAttributes", {
	enumerable: true,
	get: function() {
		return safeSetSpanJSONAttributes;
	}
});
Object.defineProperty(exports, "safeUnref", {
	enumerable: true,
	get: function() {
		return safeUnref;
	}
});
Object.defineProperty(exports, "sampleSpan", {
	enumerable: true,
	get: function() {
		return sampleSpan;
	}
});
Object.defineProperty(exports, "sentryTraceFromTraceparent", {
	enumerable: true,
	get: function() {
		return sentryTraceFromTraceparent;
	}
});
Object.defineProperty(exports, "serializeAttributes", {
	enumerable: true,
	get: function() {
		return serializeAttributes;
	}
});
Object.defineProperty(exports, "serializeEnvelope", {
	enumerable: true,
	get: function() {
		return serializeEnvelope;
	}
});
Object.defineProperty(exports, "setAsyncContextStrategy", {
	enumerable: true,
	get: function() {
		return setAsyncContextStrategy;
	}
});
Object.defineProperty(exports, "setAttribute", {
	enumerable: true,
	get: function() {
		return setAttribute;
	}
});
Object.defineProperty(exports, "setAttributes", {
	enumerable: true,
	get: function() {
		return setAttributes;
	}
});
Object.defineProperty(exports, "setCapturedScopesOnSpan", {
	enumerable: true,
	get: function() {
		return setCapturedScopesOnSpan;
	}
});
Object.defineProperty(exports, "setContext", {
	enumerable: true,
	get: function() {
		return setContext;
	}
});
Object.defineProperty(exports, "setConversationId", {
	enumerable: true,
	get: function() {
		return setConversationId;
	}
});
Object.defineProperty(exports, "setExtra", {
	enumerable: true,
	get: function() {
		return setExtra;
	}
});
Object.defineProperty(exports, "setExtras", {
	enumerable: true,
	get: function() {
		return setExtras;
	}
});
Object.defineProperty(exports, "setHttpStatus", {
	enumerable: true,
	get: function() {
		return setHttpStatus;
	}
});
Object.defineProperty(exports, "setMeasurement", {
	enumerable: true,
	get: function() {
		return setMeasurement;
	}
});
Object.defineProperty(exports, "setNormalizationDepthOverrideHint", {
	enumerable: true,
	get: function() {
		return setNormalizationDepthOverrideHint;
	}
});
Object.defineProperty(exports, "setNormalizeStringifier", {
	enumerable: true,
	get: function() {
		return setNormalizeStringifier;
	}
});
Object.defineProperty(exports, "setSkipNormalizationHint", {
	enumerable: true,
	get: function() {
		return setSkipNormalizationHint;
	}
});
Object.defineProperty(exports, "setTag", {
	enumerable: true,
	get: function() {
		return setTag;
	}
});
Object.defineProperty(exports, "setTags", {
	enumerable: true,
	get: function() {
		return setTags;
	}
});
Object.defineProperty(exports, "setUser", {
	enumerable: true,
	get: function() {
		return setUser;
	}
});
Object.defineProperty(exports, "setupIntegration", {
	enumerable: true,
	get: function() {
		return setupIntegration;
	}
});
Object.defineProperty(exports, "setupIntegrations", {
	enumerable: true,
	get: function() {
		return setupIntegrations;
	}
});
Object.defineProperty(exports, "shouldContinueTrace", {
	enumerable: true,
	get: function() {
		return shouldContinueTrace;
	}
});
Object.defineProperty(exports, "shouldFilterDataKey", {
	enumerable: true,
	get: function() {
		return shouldFilterDataKey;
	}
});
Object.defineProperty(exports, "shouldIgnoreSpan", {
	enumerable: true,
	get: function() {
		return shouldIgnoreSpan;
	}
});
Object.defineProperty(exports, "snipLine", {
	enumerable: true,
	get: function() {
		return snipLine;
	}
});
Object.defineProperty(exports, "spanIsIgnored", {
	enumerable: true,
	get: function() {
		return spanIsIgnored;
	}
});
Object.defineProperty(exports, "spanIsSampled", {
	enumerable: true,
	get: function() {
		return spanIsSampled;
	}
});
Object.defineProperty(exports, "spanIsSentrySpan", {
	enumerable: true,
	get: function() {
		return spanIsSentrySpan;
	}
});
Object.defineProperty(exports, "spanIsTracerProviderSpan", {
	enumerable: true,
	get: function() {
		return spanIsTracerProviderSpan;
	}
});
Object.defineProperty(exports, "spanJsonToSerializedStreamedSpan", {
	enumerable: true,
	get: function() {
		return spanJsonToSerializedStreamedSpan;
	}
});
Object.defineProperty(exports, "spanStreamingIntegration", {
	enumerable: true,
	get: function() {
		return spanStreamingIntegration;
	}
});
Object.defineProperty(exports, "spanTimeInputToSeconds", {
	enumerable: true,
	get: function() {
		return spanTimeInputToSeconds;
	}
});
Object.defineProperty(exports, "spanToBaggageHeader", {
	enumerable: true,
	get: function() {
		return spanToBaggageHeader;
	}
});
Object.defineProperty(exports, "spanToJSON", {
	enumerable: true,
	get: function() {
		return spanToJSON;
	}
});
Object.defineProperty(exports, "spanToStaticSpanJSON", {
	enumerable: true,
	get: function() {
		return spanToStaticSpanJSON;
	}
});
Object.defineProperty(exports, "spanToTraceContext", {
	enumerable: true,
	get: function() {
		return spanToTraceContext;
	}
});
Object.defineProperty(exports, "spanToTraceHeader", {
	enumerable: true,
	get: function() {
		return spanToTraceHeader;
	}
});
Object.defineProperty(exports, "stackParserFromStackParserOptions", {
	enumerable: true,
	get: function() {
		return stackParserFromStackParserOptions;
	}
});
Object.defineProperty(exports, "startIdleSpan", {
	enumerable: true,
	get: function() {
		return startIdleSpan;
	}
});
Object.defineProperty(exports, "startInactiveSpan", {
	enumerable: true,
	get: function() {
		return startInactiveSpan;
	}
});
Object.defineProperty(exports, "startInactiveSpan$1", {
	enumerable: true,
	get: function() {
		return startInactiveSpan$1;
	}
});
Object.defineProperty(exports, "startNewTrace", {
	enumerable: true,
	get: function() {
		return startNewTrace;
	}
});
Object.defineProperty(exports, "startSession", {
	enumerable: true,
	get: function() {
		return startSession;
	}
});
Object.defineProperty(exports, "startSpan", {
	enumerable: true,
	get: function() {
		return startSpan;
	}
});
Object.defineProperty(exports, "startSpan$1", {
	enumerable: true,
	get: function() {
		return startSpan$1;
	}
});
Object.defineProperty(exports, "startSpanManual", {
	enumerable: true,
	get: function() {
		return startSpanManual;
	}
});
Object.defineProperty(exports, "startSpanManual$1", {
	enumerable: true,
	get: function() {
		return startSpanManual$1;
	}
});
Object.defineProperty(exports, "stringMatchesSomePattern", {
	enumerable: true,
	get: function() {
		return stringMatchesSomePattern;
	}
});
Object.defineProperty(exports, "stringify", {
	enumerable: true,
	get: function() {
		return stringify;
	}
});
Object.defineProperty(exports, "stringifyValue", {
	enumerable: true,
	get: function() {
		return stringifyValue;
	}
});
Object.defineProperty(exports, "stripSentryFramesAndReverse", {
	enumerable: true,
	get: function() {
		return stripSentryFramesAndReverse;
	}
});
Object.defineProperty(exports, "suppressTracing", {
	enumerable: true,
	get: function() {
		return suppressTracing;
	}
});
Object.defineProperty(exports, "timedEventsToMeasurements", {
	enumerable: true,
	get: function() {
		return timedEventsToMeasurements;
	}
});
Object.defineProperty(exports, "timestampInSeconds", {
	enumerable: true,
	get: function() {
		return timestampInSeconds;
	}
});
Object.defineProperty(exports, "triggerHandlers", {
	enumerable: true,
	get: function() {
		return triggerHandlers;
	}
});
Object.defineProperty(exports, "truncate", {
	enumerable: true,
	get: function() {
		return truncate;
	}
});
Object.defineProperty(exports, "updateSession", {
	enumerable: true,
	get: function() {
		return updateSession;
	}
});
Object.defineProperty(exports, "updateSpanName", {
	enumerable: true,
	get: function() {
		return updateSpanName;
	}
});
Object.defineProperty(exports, "uuid4", {
	enumerable: true,
	get: function() {
		return uuid4;
	}
});
Object.defineProperty(exports, "withActiveSpan", {
	enumerable: true,
	get: function() {
		return withActiveSpan;
	}
});
Object.defineProperty(exports, "withIsolationScope", {
	enumerable: true,
	get: function() {
		return withIsolationScope;
	}
});
Object.defineProperty(exports, "withRandomSafeContext", {
	enumerable: true,
	get: function() {
		return withRandomSafeContext;
	}
});
Object.defineProperty(exports, "withScope", {
	enumerable: true,
	get: function() {
		return withScope;
	}
});
Object.defineProperty(exports, "withStaticSpan", {
	enumerable: true,
	get: function() {
		return withStaticSpan;
	}
});
Object.defineProperty(exports, "withStreamedSpan", {
	enumerable: true,
	get: function() {
		return withStreamedSpan;
	}
});
Object.defineProperty(exports, "wrapMethod", {
	enumerable: true,
	get: function() {
		return wrapMethod;
	}
});

//# sourceMappingURL=cacheOrigin.js.map