UNPKG

@cloudflare/vite-plugin

Version:
1,498 lines (1,472 loc) • 222 kB
import { WorkerEntrypoint } from "cloudflare:workers"; //#region ../workers-shared/utils/responses.ts var TemporaryRedirectResponse = class TemporaryRedirectResponse extends Response { static status = 307; constructor(location, init) { super(null, { ...init, status: TemporaryRedirectResponse.status, statusText: "Temporary Redirect", headers: { ...init?.headers, Location: location } }); } }; //#endregion //#region ../workers-shared/utils/tracing.ts function mockJaegerBindingSpan() { return { addLogs: () => {}, setTags: () => {}, end: () => {}, isRecording: true }; } function mockJaegerBinding() { return { enterSpan: (_, span, ...args) => { return span(mockJaegerBindingSpan(), ...args); }, getSpanContext: () => ({ traceId: "test-trace", spanId: "test-span", parentSpanId: "test-parent-span", traceFlags: 0 }), runWithSpanContext: (_, callback, ...args) => { return callback(...args); }, traceId: "test-trace", spanId: "test-span", parentSpanId: "test-parent-span", cfTraceIdHeader: "test-trace:test-span:0" }; } //#endregion //#region ../workers-shared/asset-worker/src/utils/rules-engine.ts const ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g; const escapeRegex = (str) => { return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&"); }; const generateGlobOnlyRuleRegExp = (rule) => { rule = rule.split("*").map(escapeRegex).join(".*"); rule = "^" + rule + "$"; return RegExp(rule); }; const generateStaticRoutingRuleMatcher = (rules) => ({ request }) => { const { pathname } = new URL(request.url); for (const rule of rules) try { if (generateGlobOnlyRuleRegExp(rule).test(pathname)) return true; } catch {} return false; }; //#endregion //#region ../workers-shared/utils/performance.ts var PerformanceTimer = class { performanceTimer; constructor(performanceTimer) { this.performanceTimer = performanceTimer; } now() { if (this.performanceTimer) return this.performanceTimer.timeOrigin + this.performanceTimer.now(); return Date.now(); } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/is.js 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]": 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$1(wat) { return isBuiltin(wat, "ErrorEvent"); } /** * 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'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. */ function isElement(wat) { return typeof Element !== "undefined" && isInstanceOf(wat, Element); } /** * Checks whether given value has a then function. * @param wat A value to be checked. */ function isThenable(wat) { return Boolean(wat && wat.then && typeof wat.then === "function"); } /** * Checks whether given value's type is a SyntheticEvent * {@link isSyntheticEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isSyntheticEvent(wat) { return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat; } /** * Checks whether given value's type is an instance of provided constructor. * {@link isInstanceOf}. * * @param wat A value to be checked. * @param base A constructor to be used in a check. * @returns A boolean representing the result. */ function isInstanceOf(wat, base) { try { return wat instanceof base; } catch (_e) { return false; } } /** * Checks whether given value's type is a Vue ViewModel. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isVueViewModel(wat) { return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/string.js /** * 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)}...`; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/version.js const SDK_VERSION = "8.9.2"; //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/worldwide.js /** Get's the global object for the current JavaScript runtime */ const GLOBAL_OBJ = globalThis; /** * 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) { const gbl = obj || GLOBAL_OBJ; const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {}; const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}; return versionedCarrier[name] || (versionedCarrier[name] = creator()); } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/browser.js const WINDOW = GLOBAL_OBJ; const DEFAULT_MAX_STRING_LENGTH = 80; /** * Given a child DOM element, returns a query-selector statement describing that * and its ancestors * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] * @returns generated DOM path */ function htmlTreeAsString(elem, options = {}) { if (!elem) return "<unknown>"; try { let currentElem = elem; const MAX_TRAVERSE_HEIGHT = 5; const out = []; let height = 0; let len = 0; const separator = " > "; const sepLength = 3; let nextStr; const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH; while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { nextStr = _htmlElementAsString(currentElem, keyAttrs); if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) break; out.push(nextStr); len += nextStr.length; currentElem = currentElem.parentNode; } return out.reverse().join(separator); } catch (_oO) { return "<unknown>"; } } /** * Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @returns generated DOM path */ function _htmlElementAsString(el, keyAttrs) { const elem = el; const out = []; let className; let classes; let key; let attr; let i; if (!elem || !elem.tagName) return ""; if (WINDOW.HTMLElement) { if (elem instanceof HTMLElement && elem.dataset) { if (elem.dataset["sentryComponent"]) return elem.dataset["sentryComponent"]; if (elem.dataset["sentryElement"]) return elem.dataset["sentryElement"]; } } out.push(elem.tagName.toLowerCase()); const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null; if (keyAttrPairs && keyAttrPairs.length) keyAttrPairs.forEach((keyAttrPair) => { out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); }); else { if (elem.id) out.push(`#${elem.id}`); className = elem.className; if (className && isString(className)) { classes = className.split(/\s+/); for (i = 0; i < classes.length; i++) out.push(`.${classes[i]}`); } } const allowedAttrs = [ "aria-label", "type", "name", "title", "alt" ]; for (i = 0; i < allowedAttrs.length; i++) { key = allowedAttrs[i]; attr = elem.getAttribute(key); if (attr) out.push(`[${key}="${attr}"]`); } return out.join(""); } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/debug-build.js /** * 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$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/logger.js /** Prefix for logging strings */ const PREFIX = "Sentry Logger "; const CONSOLE_LEVELS = [ "debug", "info", "warn", "error", "log", "assert", "trace" ]; /** This may be mutated by the console instrumentation. */ const originalConsoleMethods = {}; /** JSDoc */ /** * 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$1 = GLOBAL_OBJ.console; const wrappedFuncs = {}; const wrappedLevels = Object.keys(originalConsoleMethods); wrappedLevels.forEach((level) => { const originalConsoleMethod = originalConsoleMethods[level]; wrappedFuncs[level] = console$1[level]; console$1[level] = originalConsoleMethod; }); try { return callback(); } finally { wrappedLevels.forEach((level) => { console$1[level] = wrappedFuncs[level]; }); } } function makeLogger() { let enabled = false; const logger$1 = { enable: () => { enabled = true; }, disable: () => { enabled = false; }, isEnabled: () => enabled }; if (DEBUG_BUILD$1) CONSOLE_LEVELS.forEach((name) => { logger$1[name] = (...args) => { if (enabled) consoleSandbox(() => { GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); }); }; }); else CONSOLE_LEVELS.forEach((name) => { logger$1[name] = () => void 0; }); return logger$1; } const logger = makeLogger(); //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/dsn.js /** Regular expression used to parse a Dsn. */ const DSN_REGEX = /^(?:(\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$1) return true; const { port, projectId, protocol } = dsn; if ([ "protocol", "publicKey", "host", "projectId" ].find((component) => { if (!dsn[component]) { logger.error(`Invalid Sentry Dsn: ${component} missing`); return true; } return false; })) return false; if (!projectId.match(/^\d+$/)) { logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); return false; } if (!isValidProtocol(protocol)) { logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); return false; } if (port && isNaN(parseInt(port, 10))) { logger.error(`Invalid Sentry Dsn: Invalid port ${port}`); return false; } return true; } /** * 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; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/error.js /** An error emitted by Sentry SDKs and related utilities. */ var SentryError = class extends Error { /** Display name of this error instance. */ constructor(message, logLevel = "warn") { super(message); this.message = message; this.name = new.target.prototype.constructor.name; Object.setPrototypeOf(this, new.target.prototype); this.logLevel = logLevel; } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/object.js /** * 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 (o_O) { DEBUG_BUILD$1 && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj); } } /** * Encodes given object into url-friendly format * * @param object An object that contains serializable values * @returns string Encoded */ function urlEncode(object) { return Object.keys(object).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`).join("&"); } /** * 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 argurment 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) }; else if (isEvent(value)) { const newObj = { type: value.type, target: serializeEventTarget(value.target), currentTarget: serializeEventTarget(value.currentTarget), ...getOwnProperties(value) }; if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) newObj.detail = value.detail; return newObj; } else return value; } /** Creates a string representation of the target of an `Event` object */ function serializeEventTarget(target) { try { return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); } catch (_oO) { return "<unknown>"; } } /** Filters out all but an object's own properties */ function getOwnProperties(obj) { if (typeof obj === "object" && obj !== null) { const extractedProps = {}; for (const property in obj) if (Object.prototype.hasOwnProperty.call(obj, property)) extractedProps[property] = obj[property]; return extractedProps; } else 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, maxLength = 40) { const keys = Object.keys(convertToPlainObject(exception)); keys.sort(); if (!keys.length) return "[object has no keys]"; if (keys[0].length >= maxLength) return truncate(keys[0], maxLength); for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { const serialized = keys.slice(0, includedKeys).join(", "); if (serialized.length > maxLength) continue; if (includedKeys === keys.length) return serialized; return truncate(serialized, maxLength); } return ""; } /** * 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. */ function dropUndefinedKeys(inputValue) { return _dropUndefinedKeys(inputValue, /* @__PURE__ */ new Map()); } function _dropUndefinedKeys(inputValue, memoizationMap) { if (isPojo(inputValue)) { const memoVal = memoizationMap.get(inputValue); if (memoVal !== void 0) return memoVal; const returnValue = {}; memoizationMap.set(inputValue, returnValue); for (const key of Object.keys(inputValue)) if (typeof inputValue[key] !== "undefined") returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); return returnValue; } if (Array.isArray(inputValue)) { const memoVal = memoizationMap.get(inputValue); if (memoVal !== void 0) return memoVal; const returnValue = []; memoizationMap.set(inputValue, returnValue); inputValue.forEach((item) => { returnValue.push(_dropUndefinedKeys(item, memoizationMap)); }); return returnValue; } return inputValue; } function isPojo(input) { if (!isPlainObject(input)) return false; try { const name = Object.getPrototypeOf(input).constructor.name; return !name || name === "Object"; } catch (e) { return true; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/stacktrace.js 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++) { const line = lines[i]; if (line.length > 1024) continue; const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line; if (cleanedLine.match(/\S*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(localStack[localStack.length - 1].function || "")) localStack.pop(); localStack.reverse(); if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) { localStack.pop(); if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) localStack.pop(); } return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({ ...frame, filename: frame.filename || localStack[localStack.length - 1].filename, function: frame.function || UNKNOWN_FUNCTION })); } 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 (e) { return defaultFunctionName; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/handlers.js const handlers = {}; const instrumented = {}; /** Add a handler function. */ function addHandler(type, handler$1) { handlers[type] = handlers[type] || []; handlers[type].push(handler$1); } /** Maybe run an instrumentation function, unless it was already called. */ function maybeInstrument(type, instrumentFn) { if (!instrumented[type]) { instrumentFn(); instrumented[type] = true; } } /** Trigger handlers for a given instrumentation type. */ function triggerHandlers(type, data) { const typeHandlers = type && handlers[type]; if (!typeHandlers) return; for (const handler$1 of typeHandlers) try { handler$1(data); } catch (e) { DEBUG_BUILD$1 && logger.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler$1)}\nError:`, e); } } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/time.js const ONE_SECOND_IN_MS = 1e3; /** * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} * for accessing a high-resolution monotonic clock. */ /** * Returns a timestamp in seconds since the UNIX epoch using the Date API. * * TODO(v8): Return type should be rounded. */ function dateTimestampInSeconds() { return Date.now() / ONE_SECOND_IN_MS; } /** * 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 || !performance.now) return dateTimestampInSeconds; const approxStartingTimeOrigin = Date.now() - performance.now(); const timeOrigin = performance.timeOrigin == void 0 ? approxStartingTimeOrigin : performance.timeOrigin; return () => { return (timeOrigin + performance.now()) / 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. * * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The * skew can grow to arbitrary amounts like days, weeks or months. * See https://github.com/getsentry/sentry-javascript/issues/2590. */ const timestampInSeconds = createUnixTimestampInSecondsFunc(); /** * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. */ let _browserPerformanceTimeOriginMode; /** * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the * performance API is available. */ const browserPerformanceTimeOrigin = (() => { const { performance } = GLOBAL_OBJ; if (!performance || !performance.now) { _browserPerformanceTimeOriginMode = "none"; return; } const threshold = 3600 * 1e3; const performanceNow = performance.now(); const dateNow = Date.now(); const timeOriginDelta = performance.timeOrigin ? Math.abs(performance.timeOrigin + performanceNow - dateNow) : threshold; const timeOriginIsReliable = timeOriginDelta < threshold; const navigationStart = performance.timing && performance.timing.navigationStart; const navigationStartDelta = typeof navigationStart === "number" ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; if (timeOriginIsReliable || navigationStartDelta < threshold) if (timeOriginDelta <= navigationStartDelta) { _browserPerformanceTimeOriginMode = "timeOrigin"; return performance.timeOrigin; } else { _browserPerformanceTimeOriginMode = "navigationStart"; return navigationStart; } _browserPerformanceTimeOriginMode = "dateNow"; return dateNow; })(); //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/globalError.js 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$1) { const type = "error"; addHandler(type, handler$1); 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 && !_oldOnErrorHandler.__SENTRY_LOADER__) return _oldOnErrorHandler.apply(this, arguments); return false; }; GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/globalUnhandledRejection.js 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$1) { const type = "unhandledrejection"; addHandler(type, handler$1); maybeInstrument(type, instrumentUnhandledRejection); } function instrumentUnhandledRejection() { _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; GLOBAL_OBJ.onunhandledrejection = function(e) { triggerHandlers("unhandledrejection", e); if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) return _oldOnUnhandledRejectionHandler.apply(this, arguments); return true; }; GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/memo.js /** * Helper to decycle json objects */ function memoBuilder() { const hasWeakSet = typeof WeakSet === "function"; const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : []; function memoize(obj) { if (hasWeakSet) { if (inner.has(obj)) return true; inner.add(obj); return false; } for (let i = 0; i < inner.length; i++) if (inner[i] === obj) return true; inner.push(obj); return false; } function unmemoize(obj) { if (hasWeakSet) inner.delete(obj); else for (let i = 0; i < inner.length; i++) if (inner[i] === obj) { inner.splice(i, 1); break; } } return [memoize, unmemoize]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/misc.js /** * UUID4 generator * * @returns string Generated UUID4. */ function uuid4() { const gbl = GLOBAL_OBJ; const crypto = gbl.crypto || gbl.msCrypto; let getRandomByte = () => Math.random() * 16; try { if (crypto && crypto.randomUUID) return crypto.randomUUID().replace(/-/g, ""); if (crypto && crypto.getRandomValues) getRandomByte = () => { const typedArray = new Uint8Array(1); crypto.getRandomValues(typedArray); return typedArray[0]; }; } catch (_) {} return "10000000100040008000100000000000".replace(/[018]/g, (c) => (c ^ (getRandomByte() & 15) >> c / 4).toString(16)); } function getFirstException(event) { return event.exception && event.exception.values ? event.exception.values[0] : void 0; } /** * 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; const defaultMechanism = { type: "generic", handled: true }; const currentMechanism = firstException.mechanism; firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; if (newMechanism && "data" in newMechanism) { const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data }; firstException.mechanism.data = mergedData; } } /** * 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. * * 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 (exception && exception.__sentry_captured__) return true; try { addNonEnumerableProperty(exception, "__sentry_captured__", true); } catch (err) {} return false; } /** * Checks whether the given input is already an array, and if it isn't, wraps it in one. * * @param maybeArray Input to turn into an array, if necessary * @returns The input, if already an array, or an array with the input as the only element, if not */ function arrayify(maybeArray) { return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/normalize.js /** * 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 normallized output. * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. */ function normalize(input, depth = 100, maxProperties = Infinity) { try { return visit("", input, depth, maxProperties); } catch (err) { return { ERROR: `**non-serializable** (${err})` }; } } /** JSDoc */ function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) { 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 = Infinity, maxProperties = Infinity, memo = memoBuilder()) { const [memoize, unmemoize] = memo; if (value == null || [ "number", "boolean", "string" ].includes(typeof value) && !Number.isNaN(value)) return value; const stringified = stringifyValue(key, value); if (!stringified.startsWith("[object ")) return stringified; if (value["__sentry_skip_normalization__"]) return value; const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : 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 (err) {} 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 (key === "domain" && value && typeof value === "object" && value._events) return "[Domain]"; if (key === "domainEmitter") return "[DomainEmitter]"; if (typeof global !== "undefined" && value === global) return "[Global]"; if (typeof window !== "undefined" && value === window) return "[Window]"; if (typeof document !== "undefined" && value === document) return "[Document]"; if (isVueViewModel(value)) return "[VueViewModel]"; if (isSyntheticEvent(value)) return "[SyntheticEvent]"; if (typeof value === "number" && value !== value) return "[NaN]"; if (typeof value === "function") return `[Function: ${getFunctionName(value)}]`; if (typeof value === "symbol") return `[${String(value)}]`; if (typeof value === "bigint") return `[BigInt: ${String(value)}]`; const objName = getConstructorName(value); if (/^HTML(\w*)Element$/.test(objName)) return `[HTMLElement: ${objName}]`; return `[object ${objName}]`; } catch (err) { return `**non-serializable** (${err})`; } } function getConstructorName(value) { const prototype = Object.getPrototypeOf(value); return prototype ? 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)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/path.js /** JSDoc */ function normalizeArray(parts, allowAboveRoot) { let up = 0; for (let i = parts.length - 1; i >= 0; i--) { const last = parts[i]; if (last === ".") parts.splice(i, 1); else if (last === "..") { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } if (allowAboveRoot) for (; up--;) parts.unshift(".."); return parts; } const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/; /** JSDoc */ function splitPath(filename) { const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename; const parts = splitPathRe.exec(truncated); return parts ? parts.slice(1) : []; } /** JSDoc */ function resolve(...args) { let resolvedPath = ""; let resolvedAbsolute = false; for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { const path = i >= 0 ? args[i] : "/"; if (!path) continue; resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charAt(0) === "/"; } resolvedPath = normalizeArray(resolvedPath.split("/").filter((p) => !!p), !resolvedAbsolute).join("/"); return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; } /** JSDoc */ function trim(arr) { let start = 0; for (; start < arr.length; start++) if (arr[start] !== "") break; let end = arr.length - 1; for (; end >= 0; end--) if (arr[end] !== "") break; if (start > end) return []; return arr.slice(start, end - start + 1); } /** JSDoc */ function relative(from, to) { from = resolve(from).slice(1); to = resolve(to).slice(1); const fromParts = trim(from.split("/")); const toParts = trim(to.split("/")); const length = Math.min(fromParts.length, toParts.length); let samePartsLength = length; for (let i = 0; i < length; i++) if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } let outputParts = []; for (let i = samePartsLength; i < fromParts.length; i++) outputParts.push(".."); outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join("/"); } /** JSDoc */ function basename(path, ext) { let f = splitPath(path)[2]; if (ext && f.slice(ext.length * -1) === ext) f = f.slice(0, f.length - ext.length); return f; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/syncpromise.js /** SyncPromise internal states */ var States; (function(States$1) { /** Pending */ const PENDING = 0; States$1[States$1["PENDING"] = PENDING] = "PENDING"; /** Resolved / OK */ const RESOLVED = 1; States$1[States$1["RESOLVED"] = RESOLVED] = "RESOLVED"; /** Rejected / Error */ const REJECTED = 2; States$1[States$1["REJECTED"] = REJECTED] = "REJECTED"; })(States || (States = {})); /** * 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$1) => { resolve$1(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) { SyncPromise.prototype.__init.call(this); SyncPromise.prototype.__init2.call(this); SyncPromise.prototype.__init3.call(this); SyncPromise.prototype.__init4.call(this); this._state = States.PENDING; this._handlers = []; try { executor(this._resolve, this._reject); } catch (e) { this._reject(e); } } /** JSDoc */ then(onfulfilled, onrejected) { return new SyncPromise((resolve$1, reject) => { this._handlers.push([ false, (result) => { if (!onfulfilled) resolve$1(result); else try { resolve$1(onfulfilled(result)); } catch (e) { reject(e); } }, (reason) => { if (!onrejected) reject(reason); else try { resolve$1(onrejected(reason)); } catch (e) { reject(e); } } ]); this._executeHandlers(); }); } /** JSDoc */ catch(onrejected) { return this.then((val) => val, onrejected); } /** JSDoc */ finally(onfinally) { return new SyncPromise((resolve$1, 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$1(val); }); }); } /** JSDoc */ __init() { this._resolve = (value) => { this._setResult(States.RESOLVED, value); }; } /** JSDoc */ __init2() { this._reject = (reason) => { this._setResult(States.REJECTED, reason); }; } /** JSDoc */ __init3() { this._setResult = (state, value) => { if (this._state !== States.PENDING) return; if (isThenable(value)) { value.then(this._resolve, this._reject); return; } this._state = state; this._value = value; this._executeHandlers(); }; } /** JSDoc */ __init4() { this._executeHandlers = () => { if (this._state === States.PENDING) return; const cachedHandlers = this._handlers.slice(); this._handlers = []; cachedHandlers.forEach((handler$1) => { if (handler$1[0]) return; if (this._state === States.RESOLVED) handler$1[1](this._value); if (this._state === States.REJECTED) handler$1[2](this._value); handler$1[0] = true; }); }; } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/promisebuffer.js /** * Creates an new PromiseBuffer object with the specified limit * @param limit max number of promises that can be stored in the buffer */ function makePromiseBuffer(limit) { const buffer = []; function isReady() { return limit === void 0 || buffer.length < limit; } /** * Remove a promise from the queue. * * @param task Can be any PromiseLike<T> * @returns Removed promise. */ function remove(task) { return buffer.splice(buffer.indexOf(task), 1)[0]; } /** * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. * * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer * limit check. * @returns The original promise. */ function add(taskProducer) { if (!isReady()) return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached.")); const task = taskProducer(); if (buffer.indexOf(task) === -1) buffer.push(task); task.then(() => remove(task)).then(null, () => remove(task).then(null, () => {})); return task; } /** * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. * * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to * `true`. * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and * `false` otherwise */ function drain(timeout) { return new SyncPromise((resolve$1, reject) => { let counter = buffer.length; if (!counter) return resolve$1(true); const capturedSetTimeout = setTimeout(() => { if (timeout && timeout > 0) resolve$1(false); }, timeout); buffer.forEach((item) => { resolvedSyncPromise(item).then(() => { if (!--counter) { clearTimeout(capturedSetTimeout); resolve$1(true); } }, reject); }); }); } return { $: buffer, add, drain }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/node-stack-trace.js /** * Does this filename look like it's part of the app code? */ function filenameIsInApp(filename, isNative = false) { return !(isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//)) && filename !== void 0 && !filename.includes("node_modules/"); } /** Node Stack line parser */ function node(getModule$1) { const FILENAME_MATCH = /^\s*[-]{4,}$/; const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; return (line) => { const lineMatch = line.match(FULL_MATCH); if (lineMatch) { let object; let method; let functionName; let typeName; let methodName; if (lineMatch[1]) { functionName = lineMatch[1]; let methodStart = functionName.lastIndexOf("."); if (functionName[methodStart - 1] === ".") methodStart--; if (methodStart > 0) { object = functionName.slice(0, methodStart); method = functionName.slice(methodStart + 1); const objectEnd = object.indexOf(".Module"); if (objectEnd > 0) { functionName = functionName.slice(objectEnd + 1); object = object.slice(0, objectEnd); } } typeName = void 0; } if (method) { typeName = object; methodName = method; } if (method === "<anonymous>") { methodName = void 0; functionName = void 0; } if (functionName === void 0) { methodName = methodName || UNKNOWN_FUNCTION; functionName = typeName ? `${typeName}.${methodName}` : methodName; } let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2]; const isNative = lineMatch[5] === "native"; if (filename && filename.match(/\/[A-Z]:/)) filename = filename.slice(1); if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5]; return { filename, module: getModule$1 ? getModule$1(filename) : void 0, function: functionName, lineno: parseInt(lineMatch[3], 10) || void 0, colno: parseInt(lineMatch[4], 10) || void 0, in_app: filenameIsInApp(filename, isNative) }; }