1(function() { 2 try { 3 var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}; 4 e.SENTRY_RELEASE = { id: "b96dc26" }; 5 var n = new e.Error().stack; 6 n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "06949e32-677b-4287-82a1-3583e5aaf01d", e._sentryDebugIdIdentifier = "sentry-dbid-06949e32-677b-4287-82a1-3583e5aaf01d"); 7 } catch (e) {} 8})(); 9import { a as __toESM, n as __esmMin, r as __exportAll } from "./rolldown-runtime-sLwMD6dS.js"; 10import { Bs as isTurnstileErrorEvent, zs as init_turnstile } from "./controllers-jdPQjaCB.js"; 11import { i as isFunction, l as unsafeCast } from "./type-guards-DVyG5ljW.js"; 12import { i as require_compiler_runtime, t as require_jsx_runtime } from "./jsx-runtime-CHSMGLHp.js"; 13import { t as require_react } from "./react-CrLPhuc5.js"; 14import { n as init_icon, t as Icon } from "./icon-BNzYbsdJ.js"; 15import { r as init_button, t as Button } from "./button-DOiPZHfy.js"; 16//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/debug-build.js 17var DEBUG_BUILD$5; 18function init_debug_build() { 19 return (init_debug_build = __esmMin((() => { 20 DEBUG_BUILD$5 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 21 })))(); 22} 23//#endregion 24//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/worldwide.js 25var GLOBAL_OBJ; 26function init_worldwide() { 27 return (init_worldwide = __esmMin((() => { 28 GLOBAL_OBJ = globalThis; 29 })))(); 30} 31//#endregion 32//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/version.js 33var SDK_VERSION; 34function init_version() { 35 return (init_version = __esmMin((() => { 36 SDK_VERSION = "10.74.0"; 37 })))(); 38} 39//#endregion 40//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/carrier.js 41function getMainCarrier() { 42 getSentryCarrier(GLOBAL_OBJ); 43 return GLOBAL_OBJ; 44} 45function getSentryCarrier(carrier) { 46 const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {}; 47 __SENTRY__.version = __SENTRY__.version || "10.74.0"; 48 return __SENTRY__[SDK_VERSION] = __SENTRY__["10.74.0"] || {}; 49} 50function getGlobalSingleton(name, creator, obj = GLOBAL_OBJ) { 51 const __SENTRY__ = obj.__SENTRY__ = obj.__SENTRY__ || {}; 52 const carrier = __SENTRY__[SDK_VERSION] = __SENTRY__["10.74.0"] || {}; 53 return carrier[name] || (carrier[name] = creator()); 54} 55function init_carrier() { 56 return (init_carrier = __esmMin((() => { 57 init_version(); 58 init_worldwide(); 59 })))(); 60} 61//#endregion 62//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/debug-logger.js 63function consoleSandbox(callback) { 64 if (!("console" in GLOBAL_OBJ)) return callback(); 65 const console = GLOBAL_OBJ.console; 66 const wrappedFuncs = {}; 67 const wrappedLevels = Object.keys(originalConsoleMethods);
68 wrappedLevels.forEach((level) => { 69 const originalConsoleMethod = originalConsoleMethods[level]; 70 wrappedFuncs[level] = console[level]; 71 console[level] = originalConsoleMethod; 72 }); 73 try { 74 return callback(); 75 } finally { 76 wrappedLevels.forEach((level) => { 77 console[level] = wrappedFuncs[level]; 78 }); 79 } 80} 81function enable() { 82 _getLoggerSettings().enabled = true; 83} 84function disable() { 85 _getLoggerSettings().enabled = false; 86} 87function isEnabled$1() { 88 return _getLoggerSettings().enabled; 89} 90function log(...args) { 91 _maybeLog("log", ...args); 92} 93function warn$1(...args) { 94 _maybeLog("warn", ...args); 95} 96function error$1(...args) { 97 _maybeLog("error", ...args); 98} 99function _maybeLog(level, ...args) { 100 if (!DEBUG_BUILD$5) return; 101 if (isEnabled$1()) consoleSandbox(() => { 102 GLOBAL_OBJ.console[level](`${PREFIX$1}[${level}]:`, ...args); 103 }); 104} 105function _getLoggerSettings() { 106 if (!DEBUG_BUILD$5) return { enabled: false }; 107 return getGlobalSingleton("loggerSettings", () => ({ enabled: false })); 108} 109var CONSOLE_LEVELS$1, PREFIX$1, originalConsoleMethods, debug$2; 110function init_debug_logger() { 111 return (init_debug_logger = __esmMin((() => { 112 init_carrier(); 113 init_debug_build(); 114 init_worldwide(); 115 CONSOLE_LEVELS$1 = [ 116 "debug", 117 "info", 118 "warn", 119 "error", 120 "log", 121 "assert", 122 "trace" 123 ]; 124 PREFIX$1 = "Sentry Logger "; 125 originalConsoleMethods = {}; 126 debug$2 = { 127 /** Enable logging. */ 128 enable, 129 /** Disable logging. */ 130 disable, 131 /** Check if logging is enabled. */ 132 isEnabled: isEnabled$1, 133 /** Log a message. */ 134 log, 135 /** Log a warning. */ 136 warn: warn$1, 137 /** Log an error. */ 138 error: error$1 139 }; 140 })))(); 141} 142//#endregion 143//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/stacktrace.js 144function createStackParser(...parsers) { 145 const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map((p) => p[1]); 146 return (stack, skipFirstLines = 0, framesToPop = 0) => { 147 const frames = []; 148 const lines = stack.split("\n"); 149 for (let i = skipFirstLines; i < lines.length; i++) { 150 let line = lines[i]; 151 if (line.length > 1024) line = line.slice(0, 1024); 152 const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line; 153 if (cleanedLine.includes("Error: ")) continue; 154 for (const parser of sortedParsers) { 155 const frame = parser(cleanedLine); 156 if (frame) { 157 frames.push(frame); 158 break; 159 } 160 } 161 if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) break; 162 } 163 return stripSentryFramesAndReverse(frames.slice(framesToPop)); 164 }; 165} 166function stackParserFromStackParserOptions(stackParser) { 167 if (Array.isArray(stackParser)) return createStackParser(...stackParser); 168 return stackParser; 169} 170function stripSentryFramesAndReverse(stack) { 171 if (!stack.length) return []; 172 const localStack = Array.from(stack); 173 if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) localStack.pop(); 174 localStack.reverse(); 175 if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) { 176 localStack.pop(); 177 if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) localStack.pop(); 178 } 179 return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({ 180 ...frame, 181 filename: frame.filename || getLastStackFrame(localStack).filename, 182 function: frame.function || "?" 183 })); 184} 185function getLastStackFrame(arr) { 186 return arr[arr.length - 1] || {}; 187} 188function getFunctionName(fn) { 189 try { 190 if (!fn || typeof fn !== "function") return defaultFunctionName; 191 return fn.name || defaultFunctionName; 192 } catch { 193 return defaultFunctionName; 194 } 195} 196function getFramesFromEvent(event) { 197 const exception = event.exception; 198 if (exception) { 199 const frames = []; 200 try { 201 exception.values.forEach((value) => { 202 if (value.stacktrace.frames) frames.push(...value.stacktrace.frames); 203 }); 204 return frames; 205 } catch { 206 return; 207 } 208 } 209} 210function normalizeStackTracePath(path) { 211 let filename = path?.startsWith("file://") ? path.slice(7) : path; 212 if (filename?.match(/\/[A-Z]:/)) filename = filename.slice(1); 213 return filename; 214} 215var STACKTRACE_FRAME_LIMIT, WEBPACK_ERROR_REGEXP, STRIP_FRAME_REGEXP, defaultFunctionName; 216function init_stacktrace() { 217 return (init_stacktrace = __esmMin((() => { 218 STACKTRACE_FRAME_LIMIT = 50; 219 WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; 220 STRIP_FRAME_REGEXP = /captureMessage|captureException/; 221 defaultFunctionName = "<anonymous>"; 222 })))(); 223} 224//#endregion 225//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/instrument/handlers.js 226function addHandler$1(type, handler) { 227 handlers$2[type] = handlers$2[type] || []; 228 handlers$2[type].push(handler); 229 return () => { 230 const typeHandlers = handlers$2[type]; 231 if (typeHandlers) { 232 const index = typeHandlers.indexOf(handler); 233 if (index !== -1) typeHandlers.splice(index, 1); 234 } 235 }; 236} 237function maybeInstrument(type, instrumentFn) { 238 if (!instrumented$1[type]) { 239 instrumented$1[type] = true; 240 try { 241 instrumentFn(); 242 } catch (e) { 243 DEBUG_BUILD$5 && debug$2.error(`Error while instrumenting ${type}`, e); 244 } 245 } 246} 247function triggerHandlers$1(type, data) { 248 const typeHandlers = type && handlers$2[type]; 249 if (!typeHandlers) return; 250 for (const handler of typeHandlers) try { 251 handler(data); 252 } catch (e) { 253 DEBUG_BUILD$5 && debug$2.error(`Error while triggering instrumentation handler. 254Type: ${type} 255Name: ${getFunctionName(handler)} 256Error:`, e); 257 } 258} 259var handlers$2, instrumented$1; 260function init_handlers() { 261 return (init_handlers = __esmMin((() => { 262 init_debug_build(); 263 init_debug_logger(); 264 init_stacktrace(); 265 handlers$2 = {}; 266 instrumented$1 = {}; 267 })))(); 268} 269//#endregion 270//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/instrument/globalError.js 271function addGlobalErrorInstrumentationHandler(handler) { 272 const type = "error"; 273 addHandler$1(type, handler); 274 maybeInstrument(type, instrumentError); 275} 276function instrumentError() { 277 _oldOnErrorHandler = GLOBAL_OBJ.onerror; 278 GLOBAL_OBJ.onerror = function(msg, url, line, column, error) { 279 triggerHandlers$1("error", {
280 column, 281 error, 282 line, 283 msg, 284 url 285 }); 286 if (_oldOnErrorHandler) return _oldOnErrorHandler.apply(this, arguments); 287 return false; 288 }; 289 GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; 290} 291var _oldOnErrorHandler; 292function init_globalError() { 293 return (init_globalError = __esmMin((() => { 294 init_worldwide(); 295 init_handlers(); 296 _oldOnErrorHandler = null; 297 })))(); 298} 299//#endregion 300//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/instrument/globalUnhandledRejection.js 301function addGlobalUnhandledRejectionInstrumentationHandler(handler) { 302 const type = "unhandledrejection"; 303 addHandler$1(type, handler); 304 maybeInstrument(type, instrumentUnhandledRejection); 305} 306function instrumentUnhandledRejection() { 307 _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; 308 GLOBAL_OBJ.onunhandledrejection = function(e) { 309 triggerHandlers$1("unhandledrejection", e); 310 if (_oldOnUnhandledRejectionHandler) return _oldOnUnhandledRejectionHandler.apply(this, arguments); 311 return true; 312 }; 313 GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; 314} 315var _oldOnUnhandledRejectionHandler; 316function init_globalUnhandledRejection() { 317 return (init_globalUnhandledRejection = __esmMin((() => { 318 init_worldwide(); 319 init_handlers(); 320 _oldOnUnhandledRejectionHandler = null; 321 })))(); 322} 323//#endregion 324//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/is.js 325function isError(wat) { 326 switch (objectToString.call(wat)) { 327 case "[object Error]":
328 case "[object Exception]": 329 case "[object DOMException]": 330 case "[object WebAssembly.Exception]": return true; 331 default: return isInstanceOf(wat, Error); 332 } 333} 334function isBuiltin(wat, className) { 335 return objectToString.call(wat) === `[object ${className}]`; 336} 337function isErrorEvent$3(wat) { 338 return isBuiltin(wat, "ErrorEvent"); 339} 340function isDOMError(wat) { 341 return isBuiltin(wat, "DOMError"); 342} 343function isDOMException(wat) { 344 return isBuiltin(wat, "DOMException"); 345} 346function isString(wat) { 347 return isBuiltin(wat, "String"); 348} 349function isParameterizedString(wat) { 350 return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat; 351} 352function isPrimitive(wat) { 353 return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function"; 354} 355function isPlainObject(wat) { 356 return isBuiltin(wat, "Object"); 357} 358function isObjectLike(wat) { 359 return typeof wat === "object" && wat !== null; 360} 361function isEvent(wat) { 362 return typeof Event !== "undefined" && isInstanceOf(wat, Event); 363} 364function isRegExp(wat) { 365 return isBuiltin(wat, "RegExp"); 366} 367function isThenable(wat) { 368 return Boolean(wat?.then && typeof wat.then === "function"); 369} 370function isInstanceOf(wat, base) { 371 try { 372 return wat instanceof base; 373 } catch { 374 return false; 375 } 376} 377function isRequest(request) { 378 return typeof Request !== "undefined" && isInstanceOf(request, Request); 379} 380var objectToString; 381function init_is() { 382 return (init_is = __esmMin((() => { 383 objectToString = Object.prototype.toString; 384 })))(); 385} 386//#endregion 387//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/object.js 388function fill(source, name, replacementFactory) { 389 if (!(name in source)) return; 390 const original = source[name]; 391 if (typeof original !== "function") return; 392 const wrapped = replacementFactory(original); 393 if (typeof wrapped === "function") markFunctionWrapped(wrapped, original); 394 try { 395 source[name] = wrapped; 396 } catch { 397 DEBUG_BUILD$5 && debug$2.log(`Failed to replace method "${name}" in object`, source); 398 } 399} 400function addNonEnumerableProperty(obj, name, value) { 401 try { 402 Object.defineProperty(obj, name, { 403 value, 404 writable: true, 405 configurable: true 406 }); 407 } catch { 408 DEBUG_BUILD$5 && debug$2.log(`Failed to add non-enumerable property "${String(name)}" to object`, obj); 409 } 410} 411function markFunctionWrapped(wrapped, original) { 412 try { 413 wrapped.prototype = original.prototype = original.prototype || {}; 414 addNonEnumerableProperty(wrapped, "__sentry_original__", original); 415 } catch {} 416} 417function getOriginalFunction(func) { 418 return func.__sentry_original__; 419} 420function convertToPlainObject(value) { 421 if (isError(value)) return { 422 message: value.message, 423 name: value.name, 424 stack: value.stack, 425 ...getOwnProperties(value) 426 }; 427 if (isEvent(value)) { 428 const { type, target, currentTarget, detail } = value; 429 return { 430 type, 431 target, 432 currentTarget, 433 ...detail ? { detail } : {}, 434 ...getOwnProperties(value) 435 }; 436 } 437 return value; 438} 439function getOwnProperties(obj) { 440 if (isObjectLike(obj)) return Object.fromEntries(Object.entries(obj)); 441 return {}; 442} 443function extractExceptionKeysForMessage(exception) { 444 const keys = Object.keys(convertToPlainObject(exception)); 445 keys.sort(); 446 return !keys[0] ? "[object has no keys]" : keys.join(", "); 447} 448function init_object() { 449 return (init_object = __esmMin((() => { 450 init_debug_build(); 451 init_debug_logger(); 452 init_is(); 453 })))(); 454} 455//#endregion 456//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/randomSafeContext.js 457function withRandomSafeContext(cb) { 458 if (RESOLVED_RUNNER !== void 0) return RESOLVED_RUNNER ? RESOLVED_RUNNER(cb) : cb(); 459 const sym = /* @__PURE__ */ Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"); 460 const globalWithSymbol = GLOBAL_OBJ; 461 if (sym in globalWithSymbol && typeof globalWithSymbol[sym] === "function") { 462 RESOLVED_RUNNER = globalWithSymbol[sym]; 463 return RESOLVED_RUNNER(cb); 464 } 465 RESOLVED_RUNNER = null; 466 return cb(); 467} 468function safeMathRandom() { 469 return withRandomSafeContext(() => Math.random()); 470} 471function safeDateNow() { 472 return withRandomSafeContext(() => Date.now()); 473} 474var RESOLVED_RUNNER; 475function init_randomSafeContext() { 476 return (init_randomSafeContext = __esmMin((() => { 477 init_worldwide(); 478 })))(); 479} 480//#endregion 481//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/normalizationHints.js 482function setSkipNormalizationHint(obj) { 483 addNonEnumerableProperty(obj, SENTRY_SKIP_NORMALIZATION, true); 484} 485function setNormalizationDepthOverrideHint(obj, depth) { 486 addNonEnumerableProperty(obj, SENTRY_OVERRIDE_NORMALIZATION_DEPTH, depth); 487} 488function hasSkipNormalizationHint(value) { 489 return Boolean(value[SENTRY_SKIP_NORMALIZATION]); 490} 491function getNormalizationDepthOverrideHint(value) { 492 const v = value[SENTRY_OVERRIDE_NORMALIZATION_DEPTH]; 493 return typeof v === "number" ? v : void 0; 494} 495var SENTRY_SKIP_NORMALIZATION, SENTRY_OVERRIDE_NORMALIZATION_DEPTH; 496function init_normalizationHints() { 497 return (init_normalizationHints = __esmMin((() => { 498 init_object(); 499 SENTRY_SKIP_NORMALIZATION = /* @__PURE__ */ Symbol.for("sentry.skipNormalization"); 500 SENTRY_OVERRIDE_NORMALIZATION_DEPTH = /* @__PURE__ */ Symbol.for("sentry.overrideNormalizationDepth"); 501 })))(); 502} 503//#endregion 504//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/normalize.js 505function setNormalizeStringifier(newStringifier) { 506 stringifier = newStringifier; 507} 508function normalize(input, depth = 100, maxProperties = Infinity) { 509 try { 510 return visit("", input, depth, maxProperties); 511 } catch (err) { 512 return { ERROR: `**non-serializable** (${err})` }; 513 } 514} 515function normalizeToSize(object, depth = 3, maxSize = 102400) { 516 const normalized = normalize(object, depth); 517 if (jsonSize(normalized) > maxSize) return normalizeToSize(object, depth - 1, maxSize); 518 return normalized; 519} 520function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) { 521 const [memoize, unmemoize] = memo; 522 if (value == null || ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) return value; 523 const stringified = stringifyValue(key, value); 524 if (!stringified.startsWith("[object ")) return stringified; 525 if (hasSkipNormalizationHint(value)) return value; 526 const overrideDepth = getNormalizationDepthOverrideHint(value); 527 const remainingDepth = overrideDepth !== void 0 ? overrideDepth : depth; 528 if (remainingDepth === 0) return stringified.replace("object ", ""); 529 if (memoize(value)) return "[Circular ~]"; 530 const valueWithToJSON = value; 531 if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") try { 532 return visit("", valueWithToJSON.toJSON(), remainingDepth - 1, maxProperties, memo); 533 } catch {} 534 const normalized = Array.isArray(value) ? [] : {}; 535 let numAdded = 0; 536 const visitable = convertToPlainObject(value); 537 for (const visitKey in visitable) { 538 if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) continue; 539 if (numAdded >= maxProperties) { 540 normalized[visitKey] = "[MaxProperties ~]"; 541 break; 542 } 543 const visitValue = visitable[visitKey]; 544 normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo); 545 numAdded++; 546 } 547 unmemoize(value); 548 return normalized; 549} 550function stringifyValue(key, value) { 551 try { 552 if (stringifier) { 553 const stringified = stringifier(value); 554 if (stringified) return stringified; 555 } 556 if (typeof global !== "undefined" && value === global) return "[Global]"; 557 if (typeof value === "number" && !Number.isFinite(value)) return `[${value}]`; 558 if (typeof value === "function") return `[Function: ${getFunctionName(value)}]`; 559 if (typeof value === "symbol") return `[${String(value)}]`; 560 if (typeof value === "bigint") return `[BigInt: ${String(value)}]`; 561 return `[object ${getConstructorName$1(value)}]`; 562 } catch (err) { 563 return `**non-serializable** (${err})`; 564 } 565} 566function getConstructorName$1(value) { 567 const prototype = Object.getPrototypeOf(value); 568 return prototype?.constructor ? prototype.constructor.name : "null prototype"; 569} 570function utf8Length(value) { 571 return ~-encodeURI(value).split(/%..|./).length; 572} 573function jsonSize(value) { 574 return utf8Length(JSON.stringify(value)); 575} 576function memoBuilder() { 577 const inner = /* @__PURE__ */ new WeakSet();
578 function memoize(obj) { 579 if (inner.has(obj)) return true; 580 inner.add(obj); 581 return false; 582 } 583 function unmemoize(obj) { 584 inner.delete(obj); 585 } 586 return [memoize, unmemoize]; 587} 588var stringifier; 589function init_normalize() { 590 return (init_normalize = __esmMin((() => { 591 init_normalizationHints(); 592 init_object(); 593 init_stacktrace(); 594 })))(); 595} 596//#endregion 597//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/string.js 598function stringify(value, fallback = "[unserializable]") { 599 if (typeof value === "string") return value; 600 try { 601 return JSON.stringify(value); 602 } catch { 603 return typeof fallback === "function" ? fallback(value) : fallback; 604 } 605} 606function truncate(str, max = 0) { 607 if (typeof str !== "string" || max === 0) return str; 608 return str.length <= max ? str : `${str.slice(0, max)}...`; 609} 610function snipLine(line, colno) { 611 let newLine = line; 612 const lineLength = newLine.length; 613 if (lineLength <= 150) return newLine; 614 if (colno > lineLength) colno = lineLength; 615 let start = Math.max(colno - 60, 0); 616 if (start < 5) start = 0; 617 let end = Math.min(start + 140, lineLength); 618 if (end > lineLength - 5) end = lineLength; 619 if (end === lineLength) start = Math.max(end - 140, 0); 620 newLine = newLine.slice(start, end); 621 if (start > 0) newLine = `'{snip} ${newLine}`; 622 if (end < lineLength) newLine += " {snip}"; 623 return newLine; 624} 625function safeJoin(input, delimiter) { 626 if (!Array.isArray(input)) return ""; 627 const output = []; 628 for (let i = 0; i < input.length; i++) { 629 const value = input[i]; 630 if (isPrimitive(value)) output.push(String(value)); 631 else if (value instanceof Error) output.push(value.message ? `${value.name}: ${value.message}` : value.name); 632 else output.push(stringifyValue(void 0, value)); 633 } 634 return output.join(delimiter); 635} 636function isMatchingPattern(value, pattern, requireExactStringMatch = false) { 637 if (!isString(value)) return false; 638 if (isRegExp(pattern)) return pattern.test(value); 639 if (isString(pattern)) return requireExactStringMatch ? value === pattern : value.includes(pattern); 640 if (typeof pattern === "function") return pattern(value); 641 return false; 642} 643function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) { 644 for (const pattern of patterns) if (isMatchingPattern(testString, pattern, requireExactStringMatch)) return true; 645 return false; 646} 647function init_string() { 648 return (init_string = __esmMin((() => { 649 init_is(); 650 init_normalize(); 651 })))(); 652} 653//#endregion 654//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/misc.js 655function getCrypto() { 656 const gbl = GLOBAL_OBJ; 657 return gbl.crypto || gbl.msCrypto; 658} 659function getRandomByte() { 660 return safeMathRandom() * 16; 661} 662function uuid4(crypto = getCrypto()) { 663 try { 664 if (crypto?.randomUUID) return withRandomSafeContext(() => crypto.randomUUID()).replace(/-/g, ""); 665 } catch {} 666 if (!emptyUuid) emptyUuid = "10000000100040008000100000000000"; 667 return emptyUuid.replace(/[018]/g, (c) => (c ^ (getRandomByte() & 15) >> c / 4).toString(16)); 668} 669function getFirstException(event) { 670 return event.exception?.values?.[0]; 671} 672function getEventDescription(event) { 673 const { message, event_id: eventId } = event; 674 if (message) return message; 675 const firstException = getFirstException(event); 676 if (firstException) { 677 if (firstException.type && firstException.value) return `${firstException.type}: ${firstException.value}`; 678 return firstException.type || firstException.value || eventId || "<unknown>"; 679 } 680 return eventId || "<unknown>"; 681} 682function addExceptionTypeValue(event, value, type) { 683 const exception = event.exception = event.exception || {}; 684 const values = exception.values = exception.values || []; 685 const firstException = values[0] = values[0] || {}; 686 if (!firstException.value) firstException.value = value || ""; 687 if (!firstException.type) firstException.type = type || "Error"; 688} 689function addExceptionMechanism(event, newMechanism) { 690 const firstException = getFirstException(event); 691 if (!firstException) return; 692 const defaultMechanism = { 693 type: "generic", 694 handled: true 695 };
696 const currentMechanism = firstException.mechanism; 697 firstException.mechanism = { 698 ...defaultMechanism, 699 ...currentMechanism, 700 ...newMechanism 701 }; 702 if (newMechanism && "data" in newMechanism) { 703 const mergedData = { 704 ...currentMechanism?.data, 705 ...newMechanism.data 706 }; 707 firstException.mechanism.data = mergedData; 708 } 709} 710function addContextToFrame(lines, frame, linesOfContext = 5) { 711 if (frame.lineno === void 0) return; 712 const maxLines = lines.length; 713 const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0); 714 frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0)); 715 frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); 716 frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0)); 717} 718function checkOrSetAlreadyCaught(exception) { 719 if (isAlreadyCaptured(exception)) return true; 720 try { 721 addNonEnumerableProperty(exception, "__sentry_captured__", true); 722 } catch {} 723 return false; 724} 725function isAlreadyCaptured(exception) { 726 try { 727 return exception.__sentry_captured__; 728 } catch {} 729} 730var emptyUuid; 731function init_misc() { 732 return (init_misc = __esmMin((() => { 733 init_object(); 734 init_randomSafeContext(); 735 init_string(); 736 init_worldwide(); 737 })))(); 738} 739//#endregion 740//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/time.js 741function dateTimestampInSeconds() { 742 return safeDateNow() / ONE_SECOND_IN_MS; 743} 744function createUnixTimestampInSecondsFunc() { 745 const { performance } = GLOBAL_OBJ; 746 if (!performance?.now || !performance.timeOrigin) return dateTimestampInSeconds; 747 const timeOrigin = performance.timeOrigin; 748 return () => { 749 return (timeOrigin + withRandomSafeContext(() => performance.now())) / ONE_SECOND_IN_MS; 750 }; 751} 752function timestampInSeconds() { 753 return (_cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc()))(); 754} 755function getBrowserTimeOrigin() { 756 const { performance } = GLOBAL_OBJ; 757 if (!performance?.now) return; 758 const threshold = 3e5; 759 const performanceNow = withRandomSafeContext(() => performance.now()); 760 const dateNow = safeDateNow(); 761 const timeOrigin = performance.timeOrigin; 762 if (typeof timeOrigin === "number") { 763 if (Math.abs(timeOrigin + performanceNow - dateNow) < threshold) return timeOrigin; 764 } 765 const navigationStart = performance.timing?.navigationStart; 766 if (typeof navigationStart === "number") { 767 if (Math.abs(navigationStart + performanceNow - dateNow) < threshold) return navigationStart; 768 } 769 return dateNow - performanceNow; 770} 771function browserPerformanceTimeOrigin() { 772 if (cachedTimeOrigin === null) cachedTimeOrigin = getBrowserTimeOrigin(); 773 return cachedTimeOrigin; 774} 775var ONE_SECOND_IN_MS, _cachedTimestampInSeconds, cachedTimeOrigin; 776function init_time() { 777 return (init_time = __esmMin((() => { 778 init_randomSafeContext(); 779 init_worldwide(); 780 ONE_SECOND_IN_MS = 1e3; 781 cachedTimeOrigin = null; 782 })))(); 783} 784//#endregion 785//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/session.js 786function makeSession$1(context) { 787 const startingTime = timestampInSeconds(); 788 const session = { 789 sid: uuid4(), 790 init: true, 791 timestamp: startingTime, 792 started: startingTime, 793 duration: 0, 794 status: "ok", 795 errors: 0, 796 ignoreDuration: false, 797 toJSON: () => sessionToJSON(session) 798 }; 799 if (context) updateSession(session, context); 800 return session; 801} 802function updateSession(session, context = {}) { 803 if (context.user) { 804 if (!session.ipAddress && context.user.ip_address) session.ipAddress = context.user.ip_address; 805 if (!session.did && !context.did) session.did = context.user.id || context.user.email || context.user.username; 806 } 807 session.timestamp = context.timestamp || timestampInSeconds(); 808 if (context.abnormal_mechanism) session.abnormal_mechanism = context.abnormal_mechanism; 809 if (context.ignoreDuration) session.ignoreDuration = context.ignoreDuration; 810 if (context.sid) session.sid = context.sid.length === 32 ? context.sid : uuid4();
811 if (context.init !== void 0) session.init = context.init; 812 if (!session.did && context.did) session.did = `${context.did}`; 813 if (typeof context.started === "number") session.started = context.started; 814 if (session.ignoreDuration) session.duration = void 0; 815 else if (typeof context.duration === "number") session.duration = context.duration; 816 else { 817 const duration = session.timestamp - session.started; 818 session.duration = duration >= 0 ? duration : 0; 819 } 820 if (context.release) session.release = context.release; 821 if (context.environment) session.environment = context.environment; 822 if (!session.ipAddress && context.ipAddress) session.ipAddress = context.ipAddress; 823 if (!session.userAgent && context.userAgent) session.userAgent = context.userAgent; 824 if (typeof context.errors === "number") session.errors = context.errors; 825 if (context.status) session.status = context.status; 826} 827function closeSession(session, status) { 828 let context = {}; 829 if (status) context = { status }; 830 else if (session.status === "ok") context = { status: "exited" }; 831 updateSession(session, context); 832} 833function sessionToJSON(session) { 834 return { 835 sid: `${session.sid}`, 836 init: session.init, 837 started: (/* @__PURE__ */ new Date(session.started * 1e3)).toISOString(), 838 timestamp: (/* @__PURE__ */ new Date(session.timestamp * 1e3)).toISOString(), 839 status: session.status, 840 errors: session.errors, 841 did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0, 842 duration: session.duration, 843 abnormal_mechanism: session.abnormal_mechanism, 844 attrs: { 845 release: session.release, 846 environment: session.environment, 847 ip_address: session.ipAddress, 848 user_agent: session.userAgent 849 } 850 }; 851} 852function init_session() { 853 return (init_session = __esmMin((() => { 854 init_misc(); 855 init_time(); 856 })))(); 857} 858//#endregion 859//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/merge.js 860function merge(initialObj, mergeObj, levels = 2) { 861 if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) return mergeObj; 862 if (initialObj && Object.keys(mergeObj).length === 0) return initialObj; 863 const output = { ...initialObj }; 864 for (const key in mergeObj) if (Object.prototype.hasOwnProperty.call(mergeObj, key)) output[key] = merge(output[key], mergeObj[key], levels - 1); 865 return output; 866} 867//#endregion 868//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/propagationContext.js 869function generateTraceId() { 870 return uuid4(); 871} 872function generateSpanId() { 873 return uuid4().substring(16); 874} 875function init_propagationContext() { 876 return (init_propagationContext = __esmMin((() => { 877 init_misc(); 878 })))(); 879} 880//#endregion 881//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/weakRef.js 882function makeWeakRef(value) { 883 try { 884 const WeakRefImpl = GLOBAL_OBJ.WeakRef; 885 if (typeof WeakRefImpl === "function") return new WeakRefImpl(value); 886 } catch {} 887 return value; 888} 889function derefWeakRef(ref) { 890 if (!ref) return; 891 if (typeof ref === "object" && "deref" in ref && typeof ref.deref === "function") try { 892 return ref.deref(); 893 } catch { 894 return; 895 } 896 return ref; 897} 898function init_weakRef() { 899 return (init_weakRef = __esmMin((() => { 900 init_worldwide(); 901 })))(); 902} 903//#endregion 904//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/spanOnScope.js 905function _setSpanForScope(scope, span) { 906 if (span) addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, makeWeakRef(span)); 907 else delete scope[SCOPE_SPAN_FIELD]; 908} 909function _getSpanForScope(scope) { 910 return derefWeakRef(scope[SCOPE_SPAN_FIELD]); 911} 912var SCOPE_SPAN_FIELD; 913function init_spanOnScope() { 914 return (init_spanOnScope = __esmMin((() => { 915 init_object(); 916 init_weakRef(); 917 SCOPE_SPAN_FIELD = "_sentrySpan"; 918 })))(); 919} 920//#endregion 921//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/scope.js 922var DEFAULT_MAX_BREADCRUMBS, Scope; 923function init_scope() { 924 return (init_scope = __esmMin((() => { 925 init_debug_build(); 926 init_session(); 927 init_debug_logger(); 928 init_is(); 929 init_misc(); 930 init_propagationContext(); 931 init_randomSafeContext(); 932 init_spanOnScope(); 933 init_string(); 934 init_time(); 935 DEFAULT_MAX_BREADCRUMBS = 100; 936 Scope = class Scope {
937 constructor() { 938 this._notifyingListeners = false; 939 this._scopeListeners = []; 940 this._eventProcessors = []; 941 this._breadcrumbs = []; 942 this._attachments = []; 943 this._user = {}; 944 this._tags = {}; 945 this._attributes = {}; 946 this._extra = {}; 947 this._contexts = {}; 948 this._sdkProcessingMetadata = {}; 949 this._propagationContext = { 950 traceId: generateTraceId(), 951 sampleRand: safeMathRandom() 952 }; 953 } 954 /** 955 * Clone all data from this scope into a new scope. 956 */ 957 clone() { 958 const newScope = new Scope(); 959 newScope._breadcrumbs = [...this._breadcrumbs]; 960 newScope._tags = { ...this._tags }; 961 newScope._attributes = { ...this._attributes }; 962 newScope._extra = { ...this._extra }; 963 newScope._contexts = { ...this._contexts }; 964 if (this._contexts.flags) newScope._contexts.flags = { values: [...this._contexts.flags.values] }; 965 newScope._user = this._user; 966 newScope._level = this._level; 967 newScope._session = this._session; 968 newScope._transactionName = this._transactionName; 969 newScope._fingerprint = this._fingerprint; 970 newScope._eventProcessors = [...this._eventProcessors]; 971 newScope._attachments = [...this._attachments]; 972 newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata }; 973 newScope._propagationContext = { ...this._propagationContext }; 974 newScope._client = this._client; 975 newScope._lastEventId = this._lastEventId; 976 newScope._conversationId = this._conversationId; 977 _setSpanForScope(newScope, _getSpanForScope(this)); 978 return newScope; 979 } 980 /** 981 * Update the client assigned to this scope. 982 * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client, 983 * as well as manually created scopes. 984 */ 985 setClient(client) { 986 this._client = client; 987 } 988 /** 989 * Set the ID of the last captured error event. 990 * This is generally only captured on the isolation scope. 991 */ 992 setLastEventId(lastEventId) { 993 this._lastEventId = lastEventId; 994 } 995 /** 996 * Get the client assigned to this scope. 997 */ 998 getClient() { 999 return this._client; 1000 } 1001 /** 1002 * Get the ID of the last captured error event. 1003 * This is generally only available on the isolation scope. 1004 */ 1005 lastEventId() { 1006 return this._lastEventId; 1007 } 1008 /** 1009 * @inheritDoc 1010 */ 1011 addScopeListener(callback) { 1012 this._scopeListeners.push(callback); 1013 } 1014 /** 1015 * Add an event processor that will be called before an event is sent. 1016 */ 1017 addEventProcessor(callback) { 1018 this._eventProcessors.push(callback); 1019 return this; 1020 } 1021 /** 1022 * Set the user for this scope. 1023 * Set to `null` to unset the user. 1024 */ 1025 setUser(user) { 1026 this._user = user || { 1027 email: void 0, 1028 id: void 0, 1029 ip_address: void 0, 1030 username: void 0 1031 }; 1032 if (this._session) updateSession(this._session, { user }); 1033 this._notifyScopeListeners(); 1034 return this; 1035 } 1036 /** 1037 * Get the user from this scope. 1038 */ 1039 getUser() { 1040 return this._user; 1041 } 1042 /** 1043 * Set the conversation ID for this scope. 1044 * Set to `null` to unset the conversation ID. 1045 */ 1046 setConversationId(conversationId) { 1047 this._conversationId = conversationId || void 0; 1048 this._notifyScopeListeners(); 1049 return this; 1050 } 1051 /** 1052 * Set an object that will be merged into existing tags on the scope, 1053 * and will be sent as tags data with the event. 1054 */ 1055 setTags(tags) { 1056 this._tags = { 1057 ...this._tags, 1058 ...tags 1059 }; 1060 this._notifyScopeListeners(); 1061 return this; 1062 } 1063 /** 1064 * Set a single tag that will be sent as tags data with the event. 1065 */ 1066 setTag(key, value) { 1067 return this.setTags({ [key]: value }); 1068 } 1069 /** 1070 * Sets attributes onto the scope. 1071 * 1072 * These attributes are applied to logs, metrics and streamed spans. 1073 * 1074 * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`. 1075 * 1076 * @param newAttributes - The attributes to set on the scope, as key-value pairs. 1077 * 1078 * @example 1079 * ```typescript 1080 * scope.setAttributes({ 1081 * is_admin: true, 1082 * payment_selection: 'credit_card', 1083 * render_duration: 150, 1084 * }); 1085 * ``` 1086 */ 1087 setAttributes(newAttributes) { 1088 this._attributes = { 1089 ...this._attributes, 1090 ...newAttributes 1091 }; 1092 this._notifyScopeListeners(); 1093 return this; 1094 } 1095 /** 1096 * Sets an attribute onto the scope. 1097 * 1098 * These attributes are applied to logs, metrics and streamed spans. 1099 * 1100 * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`. 1101 * 1102 * @param key - The attribute key. 1103 * @param value - The attribute value. 1104 * 1105 * @example 1106 * ```typescript 1107 * scope.setAttribute('is_admin', true); 1108 * scope.setAttribute('render_duration', 150); 1109 * ``` 1110 */ 1111 setAttribute(key, value) { 1112 return this.setAttributes({ [key]: value }); 1113 } 1114 /** 1115 * Removes the attribute with the given key from the scope. 1116 * 1117 * @param key - The attribute key. 1118 * 1119 * @example 1120 * ```typescript 1121 * scope.removeAttribute('is_admin'); 1122 * ``` 1123 */ 1124 removeAttribute(key) { 1125 if (key in this._attributes) { 1126 delete this._attributes[key]; 1127 this._notifyScopeListeners(); 1128 } 1129 return this; 1130 } 1131 /** 1132 * Set an object that will be merged into existing extra on the scope, 1133 * and will be sent as extra data with the event. 1134 */ 1135 setExtras(extras) { 1136 this._extra = { 1137 ...this._extra, 1138 ...extras 1139 }; 1140 this._notifyScopeListeners(); 1141 return this; 1142 } 1143 /** 1144 * Set a single key:value extra entry that will be sent as extra data with the event. 1145 */ 1146 setExtra(key, extra) { 1147 this._extra = { 1148 ...this._extra, 1149 [key]: extra 1150 }; 1151 this._notifyScopeListeners(); 1152 return this; 1153 } 1154 /** 1155 * Sets the fingerprint on the scope to send with the events. 1156 * @param {string[]} fingerprint Fingerprint to group events in Sentry. 1157 */ 1158 setFingerprint(fingerprint) { 1159 this._fingerprint = fingerprint; 1160 this._notifyScopeListeners(); 1161 return this; 1162 } 1163 /** 1164 * Sets the level on the scope for future events. 1165 */ 1166 setLevel(level) { 1167 this._level = level; 1168 this._notifyScopeListeners(); 1169 return this; 1170 } 1171 /** 1172 * Sets the transaction name on the scope so that the name of e.g. taken server route or 1173 * the page location is attached to future events. 1174 *
1175 * IMPORTANT: Calling this function does NOT change the name of the currently active 1176 * root span. If you want to change the name of the active root span, use 1177 * `Sentry.updateSpanName(rootSpan, 'new name')` instead. 1178 * 1179 * By default, the SDK updates the scope's transaction name automatically on sensible 1180 * occasions, such as a page navigation or when handling a new request on the server. 1181 */ 1182 setTransactionName(name) { 1183 this._transactionName = name; 1184 this._notifyScopeListeners(); 1185 return this; 1186 } 1187 /** 1188 * Sets context data with the given name. 1189 * Data passed as context will be normalized. You can also pass `null` to unset the context. 1190 * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key. 1191 */ 1192 setContext(key, context) { 1193 if (context === null) delete this._contexts[key]; 1194 else this._contexts[key] = context; 1195 this._notifyScopeListeners(); 1196 return this; 1197 } 1198 /** 1199 * Set the session for the scope. 1200 */ 1201 setSession(session) { 1202 if (!session) delete this._session; 1203 else this._session = session; 1204 this._notifyScopeListeners(); 1205 return this; 1206 } 1207 /** 1208 * Get the session from the scope. 1209 */ 1210 getSession() { 1211 return this._session; 1212 } 1213 /** 1214 * Updates the scope with provided data. Can work in three variations:
1215 * - plain object containing updatable attributes 1216 * - Scope instance that'll extract the attributes from 1217 * - callback function that'll receive the current scope as an argument and allow for modifications 1218 */ 1219 update(captureContext) { 1220 if (!captureContext) return this; 1221 const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext; 1222 const { tags, attributes, extra, user, contexts, level, fingerprint = [], propagationContext, conversationId } = (scopeToMerge instanceof Scope ? scopeToMerge.getScopeData() : isPlainObject(scopeToMerge) ? captureContext : void 0) || {}; 1223 this._tags = { 1224 ...this._tags, 1225 ...tags 1226 }; 1227 this._attributes = { 1228 ...this._attributes, 1229 ...attributes 1230 }; 1231 this._extra = { 1232 ...this._extra, 1233 ...extra 1234 }; 1235 this._contexts = { 1236 ...this._contexts, 1237 ...contexts 1238 }; 1239 if (user && Object.keys(user).length) this._user = user; 1240 if (level) this._level = level; 1241 if (fingerprint.length) this._fingerprint = fingerprint; 1242 if (propagationContext) this._propagationContext = propagationContext; 1243 if (conversationId) this._conversationId = conversationId; 1244 return this; 1245 } 1246 /** 1247 * Clears the current scope and resets its properties. 1248 * Note: The client will not be cleared. 1249 * 1250 * @deprecated This method will be removed in v11. To reset scope state, re-initialize the SDK or run 1251 * your code in a fresh scope via `withScope` instead. 1252 */ 1253 clear() { 1254 this._breadcrumbs = []; 1255 this._tags = {}; 1256 this._attributes = {}; 1257 this._extra = {}; 1258 this._user = {}; 1259 this._contexts = {}; 1260 this._level = void 0; 1261 this._transactionName = void 0; 1262 this._fingerprint = void 0; 1263 this._session = void 0; 1264 this._conversationId = void 0; 1265 _setSpanForScope(this, void 0); 1266 this._attachments = []; 1267 this.setPropagationContext({ 1268 traceId: generateTraceId(), 1269 sampleRand: safeMathRandom() 1270 }); 1271 this._notifyScopeListeners(); 1272 return this; 1273 } 1274 /** 1275 * Adds a breadcrumb to the scope. 1276 * By default, the last 100 breadcrumbs are kept. 1277 */ 1278 addBreadcrumb(breadcrumb, maxBreadcrumbs) { 1279 const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; 1280 if (maxCrumbs <= 0) return this; 1281 const mergedBreadcrumb = { 1282 timestamp: dateTimestampInSeconds(), 1283 ...breadcrumb, 1284 message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message 1285 }; 1286 this._breadcrumbs.push(mergedBreadcrumb); 1287 if (this._breadcrumbs.length > maxCrumbs) { 1288 this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs); 1289 this._client?.recordDroppedEvent("buffer_overflow", "log_item"); 1290 } 1291 this._notifyScopeListeners(); 1292 return this; 1293 } 1294 /** 1295 * Get the last breadcrumb of the scope. 1296 */ 1297 getLastBreadcrumb() { 1298 return this._breadcrumbs[this._breadcrumbs.length - 1]; 1299 } 1300 /** 1301 * Clear all breadcrumbs from the scope. 1302 */ 1303 clearBreadcrumbs() { 1304 this._breadcrumbs = []; 1305 this._notifyScopeListeners(); 1306 return this; 1307 } 1308 /** 1309 * Add an attachment to the scope. 1310 */ 1311 addAttachment(attachment) { 1312 this._attachments.push(attachment); 1313 return this; 1314 } 1315 /** 1316 * Clear all attachments from the scope. 1317 */ 1318 clearAttachments() { 1319 this._attachments = []; 1320 return this; 1321 } 1322 /** 1323 * Get the data of this scope, which should be applied to an event during processing. 1324 */ 1325 getScopeData() { 1326 return { 1327 breadcrumbs: this._breadcrumbs, 1328 attachments: this._attachments, 1329 contexts: this._contexts, 1330 tags: this._tags, 1331 attributes: this._attributes, 1332 extra: this._extra, 1333 user: this._user, 1334 level: this._level, 1335 fingerprint: this._fingerprint || [], 1336 eventProcessors: this._eventProcessors, 1337 propagationContext: this._propagationContext, 1338 sdkProcessingMetadata: this._sdkProcessingMetadata, 1339 transactionName: this._transactionName, 1340 span: _getSpanForScope(this), 1341 conversationId: this._conversationId 1342 }; 1343 } 1344 /** 1345 * Add data which will be accessible during event processing but won't get sent to Sentry. 1346 */ 1347 setSDKProcessingMetadata(newData) { 1348 this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2); 1349 return this; 1350 } 1351 /** 1352 * Add propagation context to the scope, used for distributed tracing 1353 */ 1354 setPropagationContext(context) { 1355 this._propagationContext = context; 1356 return this; 1357 } 1358 /**
1359 * Get propagation context from the scope, used for distributed tracing 1360 */ 1361 getPropagationContext() { 1362 return this._propagationContext; 1363 } 1364 /** 1365 * Capture an exception for this scope. 1366 * 1367 * @returns {string} The id of the captured Sentry event. 1368 */ 1369 captureException(exception, hint) { 1370 const eventId = hint?.event_id || uuid4(); 1371 if (!this._client) { 1372 DEBUG_BUILD$5 && debug$2.warn("No client configured on scope - will not capture exception!"); 1373 return eventId; 1374 } 1375 const syntheticException = /* @__PURE__ */ new Error("Sentry syntheticException"); 1376 this._client.captureException(exception, { 1377 originalException: exception, 1378 syntheticException, 1379 ...hint, 1380 event_id: eventId 1381 }, this); 1382 return eventId; 1383 } 1384 /** 1385 * Capture a message for this scope. 1386 * 1387 * @returns {string} The id of the captured message. 1388 */ 1389 captureMessage(message, level, hint) { 1390 const eventId = hint?.event_id || uuid4(); 1391 if (!this._client) { 1392 DEBUG_BUILD$5 && debug$2.warn("No client configured on scope - will not capture message!"); 1393 return eventId; 1394 } 1395 const syntheticException = hint?.syntheticException ?? new Error(message); 1396 this._client.captureMessage(message, level, { 1397 originalException: message, 1398 syntheticException, 1399 ...hint, 1400 event_id: eventId 1401 }, this); 1402 return eventId; 1403 } 1404 /** 1405 * Capture a Sentry event for this scope. 1406 * 1407 * @returns {string} The id of the captured event. 1408 */ 1409 captureEvent(event, hint) { 1410 const eventId = event.event_id || hint?.event_id || uuid4(); 1411 if (!this._client) { 1412 DEBUG_BUILD$5 && debug$2.warn("No client configured on scope - will not capture event!"); 1413 return eventId; 1414 } 1415 this._client.captureEvent(event, { 1416 ...hint, 1417 event_id: eventId 1418 }, this); 1419 return eventId; 1420 } 1421 /** 1422 * This will be called on every set call. 1423 */ 1424 _notifyScopeListeners() { 1425 if (!this._notifyingListeners) { 1426 this._notifyingListeners = true; 1427 this._scopeListeners.forEach((callback) => { 1428 callback(this); 1429 }); 1430 this._notifyingListeners = false; 1431 } 1432 } 1433 }; 1434 })))(); 1435} 1436//#endregion 1437//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/defaultScopes.js 1438function getDefaultCurrentScope() { 1439 return getGlobalSingleton("defaultCurrentScope", () => new Scope()); 1440} 1441function getDefaultIsolationScope() { 1442 return getGlobalSingleton("defaultIsolationScope", () => new Scope()); 1443} 1444function init_defaultScopes() { 1445 return (init_defaultScopes = __esmMin((() => { 1446 init_carrier(); 1447 init_scope(); 1448 })))(); 1449} 1450//#endregion 1451//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/chain-and-copy-promiselike.js 1452var isActualPromise, kChainedCopy, chainAndCopyPromiseLike, copyProps; 1453function init_chain_and_copy_promiselike() { 1454 return (init_chain_and_copy_promiselike = __esmMin((() => { 1455 isActualPromise = (p) => p instanceof Promise && !p[kChainedCopy]; 1456 kChainedCopy = /* @__PURE__ */ Symbol("chained PromiseLike"); 1457 chainAndCopyPromiseLike = (original, onSuccess, onError) => { 1458 const chained = original.then((value) => { 1459 onSuccess(value); 1460 return value; 1461 }, (err) => { 1462 onError(err); 1463 throw err; 1464 }); 1465 return isActualPromise(chained) && isActualPromise(original) ? chained : copyProps(original, chained); 1466 }; 1467 copyProps = (original, chained) => { 1468 if (!chained) return original; 1469 let mutated = false; 1470 for (const key in original) { 1471 if (key in chained) continue; 1472 mutated = true; 1473 const value = original[key]; 1474 if (typeof value === "function") Object.defineProperty(chained, key, { 1475 value: (...args) => value.apply(original, args), 1476 enumerable: true, 1477 configurable: true, 1478 writable: true 1479 }); 1480 else chained[key] = value; 1481 } 1482 if (mutated) Object.assign(chained, { [kChainedCopy]: true }); 1483 return chained; 1484 }; 1485 })))(); 1486} 1487//#endregion 1488//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js 1489function getAsyncContextStack() { 1490 const sentry = getSentryCarrier(getMainCarrier()); 1491 return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()); 1492} 1493function withScope$1(callback) { 1494 return getAsyncContextStack().withScope(callback); 1495} 1496function withSetScope(scope, callback) { 1497 const stack = getAsyncContextStack(); 1498 return stack.withScope(() => { 1499 stack.getStackTop().scope = scope; 1500 return callback(scope); 1501 }); 1502} 1503function withIsolationScope$1(callback) { 1504 return getAsyncContextStack().withScope(() => { 1505 return callback(getAsyncContextStack().getIsolationScope()); 1506 }); 1507} 1508function getStackAsyncContextStrategy() { 1509 return { 1510 withIsolationScope: withIsolationScope$1, 1511 withScope: withScope$1, 1512 withSetScope, 1513 withSetIsolationScope: (_isolationScope, callback) => { 1514 return withIsolationScope$1(callback); 1515 }, 1516 getCurrentScope: () => getAsyncContextStack().getScope(), 1517 getIsolationScope: () => getAsyncContextStack().getIsolationScope() 1518 }; 1519} 1520var AsyncContextStack; 1521function init_stackStrategy() { 1522 return (init_stackStrategy = __esmMin((() => { 1523 init_defaultScopes(); 1524 init_scope(); 1525 init_chain_and_copy_promiselike(); 1526 init_is(); 1527 init_carrier(); 1528 AsyncContextStack = class { 1529 constructor(scope, isolationScope) { 1530 let assignedScope; 1531 if (!scope) assignedScope = new Scope(); 1532 else assignedScope = scope; 1533 let assignedIsolationScope; 1534 if (!isolationScope) assignedIsolationScope = new Scope(); 1535 else assignedIsolationScope = isolationScope; 1536 this._stack = [{ scope: assignedScope }]; 1537 this._isolationScope = assignedIsolationScope; 1538 } 1539 /** 1540 * Fork a scope for the stack. 1541 */ 1542 withScope(callback) { 1543 const scope = this._pushScope(); 1544 let maybePromiseResult; 1545 try { 1546 maybePromiseResult = callback(scope); 1547 } catch (e) { 1548 this._popScope(); 1549 throw e; 1550 } 1551 if (isThenable(maybePromiseResult)) return chainAndCopyPromiseLike(maybePromiseResult, () => this._popScope(), () => this._popScope()); 1552 this._popScope(); 1553 return maybePromiseResult; 1554 } 1555 /** 1556 * Get the client of the stack. 1557 */ 1558 getClient() {
1559 return this.getStackTop().client; 1560 } 1561 /** 1562 * Returns the scope of the top stack. 1563 */ 1564 getScope() { 1565 return this.getStackTop().scope; 1566 } 1567 /** 1568 * Get the isolation scope for the stack. 1569 */ 1570 getIsolationScope() { 1571 return this._isolationScope; 1572 } 1573 /** 1574 * Returns the topmost scope layer in the order domain > local > process. 1575 */ 1576 getStackTop() { 1577 return this._stack[this._stack.length - 1]; 1578 } 1579 /** 1580 * Push a scope to the stack. 1581 */ 1582 _pushScope() { 1583 const scope = this.getScope().clone(); 1584 this._stack.push({ 1585 client: this.getClient(), 1586 scope 1587 }); 1588 return scope; 1589 } 1590 /** 1591 * Pop a scope from the stack. 1592 */ 1593 _popScope() { 1594 if (this._stack.length <= 1) return false; 1595 return !!this._stack.pop(); 1596 } 1597 }; 1598 })))(); 1599} 1600//#endregion 1601//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/asyncContext/index.js 1602function getAsyncContextStrategy(carrier) { 1603 const sentry = getSentryCarrier(carrier); 1604 if (sentry.acs) return sentry.acs; 1605 return getStackAsyncContextStrategy(); 1606} 1607function init_asyncContext() { 1608 return (init_asyncContext = __esmMin((() => { 1609 init_carrier(); 1610 init_stackStrategy(); 1611 })))(); 1612} 1613//#endregion 1614//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/attributes.js 1615function isAttributeObject(maybeObj) { 1616 return typeof maybeObj === "object" && maybeObj != null && !Array.isArray(maybeObj) && Object.keys(maybeObj).includes("value"); 1617} 1618function attributeValueToTypedAttributeValue(rawValue, useFallback) { 1619 const { value, unit } = isAttributeObject(rawValue) ? rawValue : { 1620 value: rawValue, 1621 unit: void 0 1622 }; 1623 const attributeValue = getTypedAttributeValue(value); 1624 const checkedUnit = unit && typeof unit === "string" ? { unit } : {}; 1625 if (attributeValue) return { 1626 ...attributeValue, 1627 ...checkedUnit 1628 }; 1629 if (!useFallback || useFallback === "skip-undefined" && value === void 0) return; 1630 let stringValue = ""; 1631 try { 1632 stringValue = JSON.stringify(value) ?? ""; 1633 } catch {} 1634 return { 1635 value: stringValue, 1636 type: "string", 1637 ...checkedUnit 1638 }; 1639} 1640function serializeAttributes(attributes, fallback = false) { 1641 const serializedAttributes = {}; 1642 for (const [key, value] of Object.entries(attributes ?? {})) { 1643 const typedValue = attributeValueToTypedAttributeValue(value, fallback); 1644 if (typedValue) serializedAttributes[key] = typedValue; 1645 } 1646 return serializedAttributes; 1647} 1648function estimateTypedAttributesSizeInBytes(attributes) { 1649 if (!attributes) return 0; 1650 let weight = 0; 1651 for (const [key, attr] of Object.entries(attributes)) { 1652 weight += key.length * 2; 1653 weight += attr.type.length * 2; 1654 weight += (attr.unit?.length ?? 0) * 2; 1655 const val = attr.value; 1656 if (Array.isArray(val)) weight += estimatePrimitiveSizeInBytes$1(val[0]) * val.length; 1657 else if (isPrimitive(val)) weight += estimatePrimitiveSizeInBytes$1(val); 1658 else weight += 100; 1659 } 1660 return weight; 1661} 1662function estimatePrimitiveSizeInBytes$1(value) { 1663 if (typeof value === "string") return value.length * 2; 1664 else if (typeof value === "boolean") return 4; 1665 else if (typeof value === "number") return 8; 1666 return 0; 1667} 1668function getTypedAttributeValue(value) { 1669 if (Array.isArray(value)) return { 1670 value, 1671 type: "array" 1672 }; 1673 const primitiveType = typeof value === "string" ? "string" : typeof value === "boolean" ? "boolean" : typeof value === "number" && !Number.isNaN(value) ? Number.isInteger(value) ? "integer" : "double" : null; 1674 if (primitiveType) return { 1675 value, 1676 type: primitiveType 1677 }; 1678} 1679function init_attributes() { 1680 return (init_attributes = __esmMin((() => { 1681 init_is(); 1682 })))(); 1683} 1684//#endregion 1685//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/currentScopes.js 1686function getExternalPropagationContext() { 1687 return _externalPropagationContextProvider?.(); 1688} 1689function hasExternalPropagationContext() { 1690 return _externalPropagationContextProvider !== void 0; 1691} 1692function getCurrentScope() { 1693 return getAsyncContextStrategy(getMainCarrier()).getCurrentScope(); 1694} 1695function getIsolationScope() { 1696 return getAsyncContextStrategy(getMainCarrier()).getIsolationScope(); 1697} 1698function getGlobalScope() { 1699 return getGlobalSingleton("globalScope", () => new Scope()); 1700} 1701function withScope(...rest) { 1702 const acs = getAsyncContextStrategy(getMainCarrier()); 1703 if (rest.length === 2) { 1704 const [scope, callback] = rest; 1705 if (!scope) return acs.withScope(callback); 1706 return acs.withSetScope(scope, callback); 1707 } 1708 return acs.withScope(rest[0]); 1709} 1710function withIsolationScope(...rest) { 1711 const acs = getAsyncContextStrategy(getMainCarrier()); 1712 if (rest.length === 2) { 1713 const [isolationScope, callback] = rest; 1714 if (!isolationScope) return acs.withIsolationScope(callback); 1715 return acs.withSetIsolationScope(isolationScope, callback); 1716 } 1717 return acs.withIsolationScope(rest[0]); 1718} 1719function getClient() { 1720 return getCurrentScope().getClient(); 1721} 1722function getTraceContextFromScope(scope) { 1723 const externalContext = getExternalPropagationContext(); 1724 if (externalContext) return { 1725 trace_id: externalContext.traceId, 1726 span_id: externalContext.spanId 1727 }; 1728 const { traceId, parentSpanId, propagationSpanId } = scope.getPropagationContext(); 1729 const traceContext = { 1730 trace_id: traceId, 1731 span_id: propagationSpanId || generateSpanId() 1732 }; 1733 if (parentSpanId) traceContext.parent_span_id = parentSpanId; 1734 return traceContext; 1735} 1736var _externalPropagationContextProvider; 1737function init_currentScopes() { 1738 return (init_currentScopes = __esmMin((() => { 1739 init_asyncContext(); 1740 init_carrier(); 1741 init_scope(); 1742 init_propagationContext(); 1743 })))(); 1744} 1745//#endregion 1746//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/semanticAttributes.js 1747var SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT, SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS, SEMANTIC_ATTRIBUTE_USER_ID, SEMANTIC_ATTRIBUTE_USER_EMAIL, SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS, SEMANTIC_ATTRIBUTE_USER_USERNAME, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE, GEN_AI_CONVERSATION_ID_ATTRIBUTE$1; 1748function init_semanticAttributes() { 1749 return (init_semanticAttributes = __esmMin((() => { 1750 SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source"; 1751 SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate"; 1752 SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = "sentry.previous_trace_sample_rate"; 1753 SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op"; 1754 SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin"; 1755 SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = "sentry.idle_span_finish_reason"; 1756 SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit"; 1757 SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value"; 1758 SEMANTIC_ATTRIBUTE_SENTRY_RELEASE = "sentry.release"; 1759 SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT = "sentry.environment"; 1760 SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS = "sentry.sdk.integrations"; 1761 SEMANTIC_ATTRIBUTE_USER_ID = "user.id"; 1762 SEMANTIC_ATTRIBUTE_USER_EMAIL = "user.email"; 1763 SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS = "user.ip_address"; 1764 SEMANTIC_ATTRIBUTE_USER_USERNAME = "user.name"; 1765 SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name"; 1766 SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id"; 1767 SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time"; 1768 SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = "sentry.link.type"; 1769 GEN_AI_CONVERSATION_ID_ATTRIBUTE$1 = "gen_ai.conversation.id"; 1770 })))(); 1771} 1772//#endregion 1773//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spanstatus.js 1774function getSpanStatusFromHttpCode(httpStatus) { 1775 if (httpStatus < 400 && httpStatus >= 100) return { code: 1 }; 1776 if (httpStatus >= 400 && httpStatus < 500) switch (httpStatus) { 1777 case 401: return { 1778 code: 2, 1779 message: "unauthenticated" 1780 }; 1781 case 403: return { 1782 code: 2, 1783 message: "permission_denied" 1784 }; 1785 case 404: return { 1786 code: 2, 1787 message: "not_found" 1788 }; 1789 case 409: return { 1790 code: 2, 1791 message: "already_exists" 1792 }; 1793 case 413: return { 1794 code: 2, 1795 message: "failed_precondition" 1796 }; 1797 case 429: return { 1798 code: 2, 1799 message: "resource_exhausted" 1800 }; 1801 case 499: return { 1802 code: 2, 1803 message: "cancelled" 1804 }; 1805 default: return { 1806 code: 2,
1807 message: "invalid_argument" 1808 }; 1809 } 1810 if (httpStatus >= 500 && httpStatus < 600) switch (httpStatus) { 1811 case 501: return { 1812 code: 2, 1813 message: "unimplemented" 1814 }; 1815 case 503: return { 1816 code: 2, 1817 message: "unavailable" 1818 }; 1819 case 504: return { 1820 code: 2, 1821 message: "deadline_exceeded" 1822 }; 1823 default: return { 1824 code: 2, 1825 message: "internal_error" 1826 }; 1827 } 1828 return { 1829 code: 2, 1830 message: "internal_error" 1831 }; 1832} 1833function setHttpStatus(span, httpStatus) { 1834 span.setAttribute("http.response.status_code", httpStatus); 1835 const spanStatus = getSpanStatusFromHttpCode(httpStatus); 1836 if (spanStatus.message !== "unknown_error") span.setStatus(spanStatus); 1837} 1838function init_spanstatus() { 1839 return (init_spanstatus = __esmMin((() => {})))(); 1840} 1841//#endregion 1842//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/utils.js 1843function setCapturedScopesOnSpan(span, scope, isolationScope) { 1844 if (span) { 1845 addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, makeWeakRef(isolationScope)); 1846 addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope); 1847 } 1848} 1849function getCapturedScopesOnSpan(span) { 1850 const spanWithScopes = span; 1851 return { 1852 scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD], 1853 isolationScope: derefWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]) 1854 }; 1855} 1856function spanShouldInferOtelSource(span) { 1857 return span[OTEL_SOURCE_INFERENCE_SPAN_FIELD] === true; 1858} 1859function markSpanSourceAsExplicit(span) { 1860 addNonEnumerableProperty(span, OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD, true); 1861} 1862function spanIsTracerProviderSpan(span) { 1863 return span[TRACER_PROVIDER_SPAN_FIELD] === true; 1864} 1865var SCOPE_ON_START_SPAN_FIELD, ISOLATION_SCOPE_ON_START_SPAN_FIELD, OTEL_SOURCE_INFERENCE_SPAN_FIELD, OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD, TRACER_PROVIDER_SPAN_FIELD; 1866function init_utils() { 1867 return (init_utils = __esmMin((() => { 1868 init_object(); 1869 init_weakRef(); 1870 SCOPE_ON_START_SPAN_FIELD = "_sentryScope"; 1871 ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope"; 1872 OTEL_SOURCE_INFERENCE_SPAN_FIELD = /* @__PURE__ */ Symbol.for("sentry.otelSourceInference"); 1873 OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD = /* @__PURE__ */ Symbol.for("sentry.otelSourceExplicitlySet"); 1874 TRACER_PROVIDER_SPAN_FIELD = /* @__PURE__ */ Symbol.for("sentry.tracerProviderSpan"); 1875 })))(); 1876} 1877//#endregion 1878//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/baggage.js 1879function baggageHeaderToDynamicSamplingContext(baggageHeader) { 1880 const baggageObject = parseBaggageHeader(baggageHeader); 1881 if (!baggageObject) return; 1882 const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { 1883 if (key.startsWith("sentry-")) { 1884 const nonPrefixedKey = key.slice(7); 1885 acc[nonPrefixedKey] = value; 1886 } 1887 return acc; 1888 }, {}); 1889 if (Object.keys(dynamicSamplingContext).length > 0) return dynamicSamplingContext; 1890 else return; 1891} 1892function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) { 1893 if (!dynamicSamplingContext) return; 1894 return objectToBaggageHeader(Object.entries(dynamicSamplingContext).reduce((acc, [dscKey, dscValue]) => { 1895 if (dscValue) acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; 1896 return acc; 1897 }, {})); 1898} 1899function parseBaggageHeader(baggageHeader) { 1900 if (!baggageHeader || !isString(baggageHeader) && !Array.isArray(baggageHeader)) return; 1901 if (Array.isArray(baggageHeader)) return baggageHeader.reduce((acc, curr) => { 1902 const currBaggageObject = baggageHeaderToObject(curr); 1903 Object.entries(currBaggageObject).forEach(([key, value]) => { 1904 acc[key] = value; 1905 }); 1906 return acc; 1907 }, {}); 1908 return baggageHeaderToObject(baggageHeader); 1909} 1910function baggageHeaderToObject(baggageHeader) { 1911 return baggageHeader.split(",").map((baggageEntry) => { 1912 const eqIdx = baggageEntry.indexOf("="); 1913 if (eqIdx === -1) return []; 1914 return [baggageEntry.slice(0, eqIdx), baggageEntry.slice(eqIdx + 1)].map((keyOrValue) => { 1915 try { 1916 return decodeURIComponent(keyOrValue.trim()); 1917 } catch { 1918 return; 1919 } 1920 }); 1921 }).reduce((acc, [key, value]) => { 1922 if (key && value) acc[key] = value; 1923 return acc; 1924 }, {}); 1925} 1926function objectToBaggageHeader(object) { 1927 if (Object.keys(object).length === 0) return; 1928 return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { 1929 const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; 1930 const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; 1931 if (newBaggageHeader.length > 8192) { 1932 DEBUG_BUILD$5 && debug$2.warn(`Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`); 1933 return baggageHeader; 1934 } else return newBaggageHeader; 1935 }, ""); 1936} 1937var SENTRY_BAGGAGE_KEY_PREFIX; 1938function init_baggage() { 1939 return (init_baggage = __esmMin((() => { 1940 init_debug_build(); 1941 init_debug_logger(); 1942 init_is(); 1943 SENTRY_BAGGAGE_KEY_PREFIX = "sentry-"; 1944 })))(); 1945} 1946//#endregion 1947//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/dsn.js 1948function isValidProtocol(protocol) { 1949 return protocol === "http" || protocol === "https"; 1950} 1951function dsnToString(dsn, withPassword = false) { 1952 const { host, path, pass, port, projectId, protocol, publicKey } = dsn; 1953 return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`; 1954} 1955function dsnFromString(str) { 1956 const match = DSN_REGEX.exec(str); 1957 if (!match) { 1958 consoleSandbox(() => { 1959 console.error(`Invalid Sentry Dsn: ${str}`); 1960 }); 1961 return; 1962 } 1963 const [protocol, publicKey, pass = "", host = "", port = "", lastPath
1963= ""] = match.slice(1); 1964 let path = ""; 1965 let projectId = lastPath; 1966 const split = projectId.split("/"); 1967 if (split.length > 1) { 1968 path = split.slice(0, -1).join("/"); 1969 projectId = split.pop(); 1970 } 1971 if (projectId) { 1972 const projectMatch = projectId.match(/^\d+/); 1973 if (projectMatch) projectId = projectMatch[0]; 1974 } 1975 return dsnFromComponents({ 1976 host, 1977 pass, 1978 path, 1979 projectId, 1980 port, 1981 protocol, 1982 publicKey 1983 }); 1984} 1985function dsnFromComponents(components) { 1986 return { 1987 protocol: components.protocol, 1988 publicKey: components.publicKey || "", 1989 pass: components.pass || "", 1990 host: components.host, 1991 port: components.port || "", 1992 path: components.path || "", 1993 projectId: components.projectId 1994 }; 1995} 1996function validateDsn(dsn) { 1997 if (!DEBUG_BUILD$5) return true; 1998 const { port, projectId, protocol } = dsn; 1999 if ([ 2000 "protocol", 2001 "publicKey", 2002 "host", 2003 "projectId" 2004 ].find((component) => { 2005 if (!dsn[component]) { 2006 debug$2.error(`Invalid Sentry Dsn: ${component} missing`); 2007 return true; 2008 } 2009 return false; 2010 })) return false; 2011 if (!projectId.match(/^\d+$/)) { 2012 debug$2.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); 2013 return false; 2014 } 2015 if (!isValidProtocol(protocol)) { 2016 debug$2.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); 2017 return false; 2018 } 2019 if (port && isNaN(parseInt(port, 10))) { 2020 debug$2.error(`Invalid Sentry Dsn: Invalid port ${port}`); 2021 return false; 2022 } 2023 return true; 2024} 2025function extractOrgIdFromDsnHost(host) { 2026 return host.match(ORG_ID_REGEX)?.[1]; 2027} 2028function extractOrgIdFromClient(client) { 2029 const options = client.getOptions(); 2030 const { host } = client.getDsn() || {}; 2031 let org_id; 2032 if (options.orgId) org_id = String(options.orgId); 2033 else if (host) org_id = extractOrgIdFromDsnHost(host); 2034 return org_id; 2035} 2036function makeDsn(from) { 2037 const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from); 2038 if (!components || !validateDsn(components)) return; 2039 return components; 2040} 2041var ORG_ID_REGEX, DSN_REGEX; 2042function init_dsn() { 2043 return (init_dsn = __esmMin((() => { 2044 init_debug_build(); 2045 init_debug_logger(); 2046 ORG_ID_REGEX = /^o(\d+)\./; 2047 DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/; 2048 })))(); 2049} 2050//#endregion 2051//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/parseSampleRate.js 2052function parseSampleRate(sampleRate) { 2053 if (typeof sampleRate === "boolean") return Number(sampleRate); 2054 const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate; 2055 if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) return; 2056 return rate; 2057} 2058//#endregion 2059//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/tracing.js 2060function extractTraceparentData(traceparent) { 2061 if (!traceparent) return; 2062 const matches = traceparent.match(TRACEPARENT_REGEXP); 2063 if (!matches) return; 2064 let parentSampled; 2065 if (matches[3] === "1") parentSampled = true; 2066 else if (matches[3] === "0") parentSampled = false; 2067 return { 2068 traceId: matches[1], 2069 parentSampled, 2070 parentSpanId: matches[2] 2071 }; 2072} 2073function propagationContextFromHeaders(sentryTrace, baggage) { 2074 const traceparentData = extractTraceparentData(sentryTrace); 2075 const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage); 2076 if (!traceparentData?.traceId) return { 2077 traceId: generateTraceId(), 2078 sampleRand: safeMathRandom() 2079 }; 2080 const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext); 2081 if (dynamicSamplingContext) dynamicSamplingContext.sample_rand = sampleRand.toString(); 2082 const { traceId, parentSpanId, parentSampled } = traceparentData; 2083 return { 2084 traceId, 2085 parentSpanId, 2086 sampled: parentSampled, 2087 dsc: dynamicSamplingContext || {}, 2088 sampleRand 2089 }; 2090} 2091function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) { 2092 let sampledString = ""; 2093 if (sampled !== void 0) sampledString = sampled ? "-1" : "-0"; 2094 return `${traceId}-${spanId}${sampledString}`; 2095} 2096function generateTraceparentHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) { 2097 return `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`; 2098} 2099function getSampleRandFromTraceparentAndDsc(traceparentData, dsc) { 2100 const parsedSampleRand = parseSampleRate(dsc?.sample_rand); 2101 if (parsedSampleRand !== void 0) return parsedSampleRand; 2102 const parsedSampleRate = parseSampleRate(dsc?.sample_rate); 2103 if (parsedSampleRate && traceparentData?.parentSampled !== void 0) return traceparentData.parentSampled ? safeMathRandom() * parsedSampleRate : parsedSampleRate + safeMathRandom() * (1 - parsedSampleRate); 2104 else return safeMathRandom(); 2105} 2106function shouldContinueTrace(client, baggageOrgId) { 2107 const clientOrgId = extractOrgIdFromClient(client); 2108 if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) { 2109 debug$2.log(`Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`); 2110 return false;
2111 } 2112 if (client.getOptions().strictTraceContinuation || false) { 2113 if (baggageOrgId && !clientOrgId || !baggageOrgId && clientOrgId) { 2114 debug$2.log(`Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`); 2115 return false; 2116 } 2117 } 2118 return true; 2119} 2120var TRACEPARENT_REGEXP; 2121function init_tracing() { 2122 return (init_tracing = __esmMin((() => { 2123 init_debug_logger(); 2124 init_baggage(); 2125 init_dsn(); 2126 init_propagationContext(); 2127 init_randomSafeContext(); 2128 TRACEPARENT_REGEXP = /* @__PURE__ */ new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"); 2129 })))(); 2130} 2131//#endregion 2132//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/spanUtils.js 2133function spanToTransactionTraceContext(span) { 2134 const { spanId: span_id, traceId: trace_id } = span.spanContext(); 2135 const { data, op, parent_span_id, status, origin, links } = spanToJSON(span); 2136 return { 2137 parent_span_id, 2138 span_id, 2139 trace_id, 2140 data, 2141 op, 2142 status, 2143 origin, 2144 links 2145 }; 2146} 2147function spanToTraceContext(span) { 2148 const { spanId, traceId: trace_id, isRemote } = span.spanContext(); 2149 const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id; 2150 const scope = getCapturedScopesOnSpan(span).scope; 2151 return { 2152 parent_span_id, 2153 span_id: isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId, 2154 trace_id 2155 }; 2156} 2157function spanToTraceHeader(span) { 2158 const { traceId, spanId } = span.spanContext(); 2159 return generateSentryTraceHeader(traceId, spanId, spanIsSampled(span)); 2160} 2161function spanToTraceparentHeader(span) { 2162 const { traceId, spanId } = span.spanContext(); 2163 return generateTraceparentHeader(traceId, spanId, spanIsSampled(span)); 2164} 2165function convertSpanLinksForEnvelope(links) { 2166 if (links && links.length > 0) return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({ 2167 span_id: spanId, 2168 trace_id: traceId, 2169 sampled: traceFlags === 1, 2170 attributes, 2171 ...restContext 2172 })); 2173 else return; 2174} 2175function getStreamedSpanLinks(links) { 2176 if (links?.length) return links.map(({ context: { spanId, traceId, traceFlags }, attributes }) => ({ 2177 span_id: spanId, 2178 trace_id: traceId, 2179 sampled: traceFlags === 1, 2180 attributes 2181 })); 2182 else return; 2183} 2184function spanTimeInputToSeconds(input) { 2185 if (typeof input === "number") return ensureTimestampInSeconds(input); 2186 if (Array.isArray(input)) return input[0] + input[1] / 1e9; 2187 if (input instanceof Date) return ensureTimestampInSeconds(input.getTime()); 2188 return timestampInSeconds(); 2189} 2190function ensureTimestampInSeconds(timestamp) { 2191 return timestamp > 9999999999 ? timestamp / 1e3 : timestamp; 2192} 2193function spanToJSON(span) { 2194 if (spanIsSentrySpan(span)) return span.getSpanJSON(); 2195 const { spanId: span_id, traceId: trace_id } = span.spanContext(); 2196 if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { 2197 const { attributes, startTime, name, endTime, status, links } = span; 2198 return { 2199 span_id, 2200 trace_id, 2201 data: attributes, 2202 description: name, 2203 parent_span_id: getOtelParentSpanId(span), 2204 start_timestamp: spanTimeInputToSeconds(startTime), 2205 timestamp: spanTimeInputToSeconds(endTime) || void 0, 2206 status: getStatusMessage(status), 2207 op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP], 2208 origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], 2209 links: convertSpanLinksForEnvelope(links) 2210 }; 2211 } 2212 return { 2213 span_id, 2214 trace_id, 2215 start_timestamp: 0, 2216 data: {} 2217 }; 2218} 2219function spanToStreamedSpanJSON(span) { 2220 if (spanIsSentrySpan(span)) return span.getStreamedSpanJSON(); 2221 const { spanId: span_id, traceId: trace_id } = span.spanContext(); 2222 if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { 2223 const { attributes, startTime, name, endTime, status, links } = span; 2224 return { 2225 name, 2226 span_id, 2227 trace_id, 2228 parent_span_id: getOtelParentSpanId(span), 2229 start_timestamp: spanTimeInputToSeconds(startTime), 2230 end_timestamp: spanTimeInputToSeconds(endTime), 2231 is_segment: span === INTERNAL_getSegmentSpan(span), 2232 status: getSimpleStatus(status), 2233 attributes: addStatusMessageAttribute(attributes, status), 2234 links: getStreamedSpanLinks(links) 2235 }; 2236 } 2237 return { 2238 span_id, 2239 trace_id, 2240 start_timestamp: 0, 2241 name: "", 2242 end_timestamp: 0, 2243 status: "ok", 2244 is_segment: span === INTERNAL_getSegmentSpan(span) 2245 }; 2246} 2247function getOtelParentSpanId(span) { 2248 return "parentSpanId" in span ? span.parentSpanId : "parentSpanContext" in span ? span.parentSpanContext?.spanId : void 0; 2249} 2250function streamedSpanJsonToSerializedSpan(spanJson) { 2251 return {
2252 ...spanJson, 2253 attributes: serializeAttributes(spanJson.attributes), 2254 links: spanJson.links?.map((link) => ({ 2255 ...link, 2256 attributes: serializeAttributes(link.attributes) 2257 })) 2258 }; 2259} 2260function spanIsOpenTelemetrySdkTraceBaseSpan(span) { 2261 const castSpan = span; 2262 return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; 2263} 2264function spanIsSentrySpan(span) { 2265 return typeof span.getSpanJSON === "function"; 2266} 2267function spanIsSampled(span) { 2268 const { traceFlags } = span.spanContext(); 2269 return traceFlags === 1; 2270} 2271function getStatusMessage(status) { 2272 if (!status || status.code === 0) return; 2273 if (status.code === 1) return "ok"; 2274 return status.message || "internal_error"; 2275} 2276function getSimpleStatus(status) { 2277 return !status || status.code === 1 || status.code === 0 || status.message === "cancelled" ? "ok" : "error"; 2278} 2279function addStatusMessageAttribute(attributes, status) { 2280 const statusMessage = getSimpleStatus(status) === "error" ? status?.message : void 0; 2281 return { 2282 ...statusMessage && { ["sentry.status.message"]: statusMessage }, 2283 ...attributes 2284 }; 2285} 2286function addChildSpanToSpan(span, childSpan) { 2287 const rootSpan = span[ROOT_SPAN_FIELD] || span; 2288 addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan); 2289 if (!spanIsSampled(span)) return; 2290 if (!span.isRecording() && !rootSpan.isRecording()) return; 2291 if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].add(childSpan);
2292 else addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan])); 2293} 2294function removeChildSpanFromSpan(span, childSpan) { 2295 if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].delete(childSpan); 2296} 2297function getSpanDescendants(span) { 2298 const resultSet = /* @__PURE__ */ new Set(); 2299 function addSpanChildren(span2) { 2300 if (resultSet.has(span2)) return; 2301 else if (spanIsSampled(span2)) { 2302 resultSet.add(span2); 2303 const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : []; 2304 for (const childSpan of childSpans) addSpanChildren(childSpan); 2305 } 2306 } 2307 addSpanChildren(span); 2308 return Array.from(resultSet); 2309} 2310function INTERNAL_getSegmentSpan(span) { 2311 return span[ROOT_SPAN_FIELD] || span; 2312} 2313function getActiveSpan() { 2314 const acs = getAsyncContextStrategy(getMainCarrier()); 2315 if (acs.getActiveSpan) return acs.getActiveSpan(); 2316 return _getSpanForScope(getCurrentScope()); 2317} 2318function showSpanDropWarning() { 2319 if (!hasShownSpanDropWarning) { 2320 consoleSandbox(() => { 2321 console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`."); 2322 }); 2323 hasShownSpanDropWarning = true; 2324 } 2325} 2326function updateSpanName(span, name) { 2327 span.updateName(name); 2328 span.setAttributes({ 2329 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom", 2330 [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name 2331 }); 2332} 2333var hasShownSpanDropWarning, CHILD_SPANS_FIELD, ROOT_SPAN_FIELD, getRootSpan; 2334function init_spanUtils() { 2335 return (init_spanUtils = __esmMin((() => { 2336 init_asyncContext(); 2337 init_attributes(); 2338 init_carrier(); 2339 init_currentScopes(); 2340 init_semanticAttributes(); 2341 init_spanstatus(); 2342 init_utils(); 2343 init_object(); 2344 init_propagationContext(); 2345 init_time(); 2346 init_tracing(); 2347 init_debug_logger(); 2348 init_spanOnScope(); 2349 hasShownSpanDropWarning = false; 2350 CHILD_SPANS_FIELD = "_sentryChildSpans"; 2351 ROOT_SPAN_FIELD = "_sentryRootSpan"; 2352 getRootSpan = INTERNAL_getSegmentSpan; 2353 })))(); 2354} 2355//#endregion 2356//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/errors.js 2357function registerSpanErrorInstrumentation() { 2358 if (errorsInstrumented) return; 2359 function errorCallback() { 2360 const activeSpan = getActiveSpan(); 2361 const rootSpan = activeSpan && getRootSpan(activeSpan); 2362 if (rootSpan) { 2363 const message = "internal_error"; 2364 DEBUG_BUILD$5 && debug$2.log(`[Tracing] Root span: ${message} -> Global error occurred`); 2365 rootSpan.setStatus({ 2366 code: 2, 2367 message 2368 }); 2369 } 2370 } 2371 errorsInstrumented = true; 2372 addGlobalErrorInstrumentationHandler(errorCallback); 2373 addGlobalUnhandledRejectionInstrumentationHandler(errorCallback); 2374} 2375var errorsInstrumented; 2376function init_errors() { 2377 return (init_errors = __esmMin((() => { 2378 init_debug_build(); 2379 init_globalError(); 2380 init_globalUnhandledRejection(); 2381 init_debug_logger(); 2382 init_spanUtils(); 2383 init_spanstatus(); 2384 errorsInstrumented = false; 2385 })))(); 2386} 2387//#endregion 2388//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/hasSpansEnabled.js 2389function hasSpansEnabled(maybeOptions) { 2390 if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) return false; 2391 const options = maybeOptions || getClient()?.getOptions(); 2392 return !!options && (options.tracesSampleRate != null || !!options.tracesSampler); 2393} 2394function init_hasSpansEnabled() { 2395 return (init_hasSpansEnabled = __esmMin((() => { 2396 init_currentScopes(); 2397 })))(); 2398} 2399//#endregion 2400//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/should-ignore-span.js 2401function logIgnoredSpan(droppedSpan) { 2402 debug$2.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \`ignoreSpans\`.`); 2403} 2404function shouldIgnoreSpan(span, ignoreSpans) { 2405 if (!ignoreSpans?.length) return false; 2406 for (const pattern of ignoreSpans) { 2407 if (isStringOrRegExp(pattern)) { 2408 if (span.description && isMatchingPattern(span.description, pattern)) { 2409 DEBUG_BUILD$5 && logIgnoredSpan(span); 2410 return true; 2411 } 2412 continue; 2413 } 2414 const hasAttributes = !!pattern.attributes && Object.keys(pattern.attributes).length > 0; 2415 if (!pattern.name && !pattern.op && !hasAttributes) continue; 2416 const nameMatches = pattern.name ? span.description && isMatchingPattern(span.description, pattern.name) : true; 2417 const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true; 2418 const attrsMatch = pattern.attributes ? Object.entries(pattern.attributes).every(([key, valuePattern]) => _matchesAttributeValue(span.attributes?.[key], valuePattern)) : true; 2419 if (nameMatches && opMatches && attrsMatch) { 2420 DEBUG_BUILD$5 && logIgnoredSpan(span); 2421 return true; 2422 } 2423 } 2424 return false;
2425} 2426function _matchesAttributeValue(actual, pat) { 2427 if (typeof actual === "string" && (typeof pat === "string" || pat instanceof RegExp)) return isMatchingPattern(actual, pat); 2428 if (Array.isArray(actual) && Array.isArray(pat)) return actual.length === pat.length && actual.every((v, i) => v === pat[i]); 2429 return actual === pat; 2430} 2431function reparentChildSpans(spans, dropSpan) { 2432 const droppedSpanParentId = dropSpan.parent_span_id; 2433 const droppedSpanId = dropSpan.span_id; 2434 if (!droppedSpanParentId) return; 2435 for (const span of spans) if (span.parent_span_id === droppedSpanId) span.parent_span_id = droppedSpanParentId; 2436} 2437function isStringOrRegExp(value) { 2438 return typeof value === "string" || value instanceof RegExp; 2439} 2440function init_should_ignore_span() { 2441 return (init_should_ignore_span = __esmMin((() => { 2442 init_debug_build(); 2443 init_debug_logger(); 2444 init_string(); 2445 })))(); 2446} 2447//#endregion 2448//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js 2449function spanIsNonRecordingSpan(span) { 2450 return !!span && span[NON_RECORDING_SPAN_FIELD] === true; 2451} 2452var NON_RECORDING_SPAN_FIELD, SentryNonRecordingSpan; 2453function init_sentryNonRecordingSpan() { 2454 return (init_sentryNonRecordingSpan = __esmMin((() => { 2455 init_object(); 2456 init_propagationContext(); 2457 init_spanUtils(); 2458 NON_RECORDING_SPAN_FIELD = /* @__PURE__ */ Symbol.for("sentry.nonRecordingSpan"); 2459 SentryNonRecordingSpan = class { 2460 constructor(spanContext = {}) { 2461 this._traceId = spanContext.traceId || generateTraceId(); 2462 this._spanId = spanContext.spanId || generateSpanId(); 2463 this.dropReason = spanContext.dropReason; 2464 addNonEnumerableProperty(this, NON_RECORDING_SPAN_FIELD, true); 2465 } 2466 /** @inheritdoc */ 2467 spanContext() { 2468 return { 2469 spanId: this._spanId, 2470 traceId: this._traceId, 2471 traceFlags: 0 2472 }; 2473 } 2474 /** @inheritdoc */ 2475 end(_timestamp) {} 2476 /** @inheritdoc */ 2477 setAttribute(_key, _value) { 2478 return this; 2479 } 2480 /** @inheritdoc */ 2481 setAttributes(_values) { 2482 return this; 2483 } 2484 /** @inheritdoc */ 2485 setStatus(_status) { 2486 return this; 2487 } 2488 /** @inheritdoc */ 2489 updateName(_name) { 2490 return this; 2491 } 2492 /** @inheritdoc */ 2493 isRecording() { 2494 return false; 2495 } 2496 /** @inheritdoc */ 2497 addEvent(_name, _attributesOrStartTime, _startTime) { 2498 return this; 2499 } 2500 /** @inheritDoc */ 2501 addLink(_link) { 2502 return this; 2503 } 2504 /** @inheritDoc */ 2505 addLinks(_links) { 2506 return this; 2507 } 2508 /** 2509 * This should generally not be used, 2510 * but we need it for being compliant with the OTEL Span interface. 2511 * 2512 * @hidden 2513 * @internal 2514 */ 2515 recordException(_exception, _time) {} 2516 }; 2517 })))(); 2518} 2519//#endregion 2520//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/constants.js 2521var DEFAULT_ENVIRONMENT; 2522function init_constants() { 2523 return (init_constants = __esmMin((() => { 2524 DEFAULT_ENVIRONMENT = "production"; 2525 })))(); 2526} 2527//#endregion 2528//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js 2529function freezeDscOnSpan(span, dsc) { 2530 addNonEnumerableProperty(span, FROZEN_DSC_FIELD, dsc); 2531} 2532function getDynamicSamplingContextFromClient(trace_id, client) { 2533 const options = client.getOptions(); 2534 const { publicKey: public_key } = client.getDsn() || {}; 2535 const dsc = { 2536 environment: options.environment || "production", 2537 release: options.release, 2538 public_key, 2539 trace_id, 2540 org_id: extractOrgIdFromClient(client) 2541 }; 2542 client.emit("createDsc", dsc); 2543 return dsc; 2544} 2545function getDynamicSamplingContextFromScope(client, scope) { 2546 const propagationContext = scope.getPropagationContext(); 2547 return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client); 2548} 2549function getDynamicSamplingContextFromSpan(span) { 2550 const client = getClient(); 2551 if (!client) return {}; 2552 const rootSpan = getRootSpan(span); 2553 const rootSpanJson = spanToJSON(rootSpan); 2554 const rootSpanAttributes = rootSpanJson.data; 2555 const traceState = rootSpan.spanContext().traceState; 2556 const rootSpanSampleRate = traceState?.get("sentry.sample_rate") ?? rootSpanAttributes["sentry.sample_rate"] ?? rootSpanAttributes["sentry.previous_trace_sample_rate"];
2557 function applyLocalSampleRateToDsc(dsc2) { 2558 if (typeof rootSpanSampleRate === "number" || typeof rootSpanSampleRate === "string") dsc2.sample_rate = `${rootSpanSampleRate}`; 2559 return dsc2; 2560 } 2561 const frozenDsc = rootSpan[FROZEN_DSC_FIELD]; 2562 if (frozenDsc) return applyLocalSampleRateToDsc(frozenDsc); 2563 const isNonRecordingRoot = spanIsNonRecordingSpan(rootSpan); 2564 const isIgnoredRoot = isNonRecordingRoot && rootSpan.dropReason === "ignored"; 2565 if (isNonRecordingRoot && (!hasSpansEnabled(client.getOptions()) || isIgnoredRoot)) { 2566 const capturedScope = getCapturedScopesOnSpan(rootSpan).scope; 2567 if (capturedScope) { 2568 const dsc2 = { ...getDynamicSamplingContextFromScope(client, capturedScope) }; 2569 if (isIgnoredRoot) dsc2.sampled = "false"; 2570 return applyLocalSampleRateToDsc(dsc2); 2571 } 2572 } 2573 const traceStateDsc = traceState?.get("sentry.dsc"); 2574 const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc); 2575 if (dscOnTraceState) return applyLocalSampleRateToDsc(dscOnTraceState); 2576 const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client); 2577 const source = rootSpanAttributes["sentry.source"] ?? rootSpanAttributes["sentry.segment.name.source"]; 2578 const name = rootSpanJson.description; 2579 if (source !== "url" && name) dsc.transaction = name; 2580 if (hasSpansEnabled()) { 2581 dsc.sampled = String(spanIsSampled(rootSpan)); 2582 dsc.sample_rand = traceState?.get("sentry.sample_rand") ?? getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString(); 2583 } 2584 applyLocalSampleRateToDsc(dsc); 2585 client.emit("createDsc", dsc, rootSpan); 2586 return dsc; 2587} 2588function spanToBaggageHeader(span) { 2589 return dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(span)); 2590} 2591var FROZEN_DSC_FIELD; 2592function init_dynamicSamplingContext() { 2593 return (init_dynamicSamplingContext = __esmMin((() => { 2594 init_constants(); 2595 init_currentScopes(); 2596 init_semanticAttributes(); 2597 init_baggage(); 2598 init_dsn(); 2599 init_hasSpansEnabled(); 2600 init_object(); 2601 init_spanUtils(); 2602 init_sentryNonRecordingSpan(); 2603 init_utils(); 2604 FROZEN_DSC_FIELD = "_frozenDsc"; 2605 })))(); 2606} 2607//#endregion 2608//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/beforeSendSpan.js 2609function withStreamedSpan(callback) { 2610 addNonEnumerableProperty(callback, "_streamed", true); 2611 return callback; 2612} 2613function isStreamedBeforeSendSpanCallback(callback) { 2614 return !!callback && typeof callback === "function" && "_streamed" in callback && !!callback._streamed; 2615} 2616function init_beforeSendSpan() { 2617 return (init_beforeSendSpan = __esmMin((() => { 2618 init_object(); 2619 })))(); 2620} 2621//#endregion 2622//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/envelope.js 2623function createEnvelope(headers, items = []) { 2624 return [headers, items]; 2625} 2626function addItemToEnvelope(envelope, newItem) { 2627 const [headers, items] = envelope; 2628 return [headers, [...items, newItem]]; 2629} 2630function forEachEnvelopeItem(envelope, callback) { 2631 const envelopeItems = envelope[1]; 2632 for (const envelopeItem of envelopeItems) { 2633 const envelopeItemType = envelopeItem[0].type; 2634 if (callback(envelopeItem, envelopeItemType)) return true; 2635 } 2636 return false; 2637} 2638function envelopeContainsItemType(envelope, types) { 2639 return forEachEnvelopeItem(envelope, (_, type) => types.includes(type)); 2640} 2641function encodeUTF8(input) { 2642 const carrier = getSentryCarrier(GLOBAL_OBJ); 2643 return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input); 2644} 2645function decodeUTF8(input) { 2646 const carrier = getSentryCarrier(GLOBAL_OBJ); 2647 return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input); 2648} 2649function serializeEnvelope(envelope) { 2650 const [envHeaders, items] = envelope; 2651 let parts = JSON.stringify(envHeaders); 2652 function append(next) { 2653 if (typeof parts === "string") parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next]; 2654 else parts.push(typeof next === "string" ? encodeUTF8(next) : next); 2655 } 2656 for (const item of items) { 2657 const [itemHeaders, payload] = item; 2658 append(` 2659${JSON.stringify(itemHeaders)} 2660`); 2661 if (typeof payload === "string" || payload instanceof Uint8Array) append(payload); 2662 else { 2663 let stringifiedPayload; 2664 try {
2665 stringifiedPayload = JSON.stringify(payload); 2666 } catch { 2667 stringifiedPayload = JSON.stringify(normalize(payload)); 2668 } 2669 append(stringifiedPayload); 2670 } 2671 } 2672 return typeof parts === "string" ? parts : concatBuffers(parts); 2673} 2674function concatBuffers(buffers) { 2675 const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); 2676 const merged = new Uint8Array(totalLength); 2677 let offset = 0; 2678 for (const buffer of buffers) { 2679 merged.set(buffer, offset); 2680 offset += buffer.length; 2681 } 2682 return merged; 2683} 2684function parseEnvelope(env) { 2685 let buffer = typeof env === "string" ? encodeUTF8(env) : env; 2686 function readBinary(length) { 2687 const bin = buffer.subarray(0, length); 2688 buffer = buffer.subarray(length + 1); 2689 return bin; 2690 } 2691 function readJson() { 2692 let i = buffer.indexOf(10); 2693 if (i < 0) i = buffer.length; 2694 return JSON.parse(decodeUTF8(readBinary(i))); 2695 } 2696 const envelopeHeader = readJson(); 2697 const items = []; 2698 while (buffer.length) { 2699 const itemHeader = readJson(); 2700 const binaryLength = typeof itemHeader.length === "number" ? itemHeader.length : void 0; 2701 items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]); 2702 } 2703 return [envelopeHeader, items]; 2704} 2705function createSpanEnvelopeItem(spanJson) { 2706 return [{ type: "span" }, spanJson]; 2707} 2708function createAttachmentEnvelopeItem(attachment) { 2709 const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data; 2710 return [{ 2711 type: "attachment", 2712 length: buffer.length, 2713 filename: attachment.filename, 2714 content_type: attachment.contentType, 2715 attachment_type: attachment.attachmentType 2716 }, buffer]; 2717} 2718function _isOverriddenType(type) { 2719 return type in DATA_CATEGORY_OVERRIDES; 2720} 2721function envelopeItemTypeToDataCategory(type) { 2722 return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type; 2723} 2724function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { 2725 if (!metadataOrEvent?.sdk) return; 2726 const { name, version } = metadataOrEvent.sdk; 2727 return { 2728 name, 2729 version 2730 }; 2731} 2732function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) { 2733 const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext; 2734 return { 2735 event_id: event.event_id, 2736 sent_at: new Date(safeDateNow()).toISOString(), 2737 ...sdkInfo && { sdk: sdkInfo }, 2738 ...!!tunnel && dsn && { dsn: dsnToString(dsn) }, 2739 ...dynamicSamplingContext && { trace: dynamicSamplingContext } 2740 }; 2741} 2742var DATA_CATEGORY_OVERRIDES; 2743function init_envelope() { 2744 return (init_envelope = __esmMin((() => { 2745 init_carrier(); 2746 init_dsn(); 2747 init_normalize(); 2748 init_randomSafeContext(); 2749 init_worldwide(); 2750 DATA_CATEGORY_OVERRIDES = { 2751 sessions: "session", 2752 event: "error", 2753 client_report: "internal", 2754 user_report: "default", 2755 profile_chunk: "profile", 2756 replay_event: "replay", 2757 replay_recording: "replay", 2758 check_in: "monitor", 2759 raw_security: "security", 2760 log: "log_item", 2761 trace_metric: "metric" 2762 }; 2763 })))(); 2764} 2765//#endregion 2766//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/envelope.js 2767function _enhanceEventWithSdkInfo(event, newSdkInfo) { 2768 if (!newSdkInfo) return event; 2769 const eventSdkInfo = event.sdk || {}; 2770 event.sdk = { 2771 ...eventSdkInfo, 2772 name: eventSdkInfo.name || newSdkInfo.name, 2773 version: eventSdkInfo.version || newSdkInfo.version, 2774 integrations: [...event.sdk?.integrations || [], ...newSdkInfo.integrations || []], 2775 packages: [...event.sdk?.packages || [], ...newSdkInfo.packages || []], 2776 settings: event.sdk?.settings || newSdkInfo.settings ? { 2777 ...event.sdk?.settings, 2778 ...newSdkInfo.settings 2779 } : void 0 2780 }; 2781 return event; 2782} 2783function createSessionEnvelope(session, dsn, metadata, tunnel) { 2784 const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); 2785 return createEnvelope({ 2786 sent_at: new Date(safeDateNow()).toISOString(), 2787 ...sdkInfo && { sdk: sdkInfo }, 2788 ...!!tunnel && dsn && { dsn: dsnToString(dsn) } 2789 }, ["aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()]]); 2790} 2791function createEventEnvelope(event, dsn, metadata, tunnel) { 2792 const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); 2793 const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
2794 _enhanceEventWithSdkInfo(event, metadata?.sdk); 2795 const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); 2796 delete event.sdkProcessingMetadata; 2797 return createEnvelope(envelopeHeaders, [[{ type: eventType }, event]]); 2798} 2799function createSpanEnvelope(spans, client) { 2800 function dscHasRequiredProps(dsc2) { 2801 return !!dsc2.trace_id && !!dsc2.public_key; 2802 } 2803 const dsc = getDynamicSamplingContextFromSpan(spans[0]); 2804 const dsn = client?.getDsn(); 2805 const tunnel = client?.getOptions().tunnel; 2806 const headers = { 2807 sent_at: new Date(safeDateNow()).toISOString(), 2808 ...dscHasRequiredProps(dsc) && { trace: dsc }, 2809 ...!!tunnel && dsn && { dsn: dsnToString(dsn) } 2810 }; 2811 const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {}; 2812 const filteredSpans = ignoreSpans?.length ? spans.filter((span) => { 2813 const json = spanToJSON(span); 2814 return !shouldIgnoreSpan({ 2815 description: json.description, 2816 op: json.op, 2817 attributes: json.data 2818 }, ignoreSpans); 2819 }) : spans; 2820 const droppedSpans = spans.length - filteredSpans.length; 2821 if (droppedSpans) client?.recordDroppedEvent("before_send", "span", droppedSpans); 2822 const convertToSpanJSON = beforeSendSpan ? (span) => { 2823 const spanJson = spanToJSON(span); 2824 const processedSpan = !isStreamedBeforeSendSpanCallback(beforeSendSpan) ? beforeSendSpan(spanJson) : spanJson; 2825 if (!processedSpan) { 2826 showSpanDropWarning();
2827 return spanJson; 2828 } 2829 return processedSpan; 2830 } : spanToJSON; 2831 const items = []; 2832 for (const span of filteredSpans) { 2833 const spanJson = convertToSpanJSON(span); 2834 if (spanJson) items.push(createSpanEnvelopeItem(spanJson)); 2835 } 2836 return createEnvelope(headers, items); 2837} 2838function init_envelope$1() { 2839 return (init_envelope$1 = __esmMin((() => { 2840 init_dynamicSamplingContext(); 2841 init_beforeSendSpan(); 2842 init_dsn(); 2843 init_envelope(); 2844 init_randomSafeContext(); 2845 init_should_ignore_span(); 2846 init_spanUtils(); 2847 })))(); 2848} 2849//#endregion 2850//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/logSpans.js 2851function logSpanStart(span) { 2852 if (!DEBUG_BUILD$5) return; 2853 const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToJSON(span); 2854 const { spanId } = span.spanContext(); 2855 const sampled = spanIsSampled(span); 2856 const rootSpan = getRootSpan(span); 2857 const isRootSpan = rootSpan === span; 2858 const header = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`; 2859 const infoParts = [ 2860 `op: ${op}`, 2861 `name: ${description}`, 2862 `ID: ${spanId}` 2863 ]; 2864 if (parentSpanId) infoParts.push(`parent ID: ${parentSpanId}`); 2865 if (!isRootSpan) { 2866 const { op: op2, description: description2 } = spanToJSON(rootSpan); 2867 infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`); 2868 if (op2) infoParts.push(`root op: ${op2}`); 2869 if (description2) infoParts.push(`root description: ${description2}`); 2870 } 2871 debug$2.log(`${header} 2872 ${infoParts.join("\n ")}`); 2873} 2874function logSpanEnd(span) { 2875 if (!DEBUG_BUILD$5) return; 2876 const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span); 2877 const { spanId } = span.spanContext(); 2878 const msg = `[Tracing] Finishing "${op}" ${getRootSpan(span) === span ? "root " : ""}span "${description}" with ID ${spanId}`; 2879 debug$2.log(msg); 2880} 2881function init_logSpans() { 2882 return (init_logSpans = __esmMin((() => { 2883 init_debug_build(); 2884 init_debug_logger(); 2885 init_spanUtils(); 2886 })))(); 2887} 2888//#endregion 2889//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/measurement.js 2890function setMeasurement(name, value, unit, activeSpan = getActiveSpan()) { 2891 const rootSpan = activeSpan && getRootSpan(activeSpan); 2892 if (rootSpan) { 2893 DEBUG_BUILD$5 && debug$2.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`); 2894 rootSpan.addEvent(name, { 2895 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value, 2896 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit 2897 }); 2898 } 2899} 2900function timedEventsToMeasurements(events) { 2901 if (!events || events.length === 0) return; 2902 const measurements = {}; 2903 events.forEach((event) => { 2904 const attributes = event.attributes || {}; 2905 const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]; 2906 const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]; 2907 if (typeof unit === "string" && typeof value === "number") measurements[event.name] = { 2908 value, 2909 unit 2910 }; 2911 }); 2912 return measurements; 2913} 2914function init_measurement() { 2915 return (init_measurement = __esmMin((() => { 2916 init_debug_build(); 2917 init_semanticAttributes(); 2918 init_debug_logger(); 2919 init_spanUtils(); 2920 })))(); 2921} 2922//#endregion 2923//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/segmentSpanCaptureStrategy.js 2924function getSegmentSpanCaptureStrategy() { 2925 return getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy; 2926} 2927function init_segmentSpanCaptureStrategy() { 2928 return (init_segmentSpanCaptureStrategy = __esmMin((() => { 2929 init_carrier(); 2930 })))(); 2931} 2932//#endregion 2933//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/hasSpanStreamingEnabled.js 2934function hasSpanStreamingEnabled(client) { 2935 return client.getOptions().traceLifecycle === "stream"; 2936} 2937//#endregion 2938//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js 2939function isSpanTimeInput(value) { 2940 return value && typeof value === "number" || value instanceof Date || Array.isArray(value); 2941} 2942function isFullFinishedSpan(input) { 2943 return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id; 2944} 2945function isStandaloneSpan(span) { 2946 return span instanceof SentrySpan && span.isStandaloneSpan(); 2947} 2948function sendSpanEnvelope(envelope) { 2949 const client = getClient(); 2950 if (!client) return; 2951 const spanItems = envelope[1]; 2952 if (!spanItems || spanItems.length === 0) {
2953 client.recordDroppedEvent("before_send", "span"); 2954 return; 2955 } 2956 client.sendEnvelope(envelope); 2957} 2958var MAX_SPAN_COUNT, SentrySpan; 2959function init_sentrySpan() { 2960 return (init_sentrySpan = __esmMin((() => { 2961 init_currentScopes(); 2962 init_debug_build(); 2963 init_envelope$1(); 2964 init_semanticAttributes(); 2965 init_debug_logger(); 2966 init_propagationContext(); 2967 init_spanUtils(); 2968 init_time(); 2969 init_dynamicSamplingContext(); 2970 init_logSpans(); 2971 init_measurement(); 2972 init_segmentSpanCaptureStrategy(); 2973 init_utils(); 2974 MAX_SPAN_COUNT = 1e3; 2975 SentrySpan = class { 2976 /** 2977 * You should never call the constructor manually, always use `Sentry.startSpan()` 2978 * or other span methods. 2979 * @internal 2980 * @hideconstructor 2981 * @hidden 2982 */ 2983 constructor(spanContext = {}) { 2984 this._traceId = spanContext.traceId || generateTraceId(); 2985 this._spanId = spanContext.spanId || generateSpanId(); 2986 this._startTime = spanContext.startTimestamp || timestampInSeconds(); 2987 this._links = spanContext.links; 2988 this._attributes = {}; 2989 this.setAttributes({ 2990 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual", 2991 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op, 2992 ...spanContext.attributes 2993 }); 2994 this._name = spanContext.name; 2995 if (spanContext.parentSpanId) this._parentSpanId = spanContext.parentSpanId; 2996 if ("sampled" in spanContext) this._sampled = spanContext.sampled; 2997 if (spanContext.endTimestamp) this._endTime = spanContext.endTimestamp; 2998 this._events = []; 2999 this._isStandaloneSpan = spanContext.isStandalone; 3000 if (this._endTime) this._onSpanEnded(); 3001 } 3002 /** @inheritDoc */ 3003 addLink(link) { 3004 if (this._frozen) return this; 3005 if (this._links) this._links.push(link); 3006 else this._links = [link]; 3007 return this; 3008 } 3009 /** @inheritDoc */ 3010 addLinks(links) { 3011 if (this._frozen) return this; 3012 if (this._links) this._links.push(...links); 3013 else this._links = links; 3014 return this; 3015 } 3016 /** 3017 * This should generally not be used, 3018 * but it is needed for being compliant with the OTEL Span interface. 3019 * 3020 * @hidden 3021 * @internal 3022 */ 3023 recordException(_exception, _time) {} 3024 /** @inheritdoc */ 3025 spanContext() { 3026 const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this; 3027 return { 3028 spanId, 3029 traceId, 3030 traceFlags: sampled ? 1 : 0 3031 }; 3032 } 3033 /** @inheritdoc */ 3034 setAttribute(key, value) { 3035 if (this._frozen) return this; 3036 if (value === void 0) delete this._attributes[key]; 3037 else this._attributes[key] = value; 3038 if (key === "sentry.source" && value !== void 0 && spanShouldInferOtelSource(this)) markSpanSourceAsExplicit(this); 3039 return this; 3040 } 3041 /** @inheritdoc */ 3042 setAttributes(attributes) { 3043 Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key])); 3044 return this; 3045 } 3046 /** 3047 * This should generally not be used, 3048 * but we need it for browser tracing where we want to adjust the start time afterwards. 3049 * USE THIS WITH CAUTION! 3050 * 3051 * @hidden 3052 * @internal 3053 */ 3054 updateStartTime(timeInput) { 3055 if (this._frozen) return; 3056 this._startTime = spanTimeInputToSeconds(timeInput); 3057 } 3058 /** 3059 * @inheritDoc 3060 */ 3061 setStatus(value) { 3062 if (this._frozen) return this; 3063 this._status = value; 3064 return this; 3065 } 3066 /** 3067 * @inheritDoc 3068 */ 3069 updateName(name) { 3070 if (this._frozen) return this; 3071 this._name = name; 3072 if (!spanShouldInferOtelSource(this)) this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "custom"); 3073 return this; 3074 } 3075 /** @inheritdoc */ 3076 end(endTimestamp) { 3077 if (this._endTime) { 3078 this._frozen = spanIsTracerProviderSpan(this); 3079 return; 3080 } 3081 this._endTime = spanTimeInputToSeconds(endTimestamp); 3082 logSpanEnd(this); 3083 this._onSpanEnded(); 3084 this._frozen = spanIsTracerProviderSpan(this); 3085 } 3086 /** 3087 * Get JSON representation of this span. 3088 * 3089 * @hidden 3090 * @internal This method is purely for internal purposes and should not be used outside 3091 * of SDK code. If you need to get a JSON representation of a span, 3092 * use `spanToJSON(span)` instead. 3093 */ 3094 getSpanJSON() { 3095 return { 3096 data: this._attributes, 3097 description: this._name, 3098 op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP], 3099 parent_span_id: this._parentSpanId, 3100 span_id: this._spanId, 3101 start_timestamp: this._startTime, 3102 status: getStatusMessage(this._status), 3103 timestamp: this._endTime, 3104 trace_id: this._traceId, 3105 origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], 3106 profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID], 3107 exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME], 3108 measurements: timedEventsToMeasurements(this._events), 3109 is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0, 3110 segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0, 3111 links: convertSpanLinksForEnvelope(this._links) 3112 }; 3113 } 3114 /** 3115 * Get {@link StreamedSpanJSON} representation of this span. 3116 * 3117 * @hidden 3118 * @internal This method is purely for internal purposes and should not be used outside 3119 * of SDK code. If you need to get a JSON representation of a span, 3120 * use `spanToStreamedSpanJSON(span)` instead. 3121 */ 3122 getStreamedSpanJSON() { 3123 return { 3124 name: this._name ?? "", 3125 span_id: this._spanId, 3126 trace_id: this._traceId, 3127 parent_span_id: this._parentSpanId, 3128 start_timestamp: this._startTime, 3129 end_timestamp: this._endTime ?? this._startTime, 3130 is_segment: this._isStandaloneSpan || this === getRootSpan(this), 3131 status: getSimpleStatus(this._status), 3132 attributes: addStatusMessageAttribute(this._attributes, this._status), 3133 links: getStreamedSpanLinks(this._links) 3134 }; 3135 } 3136 /** @inheritdoc */ 3137 isRecording() { 3138 return !this._endTime && !!this._sampled; 3139 } 3140 /** 3141 * @inheritdoc 3142 */ 3143 addEvent(name, attributesOrStartTime, startTime) { 3144 if (this._frozen) return this; 3145 DEBUG_BUILD$5 && debug$2.log("[Tracing] Adding an event to span:", name); 3146 const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds(); 3147 const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {}; 3148 const event = { 3149 name, 3150 time: spanTimeInputToSeconds(time), 3151 attributes 3152 }; 3153 this._events.push(event); 3154 return this; 3155 } 3156 /** 3157 * This method should generally not be used, 3158 * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set. 3159 * USE THIS WITH CAUTION! 3160 * @internal 3161 * @hidden 3162 * @experimental 3163 */ 3164 isStandaloneSpan() { 3165 return !!this._isStandaloneSpan; 3166 } 3167 /** Emit `spanEnd` when the span is ended. */ 3168 _onSpanEnded() { 3169 const client = getClient(); 3170 if (client) { 3171 client.emit("spanEnd", this); 3172 if (!this._isStandaloneSpan) client.emit("afterSpanEnd", this); 3173 } 3174 const rootSpan = getRootSpan(this); 3175 const isSegmentSpan = this._isStandaloneSpan || this === rootSpan; 3176 if (this._isStandaloneSpan) { 3177 if (this._sampled) sendSpanEnvelope(createSpanEnvelope([this], client)); 3178 else { 3179 DEBUG_BUILD$5 && debug$2.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled.");
3180 if (client) client.recordDroppedEvent("sample_rate", "span"); 3181 } 3182 return; 3183 } 3184 if (!isSegmentSpan) { 3185 const strategy2 = getSegmentSpanCaptureStrategy(); 3186 if (strategy2) { 3187 const scope2 = getCapturedScopesOnSpan(this).scope || getCurrentScope(); 3188 strategy2.onChildSpanEnded(this, rootSpan, (options) => this._convertSpanToTransaction(options), scope2); 3189 } 3190 return; 3191 } 3192 if (client && hasSpanStreamingEnabled(client)) { 3193 client.emit("afterSegmentSpanEnd", this); 3194 return; 3195 } 3196 const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope(); 3197 const strategy = getSegmentSpanCaptureStrategy(); 3198 if (strategy) strategy.onSegmentSpanEnded((options) => this._convertSpanToTransaction(options), scope); 3199 else { 3200 const transactionEvent = this._convertSpanToTransaction(); 3201 if (transactionEvent) scope.captureEvent(transactionEvent); 3202 } 3203 } 3204 /** 3205 * Finish the transaction & prepare the event to send to Sentry. 3206 */ 3207 _convertSpanToTransaction(options = {}) { 3208 if (!isFullFinishedSpan(spanToJSON(this))) return; 3209 if (!this._name) { 3210 DEBUG_BUILD$5 && debug$2.warn("Transaction has no name, falling back to `<unlabeled transaction>`."); 3211 this._name = "<unlabeled transaction>"; 3212 } 3213 const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this); 3214 const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest; 3215 if (this._sampled !== true) return; 3216 options.onSpanCaptured?.(this); 3217 const spans = []; 3218 for (const descendant of getSpanDescendants(this)) { 3219 if (descendant === this || isStandaloneSpan(descendant) || options.isSpanAlreadyCaptured?.(descendant)) continue; 3220 const spanJSON = spanToJSON(descendant); 3221 if (!isFullFinishedSpan(spanJSON)) continue; 3222 options.onSpanCaptured?.(descendant); 3223 spans.push(spanJSON); 3224 } 3225 const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 3226 delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; 3227 let hasGenAiSpans = false; 3228 spans.forEach((span) => { 3229 delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; 3230 if (span.op?.startsWith("gen_ai.")) hasGenAiSpans = true; 3231 }); 3232 const transaction = { 3233 contexts: { trace: spanToTransactionTraceContext(this) }, 3234 spans: spans.length > MAX_SPAN_COUNT ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans, 3235 start_timestamp: this._startTime, 3236 timestamp: this._endTime, 3237 transaction: this._name, 3238 type: "transaction", 3239 sdkProcessingMetadata: { 3240 capturedSpanScope, 3241 capturedSpanIsolationScope, 3242 dynamicSamplingContext: getDynamicSamplingContextFromSpan(this), 3243 hasGenAiSpans 3244 }, 3245 request: normalizedRequest, 3246 ...source && { transaction_info: { source } } 3247 }; 3248 const measurements = timedEventsToMeasurements(this._events); 3249 if (measurements && Object.keys(measurements).length) { 3250 DEBUG_BUILD$5 && debug$2.log("[Measurements] Adding measurements to transaction event", JSON.stringify(measurements, void 0, 2)); 3251 transaction.measurements = measurements; 3252 } 3253 return transaction; 3254 } 3255 }; 3256 })))(); 3257} 3258//#endregion 3259//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/handleCallbackErrors.js 3260function handleCallbackErrors(fn, onError, onFinally = () => {}, onSuccess = () => {}) { 3261 let maybePromiseResult; 3262 try { 3263 maybePromiseResult = fn(); 3264 } catch (e) { 3265 onError(e); 3266 onFinally(); 3267 throw e; 3268 } 3269 return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess); 3270} 3271function maybeHandlePromiseRejection(value, onError, onFinally, onSuccess) { 3272 if (isThenable(value)) return chainAndCopyPromiseLike(value, (result) => { 3273 onFinally(); 3274 onSuccess(result); 3275 }, (err) => { 3276 onError(err); 3277 onFinally(); 3278 }); 3279 onFinally(); 3280 onSuccess(value); 3281 return value; 3282} 3283function init_handleCallbackErrors() { 3284 return (init_handleCallbackErrors = __esmMin((() => { 3285 init_chain_and_copy_promiselike(); 3286 init_is(); 3287 })))(); 3288} 3289//#endregion 3290//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/sampling.js 3291function sampleSpan(options, samplingContext, sampleRand) { 3292 if (!hasSpansEnabled(options)) return [false]; 3293 let localSampleRateWasApplied = void 0; 3294 let sampleRate; 3295 if (typeof options.tracesSampler === "function") { 3296 sampleRate = options.tracesSampler({ 3297 ...samplingContext, 3298 inheritOrSampleWith: (fallbackSampleRate) => { 3299 if (typeof samplingContext.parentSampleRate === "number") return samplingContext.parentSampleRate; 3300 if (typeof samplingContext.parentSampled === "boolean") return Number(samplingContext.parentSampled); 3301 return fallbackSampleRate; 3302 } 3303 }); 3304 localSampleRateWasApplied = true; 3305 }
3305 else if (samplingContext.parentSampled !== void 0) sampleRate = samplingContext.parentSampled; 3306 else if (typeof options.tracesSampleRate !== "undefined") { 3307 sampleRate = options.tracesSampleRate; 3308 localSampleRateWasApplied = true; 3309 } 3310 const parsedSampleRate = parseSampleRate(sampleRate); 3311 if (parsedSampleRate === void 0) { 3312 DEBUG_BUILD$5 && debug$2.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)}.`); 3313 return [false]; 3314 } 3315 if (!parsedSampleRate) { 3316 DEBUG_BUILD$5 && debug$2.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"}`); 3317 return [ 3318 false, 3319 parsedSampleRate, 3320 localSampleRateWasApplied 3321 ]; 3322 } 3323 const shouldSample = sampleRand < parsedSampleRate; 3324 if (!shouldSample) DEBUG_BUILD$5 && debug$2.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(sampleRate)})`); 3325 return [ 3326 shouldSample, 3327 parsedSampleRate, 3328 localSampleRateWasApplied 3329 ]; 3330} 3331function init_sampling() { 3332 return (init_sampling = __esmMin((() => { 3333 init_debug_build(); 3334 init_debug_logger(); 3335 init_hasSpansEnabled(); 3336 })))(); 3337} 3338//#endregion 3339//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/trace.js 3340function startSpan(options, callback) { 3341 const acs = getAcs(); 3342 if (acs.startSpan) return acs.startSpan(options, callback); 3343 const spanArguments = parseSentrySpanArguments(options); 3344 const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options; 3345 const customForkedScope = customScope?.clone(); 3346 return withScope(customForkedScope, () => { 3347 return getActiveSpanWrapper(customParentSpan)(() => { 3348 const scope = getCurrentScope(); 3349 const parentSpan = getParentSpan(scope, customParentSpan); 3350 const client = getClient(); 3351 const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, client) : createChildOrRootSpan({ 3352 parentSpan, 3353 spanArguments, 3354 forceTransaction, 3355 scope 3356 }); 3357 if (!spanIsIgnored(activeSpan) || !parentSpan) _setSpanForScope(scope, activeSpan); 3358 return handleCallbackErrors(() => callback(activeSpan), () => { 3359 const { status } = spanToJSON(activeSpan); 3360 if (activeSpan.isRecording() && (!status || status === "ok")) activeSpan.setStatus({ 3361 code: 2, 3362 message: "internal_error" 3363 }); 3364 }, () => { 3365 activeSpan.end(); 3366 }); 3367 }); 3368 }); 3369} 3370function startSpanManual(options, callback) { 3371 const acs = getAcs(); 3372 if (acs.startSpanManual) return acs.startSpanManual(options, callback); 3373 const spanArguments = parseSentrySpanArguments(options); 3374 const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options; 3375 const customForkedScope = customScope?.clone(); 3376 return withScope(customForkedScope, () => { 3377 return getActiveSpanWrapper(customParentSpan)(() => { 3378 const scope = getCurrentScope(); 3379 const parentSpan = getParentSpan(scope, customParentSpan); 3380 const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, getClient()) : createChildOrRootSpan({ 3381 parentSpan, 3382 spanArguments, 3383 forceTransaction, 3384 scope 3385 }); 3386 if (!spanIsIgnored(activeSpan) || !parentSpan) _setSpanForScope(scope, activeSpan); 3387 return handleCallbackErrors(() => callback(activeSpan, () => activeSpan.end()), () => { 3388 const { status } = spanToJSON(activeSpan); 3389 if (activeSpan.isRecording() && (!status || status === "ok")) activeSpan.setStatus({ 3390 code: 2, 3391 message: "internal_error" 3392 }); 3393 }); 3394 }); 3395 }); 3396} 3397function startInactiveSpan(options) { 3398 const acs = getAcs(); 3399 if (acs.startInactiveSpan) return acs.startInactiveSpan(options); 3400 return _startInactiveSpanImpl(options); 3401} 3402function _startInactiveSpanImpl(options) { 3403 const spanArguments = parseSentrySpanArguments(options); 3404 const { forceTransaction, parentSpan: customParentSpan } = options; 3405 return (options.scope ? (callback) => withScope(options.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback())(() => { 3406 const scope = getCurrentScope(); 3407 const parentSpan = getParentSpan(scope, customParentSpan); 3408 const client = getClient(); 3409 if (options.onlyIfParent && !parentSpan) return startMissingRequiredParentSpan(scope, client); 3410 return createChildOrRootSpan({ 3411 parentSpan, 3412 spanArguments, 3413 forceTransaction, 3414 scope 3415 }); 3416 }); 3417} 3418function withActiveSpan(span, callback) { 3419 const acs = getAcs(); 3420 if (acs.withActiveSpan) return acs.withActiveSpan(span, callback); 3421 return withScope((scope) => { 3422 _setSpanForScope(scope, span || void 0); 3423 return callback(scope); 3424 }); 3425} 3426function suppressTracing(callback) { 3427 const acs = getAcs(); 3428 if (acs.suppressTracing) return acs.suppressTracing(callback); 3429 return withScope((scope) => { 3430 scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true }); 3431 const res = callback(); 3432 scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: void 0 }); 3433 return res; 3434 }); 3435} 3436function isTracingSuppressed(scope = getCurrentScope()) { 3437 const acs = getAcs(); 3438 if (acs.isTracingSuppressed) return acs.isTracingSuppressed(scope); 3439 return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true; 3440} 3441function startNewTrace(callback) { 3442 const acs = getAcs(); 3443 if (acs.startNewTrace) return acs.startNewTrace(callback); 3444 return withScope((scope) => { 3445 scope.setPropagationContext({ 3446 traceId: generateTraceId(), 3447 sampleRand: safeMathRandom() 3448 });
3449 DEBUG_BUILD$5 && debug$2.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`); 3450 return withActiveSpan(null, callback); 3451 }); 3452} 3453function startMissingRequiredParentSpan(scope, client) { 3454 client?.recordDroppedEvent("no_parent_span", "span"); 3455 const span = new SentryNonRecordingSpan({ traceId: scope.getPropagationContext().traceId }); 3456 setCapturedScopesOnSpan(span, scope, getIsolationScope()); 3457 return span; 3458} 3459function createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }) { 3460 const isolationScope = getIsolationScope(); 3461 if (!hasSpansEnabled()) { 3462 const scopePropagationContext = scope.getPropagationContext(); 3463 const traceId = parentSpan ? parentSpan.spanContext().traceId : scopePropagationContext.traceId; 3464 const span2 = new SentryNonRecordingSpan({ traceId }); 3465 if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, span2); 3466 setCapturedScopesOnSpan(span2, scope, isolationScope); 3467 return span2; 3468 } 3469 const client = getClient(); 3470 if (_shouldIgnoreStreamedSpan(client, spanArguments)) { 3471 if (!isTracingSuppressed(scope)) client?.recordDroppedEvent("ignored", "span"); 3472 const ignoredSpan = new SentryNonRecordingSpan({ 3473 dropReason: "ignored", 3474 traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId 3475 }); 3476 if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, ignoredSpan); 3477 setCapturedScopesOnSpan(ignoredSpan, scope, isolationScope); 3478 return ignoredSpan; 3479 } 3480 let span; 3481 if (parentSpan && !forceTransaction) { 3482 span = _startChildSpan(parentSpan, scope, spanArguments, isolationScope); 3483 addChildSpanToSpan(parentSpan, span); 3484 } else if (parentSpan) { 3485 const dsc = getDynamicSamplingContextFromSpan(parentSpan); 3486 const { traceId, spanId: parentSpanId } = parentSpan.spanContext(); 3487 const parentSampled = spanIsSampled(parentSpan); 3488 span = _startRootSpan({ 3489 traceId, 3490 parentSpanId, 3491 ...spanArguments 3492 }, scope, isolationScope, parentSampled); 3493 freezeDscOnSpan(span, dsc); 3494 } else { 3495 const { traceId, dsc, parentSpanId, sampled: parentSampled } = scope.getPropagationContext(); 3496 span = _startRootSpan({ 3497 traceId, 3498 parentSpanId, 3499 ...spanArguments 3500 }, scope, isolationScope, parentSampled); 3501 if (dsc) freezeDscOnSpan(span, dsc); 3502 } 3503 logSpanStart(span); 3504 return span; 3505} 3506function parseSentrySpanArguments(options) { 3507 const initialCtx = { 3508 isStandalone: (options.experimental || {}).standalone, 3509 ...options 3510 }; 3511 if (options.startTime) { 3512 const ctx = { ...initialCtx }; 3513 ctx.startTimestamp = spanTimeInputToSeconds(options.startTime); 3514 delete ctx.startTime; 3515 return ctx; 3516 } 3517 return initialCtx; 3518} 3519function getAcs() { 3520 return getAsyncContextStrategy(getMainCarrier()); 3521} 3522function _startRootSpan(spanArguments, scope, isolationScope, parentSampled) { 3523 const client = getClient(); 3524 const options = client?.getOptions() || {}; 3525 const { name = "" } = spanArguments; 3526 const mutableSpanSamplingData = { 3527 spanAttributes: { ...spanArguments.attributes }, 3528 spanName: name, 3529 parentSampled 3530 }; 3531 client?.emit("beforeSampling", mutableSpanSamplingData, { decision: false }); 3532 const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled; 3533 const finalAttributes = mutableSpanSamplingData.spanAttributes; 3534 const currentPropagationContext = scope.getPropagationContext(); 3535 const _isTracingSuppressed = isTracingSuppressed(scope); 3536 const [sampled, sampleRate, localSampleRateWasApplied] = _isTracingSuppressed ? [false] : sampleSpan(options, { 3537 name, 3538 parentSampled: finalParentSampled, 3539 attributes: finalAttributes, 3540 normalizedRequest: isolationScope.getScopeData().sdkProcessingMetadata.normalizedRequest, 3541 parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate) 3542 }, currentPropagationContext.sampleRand); 3543 const rootSpan = new SentrySpan({ 3544 ...spanArguments, 3545 attributes: { 3546 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom", 3547 [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate !== void 0 && localSampleRateWasApplied ? sampleRate : void 0, 3548 ...finalAttributes 3549 }, 3550 sampled 3551 }); 3552 if (!sampled && client && !_isTracingSuppressed) { 3553 DEBUG_BUILD$5 && debug$2.log("[Tracing] Discarding root span because its trace was not chosen to be sampled.");
3554 client.recordDroppedEvent("sample_rate", hasSpanStreamingEnabled(client) ? "span" : "transaction"); 3555 } 3556 setCapturedScopesOnSpan(rootSpan, scope, isolationScope); 3557 if (client) client.emit("spanStart", rootSpan); 3558 return rootSpan; 3559} 3560function _startChildSpan(parentSpan, scope, spanArguments, isolationScope) { 3561 const { spanId, traceId } = parentSpan.spanContext(); 3562 const _isTracingSuppressed = isTracingSuppressed(scope); 3563 const sampled = _isTracingSuppressed ? false : spanIsSampled(parentSpan); 3564 const childSpan = sampled ? new SentrySpan({ 3565 ...spanArguments, 3566 parentSpanId: spanId, 3567 traceId, 3568 sampled 3569 }) : new SentryNonRecordingSpan({ traceId }); 3570 addChildSpanToSpan(parentSpan, childSpan); 3571 setCapturedScopesOnSpan(childSpan, scope, isolationScope); 3572 const client = getClient(); 3573 if (!client) return childSpan; 3574 if (hasSpanStreamingEnabled(client) && spanIsNonRecordingSpan(childSpan)) { 3575 if (spanIsNonRecordingSpan(parentSpan) && parentSpan.dropReason) { 3576 childSpan.dropReason = parentSpan.dropReason; 3577 client.recordDroppedEvent(parentSpan.dropReason, "span"); 3578 } else if (!_isTracingSuppressed) { 3579 childSpan.dropReason = "sample_rate"; 3580 client.recordDroppedEvent("sample_rate", "span"); 3581 } 3582 } 3583 client.emit("spanStart", childSpan); 3584 if (spanArguments.endTimestamp) { 3585 client.emit("spanEnd", childSpan); 3586 client.emit("afterSpanEnd", childSpan); 3587 } 3588 return childSpan; 3589} 3590function getParentSpan(scope, customParentSpan) { 3591 if (customParentSpan) return customParentSpan; 3592 if (customParentSpan === null) return; 3593 const span = _getSpanForScope(scope); 3594 if (!span) return; 3595 const client = getClient(); 3596 if ((client ? client.getOptions() : {}).parentSpanIsAlwaysRootSpan) return getRootSpan(span); 3597 return span; 3598} 3599function getActiveSpanWrapper(parentSpan) { 3600 return parentSpan !== void 0 ? (callback) => { 3601 return withActiveSpan(parentSpan, callback); 3602 } : (callback) => callback(); 3603} 3604function _shouldIgnoreStreamedSpan(client, spanArguments) { 3605 const ignoreSpans = client?.getOptions().ignoreSpans; 3606 if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) return false; 3607 return shouldIgnoreSpan({ 3608 description: spanArguments.name || "", 3609 op: spanArguments.attributes?.["sentry.op"] || spanArguments.op, 3610 attributes: spanArguments.attributes 3611 }, ignoreSpans); 3612} 3613function spanIsIgnored(span) { 3614 return spanIsNonRecordingSpan(span) && span.dropReason === "ignored"; 3615} 3616var SUPPRESS_TRACING_KEY, continueTrace; 3617function init_trace() { 3618 return (init_trace = __esmMin((() => { 3619 init_asyncContext(); 3620 init_carrier(); 3621 init_currentScopes(); 3622 init_debug_build(); 3623 init_semanticAttributes(); 3624 init_baggage(); 3625 init_debug_logger(); 3626 init_handleCallbackErrors(); 3627 init_hasSpansEnabled(); 3628 init_should_ignore_span(); 3629 init_propagationContext(); 3630 init_randomSafeContext(); 3631 init_spanOnScope(); 3632 init_spanUtils(); 3633 init_tracing(); 3634 init_dynamicSamplingContext(); 3635 init_logSpans(); 3636 init_sampling(); 3637 init_sentryNonRecordingSpan(); 3638 init_sentrySpan(); 3639 init_spanstatus(); 3640 init_utils(); 3641 SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__"; 3642 continueTrace = (options, callback) => { 3643 const acs = getAsyncContextStrategy(getMainCarrier()); 3644 if (acs.continueTrace) return acs.continueTrace(options, callback); 3645 const { sentryTrace, baggage } = options; 3646 const client = getClient(); 3647 const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage); 3648 if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) return startNewTrace(callback); 3649 return withScope((scope) => { 3650 const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); 3651 scope.setPropagationContext(propagationContext); 3652 _setSpanForScope(scope, void 0); 3653 return callback(); 3654 }); 3655 }; 3656 })))(); 3657} 3658//#endregion 3659//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/idleSpan.js 3660function startIdleSpan(startSpanOptions, options = {}) { 3661 const activities = /* @__PURE__ */ new Map(); 3662 let _finished = false; 3663 let _idleTimeoutID; 3664 let _childSpanTimeoutID; 3665 let _finishReason = FINISH_REASON_EXTERNAL_FINISH; 3666 let _autoFinishAllowed = !options.disableAutoFinish; 3667 const _cleanupHooks = []; 3668 const { idleTimeout = TRACING_DEFAULTS.idleTimeout, finalTimeout = TRACING_DEFAULTS.finalTimeout, childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout, beforeSpanEnd, trimIdleSpanEndTimestamp = true } = options; 3669 const client = getClient(); 3670 const scope = getCurrentScope(); 3671 if (!client || !hasSpansEnabled()) { 3672 const span2 = new SentryNonRecordingSpan({ traceId: scope.getPropagationContext().traceId }); 3673 setCapturedScopesOnSpan(span2, scope, getIsolationScope()); 3674 return span2; 3675 } 3676 const previousActiveSpan = getActiveSpan();
3677 const span = _startIdleSpan(startSpanOptions); 3678 span.end = new Proxy(span.end, { apply(target, thisArg, args) { 3679 if (beforeSpanEnd) beforeSpanEnd(span); 3680 if (spanIsNonRecordingSpan(thisArg)) return; 3681 const [definedEndTimestamp, ...rest] = args; 3682 const spanEndTimestamp = spanTimeInputToSeconds(definedEndTimestamp || timestampInSeconds()); 3683 const spans = getSpanDescendants(span).filter((child) => child !== span); 3684 const spanJson = spanToJSON(span); 3685 if (!spans.length || !trimIdleSpanEndTimestamp) { 3686 onIdleSpanEnded(spanEndTimestamp); 3687 return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]); 3688 } 3689 const ignoreSpans = client.getOptions().ignoreSpans; 3690 const latestSpanEndTimestamp = spans?.reduce((acc, current) => { 3691 const currentSpanJson = spanToJSON(current); 3692 if (!currentSpanJson.timestamp) return acc; 3693 if (ignoreSpans && shouldIgnoreSpan({ 3694 description: currentSpanJson.description, 3695 op: currentSpanJson.op, 3696 attributes: currentSpanJson.data 3697 }, ignoreSpans)) return acc; 3698 return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp; 3699 }, void 0); 3700 const spanStartTimestamp = spanJson.start_timestamp; 3701 const endTimestamp = Math.min(spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1e3 : Infinity, Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity))); 3702 onIdleSpanEnded(endTimestamp); 3703 return Reflect.apply(target, thisArg, [endTimestamp, ...rest]); 3704 } }); 3705 function _cancelIdleTimeout() { 3706 if (_idleTimeoutID) { 3707 clearTimeout(_idleTimeoutID); 3708 _idleTimeoutID = void 0; 3709 } 3710 } 3711 function _cancelChildSpanTimeout() { 3712 if (_childSpanTimeoutID) { 3713 clearTimeout(_childSpanTimeoutID); 3714 _childSpanTimeoutID = void 0; 3715 } 3716 } 3717 function _restartIdleTimeout(endTimestamp) { 3718 _cancelIdleTimeout(); 3719 _idleTimeoutID = setTimeout(() => { 3720 if (!_finished && activities.size === 0 && _autoFinishAllowed) { 3721 _finishReason = FINISH_REASON_IDLE_TIMEOUT; 3722 span.end(endTimestamp); 3723 } 3724 }, idleTimeout); 3725 } 3726 function _restartChildSpanTimeout(endTimestamp) { 3727 _cancelChildSpanTimeout(); 3728 _childSpanTimeoutID = setTimeout(() => { 3729 if (!_finished && _autoFinishAllowed) { 3730 _finishReason = FINISH_REASON_HEARTBEAT_FAILED; 3731 span.end(endTimestamp); 3732 } 3733 }, childSpanTimeout); 3734 } 3735 function _pushActivity(spanId) { 3736 _cancelIdleTimeout(); 3737 activities.set(spanId, true); 3738 _restartChildSpanTimeout(timestampInSeconds() + childSpanTimeout / 1e3); 3739 } 3740 function _popActivity(spanId) { 3741 if (activities.has(spanId)) activities.delete(spanId); 3742 if (activities.size === 0) { 3743 _restartIdleTimeout(timestampInSeconds() + idleTimeout / 1e3); 3744 _cancelChildSpanTimeout(); 3745 } 3746 } 3747 function onIdleSpanEnded(endTimestamp) { 3748 _finished = true; 3749 activities.clear(); 3750 _cleanupHooks.forEach((cleanup) => cleanup()); 3751 _setSpanForScope(scope, previousActiveSpan); 3752 const spanJSON = spanToJSON(span); 3753 const { start_timestamp: startTimestamp } = spanJSON; 3754 if (!startTimestamp) return; 3755 if (!spanJSON.data["sentry.idle_span_finish_reason"]) span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason); 3756 const currentStatus = spanJSON.status; 3757 if (!currentStatus || currentStatus === "unknown") span.setStatus({ code: 1 }); 3758 debug$2.log(`[Tracing] Idle span "${spanJSON.op}" finished`); 3759 const childSpans = getSpanDescendants(span).filter((child) => child !== span); 3760 let discardedSpans = 0; 3761 childSpans.forEach((childSpan) => { 3762 if (childSpan.isRecording()) { 3763 childSpan.setStatus({ 3764 code: 2, 3765 message: "cancelled" 3766 }); 3767 childSpan.end(endTimestamp); 3768 DEBUG_BUILD$5 && debug$2.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2)); 3769 } 3770 const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = spanToJSON(childSpan); 3771 const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp; 3772 const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3; 3773 const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError; 3774 if (DEBUG_BUILD$5) { 3775 const stringifiedSpan = JSON.stringify(childSpan, void 0, 2); 3776 if (!spanStartedBeforeIdleSpanEnd) debug$2.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan); 3777 else if (!spanEndedBeforeFinalTimeout) debug$2.log("[Tracing] Discarding span since it finished after idle span final timeout", stringifiedSpan); 3778 } 3779 if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) { 3780 removeChildSpanFromSpan(span, childSpan); 3781 discardedSpans++; 3782 } 3783 }); 3784 if (discardedSpans > 0) span.setAttribute("sentry.idle_span_discarded_spans", discardedSpans); 3785 } 3786 _cleanupHooks.push(client.on("spanStart", (startedSpan) => { 3787 if (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp || startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan()) return; 3788 if (getSpanDescendants(span).includes(startedSpan)) _pushActivity(startedSpan.spanContext().spanId); 3789 })); 3790 _cleanupHooks.push(client.on("spanEnd", (endedSpan) => { 3791 if (_finished) return; 3792 _popActivity(endedSpan.spanContext().spanId); 3793 })); 3794 _cleanupHooks.push(client.on("idleSpanEnableAutoFinish", (spanToAllowAutoFinish) => {
3795 if (spanToAllowAutoFinish === span) { 3796 _autoFinishAllowed = true; 3797 _restartIdleTimeout(); 3798 if (activities.size) _restartChildSpanTimeout(); 3799 } 3800 })); 3801 if (!options.disableAutoFinish) _restartIdleTimeout(); 3802 setTimeout(() => { 3803 if (!_finished) { 3804 span.setStatus({ 3805 code: 2, 3806 message: "deadline_exceeded" 3807 }); 3808 _finishReason = FINISH_REASON_FINAL_TIMEOUT; 3809 span.end(); 3810 } 3811 }, finalTimeout); 3812 return span; 3813} 3814function _startIdleSpan(options) { 3815 const span = startInactiveSpan(options); 3816 _setSpanForScope(getCurrentScope(), span); 3817 DEBUG_BUILD$5 && debug$2.log("[Tracing] Started span is an idle span"); 3818 return span; 3819} 3820var TRACING_DEFAULTS, FINISH_REASON_HEARTBEAT_FAILED, FINISH_REASON_IDLE_TIMEOUT, FINISH_REASON_FINAL_TIMEOUT, FINISH_REASON_EXTERNAL_FINISH; 3821function init_idleSpan() { 3822 return (init_idleSpan = __esmMin((() => { 3823 init_currentScopes(); 3824 init_debug_build(); 3825 init_semanticAttributes(); 3826 init_debug_logger(); 3827 init_hasSpansEnabled(); 3828 init_should_ignore_span(); 3829 init_spanOnScope(); 3830 init_spanUtils(); 3831 init_time(); 3832 init_sentryNonRecordingSpan(); 3833 init_sentrySpan(); 3834 init_spanstatus(); 3835 init_trace(); 3836 init_utils(); 3837 TRACING_DEFAULTS = { 3838 idleTimeout: 1e3, 3839 finalTimeout: 3e4, 3840 childSpanTimeout: 15e3 3841 }; 3842 FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed"; 3843 FINISH_REASON_IDLE_TIMEOUT = "idleTimeout"; 3844 FINISH_REASON_FINAL_TIMEOUT = "finalTimeout"; 3845 FINISH_REASON_EXTERNAL_FINISH = "externalFinish"; 3846 })))(); 3847} 3848//#endregion 3849//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/debounce.js 3850function debounce$1(func, wait, options) { 3851 let callbackReturnValue; 3852 let timerId; 3853 let maxTimerId; 3854 const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0; 3855 const setTimeoutImpl = options?.setTimeoutImpl || setTimeout; 3856 function invokeFunc() { 3857 cancelTimers(); 3858 callbackReturnValue = func(); 3859 return callbackReturnValue; 3860 } 3861 function cancelTimers() { 3862 timerId !== void 0 && clearTimeout(timerId); 3863 maxTimerId !== void 0 && clearTimeout(maxTimerId); 3864 timerId = maxTimerId = void 0; 3865 } 3866 function flush() { 3867 if (timerId !== void 0 || maxTimerId !== void 0) return invokeFunc(); 3868 return callbackReturnValue; 3869 } 3870 function debounced() { 3871 if (timerId) clearTimeout(timerId); 3872 timerId = setTimeoutImpl(invokeFunc, wait); 3873 if (maxWait && maxTimerId === void 0) maxTimerId = setTimeoutImpl(invokeFunc, maxWait); 3874 return callbackReturnValue; 3875 } 3876 debounced.cancel = cancelTimers; 3877 debounced.flush = flush; 3878 return debounced; 3879} 3880//#endregion 3881//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/bindScopeToEmitter.js 3882function isReentrantWrapperRegistration(listener) { 3883 return registeringWrapper !== void 0 && (listener === registeringWrapper || listener.listener === registeringWrapper); 3884} 3885function bindScopeToEmitter(emitter, scope = getCurrentScope()) { 3886 const ee = emitter; 3887 if (getPatchMap(ee)) return emitter; 3888 createPatchMap(ee); 3889 for (const methodName of ADD_LISTENER_METHODS) { 3890 if (typeof ee[methodName] !== "function") continue; 3891 ee[methodName] = patchAddListener(ee, ee[methodName], scope); 3892 } 3893 for (const methodName of REMOVE_LISTENER_METHODS) { 3894 if (typeof ee[methodName] !== "function") continue; 3895 ee[methodName] = patchRemoveListener(ee, ee[methodName]); 3896 } 3897 if (typeof ee.removeAllListeners === "function") ee.removeAllListeners = patchRemoveAllListeners(ee, ee.removeAllListeners); 3898 return emitter; 3899} 3900function bindListenerToScope(listener, scope) { 3901 return function(...args) { 3902 return withScope(scope, () => listener.apply(this, args)); 3903 }; 3904} 3905function isBoundListener(listener) { 3906 return typeof listener === "function"; 3907} 3908function patchAddListener(ee, original, scope) { 3909 return function(...args) { 3910 const event = args[0]; 3911 const listener = args[1]; 3912 const rest = args.slice(2); 3913 if (!isBoundListener(listener) || isReentrantWrapperRegistration(listener)) return original.apply(this, args); 3914 const map = getPatchMap(ee) || createPatchMap(ee); 3915 let listeners = map.get(event); 3916 if (!listeners) { 3917 listeners = /* @__PURE__ */ new WeakMap(); 3918 map.set(event, listeners); 3919 } 3920 let boundListener = listeners.get(listener); 3921 if (!boundListener) { 3922 boundListener = bindListenerToScope(listener, scope); 3923 listeners.set(listener, boundListener); 3924 } 3925 const previous = registeringWrapper; 3926 registeringWrapper = boundListener; 3927 try { 3928 return original.call(this, event, boundListener, ...rest); 3929 } finally { 3930 registeringWrapper = previous; 3931 } 3932 }; 3933} 3934function patchRemoveListener(ee, original) { 3935 return function(...args) { 3936 const event = args[0]; 3937 const listener = args[1]; 3938 const rest = args.slice(2); 3939 const boundListener = isBoundListener(listener) ? getPatchMap(ee)?.get(event)?.get(listener) : void 0; 3940 if (!boundListener) return original.apply(this, args); 3941 return original.call(this, event, boundListener, ...rest); 3942 }; 3943} 3944function patchRemoveAllListeners(ee, original) { 3945 return function(...args) { 3946 const map = getPatchMap(ee); 3947 if (map) { 3948 if (args.length === 0) createPatchMap(ee); 3949 else { 3950 const event = args[0]; 3951 map.delete(event); 3952 } 3953 } 3954 return original.apply(this, args); 3955 }; 3956} 3957function createPatchMap(ee) { 3958 const map = /* @__PURE__ */ new Map(); 3959 ee[SCOPE_BOUND_LISTENERS] = map; 3960 return map; 3961} 3962function getPatchMap(ee) { 3963 return ee[SCOPE_BOUND_LISTENERS]; 3964} 3965var ADD_LISTENER_METHODS, REMOVE_LISTENER_METHODS, SCOPE_BOUND_LISTENERS, registeringWrapper; 3966function init_bindScopeToEmitter() { 3967 return (init_bindScopeToEmitter = __esmMin((() => { 3968 init_currentScopes(); 3969 ADD_LISTENER_METHODS = [ 3970 "addListener", 3971 "on", 3972 "once", 3973 "prependListener", 3974 "prependOnceListener", 3975 "addEventListener" 3976 ]; 3977 REMOVE_LISTENER_METHODS = [ 3978 "removeListener", 3979 "off", 3980 "removeEventListener" 3981 ]; 3982 SCOPE_BOUND_LISTENERS = /* @__PURE__ */ Symbol("SentryScopeBoundListeners"); 3983 })))(); 3984} 3985//#endregion 3986//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/scopeData.js 3987function applyScopeDataToEvent(event, data) { 3988 const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data; 3989 applyDataToEvent(event, data); 3990 if (span) applySpanToEvent(event, span); 3991 applyFingerprintToEvent(event, fingerprint); 3992 applyBreadcrumbsToEvent(event, breadcrumbs); 3993 applySdkMetadataToEvent(event, sdkProcessingMetadata); 3994} 3995function mergeScopeData(data, mergeData) { 3996 const { extra, tags, attributes, user, contexts, level, sdkProcessingMetadata, breadcrumbs, fingerprint, eventProcessors, attachments, propagationContext, transactionName, span } = mergeData; 3997 mergeAndOverwriteScopeData(data, "extra", extra); 3998 mergeAndOverwriteScopeData(data, "tags", tags); 3999 mergeAndOverwriteScopeData(data, "attributes", attributes); 4000 mergeAndOverwriteScopeData(data, "user", user); 4001 mergeAndOverwriteScopeData(data, "contexts", contexts); 4002 data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2); 4003 if (level) data.level = level; 4004 if (transactionName) data.transactionName = transactionName; 4005 if (span) data.span = span; 4006 if (breadcrumbs.length) data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs]; 4007 if (fingerprint.length) data.fingerprint = [...data.fingerprint, ...fingerprint]; 4008 if (eventProcessors.length) data.eventProcessors = [...data.eventProcessors, ...eventProcessors]; 4009 if (attachments.length) data.attachments = [...data.attachments, ...attachments]; 4010 data.propagationContext = { 4011 ...data.propagationContext, 4012 ...propagationContext 4013 }; 4014} 4015function mergeAndOverwriteScopeData(data, prop, mergeVal) { 4016 data[prop] = merge(data[prop], mergeVal, 1); 4017} 4018function getCombinedScopeData(isolationScope, currentScope) { 4019 const scopeData = getGlobalScope().getScopeData(); 4020 isolationScope && mergeScopeData(scopeData, isolationScope.getScopeData()); 4021 currentScope && mergeScopeData(scopeData, currentScope.getScopeData()); 4022 return scopeData; 4023} 4024function applyDataToEvent(event, data) { 4025 const { extra, tags, user, contexts, level, transactionName } = data; 4026 if (Object.keys(extra).length) event.extra = { 4027 ...extra, 4028 ...event.extra 4029 }; 4030 if (Object.keys(tags).length) event.tags = { 4031 ...tags, 4032 ...event.tags 4033 }; 4034 if (Object.keys(user).length) event.user = { 4035 ...user, 4036 ...event.user 4037 }; 4038 if (Object.keys(contexts).length) event.contexts = { 4039 ...contexts, 4040 ...event.contexts 4041 }; 4042 if (level) event.level = level; 4043 if (transactionName && event.type !== "transaction") event.transaction = transactionName; 4044} 4045function applyBreadcrumbsToEvent(event, breadcrumbs) { 4046 const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs]; 4047 event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0; 4048} 4049function applySdkMetadataToEvent(event, sdkProcessingMetadata) { 4050 event.sdkProcessingMetadata = { 4051 ...event.sdkProcessingMetadata, 4052 ...sdkProcessingMetadata 4053 }; 4054} 4055function applySpanToEvent(event, span) { 4056 event.contexts = { 4057 trace: spanToTraceContext(span), 4058 ...event.contexts 4059 }; 4060 event.sdkProcessingMetadata = { 4061 dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), 4062 ...event.sdkProcessingMetadata 4063 }; 4064 const transactionName = spanToJSON(getRootSpan(span)).description; 4065 if (transactionName && !event.transaction && event.type === "transaction") event.transaction = transactionName; 4066} 4067function applyFingerprintToEvent(event, fingerprint) { 4068 event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint]
4068: []; 4069 if (fingerprint) event.fingerprint = event.fingerprint.concat(fingerprint); 4070 if (!event.fingerprint.length) delete event.fingerprint; 4071} 4072function init_scopeData() { 4073 return (init_scopeData = __esmMin((() => { 4074 init_currentScopes(); 4075 init_dynamicSamplingContext(); 4076 init_spanUtils(); 4077 })))(); 4078} 4079//#endregion 4080//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/scopeContextAttributes.js 4081function scopeContextsToSpanAttributes(contexts) { 4082 const attrs = {}; 4083 const { response, profile, cloud_resource, culture, state } = contexts; 4084 if (response) { 4085 if (response.status_code != null) attrs["http.response.status_code"] = response.status_code; 4086 if (response.body_size != null) attrs["http.response.body.size"] = response.body_size; 4087 } 4088 if (profile) { 4089 if (profile.profile_id) attrs["sentry.profile_id"] = profile.profile_id; 4090 if (profile.profiler_id) attrs["sentry.profiler_id"] = profile.profiler_id; 4091 } 4092 if (cloud_resource) { 4093 for (const [key, value] of Object.entries(cloud_resource)) if (value != null) attrs[key] = value; 4094 } 4095 if (culture) { 4096 if (culture.locale) attrs["culture.locale"] = culture.locale; 4097 if (culture.timezone) attrs["culture.timezone"] = culture.timezone; 4098 } 4099 if (state?.state && typeof state.state.type === "string") attrs["state.type"] = state.state.type; 4100 const angular = contexts["angular"]; 4101 if (angular) { 4102 const version = angular["version"]; 4103 if (typeof version === "string" || typeof version === "number") attrs["angular.version"] = version; 4104 } 4105 const react = contexts["react"]; 4106 if (react) { 4107 const version = react["version"]; 4108 if (typeof version === "string" || typeof version === "number") attrs["react.version"] = version; 4109 } 4110 return attrs; 4111} 4112//#endregion 4113//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/conventions/dist/attributes.mjs 4114var qa, ws, Jl, Nc, Cc, Pc, Lc, Kc, Xc, Yu, Vu, Fu, ju, Qu; 4115function init_attributes$1() { 4116 return (init_attributes$1 = __esmMin((() => { 4117 qa = "graphql.document"; 4118 ws = "http.url"; 4119 Jl = "params"; 4120 Nc = "sentry.sdk.name"; 4121 Cc = "sentry.sdk.version"; 4122 Pc = "sentry.segment.id"; 4123 Lc = "sentry.segment.name"; 4124 Kc = "sentry.trace_lifecycle"; 4125 Xc = "sentry.transaction"; 4126 Yu = "url.full"; 4127 Vu = "url.path"; 4128 Fu = "url.path.parameter"; 4129 ju = "url.template"; 4130 Qu = "user_agent.original"; 4131 })))(); 4132} 4133//#endregion 4134//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/captureSpan.js 4135function captureSpan(span, client) { 4136 const spanJSON = spanToStreamedSpanJSON(span); 4137 const segmentSpan = INTERNAL_getSegmentSpan(span); 4138 const serializedSegmentSpan = spanToStreamedSpanJSON(segmentSpan); 4139 const { isolationScope: spanIsolationScope, scope: spanScope } = getCapturedScopesOnSpan(span); 4140 const finalScopeData = getCombinedScopeData(spanIsolationScope, spanScope); 4141 applyCommonSpanAttributes(spanJSON, serializedSegmentSpan, client, finalScopeData); 4142 const spanKind = span.kind; 4143 client.emit("preprocessSpan", spanJSON, { spanKind }); 4144 if (spanJSON.is_segment) { 4145 applyScopeToSegmentSpan(spanJSON, finalScopeData); 4146 applySdkMetadataToSegmentSpan(spanJSON, client); 4147 client.emit("processSegmentSpan", spanJSON); 4148 } 4149 client.emit("processSpan", spanJSON); 4150 const { beforeSendSpan } = client.getOptions(); 4151 const processedSpan = beforeSendSpan && isStreamedBeforeSendSpanCallback(beforeSendSpan) ? applyBeforeSendSpanCallback(spanJSON, beforeSendSpan) : spanJSON; 4152 const spanNameSource = processedSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 4153 if (spanJSON.is_segment && spanNameSource) safeSetSpanJSONAttributes(processedSpan, { ["sentry.segment.name.source"]: spanNameSource }); 4154 return { 4155 ...streamedSpanJsonToSerializedSpan(processedSpan), 4156 _segmentSpan: segmentSpan 4157 }; 4158} 4159function applyScopeToSegmentSpan(segmentSpanJSON, scopeData) { 4160 safeSetSpanJSONAttributes(segmentSpanJSON, scopeContextsToSpanAttributes(scopeData.contexts)); 4161} 4162function safeSetSpanJSONAttributes(spanJSON, newAttributes) { 4163 const originalAttributes = spanJSON.attributes ?? (spanJSON.attributes = {});
4164 Object.entries(newAttributes).forEach(([key, value]) => { 4165 if (value != null && !(key in originalAttributes)) originalAttributes[key] = value; 4166 }); 4167} 4168function applySdkMetadataToSegmentSpan(segmentSpanJSON, client) { 4169 const integrationNames = client.getIntegrationNames(); 4170 if (!integrationNames.length) return; 4171 safeSetSpanJSONAttributes(segmentSpanJSON, { [SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS]: integrationNames }); 4172} 4173function applyCommonSpanAttributes(spanJSON, serializedSegmentSpan, client, scopeData) { 4174 const sdk = client.getSdkMetadata(); 4175 const { release, environment } = client.getOptions(); 4176 safeSetSpanJSONAttributes(spanJSON, { 4177 [Kc]: "stream", 4178 [Lc]: serializedSegmentSpan.name, 4179 [Pc]: serializedSegmentSpan.span_id, 4180 [Nc]: sdk?.sdk?.name, 4181 [Cc]: sdk?.sdk?.version, 4182 [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: release, 4183 [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: environment || "production", 4184 [SEMANTIC_ATTRIBUTE_USER_ID]: scopeData.user?.id, 4185 [SEMANTIC_ATTRIBUTE_USER_EMAIL]: scopeData.user?.email, 4186 [SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS]: scopeData.user?.ip_address, 4187 [SEMANTIC_ATTRIBUTE_USER_USERNAME]: scopeData.user?.username, 4188 ...scopeData.attributes 4189 }); 4190} 4191function applyBeforeSendSpanCallback(span, beforeSendSpan) { 4192 const modifedSpan = beforeSendSpan(span); 4193 if (!modifedSpan) { 4194 showSpanDropWarning(); 4195 return span; 4196 } 4197 return modifedSpan; 4198} 4199function init_captureSpan() { 4200 return (init_captureSpan = __esmMin((() => { 4201 init_semanticAttributes(); 4202 init_scopeData(); 4203 init_spanUtils(); 4204 init_utils(); 4205 init_beforeSendSpan(); 4206 init_constants(); 4207 init_attributes$1(); 4208 })))(); 4209} 4210//#endregion 4211//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/syncpromise.js 4212function resolvedSyncPromise(value) { 4213 return new SyncPromise((resolve) => { 4214 resolve(value); 4215 }); 4216} 4217function rejectedSyncPromise(reason) { 4218 return new SyncPromise((_, reject) => { 4219 reject(reason); 4220 }); 4221} 4222var STATE_PENDING, STATE_RESOLVED, STATE_REJECTED, SyncPromise; 4223function init_syncpromise() { 4224 return (init_syncpromise = __esmMin((() => { 4225 init_is(); 4226 STATE_PENDING = 0; 4227 STATE_RESOLVED = 1; 4228 STATE_REJECTED = 2; 4229 SyncPromise = class SyncPromise { 4230 constructor(executor) { 4231 this._state = STATE_PENDING; 4232 this._handlers = []; 4233 this._runExecutor(executor); 4234 } 4235 /** @inheritdoc */ 4236 then(onfulfilled, onrejected) { 4237 return new SyncPromise((resolve, reject) => { 4238 this._handlers.push([ 4239 false, 4240 (result) => { 4241 if (!onfulfilled) resolve(result); 4242 else try { 4243 resolve(onfulfilled(result)); 4244 } catch (e) { 4245 reject(e); 4246 } 4247 }, 4248 (reason) => { 4249 if (!onrejected) reject(reason); 4250 else try { 4251 resolve(onrejected(reason)); 4252 } catch (e) { 4253 reject(e); 4254 } 4255 } 4256 ]); 4257 this._executeHandlers(); 4258 }); 4259 } 4260 /** @inheritdoc */ 4261 catch(onrejected) { 4262 return this.then((val) => val, onrejected); 4263 } 4264 /** @inheritdoc */ 4265 finally(onfinally) { 4266 return new SyncPromise((resolve, reject) => { 4267 let val; 4268 let isRejected; 4269 return this.then((value) => { 4270 isRejected = false; 4271 val = value; 4272 if (onfinally) onfinally(); 4273 }, (reason) => { 4274 isRejected = true; 4275 val = reason; 4276 if (onfinally) onfinally(); 4277 }).then(() => { 4278 if (isRejected) { 4279 reject(val); 4280 return; 4281 } 4282 resolve(val); 4283 }); 4284 }); 4285 } 4286 /** Excute the resolve/reject handlers. */ 4287 _executeHandlers() { 4288 if (this._state === STATE_PENDING) return; 4289 const cachedHandlers = this._handlers.slice(); 4290 this._handlers = []; 4291 cachedHandlers.forEach((handler) => { 4292 if (handler[0]) return; 4293 if (this._state === STATE_RESOLVED) handler[1](this._value); 4294 if (this._state === STATE_REJECTED) handler[2](this._value); 4295 handler[0] = true; 4296 }); 4297 } 4298 /** Run the executor for the SyncPromise. */ 4299 _runExecutor(executor) { 4300 const setResult = (state, value) => { 4301 if (this._state !== STATE_PENDING) return; 4302 if (isThenable(value)) { 4303 value.then(resolve, reject); 4304 return; 4305 } 4306 this._state = state; 4307 this._value = value; 4308 this._executeHandlers(); 4309 }; 4310 const resolve = (value) => { 4311 setResult(STATE_RESOLVED, value); 4312 }; 4313 const reject = (reason) => { 4314 setResult(STATE_REJECTED, reason); 4315 };
4316 try { 4317 executor(resolve, reject); 4318 } catch (e) { 4319 reject(e); 4320 } 4321 } 4322 }; 4323 })))(); 4324} 4325//#endregion 4326//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/eventProcessors.js 4327function notifyEventProcessors(processors, event, hint, index = 0) { 4328 try { 4329 const result = _notifyEventProcessors(event, hint, processors, index); 4330 return isThenable(result) ? result : resolvedSyncPromise(result); 4331 } catch (error) { 4332 return rejectedSyncPromise(error); 4333 } 4334} 4335function _notifyEventProcessors(event, hint, processors, index) { 4336 const processor = processors[index]; 4337 if (!event || !processor) return event; 4338 const result = processor({ ...event }, hint); 4339 DEBUG_BUILD$5 && result === null && debug$2.log(`Event processor "${processor.id || "?"}" dropped event`); 4340 if (isThenable(result)) return result.then((final) => _notifyEventProcessors(final, hint, processors, index + 1)); 4341 return _notifyEventProcessors(result, hint, processors, index + 1); 4342} 4343function init_eventProcessors() { 4344 return (init_eventProcessors = __esmMin((() => { 4345 init_debug_build(); 4346 init_debug_logger(); 4347 init_is(); 4348 init_syncpromise(); 4349 })))(); 4350} 4351//#endregion 4352//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/debug-ids.js 4353function getFilenameToDebugIdMap(stackParser) { 4354 const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds; 4355 const nativeDebugIdMap = GLOBAL_OBJ._debugIds; 4356 if (!sentryDebugIdMap && !nativeDebugIdMap) return {}; 4357 const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : []; 4358 const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : []; 4359 if (cachedFilenameDebugIds && sentryDebugIdKeys.length === lastSentryKeysCount && nativeDebugIdKeys.length === lastNativeKeysCount) return cachedFilenameDebugIds; 4360 lastSentryKeysCount = sentryDebugIdKeys.length; 4361 lastNativeKeysCount = nativeDebugIdKeys.length; 4362 cachedFilenameDebugIds = {}; 4363 if (!parsedStackResults) parsedStackResults = {}; 4364 const processDebugIds = (debugIdKeys, debugIdMap) => { 4365 for (const key of debugIdKeys) { 4366 const debugId = debugIdMap[key]; 4367 const result = parsedStackResults?.[key]; 4368 if (result && cachedFilenameDebugIds && debugId) { 4369 cachedFilenameDebugIds[result[0]] = debugId; 4370 if (parsedStackResults) parsedStackResults[key] = [result[0], debugId]; 4371 } else if (debugId) { 4372 const parsedStack = stackParser(key); 4373 for (let i = parsedStack.length - 1; i >= 0; i--) { 4374 const filename = parsedStack[i]?.filename; 4375 if (filename && cachedFilenameDebugIds && parsedStackResults) { 4376 cachedFilenameDebugIds[filename] = debugId; 4377 parsedStackResults[key] = [filename, debugId]; 4378 break; 4379 } 4380 } 4381 } 4382 } 4383 }; 4384 if (sentryDebugIdMap) processDebugIds(sentryDebugIdKeys, sentryDebugIdMap); 4385 if (nativeDebugIdMap) processDebugIds(nativeDebugIdKeys, nativeDebugIdMap); 4386 return cachedFilenameDebugIds; 4387} 4388function getDebugImagesForResources(stackParser, resource_paths) { 4389 const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); 4390 if (!filenameDebugIdMap) return []; 4391 const images = []; 4392 for (const path of resource_paths) { 4393 const normalizedPath = normalizeStackTracePath(path); 4394 if (normalizedPath && filenameDebugIdMap[normalizedPath]) images.push({ 4395 type: "sourcemap", 4396 code_file: path, 4397 debug_id: filenameDebugIdMap[normalizedPath] 4398 }); 4399 } 4400 return images; 4401} 4402var parsedStackResults, lastSentryKeysCount, lastNativeKeysCount, cachedFilenameDebugIds; 4403function init_debug_ids() { 4404 return (init_debug_ids = __esmMin((() => { 4405 init_stacktrace(); 4406 init_worldwide(); 4407 })))(); 4408} 4409//#endregion 4410//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/prepareEvent.js 4411function prepareEvent(options, event, hint, scope, client, isolationScope) { 4412 const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options; 4413 const prepared = { 4414 ...event, 4415 event_id: event.event_id || hint.event_id || uuid4(), 4416 timestamp: event.timestamp || dateTimestampInSeconds() 4417 }; 4418 const integrations = hint.integrations || options.integrations.map((i) => i.name); 4419 applyClientOptions(prepared, options); 4420 applyIntegrationsMetadata(prepared, integrations); 4421 if (client) client.emit("applyFrameMetadata", event); 4422 if (event.type === void 0) applyDebugIds(prepared, options.stackParser); 4423 const finalScope = getFinalScope(scope, hint.captureContext); 4424 if (hint.mechanism) addExceptionMechanism(prepared, hint.mechanism); 4425 const clientEventProcessors = client ? client.getEventProcessors() : []; 4426 const data = getCombinedScopeData(isolationScope, finalScope); 4427 const attachments = [...hint.attachments || [], ...data.attachments]; 4428 if (attachments.length) hint.attachments = attachments; 4429 applyScopeDataToEvent(prepared, data); 4430 const eventProcessors = [...clientEventProcessors, ...data.eventProcessors]; 4431 return (hint.data && hint.data.__sentry__ === true ? resolvedSyncPromise(prepared) : notifyEventProcessors(eventProcessors, prepared, hint)).then((evt) => { 4432 if (evt) applyDebugMeta(evt); 4433 if (typeof normalizeDepth === "number" && normalizeDepth > 0) return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); 4434 return evt; 4435 }); 4436} 4437function applyClientOptions(event, options) { 4438 const { environment, release, dist, maxValueLength } = options; 4439 event.environment = event.environment || environment || "production"; 4440 if (!event.release && release) event.release = release; 4441 if (!event.dist && dist) event.dist = dist; 4442 const request = event.request; 4443 if (request?.url && maxValueLength) request.url = truncate(request.url, maxValueLength); 4444 if (maxValueLength) event.exception?.values?.forEach((exception) => { 4445 if (exception.value) exception.value = truncate(exception.value, maxValueLength); 4446 }); 4447} 4448function applyDebugIds(event, stackParser) { 4449 const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); 4450 event.exception?.values?.forEach((exception) => { 4451 exception.stacktrace?.frames?.forEach((frame) => { 4452 if (frame.filename) frame.debug_id = filenameDebugIdMap[frame.filename]; 4453 }); 4454 }); 4455} 4456function applyDebugMeta(event) { 4457 const filenameDebugIdMap = {}; 4458 event.exception?.values?.forEach((exception) => { 4459 exception.stacktrace?.frames?.forEach((frame) => { 4460 if (frame.debug_id) { 4461 if (frame.abs_path) filenameDebugIdMap[frame.abs_path] = frame.debug_id; 4462 else if (frame.filename) filenameDebugIdMap[frame.filename] = frame.debug_id; 4463 delete frame.debug_id; 4464 } 4465 }); 4466 }); 4467 if (Object.keys(filenameDebugIdMap).length === 0) return; 4468 event.debug_meta = event.debug_meta || {}; 4469 event.debug_meta.images = event.debug_meta.images || []; 4470 const images = event.debug_meta.images;
4471 Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => { 4472 images.push({ 4473 type: "sourcemap", 4474 code_file: filename, 4475 debug_id 4476 }); 4477 }); 4478} 4479function applyIntegrationsMetadata(event, integrationNames) { 4480 if (integrationNames.length > 0) { 4481 event.sdk = event.sdk || {}; 4482 event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames]; 4483 } 4484} 4485function normalizeEvent(event, depth, maxBreadth) { 4486 if (!event) return null; 4487 const normalized = { 4488 ...event, 4489 ...event.breadcrumbs && { breadcrumbs: event.breadcrumbs.map((b) => ({ 4490 ...b, 4491 ...b.data && { data: normalize(b.data, depth, maxBreadth) } 4492 })) }, 4493 ...event.user && { user: normalize(event.user, depth, maxBreadth) }, 4494 ...event.contexts && { contexts: normalize(event.contexts, depth, maxBreadth) }, 4495 ...event.extra && { extra: normalize(event.extra, depth, maxBreadth) } 4496 }; 4497 if (event.contexts?.trace && normalized.contexts) { 4498 normalized.contexts.trace = event.contexts.trace; 4499 if (event.contexts.trace.data) normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth); 4500 } 4501 if (event.spans) normalized.spans = event.spans.map((span) => { 4502 return { 4503 ...span, 4504 ...span.data && { data: normalize(span.data, depth, maxBreadth) } 4505 }; 4506 }); 4507 if (event.contexts?.flags && normalized.contexts) normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth); 4508 return normalized; 4509} 4510function getFinalScope(scope, captureContext) { 4511 if (!captureContext) return scope; 4512 const finalScope = scope ? scope.clone() : new Scope(); 4513 finalScope.update(captureContext); 4514 return finalScope; 4515} 4516function parseEventHintOrCaptureContext(hint) { 4517 if (!hint) return; 4518 if (hintIsScopeOrFunction(hint)) return { captureContext: hint }; 4519 if (hintIsScopeContext(hint)) return { captureContext: hint }; 4520 return hint; 4521} 4522function hintIsScopeOrFunction(hint) { 4523 return hint instanceof Scope || typeof hint === "function"; 4524} 4525function hintIsScopeContext(hint) { 4526 return Object.keys(hint).some((key) => captureContextKeys.includes(key)); 4527} 4528var captureContextKeys; 4529function init_prepareEvent() { 4530 return (init_prepareEvent = __esmMin((() => { 4531 init_constants(); 4532 init_eventProcessors(); 4533 init_scope(); 4534 init_debug_ids(); 4535 init_misc(); 4536 init_normalize(); 4537 init_scopeData(); 4538 init_string(); 4539 init_syncpromise(); 4540 init_time(); 4541 captureContextKeys = [ 4542 "user", 4543 "level", 4544 "extra", 4545 "contexts", 4546 "tags", 4547 "fingerprint", 4548 "propagationContext" 4549 ]; 4550 })))(); 4551} 4552//#endregion 4553//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/exports.js 4554function captureException(exception, hint) { 4555 return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); 4556} 4557function captureMessage(message, captureContext) { 4558 const level = typeof captureContext === "string" ? captureContext : void 0; 4559 const hint = typeof captureContext !== "string" ? { captureContext } : void 0; 4560 return getCurrentScope().captureMessage(message, level, hint); 4561} 4562function captureEvent(event, hint) { 4563 return getCurrentScope().captureEvent(event, hint); 4564} 4565function setContext(name, context) { 4566 getIsolationScope().setContext(name, context); 4567} 4568function setExtras(extras) { 4569 getIsolationScope().setExtras(extras); 4570} 4571function setExtra(key, extra) { 4572 getIsolationScope().setExtra(key, extra); 4573} 4574function setTags(tags) { 4575 getIsolationScope().setTags(tags); 4576} 4577function setTag(key, value) { 4578 getIsolationScope().setTag(key, value); 4579} 4580function setAttributes(attributes) { 4581 getIsolationScope().setAttributes(attributes); 4582} 4583function setAttribute(key, value) { 4584 getIsolationScope().setAttribute(key, value); 4585} 4586function setUser(user) { 4587 getIsolationScope().setUser(user); 4588} 4589function setConversationId(conversationId) { 4590 getIsolationScope().setConversationId(conversationId); 4591} 4592function lastEventId() { 4593 return getIsolationScope().lastEventId(); 4594} 4595async function flush(timeout) { 4596 const client = getClient(); 4597 if (client) return client.flush(timeout); 4598 DEBUG_BUILD$5 && debug$2.warn("Cannot flush events. No client defined."); 4599 return Promise.resolve(false); 4600} 4601async function close(timeout) { 4602 const client = getClient(); 4603 if (client) return client.close(timeout); 4604 DEBUG_BUILD$5 && debug$2.warn("Cannot flush events and disable SDK. No client defined."); 4605 return Promise.resolve(false); 4606} 4607function isInitialized$1() { 4608 return !!getClient(); 4609} 4610function isEnabled() { 4611 const client = getClient(); 4612 return client?.getOptions().enabled !== false && !!client?.getTransport(); 4613} 4614function addEventProcessor(callback) { 4615 getIsolationScope().addEventProcessor(callback); 4616} 4617function startSession(context) { 4618 const isolationScope = getIsolationScope(); 4619 const { user } = getCombinedScopeData(isolationScope, getCurrentScope()); 4620 const { userAgent } = GLOBAL_OBJ.navigator || {}; 4621 const session = makeSession$1({ 4622 user, 4623 ...userAgent && { userAgent }, 4624 ...context 4625 }); 4626 const currentSession = isolationScope.getSession(); 4627 if (currentSession?.status === "ok") updateSession(currentSession, { status: "exited" }); 4628 endSession(); 4629 isolationScope.setSession(session); 4630 return session; 4631} 4632function endSession() { 4633 const isolationScope = getIsolationScope(); 4634 const session = getCurrentScope().getSession() || isolationScope.getSession(); 4635 if (session) closeSession(session); 4636 _sendSessionUpdate(); 4637 isolationScope.setSession(); 4638} 4639function _sendSessionUpdate() { 4640 const isolationScope = getIsolationScope(); 4641 const client = getClient(); 4642 const session = isolationScope.getSession(); 4643 if (session && client) client.captureSession(session); 4644} 4645function captureSession(end = false) { 4646 if (end) { 4647 endSession(); 4648 return; 4649 } 4650 _sendSessionUpdate(); 4651} 4652function init_exports() { 4653 return (init_exports = __esmMin((() => { 4654 init_currentScopes(); 4655 init_debug_build(); 4656 init_session(); 4657 init_debug_logger(); 4658 init_prepareEvent(); 4659 init_scopeData(); 4660 init_worldwide(); 4661 })))(); 4662} 4663//#endregion 4664//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/timer.js 4665function safeUnref(timer) { 4666 if (typeof timer === "object" && typeof timer.unref === "function") timer.unref(); 4667 return timer; 4668} 4669//#endregion 4670//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/api.js 4671function getBaseApiEndpoint(dsn) { 4672 const protocol = dsn.protocol ? `${dsn.protocol}:` : ""; 4673 const port = dsn.port ? `:${dsn.port}` : ""; 4674 return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`; 4675} 4676function _getIngestEndpoint(dsn) { 4677 return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; 4678} 4679function _encodedAuth(dsn, sdkInfo) { 4680 const params = { sentry_version: "7" }; 4681 if (dsn.publicKey) params.sentry_key = dsn.publicKey; 4682 if (sdkInfo) params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`; 4683 return new URLSearchParams(params).toString(); 4684} 4685function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) { 4686 return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; 4687} 4688function getReportDialogEndpoint(dsnLike, dialogOptions) {
4689 const dsn = makeDsn(dsnLike); 4690 if (!dsn) return ""; 4691 const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; 4692 let encodedOptions = `dsn=${dsnToString(dsn)}`; 4693 for (const key in dialogOptions) { 4694 if (key === "dsn") continue; 4695 if (key === "onClose") continue; 4696 if (key === "user") { 4697 const user = dialogOptions.user; 4698 if (!user) continue; 4699 if (user.name) encodedOptions += `&name=${encodeURIComponent(user.name)}`; 4700 if (user.email) encodedOptions += `&email=${encodeURIComponent(user.email)}`; 4701 } else encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key])}`; 4702 } 4703 return `${endpoint}?${encodedOptions}`; 4704} 4705function init_api() { 4706 return (init_api = __esmMin((() => { 4707 init_dsn(); 4708 })))(); 4709} 4710//#endregion 4711//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integration.js 4712function filterDuplicates(integrations) { 4713 const integrationsByName = {}; 4714 integrations.forEach((currentInstance) => { 4715 const { name } = currentInstance; 4716 const existingInstance = integrationsByName[name]; 4717 if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) return; 4718 integrationsByName[name] = currentInstance; 4719 }); 4720 return Object.values(integrationsByName); 4721} 4722function getIntegrationsToSetup(options) { 4723 const defaultIntegrations = options.defaultIntegrations || []; 4724 const userIntegrations = options.integrations; 4725 defaultIntegrations.forEach((integration) => { 4726 integration.isDefaultInstance = true; 4727 }); 4728 let integrations; 4729 if (Array.isArray(userIntegrations)) integrations = [...defaultIntegrations, ...userIntegrations]; 4730 else if (typeof userIntegrations === "function") { 4731 const resolvedUserIntegrations = userIntegrations(defaultIntegrations); 4732 integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations]; 4733 } else integrations = defaultIntegrations; 4734 return filterDuplicates(integrations); 4735} 4736function setupIntegrations(client, integrations) { 4737 const integrationIndex = {}; 4738 integrations.forEach((integration) => { 4739 if (integration?.beforeSetup) integration.beforeSetup(client); 4740 }); 4741 integrations.forEach((integration) => { 4742 if (integration) setupIntegration(client, integration, integrationIndex); 4743 }); 4744 return integrationIndex; 4745} 4746function afterSetupIntegrations(client, integrations) { 4747 for (const integration of integrations) if (integration?.afterAllSetup) integration.afterAllSetup(client); 4748} 4749function setupIntegration(client, integration, integrationIndex) { 4750 if (integrationIndex[integration.name]) { 4751 DEBUG_BUILD$5 && debug$2.log(`Integration skipped because it was already installed: ${integration.name}`); 4752 return; 4753 } 4754 integrationIndex[integration.name] = integration; 4755 if (!installedIntegrations.includes(integration.name) && typeof integration.setupOnce === "function") { 4756 integration.setupOnce(); 4757 installedIntegrations.push(integration.name); 4758 } 4759 if (integration.setup && typeof integration.setup === "function") integration.setup(client); 4760 if (typeof integration.preprocessEvent === "function") { 4761 const callback = integration.preprocessEvent.bind(integration); 4762 client.on("preprocessEvent", (event, hint) => callback(event, hint, client)); 4763 } 4764 if (typeof integration.processEvent === "function") { 4765 const callback = integration.processEvent.bind(integration); 4766 const processor = Object.assign((event, hint) => callback(event, hint, client), { id: integration.name }); 4767 client.addEventProcessor(processor); 4768 } 4769 ["processSpan", "processSegmentSpan"].forEach((hook) => { 4770 const callback = integration[hook]; 4771 if (typeof callback === "function") client.on(hook, (span) => callback.call(integration, span, client)); 4772 }); 4773 DEBUG_BUILD$5 && debug$2.log(`Integration installed: ${integration.name}`); 4774} 4775function addIntegration(integration) { 4776 const client = getClient(); 4777 if (!client) { 4778 DEBUG_BUILD$5 && debug$2.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`); 4779 return; 4780 } 4781 client.addIntegration(integration); 4782} 4783function defineIntegration(fn) { 4784 return fn; 4785} 4786var installedIntegrations; 4787function init_integration() { 4788 return (init_integration = __esmMin((() => { 4789 init_currentScopes(); 4790 init_debug_build(); 4791 init_debug_logger(); 4792 installedIntegrations = []; 4793 })))(); 4794} 4795//#endregion 4796//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/timestampSequence.js 4797function getSequenceAttribute(timestampInSeconds) { 4798 const nowMs = Math.floor(timestampInSeconds * 1e3); 4799 if (_previousTimestampMs !== void 0 && nowMs !== _previousTimestampMs) _sequenceNumber = 0; 4800 const value = _sequenceNumber; 4801 _sequenceNumber++; 4802 _previousTimestampMs = nowMs; 4803 return { 4804 key: SEQUENCE_ATTR_KEY, 4805 value: { 4806 value, 4807 type: "integer" 4808 } 4809 }; 4810} 4811var SEQUENCE_ATTR_KEY, _sequenceNumber, _previousTimestampMs; 4812function init_timestampSequence() { 4813 return (init_timestampSequence = __esmMin((() => { 4814 SEQUENCE_ATTR_KEY = "sentry.timestamp.sequence"; 4815 _sequenceNumber = 0; 4816 })))(); 4817} 4818//#endregion 4819//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/trace-info.js 4820function _getTraceInfoFromScope(client, scope) { 4821 if (!scope) return [void 0, void 0]; 4822 return withScope(scope, () => { 4823 const span = getActiveSpan(); 4824 const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope); 4825 return [span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope), traceContext]; 4826 }); 4827} 4828function init_trace_info() { 4829 return (init_trace_info = __esmMin((() => { 4830 init_currentScopes(); 4831 init_dynamicSamplingContext(); 4832 init_spanUtils(); 4833 })))(); 4834} 4835//#endregion 4836//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/constants.js 4837var SEVERITY_TEXT_TO_SEVERITY_NUMBER; 4838function init_constants$1() { 4839 return (init_constants$1 = __esmMin((() => { 4840 SEVERITY_TEXT_TO_SEVERITY_NUMBER = { 4841 trace: 1, 4842 debug: 5, 4843 info: 9, 4844 warn: 13, 4845 error: 17, 4846 fatal: 21 4847 }; 4848 })))(); 4849} 4850//#endregion 4851//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/env.js
4852function isBrowserBundle() { 4853 return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__; 4854} 4855function getSDKSource() { 4856 /*! __SENTRY_SDK_SOURCE__ */ 4857 return "npm"; 4858} 4859//#endregion 4860//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/node.js 4861function isNodeEnv() { 4862 return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; 4863} 4864function init_node() { 4865 return (init_node = __esmMin((() => {})))(); 4866} 4867//#endregion 4868//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/isBrowser.js 4869function isBrowser() { 4870 return typeof window !== "undefined" && (!isNodeEnv() || isElectronNodeRenderer()); 4871} 4872function isElectronNodeRenderer() { 4873 return GLOBAL_OBJ.process?.type === "renderer"; 4874} 4875function init_isBrowser() { 4876 return (init_isBrowser = __esmMin((() => { 4877 init_node(); 4878 init_worldwide(); 4879 })))(); 4880} 4881//#endregion 4882//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/envelope.js 4883function createLogContainerEnvelopeItem(items, inferUserData) { 4884 const inferSetting = inferUserData ? "auto" : "never"; 4885 return [{ 4886 type: "log", 4887 item_count: items.length, 4888 content_type: "application/vnd.sentry.items.log+json" 4889 }, { 4890 version: 2, 4891 ...isBrowser() && { ingest_settings: { 4892 infer_ip: inferSetting, 4893 infer_user_agent: inferSetting 4894 } }, 4895 items 4896 }]; 4897} 4898function createLogEnvelope(logs, metadata, tunnel, dsn, inferUserData) { 4899 const headers = {}; 4900 if (metadata?.sdk) headers.sdk = { 4901 name: metadata.sdk.name, 4902 version: metadata.sdk.version 4903 }; 4904 if (!!tunnel && !!dsn) headers.dsn = dsnToString(dsn); 4905 return createEnvelope(headers, [createLogContainerEnvelopeItem(logs, inferUserData)]); 4906} 4907function init_envelope$2() { 4908 return (init_envelope$2 = __esmMin((() => { 4909 init_dsn(); 4910 init_envelope(); 4911 init_isBrowser(); 4912 })))(); 4913} 4914//#endregion 4915//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/internal.js 4916function setLogAttribute(logAttributes, key, value, setEvenIfPresent = true) { 4917 if (value && (!logAttributes[key] || setEvenIfPresent)) logAttributes[key] = value; 4918} 4919function _INTERNAL_captureSerializedLog(client, serializedLog) { 4920 const bufferMap = _getBufferMap$1(); 4921 const logBuffer = _INTERNAL_getLogBuffer(client); 4922 if (logBuffer === void 0) bufferMap.set(client, [serializedLog]); 4923 else if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) { 4924 _INTERNAL_flushLogsBuffer(client, logBuffer); 4925 bufferMap.set(client, [serializedLog]); 4926 } else bufferMap.set(client, [...logBuffer, serializedLog]); 4927} 4928function _INTERNAL_captureLog(beforeLog, currentScope = getCurrentScope(), captureSerializedLog = _INTERNAL_captureSerializedLog) { 4929 const client = currentScope?.getClient() ?? getClient(); 4930 if (!client) { 4931 DEBUG_BUILD$5 && debug$2.warn("No client available to capture log."); 4932 return; 4933 } 4934 const { release, environment, enableLogs = true, beforeSendLog } = client.getOptions(); 4935 if (!enableLogs) { 4936 DEBUG_BUILD$5 && debug$2.warn("logging option not enabled, log will not be captured."); 4937 return; 4938 } 4939 const [, traceContext] = _getTraceInfoFromScope(client, currentScope); 4940 const processedLogAttributes = { ...beforeLog.attributes }; 4941 const { user: { id, email, username }, attributes: scopeAttributes = {} } = getCombinedScopeData(getIsolationScope(), currentScope); 4942 setLogAttribute(processedLogAttributes, "user.id", id, false); 4943 setLogAttribute(processedLogAttributes, "user.email", email, false); 4944 setLogAttribute(processedLogAttributes, "user.name", username, false); 4945 setLogAttribute(processedLogAttributes, "sentry.release", release); 4946 setLogAttribute(processedLogAttributes, "sentry.environment", environment); 4947 const { name, version } = client.getSdkMetadata()?.sdk ?? {}; 4948 setLogAttribute(processedLogAttributes, "sentry.sdk.name", name); 4949 setLogAttribute(processedLogAttributes, "sentry.sdk.version", version); 4950 const replay = client.getIntegrationByName("Replay"); 4951 const replayId = replay?.getReplayId(true); 4952 setLogAttribute(processedLogAttributes, "sentry.replay_id", replayId); 4953 if (replayId && replay?.getRecordingMode() === "buffer") setLogAttribute(processedLogAttributes, "sentry._internal.replay_is_buffering", true); 4954 const beforeLogMessage = beforeLog.message; 4955 if (isParameterizedString(beforeLogMessage)) {
4956 const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage; 4957 if (__sentry_template_values__?.length) processedLogAttributes["sentry.message.template"] = __sentry_template_string__; 4958 __sentry_template_values__.forEach((param, index) => { 4959 processedLogAttributes[`sentry.message.parameter.${index}`] = param; 4960 }); 4961 } 4962 setLogAttribute(processedLogAttributes, "sentry.trace.parent_span_id", _getSpanForScope(currentScope)?.spanContext().spanId); 4963 const processedLog = { 4964 ...beforeLog, 4965 attributes: processedLogAttributes 4966 }; 4967 client.emit("beforeCaptureLog", processedLog); 4968 const log = beforeSendLog ? consoleSandbox(() => beforeSendLog(processedLog)) : processedLog; 4969 if (!log) { 4970 client.recordDroppedEvent("before_send", "log_item", 1); 4971 DEBUG_BUILD$5 && debug$2.warn("beforeSendLog returned null, log will not be captured."); 4972 return; 4973 } 4974 const { level, message, attributes: logAttributes = {}, severityNumber } = log; 4975 const timestamp = timestampInSeconds(); 4976 const sequenceAttr = getSequenceAttribute(timestamp); 4977 captureSerializedLog(client, { 4978 timestamp, 4979 level, 4980 body: _removeLoneSurrogates(String(message)), 4981 trace_id: traceContext?.trace_id, 4982 severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level], 4983 attributes: sanitizeLogAttributes({ 4984 ...serializeAttributes(scopeAttributes), 4985 ...serializeAttributes(logAttributes, true), 4986 [sequenceAttr.key]: sequenceAttr.value 4987 }) 4988 }); 4989 client.emit("afterCaptureLog", log); 4990} 4991function _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) { 4992 const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? []; 4993 if (logBuffer.length === 0) return; 4994 const clientOptions = client.getOptions(); 4995 const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo); 4996 _getBufferMap$1().set(client, []); 4997 client.emit("flushLogs"); 4998 client.sendEnvelope(envelope); 4999} 5000function _INTERNAL_getLogBuffer(client) { 5001 return _getBufferMap$1().get(client); 5002} 5003function _getBufferMap$1() { 5004 return getGlobalSingleton("clientToLogBufferMap", () => /* @__PURE__ */ new WeakMap()); 5005} 5006function sanitizeLogAttributes(attributes) { 5007 const sanitized = {}; 5008 for (const [key, attr] of Object.entries(attributes)) { 5009 const sanitizedKey = _removeLoneSurrogates(key); 5010 if (attr.type === "string") sanitized[sanitizedKey] = { 5011 ...attr, 5012 value: _removeLoneSurrogates(attr.value) 5013 }; 5014 else sanitized[sanitizedKey] = attr; 5015 } 5016 return sanitized; 5017} 5018function _removeLoneSurrogates(str) { 5019 const strObj = Object(str); 5020 const isWellFormed = strObj["isWellFormed"]; 5021 const toWellFormed = strObj["toWellFormed"]; 5022 if (typeof isWellFormed === "function" && typeof toWellFormed === "function") return isWellFormed.call(str) ? str : toWellFormed.call(str); 5023 return str; 5024} 5025var MAX_LOG_BUFFER_SIZE; 5026function init_internal() { 5027 return (init_internal = __esmMin((() => { 5028 init_attributes(); 5029 init_carrier(); 5030 init_currentScopes(); 5031 init_debug_build(); 5032 init_debug_logger(); 5033 init_is(); 5034 init_scopeData(); 5035 init_spanOnScope(); 5036 init_time(); 5037 init_timestampSequence(); 5038 init_trace_info(); 5039 init_constants$1(); 5040 init_envelope$2(); 5041 MAX_LOG_BUFFER_SIZE = 100; 5042 })))(); 5043} 5044//#endregion 5045//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/metrics/envelope.js 5046function createMetricContainerEnvelopeItem(items, inferUserData) { 5047 const inferSetting = inferUserData ? "auto" : "never"; 5048 return [{ 5049 type: "trace_metric", 5050 item_count: items.length, 5051 content_type: "application/vnd.sentry.items.trace-metric+json" 5052 }, { 5053 version: 2, 5054 ...isBrowser() && { ingest_settings: { 5055 infer_ip: inferSetting, 5056 infer_user_agent: inferSetting 5057 } }, 5058 items 5059 }]; 5060} 5061function createMetricEnvelope(metrics, metadata, tunnel, dsn, inferUserData) { 5062 const headers = {}; 5063 if (metadata?.sdk) headers.sdk = { 5064 name: metadata.sdk.name, 5065 version: metadata.sdk.version 5066 }; 5067 if (!!tunnel && !!dsn) headers.dsn = dsnToString(dsn); 5068 return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics, inferUserData)]); 5069} 5070function init_envelope$3() { 5071 return (init_envelope$3 = __esmMin((() => { 5072 init_dsn(); 5073 init_envelope(); 5074 init_isBrowser(); 5075 })))(); 5076} 5077//#endregion 5078//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/metrics/internal.js 5079function setMetricAttribute(metricAttributes, key, value, setEvenIfPresent = true) { 5080 if (value && (setEvenIfPresent || !(key in metricAttributes))) metricAttributes[key] = value; 5081} 5082function _INTERNAL_captureSerializedMetric(client, serializedMetric) { 5083 const bufferMap = _getBufferMap(); 5084 const metricBuffer = _INTERNAL_getMetricBuffer(client); 5085 if (metricBuffer === void 0) bufferMap.set(client, [serializedMetric]); 5086 else if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) { 5087 _INTERNAL_flushMetricsBuffer(client, metricBuffer); 5088 bufferMap.set(client, [serializedMetric]); 5089 } else bufferMap.set(client, [...metricBuffer, serializedMetric]); 5090} 5091function _enrichMetricAttributes(beforeMetric, client, user) { 5092 const { release, environment } = client.getOptions(); 5093 const processedMetricAttributes = { ...beforeMetric.attributes }; 5094 setMetricAttribute(processedMetricAttributes, "user.id", user.id, false); 5095 setMetricAttribute(processedMetricAttributes, "user.email", user.email, false); 5096 setMetricAttribute(processedMetricAttributes, "user.name", user.username, false); 5097 setMetricAttribute(processedMetricAttributes, "sentry.release", release); 5098 setMetricAttribute(processedMetricAttributes, "sentry.environment", environment); 5099 const { name, version } = client.getSdkMetadata()?.sdk ?? {}; 5100 setMetricAttribute(processedMetricAttributes, "sentry.sdk.name", name); 5101 setMetricAttribute(processedMetricAttributes, "sentry.sdk.version", version); 5102 const replay = client.getIntegrationByName("Replay"); 5103 const replayId = replay?.getReplayId(true); 5104 setMetricAttribute(processedMetricAttributes, "sentry.replay_id", replayId); 5105 if (replayId && replay?.getRecordingMode() === "buffer") setMetricAttribute(processedMetricAttributes, "sentry._internal.replay_is_buffering", true); 5106 return { 5107 ...beforeMetric, 5108 attributes: processedMetricAttributes 5109 }; 5110} 5111function _buildSerializedMetric(metric, client, currentScope, scopeAttributes) { 5112 const [, traceContext] = _getTraceInfoFromScope(client, currentScope); 5113 const span = _getSpanForScope(currentScope); 5114 const traceId = span ? span.spanContext().traceId : traceContext?.trace_id; 5115 const spanId = span ? span.spanContext().spanId : void 0; 5116 const timestamp = timestampInSeconds(); 5117 const sequenceAttr = getSequenceAttribute(timestamp); 5118 return { 5119 timestamp, 5120 trace_id: traceId ?? "", 5121 span_id: spanId, 5122 name: metric.name, 5123 type: metric.type, 5124 unit: metric.unit, 5125 value: metric.value, 5126 attributes: { 5127 ...serializeAttributes(scopeAttributes), 5128 ...serializeAttributes(metric.attributes, "skip-undefined"), 5129 [sequenceAttr.key]: sequenceAttr.value 5130 } 5131 }; 5132} 5133function _INTERNAL_captureMetric(beforeMetric, options) { 5134 const currentScope = options?.scope ?? getCurrentScope(); 5135 const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric; 5136 const client = currentScope?.getClient() ?? getClient(); 5137 if (!client) { 5138 DEBUG_BUILD$5 && debug$2.warn("No client available to capture metric."); 5139 return; 5140 } 5141 const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions(); 5142 if (!(enableMetrics ?? _experiments?.enableMetrics ?? true)) { 5143 DEBUG_BUILD$5 && debug$2.warn("metrics option not enabled, metric will not be captured."); 5144 return; 5145 } 5146 const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope); 5147 const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user); 5148 client.emit("processMetric", enrichedMetric); 5149 const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric; 5150 const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric; 5151 if (!processedMetric) { 5152 DEBUG_BUILD$5 && debug$2.log("`beforeSendMetric` returned `null`, will not send metric."); 5153 return; 5154 } 5155 const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes); 5156 DEBUG_BUILD$5 && debug$2.log("[Metric]", serializedMetric); 5157 captureSerializedMetric(client, serializedMetric); 5158 client.emit("afterCaptureMetric", processedMetric); 5159} 5160function _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) { 5161 const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? []; 5162 if (metricBuffer.length === 0) return; 5163 const clientOptions = client.getOptions(); 5164 const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo); 5165 _getBufferMap().set(client, []); 5166 client.emit("flushMetrics"); 5167 client.sendEnvelope(envelope); 5168} 5169function _INTERNAL_getMetricBuffer(client) { 5170 return _getBufferMap().get(client); 5171} 5172function _getBufferMap() { 5173 return getGlobalSingleton("clientToMetricBufferMap", () => /* @__PURE__ */ new WeakMap()); 5174} 5175var MAX_METRIC_BUFFER_SIZE; 5176function init_internal$1() { 5177 return (init_internal$1 = __esmMin((() => { 5178 init_attributes(); 5179 init_carrier(); 5180 init_currentScopes(); 5181 init_debug_build(); 5182 init_debug_logger(); 5183 init_scopeData(); 5184 init_spanOnScope(); 5185 init_time(); 5186 init_timestampSequence(); 5187 init_trace_info(); 5188 init_envelope$3(); 5189 MAX_METRIC_BUFFER_SIZE = 1e3; 5190 })))(); 5191} 5192//#endregion 5193//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/spanJsonToStreamedSpan.js 5194function spanJsonToSerializedStreamedSpan(span) { 5195 return streamedSpanJsonToSerializedSpan({ 5196 trace_id: span.trace_id, 5197 span_id: span.span_id, 5198 parent_span_id: span.parent_span_id, 5199 name: span.description || "", 5200 start_timestamp: span.start_timestamp, 5201 end_timestamp: span.timestamp || span.start_timestamp, 5202 status: !span.status || span.status === "ok" || span.status === "cancelled" ? "ok" : "error", 5203 is_segment: false, 5204 attributes: { ...span.data }, 5205 links: span.links 5206 }); 5207} 5208function init_spanJsonToStreamedSpan() { 5209 return (init_spanJsonToStreamedSpan = __esmMin((() => { 5210 init_spanUtils(); 5211 })))(); 5212} 5213//#endregion 5214//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/extractGenAiSpans.js 5215function extractGenAiSpansFromEvent(event, client) { 5216 if (event.type !== "transaction" || !event.spans?.length || !event.sdkProcessingMetadata?.hasGenAiSpans || client.getOptions().streamGenAiSpans === false || hasSpanStreamingEnabled(client)) return; 5217 const genAiSpans = []; 5218 const remainingSpans = []; 5219 for (const span of event.spans) if (span.op?.startsWith("gen_ai.")) genAiSpans.push(spanJsonToSerializedStreamedSpan(span)); 5220 else remainingSpans.push(span); 5221 if (genAiSpans.length === 0) return; 5222 event.spans = remainingSpans; 5223 const inferSetting = client.getDataCollectionOptions().userInfo ? "auto" : "never"; 5224 return [{ 5225 type: "span", 5226 item_count: genAiSpans.length, 5227 content_type: "application/vnd.sentry.items.span.v2+json" 5228 }, { 5229 version: 2, 5230 ...isBrowser() && { ingest_settings: { 5231 infer_ip: inferSetting, 5232 infer_user_agent: inferSetting 5233 } }, 5234 items: genAiSpans 5235 }]; 5236} 5237function init_extractGenAiSpans() { 5238 return (init_extractGenAiSpans = __esmMin((() => { 5239 init_isBrowser(); 5240 init_spanJsonToStreamedSpan(); 5241 })))(); 5242} 5243//#endregion 5244//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/promisebuffer.js 5245function makePromiseBuffer(limit = 100) { 5246 const buffer = /* @__PURE__ */ new Set(); 5247 function isReady() { 5248 return buffer.size < limit; 5249 } 5250 function remove(task) { 5251 buffer.delete(task); 5252 } 5253 function add(taskProducer) { 5254 if (!isReady()) return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR); 5255 const task = taskProducer(); 5256 buffer.add(task); 5257 task.then(() => remove(task), () => remove(task)); 5258 return task; 5259 } 5260 function drain(timeout) { 5261 if (!buffer.size) return resolvedSyncPromise(true); 5262 const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true); 5263 if (!timeout) return drainPromise; 5264 const promises = [drainPromise, new Promise((resolve) => safeUnref(setTimeout(() => resolve(false), timeout)))]; 5265 return Promise.race(promises); 5266 } 5267 return { 5268 get $() { 5269 return Array.from(buffer); 5270 }, 5271 add, 5272 drain 5273 }; 5274} 5275var SENTRY_BUFFER_FULL_ERROR; 5276function init_promisebuffer() { 5277 return (init_promisebuffer = __esmMin((() => { 5278 init_syncpromise(); 5279 SENTRY_BUFFER_FULL_ERROR = /* @__PURE__ */ Symbol.for("SentryBufferFullError"); 5280 })))(); 5281} 5282//#endregion 5283//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/ratelimit.js 5284function parseRetryAfterHeader(header, now = safeDateNow()) { 5285 const headerDelay = parseInt(`${header}`, 10); 5286 if (!isNaN(headerDelay)) return headerDelay * 1e3; 5287 const headerDate = Date.parse(`${header}`); 5288 if (!isNaN(headerDate)) return headerDate - now; 5289 return DEFAULT_RETRY_AFTER; 5290} 5291function disabledUntil(limits, dataCategory) { 5292 return limits[dataCategory] || limits.all || 0; 5293} 5294function isRateLimited(limits, dataCategory, now = safeDateNow()) { 5295 return disabledUntil(limits, dataCategory) > now; 5296} 5297function updateRateLimits(limits, { statusCode, headers }, now = safeDateNow()) { 5298 const updatedRateLimits = { ...limits }; 5299 const rateLimitHeader = headers?.["x-sentry-rate-limits"]; 5300 const retryAfterHeader = headers?.["retry-after"]; 5301 if (rateLimitHeader) for (const limit of rateLimitHeader.trim().split(",")) { 5302 const [retryAfter, categories, , , namespaces] = limit.split(":", 5); 5303 const headerDelay = parseInt(retryAfter, 10);
5304 const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3; 5305 if (!categories) updatedRateLimits.all = now + delay; 5306 else for (const category of categories.split(";")) if (category === "metric_bucket") { 5307 if (!namespaces || namespaces.split(";").includes("custom")) updatedRateLimits[category] = now + delay; 5308 } else updatedRateLimits[category] = now + delay; 5309 } 5310 else if (retryAfterHeader) updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); 5311 else if (statusCode === 429) updatedRateLimits.all = now + 6e4; 5312 return updatedRateLimits; 5313} 5314var DEFAULT_RETRY_AFTER; 5315function init_ratelimit() { 5316 return (init_ratelimit = __esmMin((() => { 5317 init_randomSafeContext(); 5318 DEFAULT_RETRY_AFTER = 6e4; 5319 })))(); 5320} 5321//#endregion 5322//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/transports/base.js 5323function createTransport(options, makeRequest, buffer = makePromiseBuffer(options.bufferSize || 64)) { 5324 let rateLimits = {}; 5325 const flush = (timeout) => buffer.drain(timeout); 5326 function send(envelope) { 5327 const filteredEnvelopeItems = []; 5328 forEachEnvelopeItem(envelope, (item, type) => { 5329 const dataCategory = envelopeItemTypeToDataCategory(type); 5330 if (isRateLimited(rateLimits, dataCategory)) options.recordDroppedEvent("ratelimit_backoff", dataCategory); 5331 else filteredEnvelopeItems.push(item); 5332 }); 5333 if (filteredEnvelopeItems.length === 0) return Promise.resolve({}); 5334 const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems); 5335 const recordEnvelopeLoss = (reason) => { 5336 if (envelopeContainsItemType(filteredEnvelope, ["client_report"])) { 5337 DEBUG_BUILD$5 && debug$2.warn(`Dropping client report. Will not send outcomes (reason: ${reason}).`); 5338 return; 5339 } 5340 forEachEnvelopeItem(filteredEnvelope, (item, type) => { 5341 options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type)); 5342 }); 5343 }; 5344 const requestTask = () => makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then((response) => { 5345 if (response.statusCode === 413) { 5346 DEBUG_BUILD$5 && debug$2.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."); 5347 recordEnvelopeLoss("send_error"); 5348 return response; 5349 } 5350 if (DEBUG_BUILD$5 && response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) debug$2.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); 5351 rateLimits = updateRateLimits(rateLimits, response); 5352 return response; 5353 }, (error) => { 5354 recordEnvelopeLoss("network_error"); 5355 DEBUG_BUILD$5 && debug$2.error("Encountered error running transport request:", error); 5356 throw error; 5357 }); 5358 return buffer.add(requestTask).then((result) => result, (error) => { 5359 if (error === SENTRY_BUFFER_FULL_ERROR) { 5360 DEBUG_BUILD$5 && debug$2.error("Skipped sending event because buffer is full."); 5361 recordEnvelopeLoss("queue_overflow"); 5362 return Promise.resolve({}); 5363 } else throw error; 5364 }); 5365 } 5366 return { 5367 send, 5368 flush 5369 }; 5370} 5371function init_base() { 5372 return (init_base = __esmMin((() => { 5373 init_debug_build(); 5374 init_debug_logger(); 5375 init_envelope(); 5376 init_promisebuffer(); 5377 init_ratelimit(); 5378 })))(); 5379} 5380//#endregion 5381//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/clientreport.js 5382function createClientReportEnvelope(discarded_events, dsn, timestamp) { 5383 const clientReportItem = [{ type: "client_report" }, { 5384 timestamp: timestamp || dateTimestampInSeconds(), 5385 discarded_events 5386 }]; 5387 return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); 5388} 5389function init_clientreport() { 5390 return (init_clientreport = __esmMin((() => { 5391 init_envelope(); 5392 init_time(); 5393 })))(); 5394} 5395//#endregion 5396//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/eventUtils.js 5397function getPossibleEventMessages(event) { 5398 const possibleMessages = []; 5399 if (event.message) possibleMessages.push(event.message); 5400 try { 5401 const lastException = event.exception.values[event.exception.values.length - 1]; 5402 if (lastException?.value) {
5403 possibleMessages.push(lastException.value); 5404 if (lastException.type) possibleMessages.push(`${lastException.type}: ${lastException.value}`); 5405 } 5406 } catch {} 5407 return possibleMessages; 5408} 5409//#endregion 5410//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/transactionEvent.js 5411function convertTransactionEventToSpanJson(event) { 5412 const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {}; 5413 return { 5414 data: data ?? {}, 5415 description: event.transaction, 5416 op, 5417 parent_span_id, 5418 span_id: span_id ?? "", 5419 start_timestamp: event.start_timestamp ?? 0, 5420 status, 5421 timestamp: event.timestamp, 5422 trace_id: trace_id ?? "", 5423 origin, 5424 profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID], 5425 exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME], 5426 measurements: event.measurements, 5427 is_segment: true 5428 }; 5429} 5430function convertSpanJsonToTransactionEvent(span) { 5431 return { 5432 type: "transaction", 5433 timestamp: span.timestamp, 5434 start_timestamp: span.start_timestamp, 5435 transaction: span.description, 5436 contexts: { trace: { 5437 trace_id: span.trace_id, 5438 span_id: span.span_id, 5439 parent_span_id: span.parent_span_id, 5440 op: span.op, 5441 status: span.status, 5442 origin: span.origin, 5443 data: { 5444 ...span.data, 5445 ...span.profile_id && { ["sentry.profile_id"]: span.profile_id }, 5446 ...span.exclusive_time && { ["sentry.exclusive_time"]: span.exclusive_time } 5447 } 5448 } }, 5449 measurements: span.measurements 5450 }; 5451} 5452function init_transactionEvent() { 5453 return (init_transactionEvent = __esmMin((() => { 5454 init_semanticAttributes(); 5455 })))(); 5456} 5457//#endregion 5458//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/data-collection/filtering-snippets.js 5459var FILTERED_VALUE, PII_HEADER_SNIPPETS, SENSITIVE_KEY_SNIPPETS, SENSITIVE_COOKIE_NAME_SNIPPETS; 5460function init_filtering_snippets() { 5461 return (init_filtering_snippets = __esmMin((() => { 5462 FILTERED_VALUE = "[Filtered]"; 5463 PII_HEADER_SNIPPETS = [ 5464 "forwarded", 5465 "-ip", 5466 "remote-", 5467 "via", 5468 "-user" 5469 ]; 5470 SENSITIVE_KEY_SNIPPETS = [ 5471 "auth", 5472 "token", 5473 "secret", 5474 "session", 5475 "password", 5476 "passwd", 5477 "pwd", 5478 "key", 5479 "jwt", 5480 "bearer", 5481 "sso", 5482 "saml", 5483 "csrf", 5484 "xsrf", 5485 "credentials", 5486 "sid", 5487 "identity", 5488 "set-cookie", 5489 "cookie" 5490 ]; 5491 SENSITIVE_COOKIE_NAME_SNIPPETS = [ 5492 ".sid", 5493 "sessid", 5494 "remember", 5495 "oidc", 5496 "pkce", 5497 "nonce", 5498 "__secure-", 5499 "__host-", 5500 "awsalb", 5501 "awselb", 5502 "akamai", 5503 "__stripe", 5504 "cognito", 5505 "firebase", 5506 "supabase", 5507 "sb-", 5508 "mfa", 5509 "2fa" 5510 ]; 5511 })))(); 5512} 5513//#endregion 5514//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/data-collection/defaultPiiToCollectionOptions.js 5515function defaultPiiToCollectionOptions(sendDefaultPii) { 5516 return sendDefaultPii === true ? { 5517 userInfo: true, 5518 cookies: true, 5519 httpHeaders: { 5520 request: true, 5521 response: true 5522 }, 5523 httpBodies: [ 5524 "incomingRequest", 5525 "outgoingRequest", 5526 "incomingResponse", 5527 "outgoingResponse" 5528 ], 5529 urlQueryParams: true, 5530 graphQL: { 5531 document: true, 5532 variables: true 5533 }, 5534 genAI: { 5535 inputs: true, 5536 outputs: true 5537 }, 5538 databaseQueryData: true, 5539 stackFrameVariables: true, 5540 frameContextLines: 7 5541 } : { 5542 userInfo: false, 5543 cookies: { deny: PII_HEADER_SNIPPETS }, 5544 httpHeaders: { 5545 request: { deny: PII_HEADER_SNIPPETS }, 5546 response: { deny: PII_HEADER_SNIPPETS } 5547 }, 5548 httpBodies: [], 5549 urlQueryParams: { deny: PII_HEADER_SNIPPETS }, 5550 graphQL: { 5551 document: true, 5552 variables: true 5553 }, 5554 genAI: { 5555 inputs: false, 5556 outputs: false 5557 }, 5558 databaseQueryData: false, 5559 stackFrameVariables: true, 5560 frameContextLines: 7 5561 }; 5562} 5563function init_defaultPiiToCollectionOptions() { 5564 return (init_defaultPiiToCollectionOptions = __esmMin((() => { 5565 init_filtering_snippets(); 5566 })))(); 5567} 5568//#endregion 5569//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/data-collection/resolveDataCollectionOptions.js 5570function resolveDataCollectionOptions(options) { 5571 const base = options.dataCollection != null ? DEFAULTS : defaultPiiToCollectionOptions(options.sendDefaultPii); 5572 const dc = options.dataCollection ?? {}; 5573 return { 5574 userInfo: dc.userInfo ?? base.userInfo, 5575 cookies: dc.cookies ?? base.cookies, 5576 httpHeaders: { 5577 request: dc.httpHeaders?.request ?? base.httpHeaders.request, 5578 response: dc.httpHeaders?.response ?? base.httpHeaders.response 5579 }, 5580 httpBodies: dc.httpBodies ?? base.httpBodies, 5581 urlQueryParams: dc.urlQueryParams ?? dc.queryParams ?? base.urlQueryParams, 5582 graphQL: { 5583 document: dc.graphQL?.document ?? base.graphQL.document, 5584 variables: dc.graphQL?.variables ?? base.graphQL.variables 5585 }, 5586 genAI: { 5587 inputs: dc.genAI?.inputs ?? base.genAI.inputs, 5588 outputs: dc.genAI?.outputs ?? base.genAI.outputs 5589 }, 5590 databaseQueryData: dc.databaseQueryData ?? base.databaseQueryData,
5591 stackFrameVariables: dc.stackFrameVariables ?? base.stackFrameVariables, 5592 frameContextLines: dc.frameContextLines ?? base.frameContextLines 5593 }; 5594} 5595var DEFAULTS; 5596function init_resolveDataCollectionOptions() { 5597 return (init_resolveDataCollectionOptions = __esmMin((() => { 5598 init_defaultPiiToCollectionOptions(); 5599 DEFAULTS = { 5600 userInfo: true, 5601 cookies: true, 5602 httpHeaders: { 5603 request: true, 5604 response: true 5605 }, 5606 httpBodies: [ 5607 "incomingRequest", 5608 "outgoingRequest", 5609 "incomingResponse", 5610 "outgoingResponse" 5611 ], 5612 urlQueryParams: true, 5613 graphQL: { 5614 document: true, 5615 variables: true 5616 }, 5617 genAI: { 5618 inputs: true, 5619 outputs: true 5620 }, 5621 databaseQueryData: true, 5622 stackFrameVariables: true, 5623 frameContextLines: 5 5624 }; 5625 })))(); 5626} 5627//#endregion 5628//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/client.js 5629function _makeInternalError(message) { 5630 return { 5631 message, 5632 [INTERNAL_ERROR_SYMBOL]: true 5633 }; 5634} 5635function _makeDoNotSendEventError(message) { 5636 return { 5637 message, 5638 [DO_NOT_SEND_EVENT_SYMBOL]: true 5639 }; 5640} 5641function _isInternalError(error) { 5642 return isObjectLike(error) && INTERNAL_ERROR_SYMBOL in error; 5643} 5644function _isDoNotSendEventError(error) { 5645 return isObjectLike(error) && DO_NOT_SEND_EVENT_SYMBOL in error; 5646} 5647function setupWeightBasedFlushing(client, afterCaptureHook, flushHook, estimateSizeFn, flushFn) { 5648 let weight = 0; 5649 let flushTimeout; 5650 let isTimerActive = false; 5651 client.on(flushHook, () => { 5652 weight = 0; 5653 clearTimeout(flushTimeout); 5654 isTimerActive = false; 5655 }); 5656 client.on(afterCaptureHook, (item) => { 5657 weight += estimateSizeFn(item); 5658 if (weight >= 8e5) flushFn(client); 5659 else if (!isTimerActive) { 5660 const flushInterval = client.getOptions()._flushInterval ?? DEFAULT_FLUSH_INTERVAL; 5661 if (flushInterval > 0) { 5662 isTimerActive = true; 5663 flushTimeout = safeUnref(setTimeout(() => { 5664 flushFn(client); 5665 }, flushInterval)); 5666 } 5667 } 5668 }); 5669 client.on("flush", () => { 5670 flushFn(client); 5671 }); 5672} 5673function getDataCategoryByType(type) { 5674 return type === "replay_event" ? "replay" : type || "error"; 5675} 5676function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) { 5677 const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; 5678 if (isThenable(beforeSendResult)) return beforeSendResult.then((event) => { 5679 if (!isPlainObject(event) && event !== null) throw _makeInternalError(invalidValueError); 5680 return event; 5681 }, (e) => { 5682 throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`); 5683 }); 5684 else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) throw _makeInternalError(invalidValueError); 5685 return beforeSendResult; 5686} 5687function processBeforeSend(client, options, event, hint) { 5688 const { beforeSend, beforeSendTransaction, ignoreSpans } = options; 5689 const beforeSendSpan = !isStreamedBeforeSendSpanCallback(options.beforeSendSpan) && options.beforeSendSpan; 5690 let processedEvent = event; 5691 if (isErrorEvent$2(processedEvent) && beforeSend) return beforeSend(processedEvent, hint); 5692 if (isTransactionEvent$1(processedEvent)) { 5693 if (beforeSendSpan || ignoreSpans) { 5694 const rootSpanJson = convertTransactionEventToSpanJson(processedEvent); 5695 if (ignoreSpans?.length && shouldIgnoreSpan({ 5696 description: rootSpanJson.description, 5697 op: rootSpanJson.op, 5698 attributes: rootSpanJson.data 5699 }, ignoreSpans)) return null; 5700 if (beforeSendSpan) { 5701 const processedRootSpanJson = beforeSendSpan(rootSpanJson); 5702 if (!processedRootSpanJson) showSpanDropWarning(); 5703 else processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson)); 5704 } 5705 if (processedEvent.spans) { 5706 const processedSpans = []; 5707 const initialSpans = processedEvent.spans; 5708 for (const span of initialSpans) { 5709 if (ignoreSpans?.length && shouldIgnoreSpan({ 5710 description: span.description, 5711 op: span.op, 5712 attributes: span.data 5713 }, ignoreSpans)) { 5714 reparentChildSpans(initialSpans, span); 5715 continue; 5716 } 5717 if (beforeSendSpan) { 5718 const processedSpan = beforeSendSpan(span); 5719 if (!processedSpan) { 5720 showSpanDropWarning(); 5721 processedSpans.push(span); 5722 } else processedSpans.push(processedSpan); 5723 } else processedSpans.push(span); 5724 } 5725 const droppedSpans = processedEvent.spans.length - processedSpans.length;
5726 if (droppedSpans) client.recordDroppedEvent("before_send", "span", droppedSpans); 5727 processedEvent.spans = processedSpans; 5728 } 5729 } 5730 if (beforeSendTransaction) { 5731 if (processedEvent.spans) { 5732 const spanCountBefore = processedEvent.spans.length; 5733 processedEvent.sdkProcessingMetadata = { 5734 ...event.sdkProcessingMetadata, 5735 spanCountBeforeProcessing: spanCountBefore 5736 }; 5737 } 5738 return beforeSendTransaction(processedEvent, hint); 5739 } 5740 } 5741 return processedEvent; 5742} 5743function isErrorEvent$2(event) { 5744 return event.type === void 0; 5745} 5746function isTransactionEvent$1(event) { 5747 return event.type === "transaction"; 5748} 5749function estimateMetricSizeInBytes(metric) { 5750 let weight = 0; 5751 if (metric.name) weight += metric.name.length * 2; 5752 weight += 8; 5753 return weight + estimateAttributesSizeInBytes(metric.attributes); 5754} 5755function estimateLogSizeInBytes(log) { 5756 let weight = 0; 5757 if (log.message) weight += log.message.length * 2; 5758 return weight + estimateAttributesSizeInBytes(log.attributes); 5759} 5760function estimateAttributesSizeInBytes(attributes) { 5761 if (!attributes) return 0; 5762 let weight = 0; 5763 Object.values(attributes).forEach((value) => { 5764 if (Array.isArray(value)) weight += value.length * estimatePrimitiveSizeInBytes(value[0]); 5765 else if (isPrimitive(value)) weight += estimatePrimitiveSizeInBytes(value); 5766 else weight += 100; 5767 }); 5768 return weight; 5769} 5770function estimatePrimitiveSizeInBytes(value) { 5771 if (typeof value === "string") return value.length * 2; 5772 else if (typeof value === "number") return 8; 5773 else if (typeof value === "boolean") return 4; 5774 return 0; 5775} 5776var ALREADY_SEEN_ERROR, MISSING_RELEASE_FOR_SESSION_ERROR, INTERNAL_ERROR_SYMBOL, DO_NOT_SEND_EVENT_SYMBOL, DEFAULT_FLUSH_INTERVAL, Client; 5777function init_client() { 5778 return (init_client = __esmMin((() => { 5779 init_api(); 5780 init_constants(); 5781 init_currentScopes(); 5782 init_debug_build(); 5783 init_envelope$1(); 5784 init_integration(); 5785 init_internal(); 5786 init_internal$1(); 5787 init_session(); 5788 init_dynamicSamplingContext(); 5789 init_beforeSendSpan(); 5790 init_extractGenAiSpans(); 5791 init_base(); 5792 init_clientreport(); 5793 init_debug_logger(); 5794 init_dsn(); 5795 init_envelope(); 5796 init_is(); 5797 init_misc(); 5798 init_prepareEvent(); 5799 init_promisebuffer(); 5800 init_randomSafeContext(); 5801 init_should_ignore_span(); 5802 init_spanUtils(); 5803 init_transactionEvent(); 5804 init_resolveDataCollectionOptions(); 5805 ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; 5806 MISSING_RELEASE_FOR_SESSION_ERROR = "Discarded session because of missing or non-string release"; 5807 INTERNAL_ERROR_SYMBOL = /* @__PURE__ */ Symbol.for("SentryInternalError"); 5808 DO_NOT_SEND_EVENT_SYMBOL = /* @__PURE__ */ Symbol.for("SentryDoNotSendEventError"); 5809 DEFAULT_FLUSH_INTERVAL = 5e3; 5810 Client = class { 5811 /** 5812 * Initializes this client instance. 5813 * 5814 * @param options Options for the client. 5815 */ 5816 constructor(options) { 5817 this._options = options; 5818 this._integrations = {}; 5819 this._numProcessing = 0; 5820 this._outcomes = {}; 5821 this._hooks = {}; 5822 this._eventProcessors = []; 5823 this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? 64); 5824 this._dataCollection = resolveDataCollectionOptions(options); 5825 if (options.dsn) this._dsn = makeDsn(options.dsn); 5826 else DEBUG_BUILD$5 && debug$2.warn("No DSN provided, client will not send events."); 5827 if (this._dsn) { 5828 const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options.tunnel, options._metadata ? options._metadata.sdk : void 0); 5829 this._transport = options.transport({ 5830 tunnel: this._options.tunnel, 5831 recordDroppedEvent: this.recordDroppedEvent.bind(this), 5832 ...options.transportOptions, 5833 url 5834 }); 5835 } 5836 this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs ?? true; 5837 if (this._options.enableLogs) setupWeightBasedFlushing(this, "afterCaptureLog", "flushLogs", estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer); 5838 if (this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true) setupWeightBasedFlushing(this, "afterCaptureMetric", "flushMetrics", estimateMetricSizeInBytes, _INTERNAL_flushMetricsBuffer); 5839 } 5840 /** 5841 * Captures an exception event and sends it to Sentry. 5842 * 5843 * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope. 5844 */ 5845 captureException(exception, hint, scope) { 5846 const eventId = uuid4(); 5847 if (checkOrSetAlreadyCaught(exception)) {
vendor: 4,336 bytes, lines 5848-5961
5848 DEBUG_BUILD$5 && debug$2.log(ALREADY_SEEN_ERROR); 5849 return eventId; 5850 } 5851 const hintWithEventId = { 5852 event_id: eventId, 5853 ...hint 5854 }; 5855 this._process(() => this.eventFromException(exception, hintWithEventId).then((event) => this._captureEvent(event, hintWithEventId, scope)).then((res) => res), "error"); 5856 return hintWithEventId.event_id; 5857 } 5858 /** 5859 * Captures a message event and sends it to Sentry. 5860 * 5861 * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope. 5862 */ 5863 captureMessage(message, level, hint, currentScope) { 5864 const hintWithEventId = { 5865 event_id: uuid4(), 5866 ...hint 5867 }; 5868 const eventMessage = isParameterizedString(message) ? message : String(message); 5869 const isMessage = isPrimitive(message); 5870 const promisedEvent = isMessage ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, hintWithEventId); 5871 this._process(() => promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope)), isMessage ? "unknown" : "error"); 5872 return hintWithEventId.event_id; 5873 } 5874 /** 5875 * Captures a manually created event and sends it to Sentry. 5876 * 5877 * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope. 5878 */ 5879 captureEvent(event, hint, currentScope) { 5880 const eventId = uuid4(); 5881 if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) { 5882 DEBUG_BUILD$5 && debug$2.log(ALREADY_SEEN_ERROR); 5883 return eventId; 5884 } 5885 const hintWithEventId = { 5886 event_id: eventId, 5887 ...hint 5888 }; 5889 const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; 5890 const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; 5891 const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; 5892 const dataCategory = getDataCategoryByType(event.type); 5893 this._process(() => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), dataCategory); 5894 return hintWithEventId.event_id; 5895 } 5896 /** 5897 * Captures a session. 5898 */ 5899 captureSession(session) { 5900 this.sendSession(session); 5901 updateSession(session, { init: false }); 5902 } 5903 /** 5904 * Get the current Dsn. 5905 */ 5906 getDsn() { 5907 return this._dsn; 5908 } 5909 /** 5910 * Get the current options. 5911 */ 5912 getOptions() { 5913 return this._options; 5914 } 5915 /** 5916 * Get the resolved data collection configuration. 5917 */ 5918 getDataCollectionOptions() { 5919 return this._dataCollection; 5920 } 5921 /** 5922 * Get the SDK metadata. 5923 * @see SdkMetadata 5924 */ 5925 getSdkMetadata() { 5926 return this._options._metadata; 5927 } 5928 /** 5929 * Returns the transport that is used by the client. 5930 * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent. 5931 */ 5932 getTransport() { 5933 return this._transport; 5934 } 5935 /** 5936 * Wait for all events to be sent or the timeout to expire, whichever comes first. 5937 * 5938 * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will 5939 * cause the client to wait until all events are sent before resolving the promise. 5940 * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are 5941 * still events in the queue when the timeout is reached. 5942 */ 5943 async flush(timeout) { 5944 const transport = this._transport; 5945 this.emit("flush"); 5946 if (!transport) return true; 5947 const clientFinished = await this._isClientDoneProcessing(timeout); 5948 const transportFlushed = await transport.flush(timeout); 5949 return clientFinished && transportFlushed; 5950 } 5951 /** 5952 * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}. 5953 * 5954 * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause 5955 * the client to wait until all events are sent before disabling itself. 5956 * @returns {Promise<boolean>} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if 5957 * it doesn't. 5958 */ 5959 async close(timeout) { 5960 const result = await this.flush(timeout); 5961 this.getOptions().enabled = false;
5962 this.emit("close"); 5963 return result; 5964 } 5965 /** 5966 * Get all installed event processors. 5967 */ 5968 getEventProcessors() { 5969 return this._eventProcessors; 5970 } 5971 /** 5972 * Adds an event processor that applies to any event processed by this client. 5973 */ 5974 addEventProcessor(eventProcessor) { 5975 this._eventProcessors.push(eventProcessor); 5976 } 5977 /** 5978 * Initialize this client. 5979 * Call this after the client was set on a scope. 5980 */ 5981 init() { 5982 if (this._isEnabled() || this._options.integrations.some(({ name }) => name.startsWith("Spotlight"))) this._setupIntegrations(); 5983 } 5984 /** 5985 * Gets an installed integration by its name. 5986 * 5987 * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed. 5988 */ 5989 getIntegrationByName(integrationName) { 5990 return this._integrations[integrationName]; 5991 } 5992 /** 5993 * Returns the names of all installed integrations. 5994 */ 5995 getIntegrationNames() { 5996 return Object.keys(this._integrations); 5997 } 5998 /** 5999 * Add an integration to the client. 6000 * This can be used to e.g. lazy load integrations. 6001 * In most cases, this should not be necessary, 6002 * and you're better off just passing the integrations via `integrations: []` at initialization time. 6003 * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so. 6004 */ 6005 addIntegration(integration) { 6006 const isAlreadyInstalled = this._integrations[integration.name]; 6007 if (!isAlreadyInstalled && integration.beforeSetup) integration.beforeSetup(this); 6008 setupIntegration(this, integration, this._integrations); 6009 if (!isAlreadyInstalled) afterSetupIntegrations(this, [integration]); 6010 } 6011 /** 6012 * Send a fully prepared event to Sentry. 6013 */ 6014 sendEvent(event, hint = {}) { 6015 this.emit("beforeSendEvent", event, hint); 6016 const genAiSpanItem = extractGenAiSpansFromEvent(event, this); 6017 let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); 6018 for (const attachment of hint.attachments || []) env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment)); 6019 if (genAiSpanItem) env = addItemToEnvelope(env, genAiSpanItem); 6020 this.sendEnvelope(env).then((sendResponse) => this.emit("afterSendEvent", event, sendResponse)); 6021 } 6022 /** 6023 * Send a session or session aggregrates to Sentry. 6024 */ 6025 sendSession(session) { 6026 const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options; 6027 if ("aggregates" in session) { 6028 const sessionAttrs = session.attrs || {}; 6029 if (!sessionAttrs.release && !clientReleaseOption) { 6030 DEBUG_BUILD$5 && debug$2.warn(MISSING_RELEASE_FOR_SESSION_ERROR); 6031 return; 6032 } 6033 sessionAttrs.release = sessionAttrs.release || clientReleaseOption; 6034 sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption; 6035 session.attrs = sessionAttrs; 6036 } else { 6037 if (!session.release && !clientReleaseOption) { 6038 DEBUG_BUILD$5 && debug$2.warn(MISSING_RELEASE_FOR_SESSION_ERROR); 6039 return; 6040 } 6041 session.release = session.release || clientReleaseOption; 6042 session.environment = session.environment || clientEnvironmentOption; 6043 } 6044 this.emit("beforeSendSession", session); 6045 const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); 6046 this.sendEnvelope(env); 6047 } 6048 /** 6049 * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry). 6050 */ 6051 recordDroppedEvent(reason, category, count = 1) { 6052 if (this._options.sendClientReports) { 6053 const key = `${reason}:${category}`;
6054 DEBUG_BUILD$5 && debug$2.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`); 6055 this._outcomes[key] = (this._outcomes[key] || 0) + count; 6056 } 6057 } 6058 /** 6059 * Register a hook on this client. 6060 */ 6061 on(hook, callback) { 6062 const hookCallbacks = this._hooks[hook] = this._hooks[hook] || /* @__PURE__ */ new Set(); 6063 const uniqueCallback = (...args) => callback(...args); 6064 hookCallbacks.add(uniqueCallback); 6065 return () => { 6066 hookCallbacks.delete(uniqueCallback); 6067 }; 6068 } 6069 /** 6070 * Emit a hook that was previously registered via `on()`. 6071 */ 6072 emit(hook, ...rest) { 6073 const callbacks = this._hooks[hook]; 6074 if (callbacks) callbacks.forEach((callback) => callback(...rest)); 6075 } 6076 /** 6077 * Send an envelope to Sentry. 6078 */ 6079 async sendEnvelope(envelope) { 6080 this.emit("beforeEnvelope", envelope); 6081 if (this._isEnabled() && this._transport) try { 6082 return await this._transport.send(envelope); 6083 } catch (reason) { 6084 DEBUG_BUILD$5 && debug$2.error("Error while sending envelope:", reason); 6085 return {}; 6086 } 6087 DEBUG_BUILD$5 && debug$2.error("Transport disabled"); 6088 return {}; 6089 } 6090 /** 6091 * Register a cleanup function to be called when the client is disposed. 6092 * This is useful for integrations that need to clean up global state. 6093 * 6094 * NOTE: This is a no-op in the base `Client` class. Subclasses like `ServerRuntimeClient` 6095 * override this method to actually register and execute cleanup callbacks. 6096 */ 6097 registerCleanup(callback) {} 6098 /** 6099 * Disposes of the client and releases all resources. 6100 * 6101 * Subclasses should override this method to clean up their own resources, including invoking 6102 * any callbacks registered via {@link Client.registerCleanup}. The base implementation is a 6103 * no-op and does NOT execute registered cleanup callbacks. 6104 * 6105 * After calling dispose(), the client should not be used anymore. 6106 */ 6107 dispose() {} 6108 /** Setup integrations for this client. */ 6109 _setupIntegrations() { 6110 const { integrations } = this._options; 6111 this._integrations = setupIntegrations(this, integrations); 6112 afterSetupIntegrations(this, integrations); 6113 } 6114 /** Updates existing session based on the provided event */ 6115 _updateSessionFromEvent(session, event) { 6116 let crashed = event.level === "fatal"; 6117 let errored = false; 6118 const exceptions = event.exception?.values; 6119 if (exceptions) { 6120 errored = true; 6121 crashed = false; 6122 for (const ex of exceptions) if (ex.mechanism?.handled === false) { 6123 crashed = true; 6124 break; 6125 } 6126 } 6127 const sessionNonTerminal = session.status === "ok"; 6128 if (sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed) { 6129 updateSession(session, { 6130 ...crashed && { status: "crashed" }, 6131 errors: session.errors || Number(errored || crashed) 6132 }); 6133 this.captureSession(session); 6134 } 6135 } 6136 /** 6137 * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying 6138 * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. 6139 * 6140 * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not 6141 * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to 6142 * `true`. 6143 * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and 6144 * `false` otherwise 6145 */ 6146 async _isClientDoneProcessing(timeout) { 6147 let ticked = 0; 6148 while (!timeout || ticked < timeout) { 6149 await new Promise((resolve) => setTimeout(resolve, 1)); 6150 if (!this._numProcessing) return true; 6151 ticked++; 6152 } 6153 return false; 6154 } 6155 /** Determines whether this SDK is enabled and a transport is present. */ 6156 _isEnabled() { 6157 return this.getOptions().enabled !== false && this._transport !== void 0; 6158 } 6159 /** 6160 * Adds common information to events. 6161 * 6162 * The information includes release and environment from `options`, 6163 * breadcrumbs and context (extra, tags and user) from the scope. 6164 * 6165 * Information that is already present in the event is never overwritten. For 6166 * nested objects, such as the context, keys are merged. 6167 * 6168 * @param event The original event. 6169 * @param hint May contain additional information about the original exception. 6170 * @param currentScope A scope containing event metadata. 6171 * @returns A new event with more information. 6172 */ 6173 _prepareEvent(event, hint, currentScope, isolationScope) { 6174 const options = this.getOptions(); 6175 const integrations = this.getIntegrationNames(); 6176 if (!hint.integrations && integrations.length) hint.integrations = integrations;
6177 this.emit("preprocessEvent", event, hint); 6178 if (!event.type) isolationScope.setLastEventId(event.event_id || hint.event_id); 6179 return prepareEvent(options, event, hint, currentScope, this, isolationScope).then((evt) => { 6180 if (evt === null) return evt; 6181 this.emit("postprocessEvent", evt, hint); 6182 evt.contexts = { 6183 trace: { 6184 ...evt.contexts?.trace, 6185 ...getTraceContextFromScope(currentScope) 6186 }, 6187 ...evt.contexts 6188 }; 6189 evt.sdkProcessingMetadata = { 6190 dynamicSamplingContext: getDynamicSamplingContextFromScope(this, currentScope), 6191 ...evt.sdkProcessingMetadata 6192 }; 6193 return evt; 6194 }); 6195 } 6196 /** 6197 * Processes the event and logs an error in case of rejection 6198 * @param event 6199 * @param hint 6200 * @param scope 6201 */ 6202 _captureEvent(event, hint = {}, currentScope = getCurrentScope(), isolationScope = getIsolationScope()) { 6203 if (DEBUG_BUILD$5 && isErrorEvent$2(event)) debug$2.log(`Captured error event \`${getPossibleEventMessages(event)[0] || "<unknown>"}\``); 6204 return this._processEvent(event, hint, currentScope, isolationScope).then((finalEvent) => { 6205 return finalEvent.event_id; 6206 }, (reason) => { 6207 if (DEBUG_BUILD$5) { 6208 if (_isDoNotSendEventError(reason)) debug$2.log(reason.message); 6209 else if (_isInternalError(reason)) debug$2.warn(reason.message); 6210 else debug$2.warn(reason); 6211 } 6212 }); 6213 } 6214 /** 6215 * Processes an event (either error or message) and sends it to Sentry. 6216 * 6217 * This also adds breadcrumbs and context information to the event. However, 6218 * platform specific meta data (such as the User's IP address) must be added 6219 * by the SDK implementor. 6220 * 6221 * 6222 * @param event The event to send to Sentry. 6223 * @param hint May contain additional information about the original exception. 6224 * @param currentScope A scope containing event metadata. 6225 * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. 6226 */ 6227 _processEvent(event, hint, currentScope, isolationScope) { 6228 const options = this.getOptions(); 6229 const { sampleRate } = options; 6230 const isTransaction = isTransactionEvent$1(event); 6231 const isError = isErrorEvent$2(event); 6232 const beforeSendLabel = `before send for type \`${event.type || "error"}\``; 6233 const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate); 6234 const dataCategory = getDataCategoryByType(event.type); 6235 return this._prepareEvent(event, hint, currentScope, isolationScope).then((prepared) => { 6236 if (prepared === null) { 6237 this.recordDroppedEvent("event_processor", dataCategory); 6238 throw _makeDoNotSendEventError("An event processor returned `null`, will not send event."); 6239 } 6240 if (hint.data?.__sentry__ === true) return prepared; 6241 return _validateBeforeSendResult(processBeforeSend(this, options, prepared, hint), beforeSendLabel); 6242 }).then((processedEvent) => { 6243 if (processedEvent === null) { 6244 this.recordDroppedEvent("before_send", dataCategory); 6245 if (isTransaction) { 6246 const spanCount = 1 + (event.spans || []).length; 6247 this.recordDroppedEvent("before_send", "span", spanCount); 6248 } 6249 throw _makeDoNotSendEventError(`${beforeSendLabel} returned \`null\`, will not send event.`); 6250 } 6251 const session = currentScope.getSession() || isolationScope.getSession(); 6252 if (isError && session) this._updateSessionFromEvent(session, processedEvent); 6253 if (isError && typeof parsedSampleRate === "number" && safeMathRandom() > parsedSampleRate) { 6254 this.recordDroppedEvent("sample_rate", "error"); 6255 throw _makeDoNotSendEventError(`Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`); 6256 } 6257 if (isTransaction) { 6258 const droppedSpanCount = (processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0) - (processedEvent.spans ? processedEvent.spans.length : 0); 6259 if (droppedSpanCount > 0) this.recordDroppedEvent("before_send", "span", droppedSpanCount); 6260 } 6261 const transactionInfo = processedEvent.transaction_info; 6262 if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { 6263 const source = "custom"; 6264 processedEvent.transaction_info = { 6265 ...transactionInfo, 6266 source 6267 }; 6268 } 6269 this.sendEvent(processedEvent, hint); 6270 return processedEvent; 6271 }).then(null, (reason) => { 6272 if (_isDoNotSendEventError(reason) || _isInternalError(reason)) throw reason; 6273 this.captureException(reason, { 6274 mechanism: { 6275 handled: false, 6276 type: "internal" 6277 }, 6278 data: { __sentry__: true }, 6279 originalException: reason 6280 }); 6281 throw _makeInternalError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. 6282Reason: ${reason}`); 6283 }); 6284 } 6285 /** 6286 * Occupies the client with processing and event 6287 */ 6288 _process(taskProducer, dataCategory) { 6289 this._numProcessing++; 6290 this._promiseBuffer.add(taskProducer).then((value) => { 6291 this._numProcessing--; 6292 return value; 6293 }, (reason) => { 6294 this._numProcessing--; 6295 if (reason === SENTRY_BUFFER_FULL_ERROR) this.recordDroppedEvent("queue_overflow", dataCategory); 6296 return reason; 6297 }); 6298 } 6299 /** 6300 * Clears outcomes on this client and returns them. 6301 */ 6302 _clearOutcomes() { 6303 const outcomes = this._outcomes; 6304 this._outcomes = {}; 6305 return Object.entries(outcomes).map(([key, quantity]) => { 6306 const [reason, category] = key.split(":"); 6307 return { 6308 reason, 6309 category, 6310 quantity 6311 }; 6312 }); 6313 } 6314 /** 6315 * Sends client reports as an envelope. 6316 */ 6317 _flushOutcomes() { 6318 DEBUG_BUILD$5 && debug$2.log("Flushing outcomes..."); 6319 const outcomes = this._clearOutcomes(); 6320 if (outcomes.length === 0) { 6321 DEBUG_BUILD$5 && debug$2.log("No outcomes to send"); 6322 return; 6323 } 6324 if (!this._dsn) { 6325 DEBUG_BUILD$5 && debug$2.log("No dsn provided, will not send outcomes"); 6326 return; 6327 } 6328 DEBUG_BUILD$5 && debug$2.log("Sending outcomes:", outcomes); 6329 const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn)); 6330 this.sendEnvelope(envelope); 6331 } 6332 }; 6333 })))(); 6334} 6335//#endregion 6336//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/sdk.js 6337function initAndBind(clientClass, options) { 6338 if (options.debug === true) { 6339 if (DEBUG_BUILD$5) debug$2.enable(); 6340 else consoleSandbox(() => { 6341 console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."); 6342 }); 6343 } 6344 getCurrentScope().update(options.initialScope); 6345 const client = new clientClass(options); 6346 setCurrentClient(client); 6347 client.init(); 6348 return client; 6349} 6350function setCurrentClient(client) { 6351 getCurrentScope().setClient(client); 6352} 6353function init_sdk() { 6354 return (init_sdk = __esmMin((() => { 6355 init_currentScopes(); 6356 init_debug_build(); 6357 init_debug_logger(); 6358 })))(); 6359} 6360//#endregion 6361//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/transports/offline.js 6362function makeOfflineTransport(createTransport) { 6363 function log(...args) { 6364 DEBUG_BUILD$5 && debug$2.log("[Offline]:", ...args); 6365 } 6366 return (options) => { 6367 const transport = createTransport(options); 6368 if (!options.createStore) throw new Error("No `createStore` function was provided"); 6369 const store = options.createStore(options); 6370 let retryDelay = START_DELAY; 6371 let flushTimer; 6372 function shouldQueue(env, error, retryDelay2) { 6373 if (envelopeContainsItemType(env, ["client_report"])) return false;
6374 if (options.shouldStore) return options.shouldStore(env, error, retryDelay2); 6375 return true; 6376 } 6377 function flushIn(delay) { 6378 if (flushTimer) clearTimeout(flushTimer); 6379 flushTimer = safeUnref(setTimeout(async () => { 6380 flushTimer = void 0; 6381 const found = await store.shift(); 6382 if (found) { 6383 log("Attempting to send previously queued event"); 6384 found[0].sent_at = new Date(safeDateNow()).toISOString(); 6385 send(found, true).catch((e) => { 6386 log("Failed to retry sending", e); 6387 }); 6388 } 6389 }, delay)); 6390 } 6391 function flushWithBackOff() { 6392 if (flushTimer) return; 6393 flushIn(retryDelay); 6394 retryDelay = Math.min(retryDelay * 2, MAX_DELAY); 6395 } 6396 async function send(envelope, isRetry = false) { 6397 if (!isRetry && envelopeContainsItemType(envelope, ["replay_event", "replay_recording"])) { 6398 await store.push(envelope); 6399 flushIn(100); 6400 return {}; 6401 } 6402 try { 6403 if (options.shouldSend && await options.shouldSend(envelope) === false) throw new Error("Envelope not sent because `shouldSend` callback returned false"); 6404 const result = await transport.send(envelope); 6405 let delay = 100; 6406 if (result) { 6407 if (result.headers?.["retry-after"]) delay = parseRetryAfterHeader(result.headers["retry-after"]); 6408 else if (result.headers?.["x-sentry-rate-limits"]) delay = 6e4; 6409 else if ((result.statusCode || 0) >= 400) return result; 6410 } 6411 flushIn(delay); 6412 retryDelay = START_DELAY; 6413 return result; 6414 } catch (e) { 6415 if (await shouldQueue(envelope, e, retryDelay)) { 6416 if (isRetry) await store.unshift(envelope); 6417 else await store.push(envelope); 6418 flushWithBackOff(); 6419 log("Error sending. Event queued.", e); 6420 return {}; 6421 } else throw e; 6422 } 6423 } 6424 if (options.flushAtStartup) flushWithBackOff(); 6425 return { 6426 send, 6427 flush: (timeout) => { 6428 if (timeout === void 0) { 6429 retryDelay = START_DELAY; 6430 flushIn(100); 6431 } 6432 return transport.flush(timeout); 6433 } 6434 }; 6435 }; 6436} 6437var START_DELAY, MAX_DELAY; 6438function init_offline() { 6439 return (init_offline = __esmMin((() => { 6440 init_debug_build(); 6441 init_debug_logger(); 6442 init_envelope(); 6443 init_randomSafeContext(); 6444 init_ratelimit(); 6445 START_DELAY = 5e3; 6446 MAX_DELAY = 36e5; 6447 })))(); 6448} 6449//#endregion 6450//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/transports/multiplexed.js 6451function eventFromEnvelope(env, types) { 6452 let event; 6453 forEachEnvelopeItem(env, (item, type) => { 6454 if (types.includes(type)) event = Array.isArray(item) ? item[1] : void 0; 6455 return !!event; 6456 }); 6457 return event; 6458} 6459function makeOverrideReleaseTransport(createTransport, release) { 6460 return (options) => { 6461 const transport = createTransport(options); 6462 return { 6463 ...transport, 6464 send: async (envelope) => { 6465 const event = eventFromEnvelope(envelope, [ 6466 "event", 6467 "transaction", 6468 "profile", 6469 "replay_event" 6470 ]); 6471 if (event) event.release = release; 6472 return transport.send(envelope); 6473 } 6474 }; 6475 }; 6476} 6477function overrideDsn(envelope, dsn) { 6478 return createEnvelope(dsn ? { 6479 ...envelope[0], 6480 dsn 6481 } : envelope[0], envelope[1]); 6482} 6483function makeMultiplexedTransport(createTransport, matcher) { 6484 return (options) => { 6485 const fallbackTransport = createTransport(options); 6486 const otherTransports = /* @__PURE__ */ new Map(); 6487 const actualMatcher = matcher || ((args) => { 6488 const event = args.getEvent(); 6489 if (event?.extra?.["MULTIPLEXED_TRANSPORT_EXTRA_KEY"] && Array.isArray(event.extra["MULTIPLEXED_TRANSPORT_EXTRA_KEY"])) return event.extra["MULTIPLEXED_TRANSPORT_EXTRA_KEY"]; 6490 return []; 6491 }); 6492 function getTransport(dsn, release) { 6493 const key = release ? `${dsn}:${release}` : dsn; 6494 let transport = otherTransports.get(key); 6495 if (!transport) { 6496 const validatedDsn = dsnFromString(dsn); 6497 if (!validatedDsn) return; 6498 const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel); 6499 transport = release ? makeOverrideReleaseTransport(createTransport, release)({ 6500 ...options, 6501 url 6502 }) : createTransport({ 6503 ...options, 6504 url 6505 }); 6506 otherTransports.set(key, transport); 6507 } 6508 return [dsn, transport]; 6509 } 6510 async function send(envelope) { 6511 function getEvent(types) { 6512 return eventFromEnvelope(envelope, types?.length ? types : ["event"]); 6513 } 6514 const transports = actualMatcher({ 6515 envelope, 6516 getEvent 6517 }).map((result) => { 6518 if (typeof result === "string") return getTransport(result, void 0); 6519 else return getTransport(result.dsn, result.release); 6520 }).filter((t) => !!t); 6521 const transportsWithFallback = transports.length ? transports : [["", fallbackTransport]]; 6522 return (await Promise.all(transportsWithFallback.map(([dsn, transport]) =>
6522 transport.send(overrideDsn(envelope, dsn)))))[0]; 6523 } 6524 async function flush(timeout) { 6525 const allTransports = [...otherTransports.values(), fallbackTransport]; 6526 return (await Promise.all(allTransports.map((transport) => transport.flush(timeout)))).every((r) => r); 6527 } 6528 return { 6529 send, 6530 flush 6531 }; 6532 }; 6533} 6534var MULTIPLEXED_TRANSPORT_EXTRA_KEY; 6535function init_multiplexed() { 6536 return (init_multiplexed = __esmMin((() => { 6537 init_api(); 6538 init_dsn(); 6539 init_envelope(); 6540 MULTIPLEXED_TRANSPORT_EXTRA_KEY = "MULTIPLEXED_TRANSPORT_EXTRA_KEY"; 6541 })))(); 6542} 6543//#endregion 6544//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/data-collection/filterKeyValueData.js 6545function isSensitiveKey(lower, denySnippets) { 6546 return denySnippets.some((snippet) => lower.includes(snippet)); 6547} 6548function filterKeyValueData(data, behavior, additionalDenyTerms) { 6549 if (behavior === false) return {}; 6550 const denySnippets = additionalDenyTerms != null ? [...SENSITIVE_KEY_SNIPPETS, ...additionalDenyTerms] : SENSITIVE_KEY_SNIPPETS; 6551 const result = {}; 6552 if (behavior === true) { 6553 for (const key of Object.keys(data)) result[key] = isSensitiveKey(key.toLowerCase(), denySnippets) ? FILTERED_VALUE : data[key]; 6554 return result; 6555 } 6556 if ("deny" in behavior) { 6557 const lowerTerms2 = behavior.deny.map((t) => t.toLowerCase()); 6558 for (const key of Object.keys(data)) { 6559 const lower = key.toLowerCase(); 6560 result[key] = isSensitiveKey(lower, denySnippets) || lowerTerms2.some((term) => lower.includes(term)) ? FILTERED_VALUE : data[key]; 6561 } 6562 return result; 6563 } 6564 const lowerTerms = behavior.allow.map((t) => t.toLowerCase()); 6565 for (const key of Object.keys(data)) { 6566 const lower = key.toLowerCase(); 6567 if (isSensitiveKey(lower, denySnippets)) result[key] = FILTERED_VALUE; 6568 else result[key] = lowerTerms.some((term) => lower.includes(term)) ? data[key] : FILTERED_VALUE; 6569 } 6570 return result; 6571} 6572function init_filterKeyValueData() { 6573 return (init_filterKeyValueData = __esmMin((() => { 6574 init_filtering_snippets(); 6575 })))(); 6576} 6577//#endregion 6578//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/cookie.js 6579function parseCookie(str) { 6580 const obj = {}; 6581 let index = 0; 6582 while (index < str.length) { 6583 const eqIdx = str.indexOf("=", index); 6584 if (eqIdx === -1) break; 6585 let endIdx = str.indexOf(";", index); 6586 if (endIdx === -1) endIdx = str.length; 6587 else if (endIdx < eqIdx) { 6588 index = str.lastIndexOf(";", eqIdx - 1) + 1; 6589 continue; 6590 } 6591 const key = str.slice(index, eqIdx).trim(); 6592 if (void 0 === obj[key]) { 6593 let val = str.slice(eqIdx + 1, endIdx).trim(); 6594 if (val.charCodeAt(0) === 34) val = val.slice(1, -1); 6595 try { 6596 obj[key] = val.indexOf("%") !== -1 ? decodeURIComponent(val) : val; 6597 } catch { 6598 obj[key] = val; 6599 } 6600 } 6601 index = endIdx + 1; 6602 } 6603 return obj; 6604} 6605//#endregion 6606//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/data-collection/filterCookies.js 6607function filterCookies(cookieString, behavior) { 6608 if (behavior === false) return {}; 6609 try { 6610 const parsed = parseCookie(cookieString); 6611 if (Object.keys(parsed).length === 0) return {}; 6612 return filterKeyValueData(parsed, behavior, SENSITIVE_COOKIE_NAME_SNIPPETS); 6613 } catch { 6614 return FILTERED_VALUE; 6615 } 6616} 6617function init_filterCookies() { 6618 return (init_filterCookies = __esmMin((() => { 6619 init_filtering_snippets(); 6620 init_filterKeyValueData(); 6621 })))(); 6622} 6623//#endregion 6624//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/url.js 6625function isURLObjectRelative(url) { 6626 return "isRelative" in url; 6627} 6628function parseStringToURLObject(url, urlBase) { 6629 const isRelative = url.indexOf("://") <= 0 && url.indexOf("//") !== 0; 6630 const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : void 0); 6631 try { 6632 if ("canParse" in URL && !URL.canParse(url, base)) return; 6633 const fullUrlObject = new URL(url, base); 6634 if (isRelative) return { 6635 isRelative, 6636 pathname: fullUrlObject.pathname, 6637 search: fullUrlObject.search, 6638 hash: fullUrlObject.hash 6639 }; 6640 return fullUrlObject; 6641 } catch {} 6642} 6643function getSanitizedUrlStringFromUrlObject(url) { 6644 if (isURLObjectRelative(url)) return url.pathname; 6645 const newUrl = new URL(url); 6646 newUrl.search = ""; 6647 newUrl.hash = ""; 6648 if (["80", "443"].includes(newUrl.port)) newUrl.port = ""; 6649 if (newUrl.password) newUrl.password = "%filtered%"; 6650 if (newUrl.username) newUrl.username = "%filtered%"; 6651 return newUrl.toString(); 6652} 6653function parseUrl(url) { 6654 if (!url) return {}; 6655 const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); 6656 if (!match) return {}; 6657 const query = match[6] || ""; 6658 const fragment = match[8] || ""; 6659 return { 6660 host: match[4], 6661 path: match[5], 6662 protocol: match[2], 6663 search: query, 6664 hash: fragment, 6665 relative: match[5] + query + fragment 6666 }; 6667} 6668function stripUrlQueryAndFragment(urlPath) { 6669 return urlPath.split(/[?#]/, 1)[0]; 6670} 6671function stripDataUrlContent(url, includeDataPrefix = true) { 6672 if (url.startsWith("data:")) { 6673 const match = url.match(/^data:([^;,]+)/); 6674 const mimeType = match ? match[1] : "text/plain"; 6675 const isBase64 = url.includes(";base64,"); 6676 const dataStart = url.indexOf(","); 6677 let dataPrefix = ""; 6678 if (includeDataPrefix && dataStart !== -1) { 6679 const data = url.slice(dataStart + 1); 6680 dataPrefix = data.length > 10 ? `${data.slice(0, 10)}... [truncated]` : data; 6681 } 6682 return `data:${mimeType}${isBase64 ? ",base64" : ""}${dataPrefix ? `,${dataPrefix}` : ""}`; 6683 } 6684 return url; 6685} 6686var DEFAULT_BASE_URL; 6687function init_url() { 6688 return (init_url = __esmMin((() => { 6689 DEFAULT_BASE_URL = "thismessage:/"; 6690 })))(); 6691} 6692//#endregion 6693//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/isSentryRequestUrl.js 6694function isSentryRequestUrl(url, client) {
6695 const dsn = client?.getDsn(); 6696 const tunnel = client?.getOptions().tunnel; 6697 return checkDsn(url, dsn) || checkTunnel(url, tunnel); 6698} 6699function checkTunnel(url, tunnel) { 6700 if (!tunnel) return false; 6701 return removeTrailingSlash(url) === removeTrailingSlash(tunnel); 6702} 6703function checkDsn(url, dsn) { 6704 const urlParts = parseStringToURLObject(url); 6705 if (!urlParts || isURLObjectRelative(urlParts)) return false; 6706 if (!dsn) return false; 6707 return hostnameMatchesDsnHost(urlParts.hostname, dsn.host) && /(^|&|\?)sentry_key=/.test(urlParts.search); 6708} 6709function hostnameMatchesDsnHost(hostname, dsnHost) { 6710 return hostname === dsnHost || dsnHost.length > 0 && hostname.endsWith(`.${dsnHost}`); 6711} 6712function removeTrailingSlash(str) { 6713 return str[str.length - 1] === "/" ? str.slice(0, -1) : str; 6714} 6715function init_isSentryRequestUrl() { 6716 return (init_isSentryRequestUrl = __esmMin((() => { 6717 init_url(); 6718 })))(); 6719} 6720//#endregion 6721//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/parameterize.js 6722function parameterize(strings, ...values) { 6723 const formatted = new String(String.raw(strings, ...values)); 6724 formatted.__sentry_template_string__ = strings.join("\0").replace(/%/g, "%%").replace(/\0/g, "%s"); 6725 formatted.__sentry_template_values__ = values; 6726 return formatted; 6727} 6728var fmt; 6729function init_parameterize() { 6730 return (init_parameterize = __esmMin((() => { 6731 fmt = parameterize; 6732 })))(); 6733} 6734//#endregion 6735//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/ipAddress.js 6736function addAutoIpAddressToSession(session) { 6737 if ("aggregates" in session) { 6738 if (session.attrs?.["ip_address"] === void 0) session.attrs = { 6739 ...session.attrs, 6740 ip_address: "{{auto}}" 6741 }; 6742 } else if (session.ipAddress === void 0) session.ipAddress = "{{auto}}"; 6743} 6744//#endregion 6745//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/sdkMetadata.js 6746function applySdkMetadata(options, name, names = [name], source = "npm") { 6747 const sdk = (options._metadata = options._metadata || {}).sdk = options._metadata.sdk || {}; 6748 if (!sdk.name) { 6749 sdk.name = `sentry.javascript.${name}`; 6750 sdk.packages = names.map((name2) => ({ 6751 name: `${source}:@sentry/${name2}`, 6752 version: SDK_VERSION 6753 })); 6754 sdk.version = SDK_VERSION; 6755 } 6756} 6757function init_sdkMetadata() { 6758 return (init_sdkMetadata = __esmMin((() => { 6759 init_version(); 6760 })))(); 6761} 6762//#endregion 6763//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/traceData.js 6764function getTraceData(options = {}) { 6765 const client = options.client || getClient(); 6766 if (!isEnabled() || !client) return {}; 6767 const acs = getAsyncContextStrategy(getMainCarrier()); 6768 if (acs.getTraceData) return acs.getTraceData(options); 6769 const scope = options.scope || getCurrentScope(); 6770 const span = options.span || getActiveSpan(); 6771 const isTwpPlaceholder = spanIsNonRecordingSpan(span) && !hasSpansEnabled(client.getOptions()); 6772 if (!span && hasExternalPropagationContext()) return {}; 6773 const sentryTrace = span && !isTwpPlaceholder ? spanToTraceHeader(span) : scopeToTraceHeader(scope); 6774 const baggage = dynamicSamplingContextToSentryBaggageHeader(span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope)); 6775 if (!TRACEPARENT_REGEXP.test(sentryTrace)) { 6776 debug$2.warn("Invalid sentry-trace data. Cannot generate trace data"); 6777 return {}; 6778 } 6779 const traceData = { 6780 "sentry-trace": sentryTrace, 6781 baggage 6782 }; 6783 if (options.propagateTraceparent) traceData.traceparent = span && !isTwpPlaceholder ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope); 6784 return traceData; 6785} 6786function scopeToTraceHeader(scope) { 6787 const { traceId, sampled, propagationSpanId } = scope.getPropagationContext(); 6788 return generateSentryTraceHeader(traceId, propagationSpanId, sampled); 6789} 6790function scopeToTraceparentHeader(scope) { 6791 const { traceId, sampled, propagationSpanId } = scope.getPropagationContext(); 6792 return generateTraceparentHeader(traceId, propagationSpanId, sampled); 6793} 6794function init_traceData() { 6795 return (init_traceData = __esmMin((() => { 6796 init_asyncContext(); 6797 init_carrier(); 6798 init_currentScopes(); 6799 init_exports(); 6800 init_debug_logger(); 6801 init_spanUtils(); 6802 init_hasSpansEnabled(); 6803 init_sentryNonRecordingSpan(); 6804 init_dynamicSamplingContext(); 6805 init_baggage(); 6806 init_tracing(); 6807 })))(); 6808} 6809//#endregion 6810//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/breadcrumbs.js 6811function addBreadcrumb(breadcrumb, hint) { 6812 const client = getClient(); 6813 const isolationScope = getIsolationScope(); 6814 if (!client) return; 6815 const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions(); 6816 if (maxBreadcrumbs <= 0) return; 6817 const mergedBreadcrumb = { 6818 timestamp: dateTimestampInSeconds(), 6819 ...breadcrumb 6820 }; 6821 const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb; 6822 if (finalBreadcrumb === null) return; 6823 if (client.emit) client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint); 6824 isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); 6825} 6826var DEFAULT_BREADCRUMBS; 6827function init_breadcrumbs() { 6828 return (init_breadcrumbs = __esmMin((() => { 6829 init_currentScopes(); 6830 init_debug_logger(); 6831 init_time(); 6832 DEFAULT_BREADCRUMBS = 100; 6833 })))(); 6834} 6835//#endregion 6836//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/functiontostring.js 6837var INTEGRATION_NAME$23, SETUP_CLIENTS$1, _functionToStringIntegration, functionToStringIntegration; 6838function init_functiontostring() { 6839 return (init_functiontostring = __esmMin((() => { 6840 init_currentScopes(); 6841 init_integration(); 6842 init_object(); 6843 INTEGRATION_NAME$23 = "FunctionToString"; 6844 SETUP_CLIENTS$1 = /* @__PURE__ */ new WeakMap(); 6845 _functionToStringIntegration = (() => { 6846 return { 6847 name: INTEGRATION_NAME$23, 6848 setupOnce() { 6849 const originalFunctionToString = Function.prototype.toString; 6850 try { 6851 Function.prototype.toString = function(...args) { 6852 const originalFunction = getOriginalFunction(this); 6853 let unwrappedFunction; 6854 try {
6855 if (SETUP_CLIENTS$1.has(getClient()) && originalFunction !== void 0) unwrappedFunction = originalFunction; 6856 } catch {} 6857 return originalFunctionToString.apply(unwrappedFunction ?? this, args); 6858 }; 6859 } catch {} 6860 }, 6861 setup(client) { 6862 SETUP_CLIENTS$1.set(client, true); 6863 } 6864 }; 6865 }); 6866 functionToStringIntegration = defineIntegration(_functionToStringIntegration); 6867 })))(); 6868} 6869//#endregion 6870//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/eventFilters.js 6871function _mergeOptions(internalOptions = {}, clientOptions = {}) { 6872 return { 6873 allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []], 6874 denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []], 6875 ignoreErrors: [ 6876 ...internalOptions.ignoreErrors || [], 6877 ...clientOptions.ignoreErrors || [], 6878 ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS 6879 ], 6880 ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []] 6881 }; 6882} 6883function _shouldDropEvent$1(event, options) { 6884 if (!event.type) { 6885 if (_isIgnoredError(event, options.ignoreErrors)) { 6886 DEBUG_BUILD$5 && debug$2.warn(`Event dropped due to being matched by \`ignoreErrors\` option. 6887Event: ${getEventDescription(event)}`); 6888 return true; 6889 } 6890 if (_isUselessError(event)) { 6891 DEBUG_BUILD$5 && debug$2.warn(`Event dropped due to not having an error message, error type or stacktrace. 6892Event: ${getEventDescription(event)}`); 6893 return true; 6894 } 6895 if (_isDeniedUrl(event, options.denyUrls)) { 6896 DEBUG_BUILD$5 && debug$2.warn(`Event dropped due to being matched by \`denyUrls\` option. 6897Event: ${getEventDescription(event)}. 6898Url: ${_getEventFilterUrl(event)}`); 6899 return true; 6900 } 6901 if (!_isAllowedUrl(event, options.allowUrls)) { 6902 DEBUG_BUILD$5 && debug$2.warn(`Event dropped due to not being matched by \`allowUrls\` option. 6903Event: ${getEventDescription(event)}. 6904Url: ${_getEventFilterUrl(event)}`); 6905 return true; 6906 } 6907 } else if (event.type === "transaction") { 6908 if (_isIgnoredTransaction(event, options.ignoreTransactions)) { 6909 DEBUG_BUILD$5 && debug$2.warn(`Event dropped due to being matched by \`ignoreTransactions\` option. 6910Event: ${getEventDescription(event)}`); 6911 return true; 6912 } 6913 } 6914 return false; 6915} 6916function _isIgnoredError(event, ignoreErrors) { 6917 if (!ignoreErrors?.length) return false; 6918 return getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors)); 6919} 6920function _isIgnoredTransaction(event, ignoreTransactions) { 6921 if (!ignoreTransactions?.length) return false; 6922 const name = event.transaction; 6923 return name ? stringMatchesSomePattern(name, ignoreTransactions) : false; 6924} 6925function _isDeniedUrl(event, denyUrls) { 6926 if (!denyUrls?.length) return false; 6927 const url = _getEventFilterUrl(event); 6928 return !url ? false : stringMatchesSomePattern(url, denyUrls); 6929} 6930function _isAllowedUrl(event, allowUrls) { 6931 if (!allowUrls?.length) return true; 6932 const url = _getEventFilterUrl(event); 6933 return !url ? true : stringMatchesSomePattern(url, allowUrls); 6934} 6935function _getLastValidUrl(frames = []) { 6936 for (let i = frames.length - 1; i >= 0; i--) { 6937 const frame = frames[i]; 6938 if (frame && frame.filename !== "<anonymous>" && frame.filename !== "[native code]") return frame.filename || null; 6939 } 6940 return null; 6941} 6942function _getEventFilterUrl(event) { 6943 try { 6944 const frames = [...event.exception?.values ?? []].reverse().find((value) => value.mechanism?.parent_id === void 0 && value.stacktrace?.frames?.length)?.stacktrace?.frames; 6945 return frames ? _getLastValidUrl(frames) : null; 6946 } catch { 6947 DEBUG_BUILD$5 && debug$2.error(`Cannot extract url for event ${getEventDescription(event)}`); 6948 return null; 6949 } 6950} 6951function _isUselessError(event) { 6952 if (!event.exception?.values?.length) return false; 6953 return !event.message && !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value); 6954} 6955var DEFAULT_IGNORE_ERRORS, INTEGRATION_NAME$22, eventFiltersIntegration, inboundFiltersIntegration; 6956function init_eventFilters() { 6957 return (init_eventFilters = __esmMin((() => { 6958 init_debug_build(); 6959 init_integration(); 6960 init_debug_logger(); 6961 init_misc(); 6962 init_string();
6963 DEFAULT_IGNORE_ERRORS = [ 6964 /^Script error\.?$/, 6965 /^Javascript error: Script error\.? on line 0$/, 6966 /^ResizeObserver loop completed with undelivered notifications.$/, 6967 /^Cannot redefine property: googletag$/, 6968 /^Can't find variable: gmo$/, 6969 /^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/, 6970 /can't redefine non-configurable property "solana"/, 6971 /vv\(\)\.getRestrictions is not a function/, 6972 /Can't find variable: _AutofillCallbackHandler/, 6973 /Object Not Found Matching Id:\d+, MethodName:simulateEvent/, 6974 /Java exception was raised during method invocation$/, 6975 /Java object is gone$/ 6976 ]; 6977 INTEGRATION_NAME$22 = "EventFilters"; 6978 eventFiltersIntegration = defineIntegration((options = {}) => { 6979 let mergedOptions; 6980 return { 6981 name: INTEGRATION_NAME$22, 6982 setup(client) { 6983 mergedOptions = _mergeOptions(options, client.getOptions()); 6984 }, 6985 processEvent(event, _hint, client) { 6986 if (!mergedOptions) mergedOptions = _mergeOptions(options, client.getOptions()); 6987 return _shouldDropEvent$1(event, mergedOptions) ? null : event; 6988 } 6989 }; 6990 }); 6991 inboundFiltersIntegration = defineIntegration(((options = {}) => { 6992 return { 6993 ...eventFiltersIntegration(options), 6994 name: "InboundFilters" 6995 }; 6996 })); 6997 })))(); 6998} 6999//#endregion 7000//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/aggregate-errors.js 7001function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, key, limit, event, hint) { 7002 if (!event.exception?.values || !hint || !isError(hint.originalException)) return; 7003 const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0; 7004 if (originalException) event.exception.values = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, hint.originalException, key, event.exception.values, originalException, 0); 7005} 7006function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error, key, prevExceptions, exception, exceptionId) { 7007 if (prevExceptions.length >= limit + 1) return prevExceptions; 7008 let newExceptions = [...prevExceptions]; 7009 if (isError(error[key])) { 7010 applyExceptionGroupFieldsForParentException(exception, exceptionId, error); 7011 const newException = exceptionFromErrorImplementation(parser, error[key]); 7012 const newExceptionId = newExceptions.length; 7013 applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); 7014 newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error[key], key, [newException, ...newExceptions], newException, newExceptionId); 7015 } 7016 if (isExceptionGroup(error)) error.errors.forEach((childError, i) => { 7017 if (isError(childError)) { 7018 applyExceptionGroupFieldsForParentException(exception, exceptionId, error); 7019 const newException = exceptionFromErrorImplementation(parser, childError); 7020 const newExceptionId = newExceptions.length; 7021 applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); 7022 newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId); 7023 } 7024 }); 7025 return newExceptions; 7026} 7027function isExceptionGroup(error) { 7028 return Array.isArray(error.errors); 7029} 7030function applyExceptionGroupFieldsForParentException(exception, exceptionId, error) { 7031 exception.mechanism = { 7032 handled: true, 7033 type: "auto.core.linked_errors", 7034 ...isExceptionGroup(error) && { is_exception_group: true }, 7035 ...exception.mechanism, 7036 exception_id: exceptionId 7037 }; 7038} 7039function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) { 7040 exception.mechanism = { 7041 handled: true, 7042 ...exception.mechanism, 7043 type: "chained", 7044 source, 7045 exception_id: exceptionId, 7046 parent_id: parentId 7047 }; 7048} 7049function init_aggregate_errors() { 7050 return (init_aggregate_errors = __esmMin((() => { 7051 init_is(); 7052 })))(); 7053} 7054//#endregion 7055//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/eventbuilder.js 7056function hasSentryFetchUrlHost(error) { 7057 return isError(error) && "__sentry_fetch_url_host__" in error && typeof error.__sentry_fetch_url_host__ === "string"; 7058} 7059function _enhanceErrorWithSentryInfo(error) { 7060 if (hasSentryFetchUrlHost(error)) return `${error.message} (${error.__sentry_fetch_url_host__})`; 7061 return error.message; 7062} 7063function init_eventbuilder() { 7064 return (init_eventbuilder = __esmMin((() => { 7065 init_is(); 7066 })))(); 7067} 7068//#endregion 7069//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/metadata.js 7070function ensureMetadataStacksAreParsed(parser) { 7071 if (!GLOBAL_OBJ._sentryModuleMetadata) return; 7072 for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) { 7073 const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack]; 7074 if (parsedStacks.has(stack)) continue; 7075 parsedStacks.add(stack); 7076 const frames = parser(stack); 7077 for (const frame of frames.reverse()) if (frame.filename) { 7078 filenameMetadataMap.set(frame.filename, metadata); 7079 break; 7080 } 7081 } 7082} 7083function getMetadataForUrl(parser, filename) { 7084 ensureMetadataStacksAreParsed(parser); 7085 return filenameMetadataMap.get(filename); 7086} 7087function addMetadataToStackFrames(parser, event) { 7088 event.exception?.values?.forEach((exception) => { 7089 exception.stacktrace?.frames?.forEach((frame) => { 7090 if (!frame.filename || frame.module_metadata) return; 7091 const metadata = getMetadataForUrl(parser, frame.filename); 7092 if (metadata) frame.module_metadata = metadata; 7093 }); 7094 }); 7095} 7096function stripMetadataFromStackFrames(event) { 7097 event.exception?.values?.forEach((exception) => { 7098 exception.stacktrace?.frames?.forEach((frame) => { 7099 delete frame.module_metadata; 7100 }); 7101 }); 7102} 7103var filenameMetadataMap, parsedStacks; 7104function init_metadata() { 7105 return (init_metadata = __esmMin((() => { 7106 init_worldwide(); 7107 filenameMetadataMap = /* @__PURE__ */ new Map(); 7108 parsedStacks = /* @__PURE__ */ new Set(); 7109 })))(); 7110} 7111//#endregion 7112//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/moduleMetadata.js 7113var moduleMetadataIntegration; 7114function init_moduleMetadata() { 7115 return (init_moduleMetadata = __esmMin((() => { 7116 init_integration(); 7117 init_metadata(); 7118 init_envelope(); 7119 moduleMetadataIntegration = defineIntegration(() => { 7120 return { 7121 name: "ModuleMetadata", 7122 setup(client) { 7123 client.on("beforeEnvelope", (envelope) => {
7124 forEachEnvelopeItem(envelope, (item, type) => { 7125 if (type === "event") { 7126 const event = Array.isArray(item) ? item[1] : void 0; 7127 if (event) { 7128 stripMetadataFromStackFrames(event); 7129 item[1] = event; 7130 } 7131 } 7132 }); 7133 }); 7134 client.on("applyFrameMetadata", (event) => { 7135 if (event.type) return; 7136 const stackParser = client.getOptions().stackParser; 7137 addMetadataToStackFrames(stackParser, event); 7138 }); 7139 } 7140 }; 7141 }); 7142 })))(); 7143} 7144//#endregion 7145//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/instrument/console.js 7146function addConsoleInstrumentationHandler(handler) { 7147 const type = "console"; 7148 const removeHandler = addHandler$1(type, handler); 7149 maybeInstrument(type, instrumentConsole); 7150 return removeHandler; 7151} 7152function instrumentConsole() { 7153 if (!("console" in GLOBAL_OBJ)) return; 7154 CONSOLE_LEVELS$1.forEach(function(level) { 7155 if (instrumentedLevels.has(level) || !(level in GLOBAL_OBJ.console)) return; 7156 instrumentedLevels.add(level); 7157 fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) { 7158 originalConsoleMethods[level] = originalConsoleMethod; 7159 return function(...args) { 7160 const firstArg = args[0]; 7161 const log = originalConsoleMethods[level]; 7162 const isFiltered = _filter.size && typeof firstArg === "string" && stringMatchesSomePattern(firstArg, _filter); 7163 if (!isFiltered) triggerHandlers$1("console", { 7164 args, 7165 level 7166 }); 7167 if (!isFiltered || DEBUG_BUILD$5 && debug$2.isEnabled()) log?.apply(GLOBAL_OBJ.console, args); 7168 }; 7169 }); 7170 }); 7171} 7172var _filter, instrumentedLevels; 7173function init_console() { 7174 return (init_console = __esmMin((() => { 7175 init_debug_build(); 7176 init_debug_logger(); 7177 init_object(); 7178 init_string(); 7179 init_worldwide(); 7180 init_handlers(); 7181 _filter = /* @__PURE__ */ new Set([]); 7182 instrumentedLevels = /* @__PURE__ */ new Set(); 7183 })))(); 7184} 7185//#endregion 7186//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/severity.js 7187function severityLevelFromString(level) { 7188 return level === "warn" ? "warning" : [ 7189 "fatal", 7190 "error", 7191 "warning", 7192 "log", 7193 "info", 7194 "debug" 7195 ].includes(level) ? level : "log"; 7196} 7197//#endregion 7198//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/captureconsole.js 7199function consoleHandler(args, level, handled) { 7200 const severityLevel = severityLevelFromString(level); 7201 const syntheticException = /* @__PURE__ */ new Error(); 7202 const captureContext = { 7203 level: severityLevelFromString(level), 7204 extra: { arguments: args } 7205 }; 7206 withScope((scope) => { 7207 scope.addEventProcessor((event) => { 7208 event.logger = "console"; 7209 addExceptionMechanism(event, { 7210 handled, 7211 type: "auto.core.capture_console" 7212 }); 7213 return event; 7214 }); 7215 if (level === "assert") { 7216 if (!args[0]) { 7217 const message2 = `Assertion failed: ${safeJoin(args.slice(1), " ") || "console.assert"}`; 7218 scope.setExtra("arguments", args.slice(1)); 7219 scope.captureMessage(message2, severityLevel, { 7220 captureContext, 7221 syntheticException 7222 }); 7223 } 7224 return; 7225 } 7226 const error = args.find((arg) => arg instanceof Error); 7227 if (error) { 7228 captureException(error, captureContext); 7229 return; 7230 } 7231 const message = safeJoin(args, " "); 7232 scope.captureMessage(message, severityLevel, { 7233 captureContext, 7234 syntheticException 7235 }); 7236 }); 7237} 7238var INTEGRATION_NAME$21, _captureConsoleIntegration, captureConsoleIntegration; 7239function init_captureconsole() { 7240 return (init_captureconsole = __esmMin((() => { 7241 init_currentScopes(); 7242 init_exports(); 7243 init_console(); 7244 init_integration(); 7245 init_debug_logger(); 7246 init_misc(); 7247 init_string(); 7248 init_worldwide(); 7249 INTEGRATION_NAME$21 = "CaptureConsole"; 7250 _captureConsoleIntegration = ((options = {}) => { 7251 const levels = options.levels || CONSOLE_LEVELS$1; 7252 const handled = options.handled ?? true; 7253 return { 7254 name: INTEGRATION_NAME$21, 7255 setup(client) { 7256 if (!("console" in GLOBAL_OBJ)) return; 7257 addConsoleInstrumentationHandler(({ args, level }) => { 7258 if (getClient() !== client || !levels.includes(level)) return; 7259 consoleHandler(args, level, handled); 7260 }); 7261 } 7262 }; 7263 }); 7264 captureConsoleIntegration = defineIntegration(_captureConsoleIntegration); 7265 })))(); 7266} 7267//#endregion 7268//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/dedupe.js 7269function _shouldDropEvent(currentEvent, previousEvent) { 7270 if (!previousEvent) return false;
7271 if (_isSameMessageEvent(currentEvent, previousEvent)) return true; 7272 if (_isSameExceptionEvent(currentEvent, previousEvent)) return true; 7273 return false; 7274} 7275function _isSameMessageEvent(currentEvent, previousEvent) { 7276 const currentMessage = currentEvent.message; 7277 const previousMessage = previousEvent.message; 7278 if (!currentMessage && !previousMessage) return false; 7279 if (currentMessage && !previousMessage || !currentMessage && previousMessage) return false; 7280 if (currentMessage !== previousMessage) return false; 7281 if (!_isSameFingerprint(currentEvent, previousEvent)) return false; 7282 if (!_isSameStacktrace(currentEvent, previousEvent)) return false; 7283 return true; 7284} 7285function _isSameExceptionEvent(currentEvent, previousEvent) { 7286 const previousException = _getExceptionFromEvent(previousEvent); 7287 const currentException = _getExceptionFromEvent(currentEvent); 7288 if (!previousException || !currentException) return false; 7289 if (previousException.type !== currentException.type || previousException.value !== currentException.value) return false; 7290 if (!_isSameFingerprint(currentEvent, previousEvent)) return false; 7291 if (!_isSameStacktrace(currentEvent, previousEvent)) return false; 7292 return true; 7293} 7294function _isSameStacktrace(currentEvent, previousEvent) { 7295 let currentFrames = getFramesFromEvent(currentEvent); 7296 let previousFrames = getFramesFromEvent(previousEvent); 7297 if (!currentFrames && !previousFrames) return true; 7298 if (currentFrames && !previousFrames || !currentFrames && previousFrames) return false; 7299 currentFrames = currentFrames; 7300 previousFrames = previousFrames; 7301 if (previousFrames.length !== currentFrames.length) return false; 7302 for (let i = 0; i < previousFrames.length; i++) { 7303 const frameA = previousFrames[i]; 7304 const frameB = currentFrames[i]; 7305 if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) return false; 7306 } 7307 return true; 7308} 7309function _isSameFingerprint(currentEvent, previousEvent) { 7310 let currentFingerprint = currentEvent.fingerprint; 7311 let previousFingerprint = previousEvent.fingerprint; 7312 if (!currentFingerprint && !previousFingerprint) return true; 7313 if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) return false; 7314 currentFingerprint = currentFingerprint; 7315 previousFingerprint = previousFingerprint; 7316 try { 7317 return !!(currentFingerprint.join("") === previousFingerprint.join("")); 7318 } catch { 7319 return false; 7320 } 7321} 7322function _getExceptionFromEvent(event) { 7323 return event.exception?.values?.[0]; 7324} 7325var INTEGRATION_NAME$20, _dedupeIntegration, dedupeIntegration; 7326function init_dedupe() { 7327 return (init_dedupe = __esmMin((() => { 7328 init_debug_build(); 7329 init_integration(); 7330 init_debug_logger(); 7331 init_stacktrace(); 7332 INTEGRATION_NAME$20 = "Dedupe"; 7333 _dedupeIntegration = (() => { 7334 let previousEvent; 7335 return { 7336 name: INTEGRATION_NAME$20, 7337 processEvent(currentEvent) { 7338 if (currentEvent.type) return currentEvent; 7339 try { 7340 if (_shouldDropEvent(currentEvent, previousEvent)) { 7341 DEBUG_BUILD$5 && debug$2.warn("Event dropped due to being a duplicate of previously captured event."); 7342 return null; 7343 } 7344 } catch {} 7345 return previousEvent = currentEvent; 7346 } 7347 }; 7348 }); 7349 dedupeIntegration = defineIntegration(_dedupeIntegration); 7350 })))(); 7351} 7352//#endregion 7353//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/extraerrordata.js 7354function _enhanceEventWithErrorData(event, hint = {}, depth, captureErrorCause, maxValueLength) { 7355 if (!hint.originalException || !isError(hint.originalException)) return event; 7356 const exceptionName = hint.originalException.name || hint.originalException.constructor.name; 7357 const errorData = _extractErrorData(hint.originalException, captureErrorCause, maxValueLength); 7358 if (errorData) { 7359 const contexts = { ...event.contexts }; 7360 const normalizedErrorData = normalize(errorData, depth); 7361 if (isPlainObject(normalizedErrorData)) { 7362 setSkipNormalizationHint(normalizedErrorData); 7363 contexts[exceptionName] = normalizedErrorData; 7364 } 7365 return { 7366 ...event, 7367 contexts 7368 }; 7369 } 7370 return event; 7371} 7372function _extractErrorData(error, captureErrorCause, maxValueLength) { 7373 try { 7374 const nativeKeys = [ 7375 "name", 7376 "message", 7377 "stack", 7378 "line", 7379 "column", 7380 "fileName", 7381 "lineNumber", 7382 "columnNumber", 7383 "toJSON" 7384 ];
7385 const extraErrorInfo = {}; 7386 for (const key of Object.keys(error)) { 7387 if (nativeKeys.indexOf(key) !== -1) continue; 7388 const value = error[key]; 7389 extraErrorInfo[key] = isError(value) || typeof value === "string" ? maxValueLength ? truncate(`${value}`, maxValueLength) : `${value}` : value; 7390 } 7391 if (captureErrorCause && error.cause !== void 0) { 7392 if (isError(error.cause)) extraErrorInfo.cause = { [error.cause.name || error.cause.constructor.name]: _extractErrorData(error.cause, false, maxValueLength) }; 7393 else extraErrorInfo.cause = error.cause; 7394 } 7395 if (typeof error.toJSON === "function") { 7396 const serializedError = error.toJSON(); 7397 for (const key of Object.keys(serializedError)) { 7398 const value = serializedError[key]; 7399 extraErrorInfo[key] = isError(value) ? value.toString() : value; 7400 } 7401 } 7402 return extraErrorInfo; 7403 } catch (oO) { 7404 DEBUG_BUILD$5 && debug$2.error("Unable to extract extra data from the Error object:", oO); 7405 } 7406 return null; 7407} 7408var INTEGRATION_NAME$19, _extraErrorDataIntegration, extraErrorDataIntegration; 7409function init_extraerrordata() { 7410 return (init_extraerrordata = __esmMin((() => { 7411 init_debug_build(); 7412 init_integration(); 7413 init_debug_logger(); 7414 init_is(); 7415 init_normalize(); 7416 init_normalizationHints(); 7417 init_string(); 7418 INTEGRATION_NAME$19 = "ExtraErrorData"; 7419 _extraErrorDataIntegration = ((options = {}) => { 7420 const { depth = 3, captureErrorCause = true } = options; 7421 return { 7422 name: INTEGRATION_NAME$19, 7423 processEvent(event, hint, client) { 7424 const { maxValueLength } = client.getOptions(); 7425 return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength); 7426 } 7427 }; 7428 }); 7429 extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration); 7430 })))(); 7431} 7432//#endregion 7433//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/path.js 7434function normalizeArray(parts, allowAboveRoot) { 7435 let up = 0; 7436 for (let i = parts.length - 1; i >= 0; i--) { 7437 const last = parts[i]; 7438 if (last === ".") parts.splice(i, 1); 7439 else if (last === "..") { 7440 parts.splice(i, 1); 7441 up++; 7442 } else if (up) { 7443 parts.splice(i, 1); 7444 up--; 7445 } 7446 } 7447 if (allowAboveRoot) for (; up--;) parts.unshift(".."); 7448 return parts; 7449} 7450function splitPath$1(filename) { 7451 const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename; 7452 const parts = splitPathRe.exec(truncated); 7453 return parts ? parts.slice(1) : []; 7454} 7455function resolve(...args) { 7456 let resolvedPath = ""; 7457 let resolvedAbsolute = false; 7458 for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { 7459 const path = i >= 0 ? args[i] : "/"; 7460 if (!path) continue; 7461 resolvedPath = `${path}/${resolvedPath}`; 7462 resolvedAbsolute = path.charAt(0) === "/"; 7463 } 7464 resolvedPath = normalizeArray(resolvedPath.split("/").filter((p) => !!p), !resolvedAbsolute).join("/"); 7465 return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; 7466} 7467function trim(arr) { 7468 let start = 0; 7469 for (; start < arr.length; start++) if (arr[start] !== "") break; 7470 let end = arr.length - 1; 7471 for (; end >= 0; end--) if (arr[end] !== "") break; 7472 if (start > end) return []; 7473 return arr.slice(start, end - start + 1); 7474} 7475function relative(from, to) { 7476 from = resolve(from).slice(1); 7477 to = resolve(to).slice(1); 7478 const fromParts = trim(from.split("/")); 7479 const toParts = trim(to.split("/")); 7480 const length = Math.min(fromParts.length, toParts.length); 7481 let samePartsLength = length; 7482 for (let i = 0; i < length; i++) if (fromParts[i] !== toParts[i]) { 7483 samePartsLength = i; 7484 break; 7485 } 7486 let outputParts = []; 7487 for (let i = samePartsLength; i < fromParts.length; i++) outputParts.push(".."); 7488 outputParts = outputParts.concat(toParts.slice(samePartsLength)); 7489 return outputParts.join("/"); 7490} 7491function basename(path, ext) { 7492 let f = splitPath$1(path)[2] || ""; 7493 if (ext && f.slice(ext.length * -1) === ext) f = f.slice(0, f.length - ext.length); 7494 return f; 7495} 7496var splitPathRe; 7497function init_path() { 7498 return (init_path = __esmMin((() => { 7499 splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/; 7500 })))(); 7501} 7502//#endregion 7503//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/rewriteframes.js 7504function generateIteratee({ isBrowser, root, prefix }) { 7505 return (frame) => { 7506 if (!frame.filename) return frame; 7507 const isWindowsFrame = /^[a-zA-Z]:\\/.test(frame.filename) || frame.filename.includes("\\") && !frame.filename.includes("/"); 7508 const startsWithSlash = /^\//.test(frame.filename); 7509 if (isBrowser) { 7510 if (root) { 7511 const oldFilename = frame.filename; 7512 if (oldFilename.indexOf(root) === 0) frame.filename = oldFilename.replace(root, prefix); 7513 } 7514 } else if (isWindowsFrame || startsWithSlash) { 7515 const filename = isWindowsFrame ? frame.filename.replace(/^[a-zA-Z]:/, "").replace(/\\/g, "/") : frame.filename; 7516 frame.filename = `${prefix}${root ? relative(root, filename) : basename(filename)}`; 7517 } 7518 return frame; 7519 }; 7520} 7521var INTEGRATION_NAME$18, rewriteFramesIntegration; 7522function init_rewriteframes() { 7523 return (init_rewriteframes = __esmMin((() => { 7524 init_integration(); 7525 init_path(); 7526 init_worldwide(); 7527 INTEGRATION_NAME$18 = "RewriteFrames"; 7528 rewriteFramesIntegration = defineIntegration((options = {}) => { 7529 const root = options.root; 7530 const prefix = options.prefix || "app:///"; 7531 const isBrowser = "window" in GLOBAL_OBJ && !!GLOBAL_OBJ.window; 7532 const iteratee = options.iteratee || generateIteratee({ 7533 isBrowser, 7534 root, 7535 prefix 7536 }); 7537 function _processExceptionsEvent(event) { 7538 try { 7539 return { 7540 ...event, 7541 exception: { 7542 ...event.exception, 7543 values: event.exception.values.map((value) => ({ 7544 ...value, 7545 ...value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) } 7546 })) 7547 } 7548 }; 7549 } catch { 7550 return event; 7551 } 7552 } 7553 function _processStacktrace(stacktrace) { 7554 return { 7555 ...stacktrace, 7556 frames: stacktrace?.frames?.map((f) => iteratee(f)) 7557 }; 7558 } 7559 return { 7560 name: INTEGRATION_NAME$18, 7561 processEvent(originalEvent) { 7562 let processedEvent = originalEvent; 7563 if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) processedEvent = _processExceptionsEvent(processedEvent); 7564 return processedEvent; 7565 } 7566 }; 7567 }); 7568 })))(); 7569} 7570//#endregion 7571//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/supabase.js 7572function markAsInstrumented(fn) { 7573 try { 7574 fn.__SENTRY_INSTRUMENTED__ = true; 7575 } catch {} 7576} 7577function isInstrumented(fn) { 7578 try { 7579 return fn.__SENTRY_INSTRUMENTED__; 7580 } catch { 7581 return false;
7582 } 7583} 7584function getMutationBodyPayloadForTelemetry(rawBody, plainBody) { 7585 if (Object.keys(plainBody).length > 0) return plainBody; 7586 if (Array.isArray(rawBody) && rawBody.length > 0) return rawBody; 7587} 7588function hasMutationBodyForDescription(rawBody, plainBody) { 7589 return getMutationBodyPayloadForTelemetry(rawBody, plainBody) !== void 0; 7590} 7591function getHeader(headers, name) { 7592 if (!headers) return; 7593 if (typeof headers.get === "function") return headers.get(name) ?? void 0; 7594 const plainHeaders = headers; 7595 const lowerCaseName = name.toLowerCase(); 7596 const key = Object.keys(plainHeaders).find((headerName) => headerName.toLowerCase() === lowerCaseName); 7597 return key !== void 0 ? plainHeaders[key] : void 0; 7598} 7599function extractOperation(method, headers = {}) { 7600 switch (method) { 7601 case "GET": return "select"; 7602 case "POST": if (getHeader(headers, "Prefer")?.includes("resolution=")) return "upsert"; 7603 else return "insert"; 7604 case "PATCH": return "update"; 7605 case "DELETE": return "delete"; 7606 default: return "<unknown-op>"; 7607 } 7608} 7609function translateFiltersIntoMethods(key, query) { 7610 if (query === "" || query === "*") return "select(*)"; 7611 if (key === "select") return `select(${query})`; 7612 if (key === "or" || key.endsWith(".or")) return `${key}${query}`; 7613 const [filter, ...value] = query.split("."); 7614 let method; 7615 if (filter?.startsWith("fts")) method = "textSearch"; 7616 else if (filter?.startsWith("plfts")) method = "textSearch[plain]"; 7617 else if (filter?.startsWith("phfts")) method = "textSearch[phrase]"; 7618 else if (filter?.startsWith("wfts")) method = "textSearch[websearch]"; 7619 else method = filter && FILTER_MAPPINGS[filter] || "filter"; 7620 return `${method}(${key}, ${value.join(".")})`; 7621} 7622function instrumentAuthOperation(operation, isAdmin = false) { 7623 return new Proxy(operation, { apply(target, thisArg, argumentsList) { 7624 return startSpan({ 7625 name: `auth ${isAdmin ? "(admin) " : ""}${operation.name}`, 7626 attributes: { 7627 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.supabase", 7628 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "db", 7629 "db.system": "postgresql", 7630 "db.operation": `auth.${isAdmin ? "admin." : ""}${operation.name}` 7631 } 7632 }, (span) => { 7633 return Reflect.apply(target, thisArg, argumentsList).then((res) => { 7634 if (isObjectLike(res) && "error" in res && res.error) { 7635 span.setStatus({ code: 2 }); 7636 captureException(res.error, { mechanism: { 7637 handled: false, 7638 type: "auto.db.supabase.auth" 7639 } }); 7640 } else span.setStatus({ code: 1 }); 7641 span.end(); 7642 return res; 7643 }).catch((err) => { 7644 span.setStatus({ code: 2 }); 7645 span.end(); 7646 captureException(err, { mechanism: { 7647 handled: false, 7648 type: "auto.db.supabase.auth" 7649 } }); 7650 throw err; 7651 }).then(...argumentsList); 7652 }); 7653 } }); 7654} 7655function instrumentSupabaseAuthClient(supabaseClientInstance) { 7656 const auth = supabaseClientInstance.auth; 7657 if (!auth || isInstrumented(supabaseClientInstance.auth)) return; 7658 for (const operation of AUTH_OPERATIONS_TO_INSTRUMENT) { 7659 const authOperation = auth[operation]; 7660 if (!authOperation) continue; 7661 if (typeof supabaseClientInstance.auth[operation] === "function") supabaseClientInstance.auth[operation] = instrumentAuthOperation(authOperation); 7662 } 7663 for (const operation of AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT) { 7664 const authOperation = auth.admin[operation]; 7665 if (!authOperation) continue; 7666 if (typeof supabaseClientInstance.auth.admin[operation] === "function") supabaseClientInstance.auth.admin[operation] = instrumentAuthOperation(authOperation, true); 7667 } 7668 markAsInstrumented(supabaseClientInstance.auth); 7669} 7670function instrumentSupabaseClientConstructor(SupabaseClient, _options) { 7671 if (isInstrumented(SupabaseClient.prototype.from)) return; 7672 SupabaseClient.prototype.from = new Proxy(SupabaseClient.prototype.from, { apply(target, thisArg, argumentsList) { 7673 const rv = Reflect.apply(target, thisArg, argumentsList); 7674 const PostgRESTQueryBuilder = rv.constructor; 7675 instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder, _options); 7676 return rv; 7677 } }); 7678 markAsInstrumented(SupabaseClient.prototype.from); 7679} 7680function instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder, _options) { 7681 if (isInstrumented(PostgRESTFilterBuilder.prototype.then)) return; 7682 PostgRESTFilterBuilder.prototype.then = new Proxy(PostgRESTFilterBuilder.prototype.then, { apply(target, thisArg, argumentsList) { 7683 const operations = DB_OPERATIONS_TO_INSTRUMENT; 7684 const typedThis = thisArg; 7685 const operation = extractOperation(typedThis.method, typedThis.headers); 7686 if (!operations.includes(operation)) return Reflect.apply(target, thisArg, argumentsList); 7687 if (!typedThis?.url?.pathname || typeof typedThis.url.pathname !== "string") return Reflect.apply(target, thisArg, argumentsList); 7688 const pathParts = typedThis.url.pathname.split("/"); 7689 const table = pathParts.length > 0 ? pathParts[pathParts.length - 1] : ""; 7690 const queryItems = [];
7691 for (const [key, value] of typedThis.url.searchParams.entries()) queryItems.push(translateFiltersIntoMethods(key, value)); 7692 const body = /* @__PURE__ */ Object.create(null); 7693 if (isPlainObject(typedThis.body)) for (const [key, value] of Object.entries(typedThis.body)) body[key] = value; 7694 const client = getClient(); 7695 const shouldSendData = _options.sendOperationData ?? client?.getDataCollectionOptions().databaseQueryData === true; 7696 const bodyPayload = getMutationBodyPayloadForTelemetry(typedThis.body, body); 7697 const mutationPart = operation === "select" ? "" : `${operation}${hasMutationBodyForDescription(typedThis.body, body) ? "(...) " : ""}`; 7698 const queryPart = shouldSendData ? queryItems.join(" ") : queryItems.length > 0 ? "[redacted]" : ""; 7699 const descriptionMiddle = [mutationPart.trimEnd(), queryPart].filter(Boolean).join(" "); 7700 const description = descriptionMiddle ? `${descriptionMiddle} from(${table})` : `from(${table})`; 7701 const attributes = { 7702 "db.table": table, 7703 "db.schema": typedThis.schema, 7704 "db.url": typedThis.url.origin, 7705 "db.sdk": getHeader(typedThis.headers, "X-Client-Info"), 7706 "db.system": "postgresql", 7707 "db.operation": operation, 7708 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.supabase", 7709 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "db" 7710 }; 7711 if (queryItems.length && shouldSendData) attributes["db.query"] = queryItems; 7712 if (bodyPayload !== void 0 && shouldSendData) attributes["db.body"] = bodyPayload; 7713 return startSpan({ 7714 name: description, 7715 attributes 7716 }, (span) => { 7717 return Reflect.apply(target, thisArg, []).then((res) => { 7718 if (span) { 7719 if (res && typeof res === "object" && "status" in res) setHttpStatus(span, res.status || 500); 7720 span.end(); 7721 } 7722 if (res?.error) { 7723 const err = new Error(res.error.message); 7724 if (res.error.code) err.code = res.error.code; 7725 if (res.error.details) err.details = res.error.details; 7726 const supabaseContext = {}; 7727 if (queryItems.length && shouldSendData) supabaseContext.query = queryItems; 7728 if (bodyPayload !== void 0 && shouldSendData) supabaseContext.body = bodyPayload; 7729 captureException(err, (scope) => { 7730 scope.addEventProcessor((e) => { 7731 addExceptionMechanism(e, { 7732 handled: false, 7733 type: "auto.db.supabase.postgres" 7734 }); 7735 return e; 7736 }); 7737 scope.setContext("supabase", supabaseContext); 7738 return scope; 7739 }); 7740 } 7741 const breadcrumb = { 7742 type: "supabase", 7743 category: `db.${operation}`, 7744 message: description 7745 }; 7746 const data = {}; 7747 if (queryItems.length && shouldSendData) data.query = queryItems; 7748 if (bodyPayload !== void 0 && shouldSendData) data.body = bodyPayload; 7749 if (Object.keys(data).length) breadcrumb.data = data; 7750 addBreadcrumb(breadcrumb); 7751 return res; 7752 }, (err) => { 7753 if (span) { 7754 setHttpStatus(span, 500); 7755 span.end(); 7756 } 7757 throw err; 7758 }).then(...argumentsList); 7759 }); 7760 } }); 7761 markAsInstrumented(PostgRESTFilterBuilder.prototype.then); 7762} 7763function instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder, _options) { 7764 for (const operation of DB_OPERATIONS_TO_INSTRUMENT) { 7765 if (isInstrumented(PostgRESTQueryBuilder.prototype[operation])) continue; 7766 PostgRESTQueryBuilder.prototype[operation] = new Proxy(PostgRESTQueryBuilder.prototype[operation], { apply(target, thisArg, argumentsList) { 7767 const rv = Reflect.apply(target, thisArg, argumentsList); 7768 const PostgRESTFilterBuilder = rv.constructor; 7769 DEBUG_BUILD$5 && debug$2.log(`Instrumenting ${operation} operation's PostgRESTFilterBuilder`); 7770 instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder, _options); 7771 return rv; 7772 } }); 7773 markAsInstrumented(PostgRESTQueryBuilder.prototype[operation]); 7774 } 7775} 7776var AUTH_OPERATIONS_TO_INSTRUMENT, AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT, FILTER_MAPPINGS, DB_OPERATIONS_TO_INSTRUMENT, instrumentSupabaseClient, INTEGRATION_NAME$17, _supabaseIntegration, supabaseIntegration; 7777function init_supabase() { 7778 return (init_supabase = __esmMin((() => { 7779 init_breadcrumbs(); 7780 init_currentScopes(); 7781 init_debug_build(); 7782 init_exports(); 7783 init_integration(); 7784 init_semanticAttributes(); 7785 init_debug_logger(); 7786 init_misc(); 7787 init_is(); 7788 init_spanstatus(); 7789 init_trace(); 7790 AUTH_OPERATIONS_TO_INSTRUMENT = [ 7791 "reauthenticate", 7792 "signInAnonymously", 7793 "signInWithOAuth", 7794 "signInWithIdToken", 7795 "signInWithOtp", 7796 "signInWithPassword", 7797 "signInWithSSO", 7798 "signOut", 7799 "signUp", 7800 "verifyOtp" 7801 ]; 7802 AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT = [ 7803 "createUser", 7804 "deleteUser", 7805 "listUsers", 7806 "getUserById", 7807 "updateUserById", 7808 "inviteUserByEmail" 7809 ]; 7810 FILTER_MAPPINGS = { 7811 eq: "eq", 7812 neq: "neq", 7813 gt: "gt", 7814 gte: "gte", 7815 lt: "lt", 7816 lte: "lte", 7817 like: "like", 7818 "like(all)": "likeAllOf", 7819 "like(any)": "likeAnyOf", 7820 ilike: "ilike", 7821 "ilike(all)": "ilikeAllOf", 7822 "ilike(any)": "ilikeAnyOf", 7823 is: "is", 7824 in: "in", 7825 cs: "contains", 7826 cd: "containedBy", 7827 sr: "rangeGt", 7828 nxl: "rangeGte", 7829 sl: "rangeLt", 7830 nxr: "rangeLte", 7831 adj: "rangeAdjacent", 7832 ov: "overlaps", 7833 fts: "", 7834 plfts: "plain", 7835 phfts: "phrase", 7836 wfts: "websearch", 7837 not: "not" 7838 };
7839 DB_OPERATIONS_TO_INSTRUMENT = [ 7840 "select", 7841 "insert", 7842 "upsert", 7843 "update", 7844 "delete" 7845 ]; 7846 instrumentSupabaseClient = (supabaseClient, options = {}) => { 7847 if (!supabaseClient) { 7848 DEBUG_BUILD$5 && debug$2.warn("Supabase integration was not installed because no Supabase client was provided."); 7849 return; 7850 } 7851 instrumentSupabaseClientConstructor(supabaseClient.constructor === Function ? supabaseClient : supabaseClient.constructor, options); 7852 instrumentSupabaseAuthClient(supabaseClient); 7853 }; 7854 INTEGRATION_NAME$17 = "Supabase"; 7855 _supabaseIntegration = ((supabaseClient, options) => { 7856 return { 7857 setupOnce() { 7858 instrumentSupabaseClient(supabaseClient, options); 7859 }, 7860 name: INTEGRATION_NAME$17 7861 }; 7862 }); 7863 supabaseIntegration = defineIntegration((options) => { 7864 return _supabaseIntegration(options.supabaseClient, { sendOperationData: options.sendOperationData }); 7865 }); 7866 })))(); 7867} 7868//#endregion 7869//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/zoderrors.js 7870function originalExceptionIsZodError(originalException) { 7871 return isError(originalException) && originalException.name === "ZodError" && Array.isArray(originalException.issues); 7872} 7873function flattenIssue(issue) { 7874 return { 7875 ...issue, 7876 path: "path" in issue && Array.isArray(issue.path) ? issue.path.join(".") : void 0, 7877 keys: "keys" in issue ? JSON.stringify(issue.keys) : void 0, 7878 unionErrors: "unionErrors" in issue ? JSON.stringify(issue.unionErrors) : void 0 7879 }; 7880} 7881function flattenIssuePath(path) { 7882 return path.map((p) => { 7883 if (typeof p === "number") return "<array>"; 7884 else return p; 7885 }).join("."); 7886} 7887function formatIssueMessage(zodError) { 7888 const errorKeyMap = /* @__PURE__ */ new Set(); 7889 for (const iss of zodError.issues) { 7890 const issuePath = flattenIssuePath(iss.path); 7891 if (issuePath.length > 0) errorKeyMap.add(issuePath); 7892 } 7893 const errorKeys = Array.from(errorKeyMap); 7894 if (errorKeys.length === 0) { 7895 let rootExpectedType = "variable"; 7896 if (zodError.issues.length > 0) { 7897 const iss = zodError.issues[0]; 7898 if (iss !== void 0 && "expected" in iss && typeof iss.expected === "string") rootExpectedType = iss.expected; 7899 } 7900 return `Failed to validate ${rootExpectedType}`; 7901 } 7902 return `Failed to validate keys: ${truncate(errorKeys.join(", "), 100)}`; 7903} 7904function applyZodErrorsToEvent(limit, saveZodIssuesAsAttachment = false, event, hint) { 7905 if (!event.exception?.values || !hint.originalException || !originalExceptionIsZodError(hint.originalException) || hint.originalException.issues.length === 0) return event; 7906 try { 7907 const flattenedIssues = (saveZodIssuesAsAttachment ? hint.originalException.issues : hint.originalException.issues.slice(0, limit)).map(flattenIssue); 7908 if (saveZodIssuesAsAttachment) { 7909 if (!Array.isArray(hint.attachments)) hint.attachments = []; 7910 hint.attachments.push({ 7911 filename: "zod_issues.json", 7912 data: JSON.stringify({ issues: flattenedIssues }) 7913 }); 7914 } 7915 return { 7916 ...event, 7917 exception: { 7918 ...event.exception, 7919 values: [{ 7920 ...event.exception.values[0], 7921 value: formatIssueMessage(hint.originalException) 7922 }, ...event.exception.values.slice(1)] 7923 }, 7924 extra: { 7925 ...event.extra, 7926 "zoderror.issues": flattenedIssues.slice(0, limit) 7927 } 7928 }; 7929 } catch (e) { 7930 return { 7931 ...event, 7932 extra: { 7933 ...event.extra, 7934 "zoderrors sentry integration parse error": { 7935 message: "an exception was thrown while processing ZodError within applyZodErrorsToEvent()", 7936 error: e instanceof Error ? `${e.name}: ${e.message} 7937${e.stack}` : "unknown" 7938 } 7939 } 7940 }; 7941 } 7942} 7943var DEFAULT_LIMIT$1, INTEGRATION_NAME$16, _zodErrorsIntegration, zodErrorsIntegration; 7944function init_zoderrors() { 7945 return (init_zoderrors = __esmMin((() => { 7946 init_integration(); 7947 init_is(); 7948 init_string(); 7949 DEFAULT_LIMIT$1 = 10; 7950 INTEGRATION_NAME$16 = "ZodErrors"; 7951 _zodErrorsIntegration = ((options = {}) => { 7952 const limit = options.limit ?? DEFAULT_LIMIT$1; 7953 return { 7954 name: INTEGRATION_NAME$16, 7955 processEvent(originalEvent, hint) { 7956 return applyZodErrorsToEvent(limit, options.saveZodIssuesAsAttachment, originalEvent, hint); 7957 } 7958 }; 7959 }); 7960 zodErrorsIntegration = defineIntegration(_zodErrorsIntegration); 7961 })))(); 7962} 7963//#endregion 7964//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/third-party-errors-filter.js 7965function isSentryInternalFrame(frame, frameIndex, insideSentryWrapped) { 7966 if (frameIndex !== 0) return false;
7967 if (insideSentryWrapped && isLikelyMinifiedSentryWrappedFrame(frame)) return true; 7968 if (frame.function === "sentryWrapped") return true; 7969 if (!frame.context_line || !frame.filename) return false; 7970 if (!frame.filename.includes("sentry") || !frame.filename.includes("helpers") || !frame.context_line.includes(SENTRY_INTERNAL_FN_APPLY)) return false; 7971 if (frame.pre_context) { 7972 const len = frame.pre_context.length; 7973 for (let i = 0; i < len; i++) if (frame.pre_context[i]?.includes(SENTRY_INTERNAL_COMMENT)) return true; 7974 } 7975 return false; 7976} 7977function getBundleKeysForAllFramesWithFilenames(event, ignoreSentryInternalFrames, insideSentryWrapped) { 7978 const frames = getFramesFromEvent(event); 7979 if (!frames) return; 7980 return frames.filter((frame, index) => { 7981 if (!frame.filename) return false; 7982 if (frame.lineno == null && frame.colno == null && frame.instruction_addr == null) return false; 7983 return !ignoreSentryInternalFrames || !isSentryInternalFrame(frame, index, !!insideSentryWrapped); 7984 }).map((frame) => { 7985 if (!frame.module_metadata) return []; 7986 return Object.keys(frame.module_metadata).filter((key) => key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX)).map((key) => key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length)); 7987 }); 7988} 7989function isLikelyMinifiedSentryWrappedFrame(frame) { 7990 return !frame.context_line && !frame.pre_context && !!frame.function && frame.function.length <= 2; 7991} 7992var thirdPartyErrorFilterIntegration, BUNDLER_PLUGIN_APP_KEY_PREFIX, SENTRY_INTERNAL_COMMENT, SENTRY_INTERNAL_FN_APPLY; 7993function init_third_party_errors_filter() { 7994 return (init_third_party_errors_filter = __esmMin((() => { 7995 init_integration(); 7996 init_metadata(); 7997 init_envelope(); 7998 init_stacktrace(); 7999 init_worldwide(); 8000 thirdPartyErrorFilterIntegration = defineIntegration((options) => { 8001 return { 8002 name: "ThirdPartyErrorsFilter", 8003 setup(client) { 8004 client.on("beforeEnvelope", (envelope) => { 8005 forEachEnvelopeItem(envelope, (item, type) => { 8006 if (type === "event") { 8007 const event = Array.isArray(item) ? item[1] : void 0; 8008 if (event) { 8009 stripMetadataFromStackFrames(event); 8010 item[1] = event; 8011 } 8012 } 8013 }); 8014 }); 8015 client.on("applyFrameMetadata", (event) => { 8016 if (event.type) return; 8017 const stackParser = client.getOptions().stackParser; 8018 addMetadataToStackFrames(stackParser, event); 8019 }); 8020 }, 8021 preprocessEvent(event) { 8022 if (options.ignoreSentryInternalFrames && (GLOBAL_OBJ._sentryWrappedDepth ?? 0) > 0) event.sdkProcessingMetadata = { 8023 ...event.sdkProcessingMetadata, 8024 insideSentryWrapped: true 8025 }; 8026 }, 8027 processEvent(event) { 8028 const insideSentryWrapped = options.ignoreSentryInternalFrames ? event.sdkProcessingMetadata?.insideSentryWrapped === true && event.exception?.values?.length === 1 : false; 8029 const frameKeys = getBundleKeysForAllFramesWithFilenames(event, options.ignoreSentryInternalFrames, insideSentryWrapped); 8030 if (frameKeys) { 8031 if (frameKeys[options.behaviour === "drop-error-if-contains-third-party-frames" || options.behaviour === "apply-tag-if-contains-third-party-frames" ? "some" : "every"]((keys) => !keys.some((key) => options.filterKeys.includes(key)))) { 8032 if (options.behaviour === "drop-error-if-contains-third-party-frames" || options.behaviour === "drop-error-if-exclusively-contains-third-party-frames") return null; 8033 else event.tags = { 8034 ...event.tags, 8035 third_party_code: true 8036 }; 8037 } 8038 } 8039 return event; 8040 } 8041 }; 8042 }); 8043 BUNDLER_PLUGIN_APP_KEY_PREFIX = "_sentryBundlerPluginAppKey:"; 8044 SENTRY_INTERNAL_COMMENT = "Attempt to invoke user-land function"; 8045 SENTRY_INTERNAL_FN_APPLY = "fn.apply(this, wrappedArguments)"; 8046 })))(); 8047} 8048//#endregion 8049//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/featureFlags.js 8050function _INTERNAL_copyFlagsFromScopeToEvent(event) { 8051 if (event.type) return event; 8052 const flagContext = getCurrentScope().getScopeData().contexts.flags; 8053 const flagBuffer = flagContext ? flagContext.values : []; 8054 if (!flagBuffer.length) return event; 8055 if (event.contexts === void 0) event.contexts = {}; 8056 event.contexts.flags = { values: [...flagBuffer] }; 8057 return event; 8058} 8059function _INTERNAL_insertFlagToScope(name, value, maxSize = 100) { 8060 const scopeContexts = getCurrentScope().getScopeData().contexts; 8061 if (!scopeContexts.flags) scopeContexts.flags = { values: [] }; 8062 const flags = scopeContexts.flags.values;
8063 _INTERNAL_insertToFlagBuffer(flags, name, value, maxSize); 8064} 8065function _INTERNAL_insertToFlagBuffer(flags, name, value, maxSize) { 8066 if (typeof value !== "boolean") return; 8067 if (flags.length > maxSize) { 8068 DEBUG_BUILD$5 && debug$2.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`); 8069 return; 8070 } 8071 const index = flags.findIndex((f) => f.flag === name); 8072 if (index !== -1) flags.splice(index, 1); 8073 if (flags.length === maxSize) flags.shift(); 8074 flags.push({ 8075 flag: name, 8076 result: value 8077 }); 8078} 8079function _INTERNAL_addFeatureFlagToActiveSpan(name, value, maxFlagsPerSpan = 10) { 8080 if (typeof value !== "boolean") return; 8081 const span = getActiveSpan(); 8082 if (!span) return; 8083 const attributes = spanToJSON(span).data; 8084 if (`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}` in attributes) { 8085 span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value); 8086 return; 8087 } 8088 if (Object.keys(attributes).filter((key) => key.startsWith(SPAN_FLAG_ATTRIBUTE_PREFIX)).length < maxFlagsPerSpan) span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value); 8089} 8090var SPAN_FLAG_ATTRIBUTE_PREFIX; 8091function init_featureFlags() { 8092 return (init_featureFlags = __esmMin((() => { 8093 init_currentScopes(); 8094 init_debug_build(); 8095 init_debug_logger(); 8096 init_spanUtils(); 8097 SPAN_FLAG_ATTRIBUTE_PREFIX = "flag.evaluation."; 8098 })))(); 8099} 8100//#endregion 8101//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/featureFlags/featureFlagsIntegration.js 8102var featureFlagsIntegration; 8103function init_featureFlagsIntegration() { 8104 return (init_featureFlagsIntegration = __esmMin((() => { 8105 init_integration(); 8106 init_featureFlags(); 8107 featureFlagsIntegration = defineIntegration(() => { 8108 return { 8109 name: "FeatureFlags", 8110 processEvent(event, _hint, _client) { 8111 return _INTERNAL_copyFlagsFromScopeToEvent(event); 8112 }, 8113 addFeatureFlag(name, value) { 8114 _INTERNAL_insertFlagToScope(name, value); 8115 _INTERNAL_addFeatureFlagToActiveSpan(name, value); 8116 } 8117 }; 8118 }); 8119 })))(); 8120} 8121//#endregion 8122//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/featureFlags/growthbook.js 8123function _wrapAndCaptureBooleanResult(original) { 8124 return function(...args) { 8125 const flagName = args[0]; 8126 const result = original.apply(this, args); 8127 if (typeof flagName === "string" && typeof result === "boolean") { 8128 _INTERNAL_insertFlagToScope(flagName, result); 8129 _INTERNAL_addFeatureFlagToActiveSpan(flagName, result); 8130 } 8131 return result; 8132 }; 8133} 8134var growthbookIntegration$1; 8135function init_growthbook() { 8136 return (init_growthbook = __esmMin((() => { 8137 init_integration(); 8138 init_featureFlags(); 8139 init_object(); 8140 growthbookIntegration$1 = defineIntegration(({ growthbookClass }) => { 8141 return { 8142 name: "GrowthBook", 8143 setupOnce() { 8144 const proto = growthbookClass.prototype; 8145 if (typeof proto.isOn === "function") fill(proto, "isOn", _wrapAndCaptureBooleanResult); 8146 if (typeof proto.getFeatureValue === "function") fill(proto, "getFeatureValue", _wrapAndCaptureBooleanResult); 8147 }, 8148 processEvent(event, _hint, _client) { 8149 return _INTERNAL_copyFlagsFromScopeToEvent(event); 8150 } 8151 }; 8152 }); 8153 })))(); 8154} 8155//#endregion 8156//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/conversationId.js 8157var INTEGRATION_NAME$15, _conversationIdIntegration, conversationIdIntegration; 8158function init_conversationId() { 8159 return (init_conversationId = __esmMin((() => { 8160 init_currentScopes(); 8161 init_integration(); 8162 init_semanticAttributes(); 8163 init_spanUtils(); 8164 INTEGRATION_NAME$15 = "ConversationId"; 8165 _conversationIdIntegration = (() => { 8166 return { 8167 name: INTEGRATION_NAME$15, 8168 setup(client) { 8169 client.on("spanStart", (span) => { 8170 const scopeData = getCurrentScope().getScopeData(); 8171 const isolationScopeData = getIsolationScope().getScopeData(); 8172 const conversationId = scopeData.conversationId || isolationScopeData.conversationId; 8173 if (conversationId) { 8174 const { op, data: attributes, description: name } = spanToJSON(span); 8175 if (!op?.startsWith("gen_ai.") && !attributes["ai.operationId"] && !name?.startsWith("ai.")) return; 8176 span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE$1, conversationId); 8177 } 8178 }); 8179 } 8180 }; 8181 }); 8182 conversationIdIntegration = defineIntegration(_conversationIdIntegration); 8183 })))(); 8184} 8185//#endregion 8186//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/fetch.js 8187function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders, spans, spanOriginOrOptions) { 8188 if (!handlerData.fetchData) return; 8189 const { method, url } = handlerData.fetchData; 8190 const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(url); 8191 if (handlerData.endTimestamp) { 8192 const spanId = handlerData.fetchData.__span; 8193 if (!spanId) return; 8194 const span2 = spans[spanId];
8195 if (span2) { 8196 if (shouldCreateSpanResult) { 8197 endSpan(span2, handlerData); 8198 _callOnRequestSpanEnd(span2, handlerData, spanOriginOrOptions); 8199 } 8200 delete spans[spanId]; 8201 } 8202 return; 8203 } 8204 const { spanOrigin = "auto.http.browser", propagateTraceparent = false } = typeof spanOriginOrOptions === "object" ? spanOriginOrOptions : { spanOrigin: spanOriginOrOptions }; 8205 const client = getClient(); 8206 const hasParent = !!getActiveSpan(); 8207 const shouldEmitSpan = hasParent || !!client && hasSpanStreamingEnabled(client); 8208 const span = shouldCreateSpanResult && shouldEmitSpan ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin)) : new SentryNonRecordingSpan(); 8209 const spanForTraceHeaders = spanIsIgnored(span) && hasParent ? void 0 : span; 8210 if (shouldCreateSpanResult && !shouldEmitSpan) client?.recordDroppedEvent("no_parent_span", "span"); 8211 handlerData.fetchData.__span = span.spanContext().spanId; 8212 spans[span.spanContext().spanId] = span; 8213 if (shouldAttachHeaders(handlerData.fetchData.url)) { 8214 const request = handlerData.args[0]; 8215 const options = { ...handlerData.args[1] || {} }; 8216 const headers = _INTERNAL_getTracingHeadersForFetchRequest(request, options, hasSpansEnabled() && shouldEmitSpan ? spanForTraceHeaders : void 0, propagateTraceparent); 8217 if (headers) { 8218 handlerData.args[1] = options; 8219 options.headers = headers; 8220 } 8221 } 8222 if (client) { 8223 const fetchHint = { 8224 input: handlerData.args, 8225 response: handlerData.response, 8226 startTimestamp: handlerData.startTimestamp, 8227 endTimestamp: handlerData.endTimestamp 8228 }; 8229 client.emit("beforeOutgoingRequestSpan", span, fetchHint); 8230 } 8231 return span; 8232} 8233function _callOnRequestSpanEnd(span, handlerData, spanOriginOrOptions) { 8234 (typeof spanOriginOrOptions === "object" && spanOriginOrOptions !== null ? spanOriginOrOptions.onRequestSpanEnd : void 0)?.(span, { 8235 headers: handlerData.response?.headers, 8236 error: handlerData.error 8237 }); 8238} 8239function _INTERNAL_getTracingHeadersForFetchRequest(request, fetchOptionsObj, span, propagateTraceparent) { 8240 const traceHeaders = getTraceData({ 8241 span, 8242 propagateTraceparent 8243 }); 8244 const sentryTrace = traceHeaders["sentry-trace"]; 8245 const baggage = traceHeaders.baggage; 8246 const traceparent = traceHeaders.traceparent; 8247 if (!sentryTrace) return; 8248 const originalHeaders = fetchOptionsObj.headers || (isRequest(request) ? request.headers : void 0); 8249 if (!originalHeaders) return { 8250 "sentry-trace": sentryTrace, 8251 ...baggage && { baggage }, 8252 ...traceparent && { traceparent } 8253 }; 8254 else if (isHeaders(originalHeaders)) { 8255 const newHeaders = new Headers(originalHeaders); 8256 if (!newHeaders.get("sentry-trace")) newHeaders.set("sentry-trace", sentryTrace); 8257 if (propagateTraceparent && traceparent && !newHeaders.get("traceparent")) newHeaders.set("traceparent", traceparent); 8258 if (baggage) { 8259 const prevBaggageHeader = newHeaders.get("baggage"); 8260 if (!prevBaggageHeader) newHeaders.set("baggage", baggage); 8261 else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) newHeaders.set("baggage", `${prevBaggageHeader},${baggage}`); 8262 } 8263 return newHeaders; 8264 } else if (isHeadersInitTupleArray(originalHeaders)) { 8265 const newHeaders = [...originalHeaders]; 8266 if (!newHeaders.find((header) => header[0] === "sentry-trace")) newHeaders.push(["sentry-trace", sentryTrace]); 8267 if (propagateTraceparent && traceparent && !newHeaders.find((header) => header[0] === "traceparent")) newHeaders.push(["traceparent", traceparent]); 8268 const prevBaggageHeaderWithSentryValues = originalHeaders.find((header) => header[0] === "baggage" && typeof header[1] === "string" && baggageHeaderHasSentryBaggageValues(header[1])); 8269 if (baggage && !prevBaggageHeaderWithSentryValues) newHeaders.push(["baggage", baggage]); 8270 return newHeaders; 8271 } else { 8272 const existingSentryTraceHeader = "sentry-trace" in originalHeaders ? originalHeaders["sentry-trace"] : void 0; 8273 const existingTraceparentHeader = "traceparent" in originalHeaders ? originalHeaders.traceparent : void 0; 8274 const existingBaggageHeader = "baggage" in originalHeaders ? originalHeaders.baggage : void 0; 8275 const newBaggageHeaders = existingBaggageHeader ? Array.isArray(existingBaggageHeader) ? [...existingBaggageHeader] : [existingBaggageHeader] : []; 8276 const prevBaggageHeaderWithSentryValues = existingBaggageHeader && (Array.isArray(existingBaggageHeader) ? existingBaggageHeader.find((headerItem) => baggageHeaderHasSentryBaggageValues(headerItem)) : baggageHeaderHasSentryBaggageValues(existingBaggageHeader)); 8277 if (baggage && !prevBaggageHeaderWithSentryValues) newBaggageHeaders.push(baggage); 8278 const newHeaders = Object.assign({}, originalHeaders, { 8279 "sentry-trace": existingSentryTraceHeader ?? sentryTrace, 8280 ...newBaggageHeaders.length > 0 && { baggage: newBaggageHeaders.join(",") } 8281 }); 8282 if (propagateTraceparent && traceparent && !existingTraceparentHeader) newHeaders.traceparent = traceparent; 8283 return newHeaders; 8284 } 8285} 8286function endSpan(span, handlerData) { 8287 if (handlerData.response) { 8288 setHttpStatus(span, handlerData.response.status); 8289 const contentLength = handlerData.response?.headers?.get("content-length"); 8290 if (contentLength) { 8291 const contentLengthNum = parseInt(contentLength); 8292 if (contentLengthNum > 0) span.setAttribute("http.response_content_length", contentLengthNum); 8293 } 8294 } else if (handlerData.error) span.setStatus({ 8295 code: 2, 8296 message: "internal_error" 8297 }); 8298 span.end(); 8299} 8300function baggageHeaderHasSentryBaggageValues(baggageHeader) { 8301 if (typeof baggageHeader !== "string") return false;
8302 return baggageHeader.split(",").some((baggageEntry) => baggageEntry.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX)); 8303} 8304function isHeaders(headers) { 8305 return typeof Headers !== "undefined" && isInstanceOf(headers, Headers); 8306} 8307function isHeadersInitTupleArray(headers) { 8308 if (!Array.isArray(headers)) return false; 8309 return headers.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string"); 8310} 8311function getSpanStartOptions(url, method, spanOrigin) { 8312 if (url.startsWith("data:")) return { 8313 name: `${method} ${stripDataUrlContent(url)}`, 8314 attributes: getFetchSpanAttributes(url, void 0, method, spanOrigin) 8315 }; 8316 const parsedUrl = parseStringToURLObject(url); 8317 return { 8318 name: `${method} ${parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url}`, 8319 attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin) 8320 }; 8321} 8322function getFetchSpanAttributes(url, parsedUrl, method, spanOrigin) { 8323 const attributes = { 8324 url: stripDataUrlContent(url), 8325 type: "fetch", 8326 "http.method": method, 8327 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin, 8328 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client" 8329 }; 8330 if (parsedUrl) { 8331 if (!isURLObjectRelative(parsedUrl)) { 8332 attributes[ws] = stripDataUrlContent(parsedUrl.href); 8333 attributes[Yu] = stripDataUrlContent(parsedUrl.href); 8334 attributes["server.address"] = parsedUrl.host; 8335 } 8336 if (parsedUrl.search) attributes["http.query"] = parsedUrl.search; 8337 if (parsedUrl.hash) attributes["http.fragment"] = parsedUrl.hash; 8338 } 8339 return attributes; 8340} 8341function init_fetch() { 8342 return (init_fetch = __esmMin((() => { 8343 init_attributes$1(); 8344 init_currentScopes(); 8345 init_semanticAttributes(); 8346 init_spanUtils(); 8347 init_spanstatus(); 8348 init_is(); 8349 init_hasSpansEnabled(); 8350 init_sentryNonRecordingSpan(); 8351 init_baggage(); 8352 init_trace(); 8353 init_traceData(); 8354 init_url(); 8355 })))(); 8356} 8357//#endregion 8358//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/feedback.js 8359function captureFeedback(params, hint = {}, scope = getCurrentScope()) { 8360 const { message, name, email, url, source, associatedEventId, tags } = params; 8361 const feedbackEvent = { 8362 contexts: { feedback: { 8363 contact_email: email, 8364 name, 8365 message, 8366 url, 8367 source, 8368 associated_event_id: associatedEventId 8369 } }, 8370 type: "feedback", 8371 level: "info", 8372 tags 8373 }; 8374 const client = scope?.getClient() || getClient(); 8375 if (client) client.emit("beforeSendFeedback", feedbackEvent, hint); 8376 return scope.captureEvent(feedbackEvent, hint); 8377} 8378function init_feedback() { 8379 return (init_feedback = __esmMin((() => { 8380 init_currentScopes(); 8381 })))(); 8382} 8383//#endregion 8384//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/public-api.js 8385var public_api_exports$1 = /* @__PURE__ */ __exportAll({ 8386 debug: () => debug$1, 8387 error: () => error, 8388 fatal: () => fatal, 8389 fmt: () => fmt, 8390 info: () => info, 8391 trace: () => trace, 8392 warn: () => warn 8393}); 8394function captureLog(level, message, attributes, scope, severityNumber) { 8395 _INTERNAL_captureLog({ 8396 level, 8397 message, 8398 attributes, 8399 severityNumber 8400 }, scope); 8401} 8402function trace(message, attributes, { scope } = {}) { 8403 captureLog("trace", message, attributes, scope); 8404} 8405function debug$1(message, attributes, { scope } = {}) { 8406 captureLog("debug", message, attributes, scope); 8407} 8408function info(message, attributes, { scope } = {}) { 8409 captureLog("info", message, attributes, scope); 8410} 8411function warn(message, attributes, { scope } = {}) { 8412 captureLog("warn", message, attributes, scope); 8413} 8414function error(message, attributes, { scope } = {}) { 8415 captureLog("error", message, attributes, scope); 8416} 8417function fatal(message, attributes, { scope } = {}) { 8418 captureLog("fatal", message, attributes, scope); 8419} 8420function init_public_api() { 8421 return (init_public_api = __esmMin((() => { 8422 init_internal(); 8423 init_parameterize(); 8424 })))(); 8425} 8426//#endregion 8427//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/utils.js 8428function formatConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) { 8429 return "util" in GLOBAL_OBJ && typeof GLOBAL_OBJ.util.format === "function" ? GLOBAL_OBJ.util.format(...values) : safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth); 8430} 8431function safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) { 8432 return values.map((value) => isPrimitive(value) ? String(value) : JSON.stringify(normalize(value, normalizeDepth, normalizeMaxBreadth))).join(" "); 8433} 8434function hasConsoleSubstitutions(str) { 8435 return /%[sdifocO]/.test(str); 8436} 8437function createConsoleTemplateAttributes(firstArg, followingArgs) { 8438 const attributes = {}; 8439 attributes["sentry.message.template"] = `${firstArg} ${new Array(followingArgs.length).fill("{}").join(" ")}`;
8440 followingArgs.forEach((arg, index) => { 8441 attributes[`sentry.message.parameter.${index}`] = arg; 8442 }); 8443 return attributes; 8444} 8445function init_utils$1() { 8446 return (init_utils$1 = __esmMin((() => { 8447 init_is(); 8448 init_normalize(); 8449 init_worldwide(); 8450 })))(); 8451} 8452//#endregion 8453//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/logs/console-integration.js 8454var INTEGRATION_NAME$14, DEFAULT_ATTRIBUTES, _consoleLoggingIntegration, consoleLoggingIntegration; 8455function init_console_integration() { 8456 return (init_console_integration = __esmMin((() => { 8457 init_currentScopes(); 8458 init_debug_build(); 8459 init_console(); 8460 init_integration(); 8461 init_semanticAttributes(); 8462 init_debug_logger(); 8463 init_is(); 8464 init_normalize(); 8465 init_internal(); 8466 init_utils$1(); 8467 INTEGRATION_NAME$14 = "ConsoleLogs"; 8468 DEFAULT_ATTRIBUTES = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.log.console" }; 8469 _consoleLoggingIntegration = ((options = {}) => { 8470 const levels = options.levels || CONSOLE_LEVELS$1; 8471 return { 8472 name: INTEGRATION_NAME$14, 8473 setup(client) { 8474 const { enableLogs, normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = client.getOptions(); 8475 if (!enableLogs) { 8476 DEBUG_BUILD$5 && debug$2.warn("`enableLogs` is not enabled, ConsoleLogs integration disabled"); 8477 return; 8478 } 8479 const unsubscribe = addConsoleInstrumentationHandler(({ args, level }) => { 8480 if (getClient() !== client || !levels.includes(level)) return; 8481 const firstArg = args[0]; 8482 const followingArgs = args.slice(1); 8483 if (level === "assert") { 8484 if (!firstArg) _INTERNAL_captureLog({ 8485 level: "error", 8486 message: followingArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(followingArgs, normalizeDepth, normalizeMaxBreadth)}` : "Assertion failed", 8487 attributes: DEFAULT_ATTRIBUTES 8488 }); 8489 return; 8490 } 8491 const isLevelLog = level === "log"; 8492 const attributes = { ...DEFAULT_ATTRIBUTES }; 8493 if (isPlainObject(firstArg)) { 8494 Object.assign(attributes, normalize(firstArg, normalizeDepth, normalizeMaxBreadth)); 8495 const remainingArgsStartIndex = typeof args[1] === "string" ? 2 : 1; 8496 args.slice(remainingArgsStartIndex).forEach((arg, index) => { 8497 attributes[`sentry.message.parameter.${index}`] = normalize(arg, normalizeDepth, normalizeMaxBreadth); 8498 }); 8499 } else if (followingArgs.length > 0 && typeof firstArg === "string" && !hasConsoleSubstitutions(firstArg)) { 8500 const templateAttrs = createConsoleTemplateAttributes(firstArg, followingArgs); 8501 for (const [key, value] of Object.entries(templateAttrs)) attributes[key] = key.startsWith("sentry.message.parameter.") ? normalize(value, normalizeDepth, normalizeMaxBreadth) : value; 8502 } 8503 _INTERNAL_captureLog({ 8504 level: isLevelLog ? "info" : level, 8505 message: formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth), 8506 severityNumber: isLevelLog ? 10 : void 0, 8507 attributes 8508 }); 8509 }); 8510 client.registerCleanup(unsubscribe); 8511 } 8512 }; 8513 }); 8514 consoleLoggingIntegration = defineIntegration(_consoleLoggingIntegration); 8515 })))(); 8516} 8517//#endregion 8518//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/metrics/public-api.js 8519var public_api_exports = /* @__PURE__ */ __exportAll({ 8520 count: () => count, 8521 distribution: () => distribution, 8522 gauge: () => gauge 8523}); 8524function captureMetric(type, name, value, options) { 8525 _INTERNAL_captureMetric({ 8526 type, 8527 name, 8528 value, 8529 unit: options?.unit, 8530 attributes: options?.attributes 8531 }, { scope: options?.scope }); 8532} 8533function count(name, value = 1, options) { 8534 captureMetric("counter", name, value, options); 8535} 8536function gauge(name, value, options) { 8537 captureMetric("gauge", name, value, options); 8538} 8539function distribution(name, value, options) { 8540 captureMetric("distribution", name, value, options); 8541} 8542function init_public_api$1() { 8543 return (init_public_api$1 = __esmMin((() => { 8544 init_internal$1(); 8545 })))(); 8546} 8547//#endregion 8548//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/integrations/consola.js 8549function createConsolaReporter(options = {}) { 8550 const levels = new Set(options.levels ?? DEFAULT_CAPTURED_LEVELS); 8551 const providedClient = options.client; 8552 return { log(logObj) { 8553 const { type, level, message: consolaMessage, args, tag, date: _date, ...rest } = logObj; 8554 const client = providedClient || getClient(); 8555 if (!client) return; 8556 const logSeverityLevel = getLogSeverityLevel(type, level); 8557 if (!levels.has(logSeverityLevel)) return; 8558 const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = client.getOptions(); 8559 const attributes = {}; 8560 for (const [key, value] of Object.entries(rest)) attributes[key] = normalize(value, normalizeDepth, normalizeMaxBreadth); 8561 attributes["sentry.origin"] = "auto.log.consola"; 8562 if (tag) attributes["consola.tag"] = tag; 8563 if (type) attributes["consola.type"] = type; 8564 if (level != null && typeof level === "number") attributes["consola.level"] = level; 8565 const extractionResult = processExtractedAttributes(defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth), normalizeDepth, normalizeMaxBreadth); 8566 if (extractionResult?.attributes) Object.assign(attributes, extractionResult.attributes); 8567 _INTERNAL_captureLog({ 8568 level: logSeverityLevel, 8569 message: extractionResult?.message || consolaMessage || args && formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth) || "", 8570 attributes 8571 }); 8572 } }; 8573} 8574function getLogSeverityLevel(type, level) { 8575 if (type === "verbose") return "debug"; 8576 if (type === "silent") return "trace"; 8577 if (type) { 8578 const mappedLevel = CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP[type]; 8579 if (mappedLevel) return mappedLevel; 8580 } 8581 if (typeof level === "number") { 8582 const mappedLevel = CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[level]; 8583 if (mappedLevel) return mappedLevel; 8584 } 8585 return "info"; 8586} 8587function defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth) { 8588 if (!args?.length) return { message: "" }; 8589 const message = formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth); 8590 const firstArg = args[0]; 8591 if (isPlainObject(firstArg)) { 8592 const remainingArgsStartIndex = typeof args[1] === "string" ? 2 : 1; 8593 return { 8594 message, 8595 attributes: firstArg, 8596 messageParameters: args.slice(remainingArgsStartIndex) 8597 }; 8598 } else { 8599 const followingArgs = args.slice(1); 8600 const shouldAddTemplateAttr = followingArgs.length > 0 && typeof firstArg === "string" && !hasConsoleSubstitutions(firstArg); 8601 return { 8602 message, 8603 messageTemplate: shouldAddTemplateAttr ? firstArg : void 0, 8604 messageParameters: shouldAddTemplateAttr ? followingArgs : void 0 8605 }; 8606 } 8607} 8608function processExtractedAttributes(extractionResult, normalizeDepth, normalizeMaxBreadth) { 8609 const { message, attributes, messageTemplate, messageParameters } = extractionResult; 8610 const messageParamAttributes = {}; 8611 if (messageTemplate && messageParameters) { 8612 const templateAttrs = createConsoleTemplateAttributes(messageTemplate, messageParameters); 8613 for (const [key, value] of Object.entries(templateAttrs)) messageParamAttributes[key] = key.startsWith("sentry.message.parameter.") ? normalize(value, normalizeDepth, normalizeMaxBreadth) : value; 8614 } else if (messageParameters && messageParameters.length >
8614 0) messageParameters.forEach((arg, index) => { 8615 messageParamAttributes[`sentry.message.parameter.${index}`] = normalize(arg, normalizeDepth, normalizeMaxBreadth); 8616 }); 8617 return { 8618 message, 8619 attributes: { 8620 ...normalize(attributes, normalizeDepth, normalizeMaxBreadth), 8621 ...messageParamAttributes 8622 } 8623 }; 8624} 8625var DEFAULT_CAPTURED_LEVELS, CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP, CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP; 8626function init_consola() { 8627 return (init_consola = __esmMin((() => { 8628 init_currentScopes(); 8629 init_internal(); 8630 init_utils$1(); 8631 init_is(); 8632 init_normalize(); 8633 DEFAULT_CAPTURED_LEVELS = [ 8634 "trace", 8635 "debug", 8636 "info", 8637 "warn", 8638 "error", 8639 "fatal" 8640 ]; 8641 CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP = { 8642 silent: "trace", 8643 fatal: "fatal", 8644 error: "error", 8645 warn: "warn", 8646 log: "info", 8647 info: "info", 8648 success: "info", 8649 fail: "error", 8650 ready: "info", 8651 start: "info", 8652 box: "info", 8653 debug: "debug", 8654 trace: "trace", 8655 verbose: "debug", 8656 critical: "fatal", 8657 notice: "info" 8658 }; 8659 CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = { 8660 0: "fatal", 8661 1: "warn", 8662 2: "info", 8663 3: "info", 8664 4: "debug", 8665 5: "trace" 8666 }; 8667 })))(); 8668} 8669//#endregion 8670//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js 8671var GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENA
8671LTY_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE, GEN_AI_TOOL_NAME_ATTRIBUTE, GEN_AI_TOOL_CALL_ID_ATTRIBUTE, GEN_AI_TOOL_TYPE_ATTRIBUTE, GEN_AI_TOOL_INPUT_ATTRIBUTE, GEN_AI_TOOL_OUTPUT_ATTRIBUTE, GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE; 8672function init_gen_ai_attributes() { 8673 return (init_gen_ai_attributes = __esmMin((() => { 8674 GEN_AI_PROMPT_ATTRIBUTE = "gen_ai.prompt"; 8675 GEN_AI_SYSTEM_ATTRIBUTE = "gen_ai.system"; 8676 GEN_AI_REQUEST_MODEL_ATTRIBUTE = "gen_ai.request.model"; 8677 GEN_AI_REQUEST_STREAM_ATTRIBUTE = "gen_ai.request.stream"; 8678 GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = "gen_ai.request.temperature"; 8679 GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = "gen_ai.request.max_tokens";
8680 GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = "gen_ai.request.frequency_penalty"; 8681 GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = "gen_ai.request.presence_penalty"; 8682 GEN_AI_REQUEST_TOP_P_ATTRIBUTE = "gen_ai.request.top_p"; 8683 GEN_AI_REQUEST_TOP_K_ATTRIBUTE = "gen_ai.request.top_k"; 8684 GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = "gen_ai.request.encoding_format"; 8685 GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = "gen_ai.request.dimensions"; 8686 GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = "gen_ai.response.finish_reasons"; 8687 GEN_AI_RESPONSE_MODEL_ATTRIBUTE = "gen_ai.response.model"; 8688 GEN_AI_RESPONSE_ID_ATTRIBUTE = "gen_ai.response.id"; 8689 GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = "gen_ai.response.stop_reason"; 8690 GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.input_tokens"; 8691 GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.output_tokens"; 8692 GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = "gen_ai.usage.total_tokens"; 8693 GEN_AI_OPERATION_NAME_ATTRIBUTE = "gen_ai.operation.name"; 8694 GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = "sentry.sdk_meta.gen_ai.input.messages.original_length"; 8695 GEN_AI_INPUT_MESSAGES_ATTRIBUTE = "gen_ai.input.messages"; 8696 GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = "gen_ai.system_instructions"; 8697 GEN_AI_RESPONSE_TEXT_ATTRIBUTE = "gen_ai.response.text"; 8698 GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = "gen_ai.request.available_tools"; 8699 GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = "gen_ai.response.streaming"; 8700 GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = "gen_ai.response.tool_calls"; 8701 GEN_AI_AGENT_NAME_ATTRIBUTE = "gen_ai.agent.name"; 8702 GEN_AI_PIPELINE_NAME_ATTRIBUTE = "gen_ai.pipeline.name"; 8703 GEN_AI_CONVERSATION_ID_ATTRIBUTE = "gen_ai.conversation.id"; 8704 GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.cache_creation_input_tokens"; 8705 GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.cache_read_input_tokens"; 8706 GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = "gen_ai.invoke_agent"; 8707 GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = "gen_ai.embeddings.input"; 8708 GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = "gen_ai.embeddings"; 8709 GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = "gen_ai.execute_tool"; 8710 GEN_AI_TOOL_NAME_ATTRIBUTE = "gen_ai.tool.name"; 8711 GEN_AI_TOOL_CALL_ID_ATTRIBUTE = "gen_ai.tool.call.id"; 8712 GEN_AI_TOOL_TYPE_ATTRIBUTE = "gen_ai.tool.type"; 8713 GEN_AI_TOOL_INPUT_ATTRIBUTE = "gen_ai.tool.input"; 8714 GEN_AI_TOOL_OUTPUT_ATTRIBUTE = "gen_ai.tool.output"; 8715 GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = "gen_ai.tool.description"; 8716 })))(); 8717} 8718//#endregion 8719//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/ai/mediaStripping.js 8720function isContentMedia(part) { 8721 if (!part || typeof part !== "object") return false; 8722 return isContentMediaSource(part) || hasInlineData(part) || hasImageUrl(part) || hasInputAudio(part) || hasFileData(part) || hasMediaTypeData(part) || hasVercelFileData(part) || hasVercelImageData(part) || hasBlobOrBase64Type(part) || hasB64Json(part) || hasImageGenerationResult(part) || hasDataUri(part); 8723} 8724function hasImageUrl(part) { 8725 if (!("image_url" in part)) return false; 8726 if (typeof part.image_url === "string") return part.image_url.startsWith("data:"); 8727 return hasNestedImageUrl(part); 8728} 8729function hasNestedImageUrl(part) { 8730 return "image_url" in part && !!part.image_url && typeof part.image_url === "object" && "url" in part.image_url && typeof part.image_url.url === "string" && part.image_url.url.startsWith("data:"); 8731} 8732function isContentMediaSource(part) { 8733 return "type" in part && typeof part.type === "string" && "source" in part && isContentMedia(part.source); 8734} 8735function hasInlineData(part) { 8736 return "inlineData" in part && !!part.inlineData && typeof part.inlineData === "object" && "data" in part.inlineData && typeof part.inlineData.data === "string"; 8737} 8738function hasInputAudio(part) { 8739 return "type" in part && part.type === "input_audio" && "input_audio" in part && !!part.input_audio && typeof part.input_audio === "object" && "data" in part.input_audio && typeof part.input_audio.data === "string"; 8740} 8741function hasFileData(part) { 8742 return "type" in part && part.type === "file" && "file" in part && !!part.file && typeof part.file === "object" && "file_data" in part.file && typeof part.file.file_data === "string"; 8743} 8744function hasMediaTypeData(part) { 8745 return "media_type" in part && typeof part.media_type === "string" && "data" in part; 8746} 8747function hasVercelFileData(part) { 8748 return "type" in part && part.type === "file" && "mediaType" in part && typeof part.mediaType === "string" && "data" in part && typeof part.data === "string" && !part.data.startsWith("http://") && !part.data.startsWith("https://"); 8749} 8750function hasVercelImageData(part) { 8751 return "type" in part && part.type === "image" && "image" in part && typeof part.image === "string" && !part.image.startsWith("http://") && !part.image.startsWith("https://"); 8752} 8753function hasBlobOrBase64Type(part) { 8754 return "type" in part && (part.type === "blob" || part.type === "base64"); 8755} 8756function hasB64Json(part) { 8757 return "b64_json" in part; 8758} 8759function hasImageGenerationResult(part) { 8760 return "type" in part && "result" in part && part.type === "image_generation"; 8761} 8762function hasDataUri(part) { 8763 return "uri" in part && typeof part.uri === "string" && part.uri.startsWith("data:"); 8764} 8765function stripInlineMediaFromSingleMessage(part) { 8766 const strip = { ...part }; 8767 if (isContentMedia(strip.source)) strip.source = stripInlineMediaFromSingleMessage(strip.source); 8768 if (hasInlineData(part)) strip.inlineData = { 8769 ...part.inlineData, 8770 data: REMOVED_STRING 8771 }; 8772 if (hasNestedImageUrl(part)) strip.image_url = { 8773 ...part.image_url, 8774 url: REMOVED_STRING 8775 }; 8776 if (hasInputAudio(part)) strip.input_audio = { 8777 ...part.input_audio, 8778 data: REMOVED_STRING 8779 }; 8780 if (hasFileData(part)) strip.file = { 8781 ...part.file, 8782 file_data: REMOVED_STRING 8783 }; 8784 for (const field of MEDIA_FIELDS) if (typeof strip[field] === "string") strip[field] = REMOVED_STRING; 8785 return strip; 8786} 8787var REMOVED_STRING, MEDIA_FIELDS; 8788function init_mediaStripping() { 8789 return (init_mediaStripping = __esmMin((() => { 8790 REMOVED_STRING = "[Blob substitute]"; 8791 MEDIA_FIELDS = [ 8792 "image_url", 8793 "data", 8794 "content", 8795 "b64_json", 8796 "result", 8797 "uri", 8798 "image" 8799 ]; 8800 })))(); 8801} 8802//#endregion 8803//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/ai/messageTruncation.js 8804function truncateTextByBytes(text, maxBytes) { 8805 if (utf8Bytes(text) <= maxBytes) return text; 8806 let low = 0; 8807 let high = text.length; 8808 let bestFit = ""; 8809 while (low <= high) { 8810 const mid = Math.floor((low + high) / 2); 8811 const candidate = text.slice(0, mid); 8812 if (utf8Bytes(candidate) <= maxBytes) { 8813 bestFit = candidate; 8814 low = mid + 1; 8815 } else high = mid - 1; 8816 } 8817 return bestFit; 8818} 8819function getItemText(item) { 8820 if (typeof item === "string") return item; 8821 if ("text" in item && typeof item.text === "string") return item.text; 8822 return ""; 8823} 8824function withItemText(item, text) { 8825 if (typeof item === "string") return text; 8826 return { 8827 ...item, 8828 text 8829 }; 8830} 8831function isContentMessage(message) { 8832 return message !== null && typeof message === "object" && "content" in message && typeof message.content === "string"; 8833} 8834function isContentArrayMessage(message) { 8835 return message !== null && typeof message === "object" && "content" in message && Array.isArray(message.content); 8836} 8837function isPartsMessage(message) { 8838 return message !== null && typeof message === "object" && "parts" in message && Array.isArray(message.parts) && message.parts.length > 0; 8839} 8840function truncateContentMessage(message, maxBytes) { 8841 const emptyMessage = { 8842 ...message, 8843 content: "" 8844 }; 8845 const availableForContent = maxBytes - jsonBytes(emptyMessage); 8846 if (availableForContent <= 0) return []; 8847 const truncatedContent = truncateTextByBytes(message.content, availableForContent); 8848 return [{ 8849 ...message, 8850 content: truncatedContent 8851 }]; 8852} 8853function getArrayItems(message) { 8854 if ("parts" in message && Array.isArray(message.parts)) return { 8855 key: "parts", 8856 items: message.parts 8857 }; 8858 if ("content" in message && Array.isArray(message.content)) return { 8859 key: "content", 8860 items: message.content 8861 }; 8862 return { 8863 key: null, 8864 items: [] 8865 }; 8866} 8867function truncateArrayMessage(message, maxBytes) { 8868 const { key, items } = getArrayItems(message); 8869 if (key === null || items.length === 0) return []; 8870 const emptyItems = items.map((item) => withItemText(item, "")); 8871 let remainingBytes = maxBytes - jsonBytes({ 8872 ...message, 8873 [key]: emptyItems 8874 }); 8875 if (remainingBytes <= 0) return []; 8876 const includedItems = []; 8877 for (const item of items) { 8878 const text = getItemText(item); 8879 const textSize = utf8Bytes(text); 8880 if (textSize <= remainingBytes) { 8881 includedItems.push(item); 8882 remainingBytes -= textSize; 8883 } else if (includedItems.length === 0) { 8884 const truncated = truncateTextByBytes(text, remainingBytes); 8885 if (truncated) includedItems.push(withItemText(item, truncated)); 8886 break; 8887 } else break; 8888 } 8889 if (includedItems.length <= 0) return []; 8890 else return [{ 8891 ...message, 8892 [key]: includedItems 8893 }]; 8894} 8895function truncateSingleMessage(message, maxBytes) { 8896 if (!message) return []; 8897 if (typeof message === "string") { 8898 const truncated = truncateTextByBytes(message, maxBytes); 8899 return truncated ? [truncated] : []; 8900 } 8901 if (typeof message !== "object") return []; 8902 if (isContentMessage(message)) return truncateContentMessage(message, maxBytes); 8903 if (isContentArrayMessage(message) || isPartsMessage(message)) return truncateArrayMessage(message, maxBytes); 8904 return []; 8905} 8906function stripInlineMediaFromMessages(messages) { 8907 return messages.map((message) => { 8908 let newMessage = void 0; 8909 if (!!message && typeof message === "object") { 8910 if (isContentArrayMessage(message)) newMessage = { 8911 ...message, 8912 content: stripInlineMediaFromMessages(message.content) 8913 }; 8914 else if ("content" in message && isContentMedia(message.content)) newMessage = { 8915 ...message, 8916 content: stripInlineMediaFromSingleMessage(message.content) 8917 }; 8918 if (isPartsMessage(message)) newMessage = { 8919 ...newMessage ?? message, 8920 parts: stripInlineMediaFromMessages(message.parts) 8921 }; 8922 if (isContentMedia(newMessage)) newMessage = stripInlineMediaFromSingleMessage(newMessage); 8923 else if (isContentMedia(message)) newMessage = stripInlineMediaFromSingleMessage(message); 8924 } 8925 return newMessage ?? message; 8926 }); 8927} 8928function truncateMessagesByBytes(messages, maxBytes) { 8929 if (!Array.isArray(messages) || messages.length === 0) return messages; 8930 const effectiveMaxBytes = maxBytes - 2; 8931 const lastMessage = messages[messages.length - 1]; 8932 const stripped = stripInlineMediaFromMessages([lastMessage]); 8933 const strippedMessage = stripped[0]; 8934 if (jsonBytes(strippedMessage) <= effectiveMaxBytes) return stripped; 8935 return truncateSingleMessage(strippedMessage, effectiveMaxBytes); 8936} 8937function truncateGenAiMessages(messages) { 8938 return truncateMessagesByBytes(messages, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT); 8939} 8940function truncateGenAiStringInput(input) { 8941 return truncateTextByBytes(input, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT); 8942} 8943var DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT, utf8Bytes, jsonBytes; 8944function init_messageTruncation() { 8945 return (init_messageTruncation = __esmMin((() => { 8946 init_mediaStripping(); 8947 DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT = 2e4; 8948 utf8Bytes = (text) => { 8949 return new TextEncoder().encode(text).length; 8950 }; 8951 jsonBytes = (value) => { 8952 return utf8Bytes(JSON.stringify(value)); 8953 }; 8954 })))(); 8955} 8956//#endregion 8957//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/ai/utils.js 8958function resolveAIRecordingOptions(options) { 8959 const genAI = getClient()?.getDataCollectionOptions().genAI; 8960 return { 8961 ...options, 8962 recordInputs: options?.recordInputs ?? genAI?.inputs ?? false, 8963 recordOutputs: options?.recordOutputs ?? genAI?.outputs ?? false 8964 }; 8965} 8966function shouldEnableTruncation(enableTruncation) { 8967 if (enableTruncation !== void 0) return enableTruncation; 8968 const client = getClient(); 8969 if (!client) return true; 8970 return !hasSpanStreamingEnabled(client) && client.getOptions().streamGenAiSpans === false; 8971} 8972function buildMethodPath(currentPath, prop) { 8973 return currentPath ? `${currentPath}.${prop}` : prop; 8974} 8975function setTokenUsageAttributes(span, promptTokens, completionTokens, cachedInputTokens, cachedOutputTokens) { 8976 if (promptTokens !== void 0) span.setAttributes({ [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens }); 8977 if (completionTokens !== void 0) span.setAttributes({ [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens }); 8978 if (promptTokens !== void 0 || completionTokens !== void 0 || c
8978achedInputTokens !== void 0 || cachedOutputTokens !== void 0) { 8979 const totalTokens = (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0); 8980 span.setAttributes({ [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens }); 8981 } 8982} 8983function endStreamSpan(span, state, recordOutputs) { 8984 if (!span.isRecording()) return; 8985 const attrs = { [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true }; 8986 if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId; 8987 if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel; 8988 if (state.promptTokens !== void 0) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens; 8989 if (state.completionTokens !== void 0) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens; 8990 if (state.totalTokens !== void 0) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens; 8991 else if (state.promptTokens !== void 0 || state.completionTokens !== void 0 || state.cacheCreationInputTokens !== void 0 || state.cacheReadInputTokens !== void 0) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = (state.promptTokens ?? 0) + (state.completionTokens ?? 0) + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0); 8992 if (state.finishReasons.length) attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons); 8993 if (recordOutputs && state.responseTexts.length) attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join(""); 8994 if (recordOutputs && state.toolCalls.length) attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls); 8995 span.setAttributes(attrs); 8996 span.end(); 8997} 8998function getTruncatedJsonString(value) { 8999 if (typeof value === "string") return truncateGenAiStringInput(value); 9000 try { 9001 return JSON.stringify(Array.isArray(value) ? truncateGenAiMessages(value) : value); 9002 } catch { 9003 return "[unserializable]"; 9004 } 9005} 9006function extractSystemInstructions(messages) { 9007 if (!Array.isArray(messages)) return { 9008 systemInstructions: void 0, 9009 filteredMessages: messages 9010 }; 9011 const systemMessageIndex = messages.findIndex((msg) => msg && typeof msg === "object" && "role" in msg && msg.role === "system"); 9012 if (systemMessageIndex === -1) return { 9013 systemInstructions: void 0, 9014 filteredMessages: messages 9015 }; 9016 const systemMessage = messages[systemMessageIndex]; 9017 const systemContent = typeof systemMessage.content === "string" ? systemMessage.content : systemMessage.content !== void 0 ? JSON.stringify(systemMessage.content) : void 0; 9018 if (!systemContent) return { 9019 systemInstructions: void 0, 9020 filteredMessages: messages 9021 }; 9022 return { 9023 systemInstructions: JSON.stringify([{ 9024 type: "text", 9025 content: systemContent 9026 }]), 9027 filteredMessages: [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)] 9028 }; 9029} 9030async function createWithResponseWrapper(originalWithResponse, instrumentedPromise) { 9031 const [instrumentedResult, originalWrapper] = await Promise.all([instrumentedPromise, originalWithResponse]); 9032 if (originalWrapper && typeof originalWrapper === "object" && "data" in originalWrapper) return { 9033 ...originalWrapper, 9034 data: instrumentedResult 9035 }; 9036 return instrumentedResult; 9037} 9038function wrapPromiseWithMethods(originalPromiseLike, instrumentedPromise) { 9039 if (!isThenable(originalPromiseLike)) return instrumentedPromise; 9040 return new Proxy(originalPromiseLike, { get(target, prop) { 9041 const source = prop in Promise.prototype || prop === Symbol.toStringTag ? instrumentedPromise : target; 9042 const value = Reflect.get(source, prop); 9043 if (prop === "withResponse" && typeof value === "function") return function wrappedWithResponse() { 9044 return createWithResponseWrapper(value.call(target), instrumentedPromise); 9045 }; 9046 return typeof value === "function" ? value.bind(source) : value; 9047 } }); 9048} 9049function init_utils$2() { 9050 return (init_utils$2 = __esmMin((() => { 9051 init_currentScopes(); 9052 init_is(); 9053 init_gen_ai_attributes(); 9054 init_messageTruncation(); 9055 })))(); 9056} 9057//#endregion 9058//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/openai/constants.js 9059var OPENAI_METHOD_REGISTRY, RESPONSES_TOOL_CALL_EVENT_TYPES, RESPONSE_EVENT_TYPES; 9060function init_constants$2() { 9061 return (init_constants$2 = __esmMin((() => { 9062 OPENAI_METHOD_REGISTRY = { 9063 "responses.create": { operation: "chat" },
9064 "chat.completions.create": { operation: "chat" }, 9065 "embeddings.create": { operation: "embeddings" }, 9066 "conversations.create": { operation: "chat" } 9067 }; 9068 RESPONSES_TOOL_CALL_EVENT_TYPES = [ 9069 "response.output_item.added", 9070 "response.function_call_arguments.delta", 9071 "response.function_call_arguments.done", 9072 "response.output_item.done" 9073 ]; 9074 RESPONSE_EVENT_TYPES = [ 9075 "response.created", 9076 "response.in_progress", 9077 "response.failed", 9078 "response.completed", 9079 "response.incomplete", 9080 "response.queued", 9081 "response.output_text.delta", 9082 ...RESPONSES_TOOL_CALL_EVENT_TYPES 9083 ]; 9084 })))(); 9085} 9086//#endregion 9087//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/openai/utils.js 9088function isResponsesApiStreamEvent(event) { 9089 return event !== null && typeof event === "object" && "type" in event && typeof event.type === "string" && event.type.startsWith("response."); 9090} 9091function isChatCompletionChunk(event) { 9092 return event !== null && typeof event === "object" && "object" in event && event.object === "chat.completion.chunk"; 9093} 9094function addResponseAttributes$2(span, result, recordOutputs) { 9095 if (!result || typeof result !== "object") return; 9096 const response = result; 9097 const attrs = {}; 9098 if (typeof response.id === "string") attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = response.id; 9099 if (typeof response.model === "string") attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = response.model; 9100 if (response.object === "conversation" && typeof response.id === "string") attrs[GEN_AI_CONVERSATION_ID_ATTRIBUTE] = response.id; 9101 if (response.usage && typeof response.usage === "object") { 9102 const usage = response.usage; 9103 const inputTokens = usage.prompt_tokens ?? usage.input_tokens; 9104 if (typeof inputTokens === "number") attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = inputTokens; 9105 const outputTokens = usage.completion_tokens ?? usage.output_tokens; 9106 if (typeof outputTokens === "number") attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = outputTokens; 9107 if (typeof usage.total_tokens === "number") attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = usage.total_tokens; 9108 } 9109 if (Array.isArray(response.choices)) { 9110 const choices = response.choices; 9111 const finishReasons = choices.map((choice) => choice.finish_reason).filter((reason) => typeof reason === "string"); 9112 if (finishReasons.length > 0) attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(finishReasons); 9113 if (recordOutputs) { 9114 const responseTexts = choices.map((choice) => { 9115 return choice.message?.content || ""; 9116 }); 9117 attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = JSON.stringify(responseTexts); 9118 const toolCalls = choices.map((choice) => { 9119 return choice.message?.tool_calls; 9120 }).filter((calls) => Array.isArray(calls) && calls.length > 0).flat(); 9121 if (toolCalls.length > 0) attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(toolCalls); 9122 } 9123 } 9124 if (typeof response.status === "string") { 9125 if (!attrs["gen_ai.response.finish_reasons"]) attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify([response.status]); 9126 } 9127 if (recordOutputs) { 9128 if (typeof response.output_text === "string" && !attrs["gen_ai.response.text"]) attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = response.output_text; 9129 if (Array.isArray(response.output) && response.output.length > 0 && !attrs["gen_ai.response.tool_calls"]) { 9130 const functionCalls = response.output.filter((item) => item?.type === "function_call"); 9131 if (functionCalls.length > 0) attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(functionCalls); 9132 } 9133 } 9134 span.setAttributes(attrs); 9135} 9136function extractConversationId(params) { 9137 if ("conversation" in params && typeof params.conversation === "string") return params.conversation; 9138 if ("previous_response_id" in params && typeof params.previous_response_id === "string") return params.previous_response_id; 9139} 9140function extractRequestParameters(params) { 9141 const attributes = { [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: params.model ?? "unknown" }; 9142 if ("temperature" in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature; 9143 if ("top_p" in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p; 9144 if ("frequency_penalty" in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENA
9144LTY_ATTRIBUTE] = params.frequency_penalty; 9145 if ("presence_penalty" in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = params.presence_penalty; 9146 if ("stream" in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream; 9147 if ("encoding_format" in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format; 9148 if ("dimensions" in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions; 9149 const conversationId = extractConversationId(params); 9150 if (conversationId) attributes[GEN_AI_CONVERSATION_ID_ATTRIBUTE] = conversationId; 9151 return attributes; 9152} 9153function init_utils$3() { 9154 return (init_utils$3 = __esmMin((() => { 9155 init_gen_ai_attributes(); 9156 })))(); 9157} 9158//#endregion 9159//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js 9160function processChatCompletionToolCalls(toolCalls, state) { 9161 for (const toolCall of toolCalls) { 9162 const index = toolCall.index; 9163 if (index === void 0 || !toolCall.function) continue; 9164 if (!(index in state.chatCompletionToolCalls)) state.chatCompletionToolCalls[index] = { 9165 ...toolCall, 9166 function: { 9167 name: toolCall.function.name, 9168 arguments: toolCall.function.arguments || "" 9169 } 9170 }; 9171 else { 9172 const existingToolCall = state.chatCompletionToolCalls[index]; 9173 if (toolCall.function.arguments && existingToolCall?.function) existingToolCall.function.arguments += toolCall.function.arguments; 9174 } 9175 } 9176} 9177function processChatCompletionChunk(chunk, state, recordOutputs) { 9178 state.responseId = chunk.id ?? state.responseId; 9179 state.responseModel = chunk.model ?? state.responseModel; 9180 if (chunk.usage) { 9181 state.promptTokens = chunk.usage.prompt_tokens; 9182 state.completionTokens = chunk.usage.completion_tokens; 9183 state.totalTokens = chunk.usage.total_tokens; 9184 } 9185 for (const choice of chunk.choices ?? []) { 9186 if (recordOutputs) { 9187 if (choice.delta?.content) state.responseTexts.push(choice.delta.content); 9188 if (choice.delta?.tool_calls) processChatCompletionToolCalls(choice.delta.tool_calls, state); 9189 } 9190 if (choice.finish_reason) state.finishReasons.push(choice.finish_reason); 9191 } 9192} 9193function processResponsesApiEvent(streamEvent, state, recordOutputs, span) { 9194 if (!(streamEvent && typeof streamEvent === "object")) { 9195 state.eventTypes.push("unknown:non-object"); 9196 return; 9197 } 9198 if (streamEvent instanceof Error) { 9199 span.setStatus({ 9200 code: 2, 9201 message: "internal_error" 9202 }); 9203 captureException(streamEvent, { mechanism: { 9204 handled: false, 9205 type: "auto.ai.openai.stream-response" 9206 } }); 9207 return; 9208 } 9209 if (!("type" in streamEvent)) return; 9210 const event = streamEvent; 9211 if (!RESPONSE_EVENT_TYPES.includes(event.type)) { 9212 state.eventTypes.push(event.type); 9213 return; 9214 } 9215 if (recordOutputs) { 9216 if (event.type === "response.output_item.done" && "item" in event) state.responsesApiToolCalls.push(event.item); 9217 if (event.type === "response.output_text.delta" && "delta" in event && event.delta) { 9218 state.responseTexts.push(event.delta); 9219 return; 9220 } 9221 } 9222 if ("response" in event) { 9223 const { response } = event; 9224 state.responseId = response.id ?? state.responseId; 9225 state.responseModel = response.model ?? state.responseModel; 9226 if (response.usage) { 9227 state.promptTokens = response.usage.input_tokens; 9228 state.completionTokens = response.usage.output_tokens; 9229 state.totalTokens = response.usage.total_tokens; 9230 } 9231 if (response.status) state.finishReasons.push(response.status); 9232 if (recordOutputs && response.output_text) state.responseTexts.push(response.output_text); 9233 } 9234} 9235async function* instrumentStream$1(stream, span, recordOutputs) { 9236 const state = { 9237 eventTypes: [], 9238 responseTexts: [], 9239 finishReasons: [], 9240 responseId: "", 9241 responseModel: "", 9242 promptTokens: void 0, 9243 completionTokens: void 0, 9244 totalTokens: void 0, 9245 chatCompletionToolCalls: {}, 9246 responsesApiToolCalls: [] 9247 }; 9248 try { 9249 for await (const event of stream) { 9250 if (isChatCompletionChunk(event)) processChatCompletionChunk(event, state, recordOutputs); 9251 else if (isResponsesApiStreamEvent(event)) processResponsesApiEvent(event, state, recordOutputs, span); 9252 yield event; 9253 } 9254 } finally { 9255 const allToolCalls = [...Object.values(state.chatCompletionToolCalls), ...state.responsesApiToolCalls]; 9256 endStreamSpan(span, { 9257 ...state, 9258 toolCalls: allToolCalls 9259 }, recordOutputs); 9260 } 9261} 9262function init_streaming() { 9263 return (init_streaming = __esmMin((() => { 9264 init_exports(); 9265 init_spanstatus(); 9266 init_utils$2(); 9267 init_constants$2();
9268 init_utils$3(); 9269 })))(); 9270} 9271//#endregion 9272//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/openai/index.js 9273function extractAvailableTools(params) { 9274 const tools = Array.isArray(params.tools) ? params.tools : []; 9275 const webSearchOptions = params.web_search_options && typeof params.web_search_options === "object" ? [{ 9276 type: "web_search_options", 9277 ...params.web_search_options 9278 }] : []; 9279 const availableTools = [...tools, ...webSearchOptions]; 9280 if (availableTools.length === 0) return; 9281 try { 9282 return JSON.stringify(availableTools); 9283 } catch (error) { 9284 DEBUG_BUILD$5 && debug$2.error("Failed to serialize OpenAI tools:", error); 9285 return; 9286 } 9287} 9288function extractRequestAttributes$2(args, operationName) { 9289 const attributes = { 9290 [GEN_AI_SYSTEM_ATTRIBUTE]: "openai", 9291 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operationName, 9292 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.openai" 9293 }; 9294 if (args.length > 0 && typeof args[0] === "object" && args[0] !== null) { 9295 const params = args[0]; 9296 const availableTools = extractAvailableTools(params); 9297 if (availableTools) attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = availableTools; 9298 Object.assign(attributes, extractRequestParameters(params)); 9299 } else attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = "unknown"; 9300 return attributes; 9301} 9302function addRequestAttributes(span, params, operationName, enableTruncation) { 9303 if (operationName === "embeddings" && "input" in params) { 9304 const input = params.input; 9305 if (input == null) return; 9306 if (typeof input === "string" && input.length === 0) return; 9307 if (Array.isArray(input) && input.length === 0) return; 9308 span.setAttribute(GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, typeof input === "string" ? input : JSON.stringify(input)); 9309 return; 9310 } 9311 const src = "input" in params ? params.input : "messages" in params ? params.messages : void 0; 9312 if (!src) return; 9313 if (Array.isArray(src) && src.length === 0) return; 9314 const { systemInstructions, filteredMessages } = extractSystemInstructions(src); 9315 if (systemInstructions) span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions); 9316 span.setAttribute(GEN_AI_INPUT_MESSAGES_ATTRIBUTE, enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages)); 9317 if (Array.isArray(filteredMessages)) span.setAttribute(GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, filteredMessages.length); 9318 else span.setAttribute(GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, 1); 9319} 9320function instrumentMethod$2(originalMethod, methodPath, instrumentedMethod, context, options) { 9321 return function instrumentedCall(...args) { 9322 const operationName = instrumentedMethod.operation || "unknown"; 9323 const requestAttributes = extractRequestAttributes$2(args, operationName); 9324 const model = requestAttributes["gen_ai.request.model"] || "unknown"; 9325 const params = args[0]; 9326 const isStreamRequested = params && typeof params === "object" && params.stream === true; 9327 const spanConfig = { 9328 name: `${operationName} ${model}`, 9329 op: `gen_ai.${operationName}`, 9330 attributes: requestAttributes 9331 }; 9332 if (isStreamRequested) { 9333 let originalResult2; 9334 const instrumentedPromise2 = startSpanManual(spanConfig, (span) => { 9335 originalResult2 = originalMethod.apply(context, args); 9336 if (options.recordInputs && params) addRequestAttributes(span, params, operationName, shouldEnableTruncation(options.enableTruncation)); 9337 return (async () => { 9338 try { 9339 return instrumentStream$1(await originalResult2, span, options.recordOutputs ?? false); 9340 } catch (error) { 9341 span.setStatus({ 9342 code: 2, 9343 message: "internal_error" 9344 }); 9345 span.end(); 9346 throw error; 9347 } 9348 })(); 9349 }); 9350 return wrapPromiseWithMethods(originalResult2, instrumentedPromise2); 9351 } 9352 let originalResult; 9353 const instrumentedPromise = startSpan(spanConfig, (span) => { 9354 originalResult = originalMethod.apply(context, args); 9355 if (options.recordInputs && params) addRequestAttributes(span, params, operationName, shouldEnableTruncation(options.enableTruncation)); 9356 return originalResult.then((result) => { 9357 addResponseAttributes$2(span, result, options.recordOutputs); 9358 return result; 9359 }); 9360 }); 9361 return wrapPromiseWithMethods(originalResult, instrumentedPromise); 9362 }; 9363} 9364function createDeepProxy$1(target, currentPath = "", options) { 9365 return new Proxy(target, { get(obj, prop) { 9366 const value = obj[prop]; 9367 const methodPath = buildMethodPath(currentPath, String(prop)); 9368 const instrumentedMethod = OPENAI_METHOD_REGISTRY[methodPath]; 9369 if (typeof value === "function" && instrumentedMethod) return instrumentMethod$2(value, methodPath, instrumentedMethod, obj, options); 9370 if (typeof value === "function") return value.bind(obj); 9371 if (value && typeof value === "object") return createDeepProxy$1(value, methodPath, options); 9372 return value; 9373 } }); 9374} 9375function instrumentOpenAiClient(client, options) {
9376 return createDeepProxy$1(client, "", resolveAIRecordingOptions(options)); 9377} 9378function init_openai() { 9379 return (init_openai = __esmMin((() => { 9380 init_debug_build(); 9381 init_semanticAttributes(); 9382 init_debug_logger(); 9383 init_string(); 9384 init_spanstatus(); 9385 init_trace(); 9386 init_gen_ai_attributes(); 9387 init_utils$2(); 9388 init_constants$2(); 9389 init_streaming(); 9390 init_utils$3(); 9391 })))(); 9392} 9393//#endregion 9394//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/constants.js 9395var ANTHROPIC_METHOD_REGISTRY; 9396function init_constants$3() { 9397 return (init_constants$3 = __esmMin((() => { 9398 ANTHROPIC_METHOD_REGISTRY = { 9399 "messages.create": { operation: "chat" }, 9400 "messages.stream": { 9401 operation: "chat", 9402 streaming: true 9403 }, 9404 "messages.countTokens": { operation: "chat" }, 9405 "models.get": { operation: "models" }, 9406 "completions.create": { operation: "chat" }, 9407 "models.retrieve": { operation: "models" }, 9408 "beta.messages.create": { operation: "chat" } 9409 }; 9410 })))(); 9411} 9412//#endregion 9413//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/utils.js 9414function setMessagesAttribute(span, messages, enableTruncation) { 9415 if (Array.isArray(messages) && messages.length === 0) return; 9416 const { systemInstructions, filteredMessages } = extractSystemInstructions(messages); 9417 if (systemInstructions) span.setAttributes({ [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions }); 9418 const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1; 9419 span.setAttributes({ 9420 [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages), 9421 [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength 9422 }); 9423} 9424function mapAnthropicErrorToStatusMessage(errorType) { 9425 if (!errorType) return "internal_error"; 9426 return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || "internal_error"; 9427} 9428function handleResponseError(span, response) { 9429 if (response.error) { 9430 span.setStatus({ 9431 code: 2, 9432 message: mapAnthropicErrorToStatusMessage(response.error.type) 9433 }); 9434 captureException(response.error, { mechanism: { 9435 handled: false, 9436 type: "auto.ai.anthropic.anthropic_error" 9437 } }); 9438 } 9439} 9440function messagesFromParams(params) { 9441 const { system, messages, input } = params; 9442 const systemMessages = typeof system === "string" ? [{ 9443 role: "system", 9444 content: params.system 9445 }] : []; 9446 const userMessages = (Array.isArray(input) ? input : input != null ? [input] : void 0) ?? (Array.isArray(messages) ? messages : messages != null ? [messages] : []); 9447 return [...systemMessages, ...userMessages]; 9448} 9449var ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS; 9450function init_utils$4() { 9451 return (init_utils$4 = __esmMin((() => { 9452 init_exports(); 9453 init_string(); 9454 init_spanstatus(); 9455 init_gen_ai_attributes(); 9456 init_utils$2(); 9457 ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS = { 9458 invalid_request_error: "invalid_argument", 9459 authentication_error: "unauthenticated", 9460 permission_error: "permission_denied", 9461 not_found_error: "not_found", 9462 request_too_large: "failed_precondition", 9463 rate_limit_error: "resource_exhausted", 9464 api_error: "internal_error", 9465 overloaded_error: "unavailable" 9466 }; 9467 })))(); 9468} 9469//#endregion 9470//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js 9471function isErrorEvent$1(event, span) { 9472 if ("type" in event && typeof event.type === "string") { 9473 if (event.type === "error") { 9474 span.setStatus({ 9475 code: 2, 9476 message: mapAnthropicErrorToStatusMessage(event.error?.type) 9477 }); 9478 return true; 9479 } 9480 } 9481 return false; 9482} 9483function handleMessageMetadata(event, state) { 9484 if (event.type === "message_delta") { 9485 if (event.usage && typeof event.usage.output_tokens === "number") state.completionTokens = event.usage.output_tokens; 9486 if (event.delta?.stop_reason) state.finishReasons.push(event.delta.stop_reason); 9487 } 9488 if (event.message) { 9489 const message = event.message; 9490 if (message.id) state.responseId = message.id; 9491 if (message.model) state.responseModel = message.model; 9492 if (message.usage) { 9493 if (typeof message.usage.input_tokens === "number") state.promptTokens = message.usage.input_tokens; 9494 if (typeof message.usage.cache_creation_input_tokens === "number") state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens; 9495 if (typeof message.usage.cache_read_input_tokens === "number") state.cacheReadInputTokens = message.usage.cache_read_input_tokens; 9496 } 9497 } 9498} 9499function handleContentBlockStart(event, state) { 9500 if (event.type !== "content_block_start" || typeof event.index !== "number" || !event.content_block) return; 9501 if (event.content_block.type === "tool_use" || event.content_block.type === "server_tool_use") state.activeToolBlocks[event.index] = { 9502 id: event.content_block.id, 9503 name: event.content_block.name, 9504 inputJsonParts: [] 9505 }; 9506} 9507function handleContentBlockDelta(event, state, recordOutputs) { 9508 if (event.type !== "content_block_delta" || !event.delta) return; 9509 if (typeof event.index === "number" && "partial_json" in event.delta && typeof event.delta.partial_json === "string") { 9510 const active = state.activeToolBlocks[event.index]; 9511 if (active) active.inputJsonParts.push(event.delta.partial_json); 9512 } 9513 if (recordOutputs && typeof event.delta.text === "string") state.responseTexts.push(event.delta.text); 9514} 9515function handleContentBlockStop(event, state) { 9516 if (event.type !== "content_block_stop" || typeof event.index !== "number") return; 9517 const active = state.activeToolBlocks[event.index]; 9518 if (!active) return; 9519 const raw = active.inputJsonParts.join(""); 9520 let parsedInput; 9521 try { 9522 parsedInput = raw ? JSON.parse(raw) : {}; 9523 } catch { 9524 parsedInput = { __unparsed: raw }; 9525 } 9526 state.toolCalls.push({ 9527 type: "tool_use", 9528 id: active.id, 9529 name: active.name, 9530 input: parsedInput 9531 }); 9532 delete state.activeToolBlocks[event.index]; 9533} 9534function processEvent(event, state, recordOutputs, span) { 9535 if (!(event && typeof event === "object")) return; 9536 if (isErrorEvent$1(event, span)) return; 9537 handleMessageMetadata(event, state); 9538 handleContentBlockStart(event, state); 9539 handleContentBlockDelta(event, state, recordOutputs); 9540 handleContentBlockStop(event, state); 9541} 9542async function* instrumentAsyncIterableStream(stream, span, recordOutputs) { 9543 const state = { 9544 responseTexts: [], 9545 finishReasons: [], 9546 responseId: "", 9547 responseModel: "", 9548 promptTokens: void 0, 9549 completionTokens: void 0, 9550 cacheCreationInputTokens: void 0, 9551 cacheReadInputTokens: void 0, 9552 toolCalls: [], 9553 activeToolBlocks: {} 9554 }; 9555 try { 9556 for await (const event of stream) { 9557 processEvent(event, state, recordOutputs, span); 9558 yield event; 9559 } 9560 } finally { 9561 endStreamSpan(span, state, recordOutputs); 9562 } 9563} 9564function instrumentMessageStream(stream, span, recordOutputs) { 9565 const state = { 9566 responseTexts: [], 9567 finishReasons: [], 9568 responseId: "", 9569 responseModel: "", 9570 promptTokens: void 0, 9571 completionTokens: void 0, 9572 cacheCreationInputTokens: void 0, 9573 cacheReadInputTokens: void 0, 9574 toolCalls: [], 9575 activeToolBlocks: {} 9576 }; 9577 stream.on("streamEvent", (event) => { 9578 processEvent(event, state, recordOutputs, span); 9579 }); 9580 stream.on("message", () => { 9581 endStreamSpan(span, state, recordOutputs); 9582 }); 9583 stream.on("error", (error) => { 9584 captureException(error, { mechanism: { 9585 handled: false, 9586 type: "auto.ai.anthropic.stream_error" 9587 } });
9588 if (span.isRecording()) { 9589 span.setStatus({ 9590 code: 2, 9591 message: "internal_error" 9592 }); 9593 span.end(); 9594 } 9595 }); 9596 return stream; 9597} 9598function init_streaming$1() { 9599 return (init_streaming$1 = __esmMin((() => { 9600 init_exports(); 9601 init_spanstatus(); 9602 init_utils$2(); 9603 init_utils$4(); 9604 })))(); 9605} 9606//#endregion 9607//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js 9608function extractRequestAttributes$1(args, methodPath, operationName) { 9609 const attributes = { 9610 [GEN_AI_SYSTEM_ATTRIBUTE]: "anthropic", 9611 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operationName, 9612 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.anthropic" 9613 }; 9614 if (args.length > 0 && typeof args[0] === "object" && args[0] !== null) { 9615 const params = args[0]; 9616 if (params.tools && Array.isArray(params.tools)) attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools); 9617 attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? "unknown"; 9618 if ("temperature" in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature; 9619 if ("top_p" in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p; 9620 if ("stream" in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream; 9621 if ("top_k" in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k; 9622 if ("frequency_penalty" in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENA
9622LTY_ATTRIBUTE] = params.frequency_penalty; 9623 if ("max_tokens" in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens; 9624 } else if (methodPath === "models.retrieve" || methodPath === "models.get") attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0]; 9625 else attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = "unknown"; 9626 return attributes; 9627} 9628function addPrivateRequestAttributes$1(span, params, enableTruncation) { 9629 setMessagesAttribute(span, messagesFromParams(params), enableTruncation); 9630 if ("prompt" in params) span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) }); 9631} 9632function addContentAttributes(span, response) { 9633 if ("content" in response) { 9634 if (Array.isArray(response.content)) { 9635 span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content.map((item) => item.text).filter((text) => !!text).join("") }); 9636 const toolCalls = []; 9637 for (const item of response.content) if (item.type === "tool_use" || item.type === "server_tool_use") toolCalls.push(item); 9638 if (toolCalls.length > 0) span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) }); 9639 } 9640 } 9641 if ("completion" in response) span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion }); 9642 if ("input_tokens" in response) span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) }); 9643} 9644function addMetadataAttributes(span, response) { 9645 if ("id" in response && "model" in response) { 9646 span.setAttributes({ 9647 [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id, 9648 [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model 9649 }); 9650 if ("usage" in response && response.usage) setTokenUsageAttributes(span, response.usage.input_tokens, response.usage.output_tokens, response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens); 9651 } 9652} 9653function addResponseAttributes$1(span, response, recordOutputs) { 9654 if (!response || typeof response !== "object") return; 9655 if ("type" in response && response.type === "error") { 9656 handleResponseError(span, response); 9657 return; 9658 } 9659 if (recordOutputs) addContentAttributes(span, response); 9660 addMetadataAttributes(span, response); 9661} 9662function handleStreamingError(error, span) { 9663 if (span.isRecording()) { 9664 span.setStatus({ 9665 code: 2, 9666 message: "internal_error" 9667 }); 9668 span.end(); 9669 } 9670 throw error; 9671} 9672function handleStreamingRequest(target, invocationThis, args, requestAttributes, operationName, methodPath, params, options, isStreamRequested, isStreamingMethod) { 9673 const spanConfig = { 9674 name: `${operationName} ${requestAttributes["gen_ai.request.model"] ?? "unknown"}`, 9675 op: `gen_ai.${operationName}`, 9676 attributes: requestAttributes 9677 }; 9678 if (isStreamRequested && !isStreamingMethod) { 9679 let originalResult; 9680 const instrumentedPromise = startSpanManual(spanConfig, (span) => { 9681 originalResult = target.apply(invocationThis, args); 9682 if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params, shouldEnableTruncation(options.enableTruncation)); 9683 return (async () => { 9684 try { 9685 return instrumentAsyncIterableStream(await originalResult, span, options.recordOutputs ?? false); 9686 } catch (error) { 9687 return handleStreamingError(error, span); 9688 } 9689 })(); 9690 }); 9691 return wrapPromiseWithMethods(originalResult, instrumentedPromise); 9692 } else return startSpanManual(spanConfig, (span) => { 9693 try { 9694 if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params, shouldEnableTruncation(options.enableTruncation)); 9695 suppressDelegatedCreate = true; 9696 const messageStream = target.apply(invocationThis, args); 9697 suppressDelegatedCreate = false; 9698 return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false); 9699 } catch (error) { 9700 suppressDelegatedCreate = false; 9701 return handleStreamingError(error, span); 9702 } 9703 }); 9704} 9705function instrumentMethod$1(originalMethod, methodPath, instrumentedMethod, context, options) { 9706 return new Proxy(originalMethod, { apply(target, thisArg, args) { 9707 const invocationThis = thisArg !== void 0 ? thisArg : context; 9708 const isStreamingMethod = instrumentedMethod.streaming === true; 9709 if (!isStreamingMethod && suppressDelegatedCreate) return target.apply(invocationThis, args); 9710 const operationName = instrumentedMethod.operation || "unknown"; 9711 const requestAttributes = extractRequestAttributes$1(args, methodPath, operationName); 9712 const model = requestAttributes["gen_ai.request.model"] ?? "unknown"; 9713 const params = typeof args[0] === "object" ? args[0] : void 0; 9714 const isStreamRequested = Boolean(params?.stream); 9715 if (isStreamRequested || isStreamingMethod) return handleStreamingRequest(target, invocationThis, args, requestAttributes, operationName, methodPath, params, options, isStreamRequested, isStreamingMethod); 9716 let originalResult; 9717 const instrumentedPromise = startSpan({ 9718 name: `${operationName} ${model}`, 9719 op: `gen_ai.${operationName}`, 9720 attributes: requestAttributes 9721 }, (span) => { 9722 originalResult = target.apply(invocationThis, args); 9723 if (options.recordInputs && params) addPrivateRequestAttributes$1(span, params, shouldEnableTruncation(options.enableTruncation)); 9724 return originalResult.then((result) => { 9725 addResponseAttributes$1(span, result, options.recordOutputs); 9726 return result; 9727 }); 9728 }); 9729 return wrapPromiseWithMethods(originalResult, instrumentedPromise); 9730 } }); 9731} 9732function instrumentClientInPlace(client, options) { 9733 for (const methodPath of Object.keys(ANTHROPIC_METHOD_REGISTRY)) { 9734 const segments = methodPath.split("."); 9735 const methodName = segments.pop(); 9736 let owner = client; 9737 for (const segment of segments) owner = owner?.[segment]; 9738 if (!owner || typeof owner[methodName] !== "function") continue; 9739 const originalMethod = owner[methodName]; 9740 if (INSTRUMENTED_METHODS.has(originalMethod)) continue; 9741 const instrumented = instrumentMethod$1(originalMethod, methodPath, ANTHROPIC_METHOD_REGISTRY[methodPath], owner, options); 9742 INSTRUMENTED_METHODS.add(instrumented); 9743 owner[methodName] = instrumented; 9744 } 9745 return client; 9746} 9747function instrumentAnthropicAiClient(anthropicAiClient, options) { 9748 return instrumentClientInPlace(anthropicAiClient, resolveAIRecordingOptions(options)); 9749} 9750var suppressDelegatedCreate, INSTRUMENTED_METHODS; 9751function init_anthropic_ai() { 9752 return (init_anthropic_ai = __esmMin((() => { 9753 init_semanticAttributes(); 9754 init_spanstatus(); 9755 init_trace(); 9756 init_gen_ai_attributes(); 9757 init_utils$2(); 9758 init_constants$3(); 9759 init_streaming$1(); 9760 init_utils$4(); 9761 suppressDelegatedCreate = false;
9762 INSTRUMENTED_METHODS = /* @__PURE__ */ new WeakSet(); 9763 })))(); 9764} 9765//#endregion 9766//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/google-genai/constants.js 9767var GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME; 9768function init_constants$4() { 9769 return (init_constants$4 = __esmMin((() => { 9770 GOOGLE_GENAI_METHOD_REGISTRY = { 9771 "models.generateContent": { operation: "generate_content" }, 9772 "models.generateContentStream": { 9773 operation: "generate_content", 9774 streaming: true 9775 }, 9776 "models.embedContent": { operation: "embeddings" }, 9777 "chats.create": { proxyResultPath: "chat" }, 9778 "chat.sendMessage": { operation: "chat" }, 9779 "chat.sendMessageStream": { 9780 operation: "chat", 9781 streaming: true 9782 } 9783 }; 9784 GOOGLE_GENAI_SYSTEM_NAME = "google_genai"; 9785 })))(); 9786} 9787//#endregion 9788//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js 9789function isErrorChunk(chunk, span) { 9790 const feedback = chunk?.promptFeedback; 9791 if (feedback?.blockReason) { 9792 const message = feedback.blockReasonMessage ?? feedback.blockReason; 9793 span.setStatus({ 9794 code: 2, 9795 message: "internal_error" 9796 }); 9797 captureException(`Content blocked: ${message}`, { mechanism: { 9798 handled: false, 9799 type: "auto.ai.google_genai" 9800 } }); 9801 return true; 9802 } 9803 return false; 9804} 9805function handleResponseMetadata(chunk, state) { 9806 if (typeof chunk.responseId === "string") state.responseId = chunk.responseId; 9807 if (typeof chunk.modelVersion === "string") state.responseModel = chunk.modelVersion; 9808 const usage = chunk.usageMetadata; 9809 if (usage) { 9810 if (typeof usage.promptTokenCount === "number") state.promptTokens = usage.promptTokenCount; 9811 if (typeof usage.candidatesTokenCount === "number") state.completionTokens = usage.candidatesTokenCount; 9812 if (typeof usage.totalTokenCount === "number") state.totalTokens = usage.totalTokenCount; 9813 } 9814} 9815function handleCandidateContent(chunk, state, recordOutputs) { 9816 if (Array.isArray(chunk.functionCalls)) state.toolCalls.push(...chunk.functionCalls); 9817 for (const candidate of chunk.candidates ?? []) { 9818 if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) state.finishReasons.push(candidate.finishReason); 9819 for (const part of candidate?.content?.parts ?? []) { 9820 if (recordOutputs && part.text) state.responseTexts.push(part.text); 9821 if (part.functionCall) state.toolCalls.push({ 9822 type: "function", 9823 id: part.functionCall.id, 9824 name: part.functionCall.name, 9825 arguments: part.functionCall.args 9826 }); 9827 } 9828 } 9829} 9830function processChunk(chunk, state, recordOutputs, span) { 9831 if (!chunk || isErrorChunk(chunk, span)) return; 9832 handleResponseMetadata(chunk, state); 9833 handleCandidateContent(chunk, state, recordOutputs); 9834} 9835async function* instrumentStream(stream, span, recordOutputs) { 9836 const state = { 9837 responseTexts: [], 9838 finishReasons: [], 9839 toolCalls: [] 9840 }; 9841 try { 9842 for await (const chunk of stream) { 9843 processChunk(chunk, state, recordOutputs, span); 9844 yield chunk; 9845 } 9846 } finally { 9847 endStreamSpan(span, state, recordOutputs); 9848 } 9849} 9850function init_streaming$2() { 9851 return (init_streaming$2 = __esmMin((() => { 9852 init_exports(); 9853 init_spanstatus(); 9854 init_utils$2(); 9855 })))(); 9856} 9857//#endregion 9858//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/google-genai/utils.js 9859function contentUnionToMessages(content, role = "user") { 9860 if (typeof content === "string") return [{ 9861 role, 9862 content 9863 }]; 9864 if (Array.isArray(content)) return content.flatMap((content2) => contentUnionToMessages(content2, role)); 9865 if (typeof content !== "object" || !content) return []; 9866 if ("role" in content && typeof content.role === "string") return [content]; 9867 if ("parts" in content) return [{ 9868 ...content, 9869 role 9870 }]; 9871 return [{ 9872 role, 9873 content 9874 }]; 9875} 9876//#endregion 9877//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js 9878function extractModel(params, context) { 9879 if ("model" in params && typeof params.model === "string") return params.model; 9880 if (context && typeof context === "object") { 9881 const contextObj = context; 9882 if ("model" in contextObj && typeof contextObj.model === "string") return contextObj.model; 9883 if ("modelVersion" in contextObj && typeof contextObj.modelVersion === "string") return contextObj.modelVersion; 9884 } 9885 return "unknown"; 9886} 9887function extractConfigAttributes(config) { 9888 const attributes = {}; 9889 if ("temperature" in config && typeof config.temperature === "number") attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = config.temperature; 9890 if ("topP" in config && typeof config.topP === "number") attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = config.topP; 9891 if ("topK" in config && typeof config.topK === "number") attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = config.topK; 9892 if ("maxOutputTokens" in config && typeof config.maxOutputTokens === "number") attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = config.maxOutputTokens; 9893 if ("frequencyPenalty" in config && typeof config.frequencyPenalty === "number") attributes[GEN_AI_REQUEST_FREQUENCY_PENA
9893LTY_ATTRIBUTE] = config.frequencyPenalty; 9894 if ("presencePenalty" in config && typeof config.presencePenalty === "number") attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = config.presencePenalty; 9895 return attributes; 9896} 9897function extractRequestAttributes(operationName, params, context) { 9898 const attributes = { 9899 [GEN_AI_SYSTEM_ATTRIBUTE]: GOOGLE_GENAI_SYSTEM_NAME, 9900 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operationName, 9901 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.google_genai" 9902 }; 9903 if (params) { 9904 attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel(params, context); 9905 if ("config" in params && typeof params.config === "object" && params.config) { 9906 const config = params.config; 9907 Object.assign(attributes, extractConfigAttributes(config)); 9908 if ("tools" in config && Array.isArray(config.tools)) { 9909 const functionDeclarations = config.tools.flatMap((tool) => tool.functionDeclarations); 9910 attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(functionDeclarations); 9911 } 9912 } 9913 } else attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel({}, context); 9914 return attributes; 9915} 9916function addPrivateRequestAttributes(span, params, operationName, enableTruncation) { 9917 if (operationName === "embeddings") { 9918 const contents = params.contents; 9919 if (contents != null) span.setAttribute(GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, typeof contents === "string" ? contents : JSON.stringify(contents)); 9920 return; 9921 } 9922 const messages = []; 9923 if ("config" in params && params.config && typeof params.config === "object" && "systemInstruction" in params.config && params.config.systemInstruction) messages.push(...contentUnionToMessages(params.config.systemInstruction, "system")); 9924 if ("history" in params) messages.push(...contentUnionToMessages(params.history, "user")); 9925 if ("contents" in params) messages.push(...contentUnionToMessages(params.contents, "user")); 9926 if ("message" in params) messages.push(...contentUnionToMessages(params.message, "user")); 9927 if (Array.isArray(messages) && messages.length) { 9928 const { systemInstructions, filteredMessages } = extractSystemInstructions(messages); 9929 if (systemInstructions) span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions); 9930 const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0; 9931 span.setAttributes({ 9932 [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength, 9933 [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages) 9934 }); 9935 } 9936} 9937function addResponseAttributes(span, response, recordOutputs) { 9938 if (!response || typeof response !== "object") return; 9939 if (response.modelVersion) span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, response.modelVersion); 9940 if (response.usageMetadata && typeof response.usageMetadata === "object") { 9941 const usage = response.usageMetadata; 9942 if (typeof usage.promptTokenCount === "number") span.setAttributes({ [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: usage.promptTokenCount }); 9943 if (typeof usage.candidatesTokenCount === "number") span.setAttributes({ [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: usage.candidatesTokenCount }); 9944 if (typeof usage.totalTokenCount === "number") span.setAttributes({ [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: usage.totalTokenCount }); 9945 } 9946 if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) { 9947 const responseTexts = response.candidates.map((candidate) => { 9948 if (candidate.content?.parts && Array.isArray(candidate.content.parts)) return candidate.content.parts.map((part) => typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join(""); 9949 return ""; 9950 }).filter((text) => text.length > 0); 9951 if (responseTexts.length > 0) span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: responseTexts.join("") }); 9952 } 9953 if (recordOutputs && response.functionCalls) { 9954 const functionCalls = response.functionCalls; 9955 if (Array.isArray(functionCalls) && functionCalls.length > 0) span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls) }); 9956 } 9957} 9958function instrumentMethod(originalMethod, methodPath, instrumentedMethod, context, options) { 9959 const isEmbeddings = instrumentedMethod.operation === "embeddings";
9960 return new Proxy(originalMethod, { apply(target, _, args) { 9961 const operationName = instrumentedMethod.operation || "unknown"; 9962 const params = args[0]; 9963 const requestAttributes = extractRequestAttributes(operationName, params, context); 9964 const model = requestAttributes["gen_ai.request.model"] ?? "unknown"; 9965 if (instrumentedMethod.streaming) return startSpanManual({ 9966 name: `${operationName} ${model}`, 9967 op: `gen_ai.${operationName}`, 9968 attributes: requestAttributes 9969 }, async (span) => { 9970 try { 9971 if (options.recordInputs && params) addPrivateRequestAttributes(span, params, operationName, shouldEnableTruncation(options.enableTruncation)); 9972 return instrumentStream(await target.apply(context, args), span, Boolean(options.recordOutputs)); 9973 } catch (error) { 9974 span.setStatus({ 9975 code: 2, 9976 message: "internal_error" 9977 }); 9978 span.end(); 9979 throw error; 9980 } 9981 }); 9982 return startSpan({ 9983 name: `${operationName} ${model}`, 9984 op: `gen_ai.${operationName}`, 9985 attributes: requestAttributes 9986 }, (span) => { 9987 if (options.recordInputs && params) addPrivateRequestAttributes(span, params, operationName, shouldEnableTruncation(options.enableTruncation)); 9988 return handleCallbackErrors(() => target.apply(context, args), () => {}, () => {}, (result) => { 9989 if (!isEmbeddings) addResponseAttributes(span, result, options.recordOutputs); 9990 }); 9991 }); 9992 } }); 9993} 9994function createDeepProxy(target, currentPath = "", options) { 9995 return new Proxy(target, { get: (t, prop, receiver) => { 9996 const value = Reflect.get(t, prop, receiver); 9997 const methodPath = buildMethodPath(currentPath, String(prop)); 9998 const instrumentedMethod = GOOGLE_GENAI_METHOD_REGISTRY[methodPath]; 9999 if (typeof value === "function" && instrumentedMethod) { 10000 const wrappedMethod = instrumentedMethod.operation ? instrumentMethod(value, methodPath, instrumentedMethod, t, options) : value.bind(t); 10001 if (!instrumentedMethod.proxyResultPath) return wrappedMethod; 10002 return function(...args) { 10003 const result = wrappedMethod(...args); 10004 if (result && typeof result === "object") return createDeepProxy(result, instrumentedMethod.proxyResultPath, options); 10005 return result; 10006 }; 10007 } 10008 if (typeof value === "function") return value.bind(t); 10009 if (value && typeof value === "object") return createDeepProxy(value, methodPath, options); 10010 return value; 10011 } }); 10012} 10013function instrumentGoogleGenAIClient(client, options) { 10014 return createDeepProxy(client, "", resolveAIRecordingOptions(options)); 10015} 10016function init_google_genai() { 10017 return (init_google_genai = __esmMin((() => { 10018 init_semanticAttributes(); 10019 init_string(); 10020 init_spanstatus(); 10021 init_trace(); 10022 init_handleCallbackErrors(); 10023 init_gen_ai_attributes(); 10024 init_utils$2(); 10025 init_constants$4(); 10026 init_streaming$2(); 10027 })))(); 10028} 10029//#endregion 10030//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langchain/constants.js 10031var LANGCHAIN_ORIGIN, ROLE_MAP; 10032function init_constants$5() { 10033 return (init_constants$5 = __esmMin((() => { 10034 LANGCHAIN_ORIGIN = "auto.ai.langchain"; 10035 ROLE_MAP = { 10036 human: "user", 10037 ai: "assistant", 10038 assistant: "assistant", 10039 system: "system", 10040 function: "function", 10041 tool: "tool" 10042 }; 10043 })))(); 10044} 10045//#endregion 10046//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js 10047function normalizeContent(v) { 10048 if (Array.isArray(v)) try { 10049 const stripped = v.map((part) => part && typeof part === "object" && isContentMedia(part) ? stripInlineMediaFromSingleMessage(part) : part); 10050 return JSON.stringify(stripped); 10051 } catch { 10052 return String(v); 10053 } 10054 return stringify(v, String); 10055} 10056function normalizeMessageRole(role) { 10057 const normalized = role.toLowerCase(); 10058 return ROLE_MAP[normalized] ?? normalized; 10059} 10060function normalizeRoleNameFromCtor(name) { 10061 if (name.includes("System")) return "system"; 10062 if (name.includes("Human")) return "user"; 10063 if (name.includes("AI") || name.includes("Assistant")) return "assistant"; 10064 if (name.includes("Function")) return "function"; 10065 if (name.includes("Tool")) return "tool"; 10066 return "user"; 10067} 10068function getInvocationParams(tags) { 10069 if (!tags || Array.isArray(tags)) return void 0; 10070 return tags.invocation_params; 10071} 10072function normalizeLangChainMessages(messages) { 10073 return messages.map((message) => { 10074 const maybeGetType = message._getType; 10075 if (typeof maybeGetType === "function") return { 10076 role: normalizeMessageRole(maybeGetType.call(message)), 10077 content: normalizeContent(message.content) 10078 }; 10079 if (message.lc === 1 && message.kwargs) { 10080 const id = message.id; 10081 const messageType = Array.isArray(id) && id.length > 0 ? id[id.length - 1] : ""; 10082 return { 10083 role: normalizeMessageRole(typeof messageType === "string" ? normalizeRoleNameFromCtor(messageType) : "user"), 10084 content: normalizeContent(message.kwargs?.content) 10085 }; 10086 } 10087 if (message.type) return { 10088 role: normalizeMessageRole(String(message.type).toLowerCase()), 10089 content: normalizeContent(message.content) 10090 }; 10091 if (message.role) return { 10092 role: normalizeMessageRole(String(message.role)), 10093 content: normalizeContent(message.content) 10094 }; 10095 const ctor = message.constructor?.name; 10096 if (ctor && ctor !== "Object") return { 10097 role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)), 10098 content: normalizeContent(message.content) 10099 }; 10100 return { 10101 role: "user", 10102 content: normalizeContent(message.content) 10103 }; 10104 }); 10105} 10106function extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata) { 10107 const attrs = {}; 10108 const kwargs = "kwargs" in serialized ? serialized.kwargs : void 0; 10109 const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature; 10110 setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, temperature); 10111 const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens; 10112 setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, maxTokens); 10113 const topP = invocationParams?.top_p ?? kwargs?.top_p; 10114 setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, topP); 10115 const frequencyPenalty = invocationParams?.frequency_penalty;
10116 setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, frequencyPenalty); 10117 const presencePenalty = invocationParams?.presence_penalty; 10118 setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, presencePenalty); 10119 if (invocationParams && "stream" in invocationParams) setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream)); 10120 return attrs; 10121} 10122function baseRequestAttributes(system, modelName, serialized, invocationParams, langSmithMetadata) { 10123 return { 10124 [GEN_AI_SYSTEM_ATTRIBUTE]: stringify(system ?? "langchain", String), 10125 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "chat", 10126 [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: stringify(modelName, String), 10127 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, 10128 ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata) 10129 }; 10130} 10131function extractLLMRequestAttributes(llm, prompts, recordInputs, enableTruncation, invocationParams, langSmithMetadata) { 10132 const system = langSmithMetadata?.ls_provider; 10133 const attrs = baseRequestAttributes(system, invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? "unknown", llm, invocationParams, langSmithMetadata); 10134 if (recordInputs && Array.isArray(prompts) && prompts.length > 0) { 10135 setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, prompts.length); 10136 const messages = prompts.map((p) => ({ 10137 role: "user", 10138 content: p 10139 })); 10140 setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, enableTruncation ? getTruncatedJsonString(messages) : stringify(messages)); 10141 } 10142 return attrs; 10143} 10144function extractChatModelRequestAttributes(llm, langChainMessages, recordInputs, enableTruncation, invocationParams, langSmithMetadata) { 10145 const attrs = baseRequestAttributes(langSmithMetadata?.ls_provider ?? llm.id?.[2], invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? "unknown", llm, invocationParams, langSmithMetadata); 10146 if (recordInputs && Array.isArray(langChainMessages) && langChainMessages.length > 0) { 10147 const { systemInstructions, filteredMessages } = extractSystemInstructions(normalizeLangChainMessages(langChainMessages.flat())); 10148 if (systemInstructions) setIfDefined(attrs, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions); 10149 const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0; 10150 setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, filteredLength); 10151 setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages)); 10152 } 10153 return attrs; 10154} 10155function addToolCallsAttributes(generations, attrs) { 10156 const toolCalls = []; 10157 const flatGenerations = generations.flat(); 10158 for (const gen of flatGenerations) { 10159 const msgToolCalls = gen.message?.tool_calls; 10160 if (Array.isArray(msgToolCalls) && msgToolCalls.length > 0) toolCalls.push(...msgToolCalls); 10161 else { 10162 const content = gen.message?.content; 10163 if (Array.isArray(content)) for (const item of content) { 10164 const t = item; 10165 if (t.type === "tool_use") toolCalls.push(t); 10166 } 10167 } 10168 } 10169 if (toolCalls.length > 0) setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, stringify(toolCalls, String)); 10170} 10171function addTokenUsageAttributes(llmOutput, attrs) { 10172 if (!llmOutput) return; 10173 const tokenUsage = llmOutput.tokenUsage; 10174 const anthropicUsage = llmOutput.usage; 10175 if (tokenUsage) { 10176 setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, tokenUsage.promptTokens); 10177 setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, tokenUsage.completionTokens); 10178 setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, tokenUsage.totalTokens); 10179 } else if (anthropicUsage) { 10180 setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.input_tokens); 10181 setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, anthropicUsage.output_tokens); 10182 const input = Number(anthropicUsage.input_tokens); 10183 const output = Number(anthropicUsage.output_tokens); 10184 const total = (Number.isNaN(input) ? 0 : input) + (Number.isNaN(output) ? 0 : output); 10185 if (total > 0) setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, total); 10186 if (anthropicUsage.cache_creation_input_tokens !== void 0) setNumberIfDefined(attrs, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.cache_creation_input_tokens); 10187 if (anthropicUsage.cache_read_input_tokens !== void 0) setNumberIfDefined(attrs, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.cache_read_input_tokens); 10188 } 10189} 10190function extractLlmResponseAttributes(llmResult, recordOutputs) { 10191 if (!llmResult) return; 10192 const attrs = {}; 10193 if (Array.isArray(llmResult.generations)) { 10194 const finishReasons = llmResult.generations.flat().map((g) => { 10195 if (g.generationInfo?.finish_reason) return g.generationInfo.finish_reason; 10196 if (g.generation_info?.finish_reason) return g.generation_info.finish_reason; 10197 return null; 10198 }).filter((r) => typeof r === "string"); 10199 if (finishReasons.length > 0) setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, stringify(finishReasons, String)); 10200 addToolCallsAttributes(llmResult.generations, attrs); 10201 if (recordOutputs) { 10202 const texts = llmResult.generations.flat().map((gen) => gen.text ?? gen.message?.content).filter((t) => typeof t === "string"); 10203 if (texts.length > 0) setIfDefined(attrs, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, stringify(texts, String)); 10204 } 10205 } 10206 addTokenUsageAttributes(llmResult.llmOutput, attrs); 10207 const llmOutput = llmResult.llmOutput; 10208 const v1Message = (llmResult.generations?.[0]?.[0])?.message; 10209 const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name; 10210 if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, modelName); 10211 const responseId = llmOutput?.id ?? v1Message?.id; 10212 if (responseId) setIfDefined(attrs, GEN_AI_RESPONSE_ID_ATTRIBUTE, responseId); 10213 const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason; 10214 if (stopReason) setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, stringify(stopReason, String)); 10215 return attrs; 10216} 10217function getAgentNameFromMetadata(metadata) { 10218 const attrs = {}; 10219 const agentName = metadata?.lc_agent_name; 10220 if (typeof agentName === "string") attrs[GEN_AI_AGENT_NAME_ATTRIBUTE] = agentName; 10221 return attrs; 10222} 10223function extractToolDefinitions(extraParams) { 10224 const tools = extraParams?.invocation_params?.tools ?? extraParams?.options?.tools; 10225 if (!Array.isArray(tools) || tools.length === 0) return void 0; 10226 const toolDefs = tools.map((tool) => { 10227 const fn = tool.function; 10228 return { 10229 type: "function", 10230 name: tool.name ?? fn?.name ?? "", 10231 description: tool.description ?? fn?.description 10232 }; 10233 }); 10234 return JSON.stringify(toolDefs); 10235} 10236function isCallbackManager(value) { 10237 if (!value || typeof value !== "object") return false;
10238 const candidate = value; 10239 return typeof candidate.addHandler === "function" && typeof candidate.copy === "function"; 10240} 10241function isSentryHandler(handler) { 10242 return typeof handler === "object" && handler?.name === "SentryCallbackHandler"; 10243} 10244function containsSentryHandler(handlers) { 10245 return handlers.some(isSentryHandler); 10246} 10247function _INTERNAL_mergeLangChainCallbackHandler(existing, sentryHandler) { 10248 if (!existing) return [sentryHandler]; 10249 if (isCallbackManager(existing)) { 10250 if (containsSentryHandler(existing.handlers ?? [])) return existing; 10251 const copied = existing.copy(); 10252 copied.addHandler(sentryHandler, true); 10253 return copied; 10254 } 10255 const handlers = Array.isArray(existing) ? existing : [existing]; 10256 if (containsSentryHandler(handlers)) return existing; 10257 return [...handlers, sentryHandler]; 10258} 10259var setIfDefined, setNumberIfDefined; 10260function init_utils$6() { 10261 return (init_utils$6 = __esmMin((() => { 10262 init_semanticAttributes(); 10263 init_string(); 10264 init_gen_ai_attributes(); 10265 init_mediaStripping(); 10266 init_utils$2(); 10267 init_constants$5(); 10268 setIfDefined = (target, key, value) => { 10269 if (value != null) target[key] = value; 10270 }; 10271 setNumberIfDefined = (target, key, value) => { 10272 const n = Number(value); 10273 if (!Number.isNaN(n)) target[key] = n; 10274 }; 10275 })))(); 10276} 10277//#endregion 10278//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langchain/index.js 10279function createLangChainCallbackHandler(options = {}) { 10280 const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); 10281 const enableTruncation = shouldEnableTruncation(options.enableTruncation); 10282 const spanMap = /* @__PURE__ */ new Map(); 10283 const exitSpan = (runId) => { 10284 const span = spanMap.get(runId); 10285 if (span?.isRecording()) { 10286 span.end(); 10287 spanMap.delete(runId); 10288 } 10289 }; 10290 const handler = { 10291 lc_serializable: false, 10292 lc_namespace: [ 10293 "langchain_core", 10294 "callbacks", 10295 "sentry" 10296 ], 10297 lc_secrets: void 0, 10298 lc_attributes: void 0, 10299 lc_aliases: void 0, 10300 lc_serializable_keys: void 0, 10301 lc_id: [ 10302 "langchain_core", 10303 "callbacks", 10304 "sentry" 10305 ], 10306 lc_kwargs: {}, 10307 name: "SentryCallbackHandler", 10308 ignoreLLM: false, 10309 ignoreChain: false, 10310 ignoreAgent: false, 10311 ignoreRetriever: false, 10312 ignoreCustomEvent: false, 10313 raiseError: false, 10314 awaitHandlers: true, 10315 handleLLMStart(llm, prompts, runId, _parentRunId, _extraParams, tags, metadata, _runName) { 10316 const invocationParams = getInvocationParams(tags); 10317 const attributes = extractLLMRequestAttributes(llm, prompts, recordInputs, enableTruncation, invocationParams, metadata); 10318 const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]; 10319 const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]; 10320 startSpanManual({ 10321 name: `${operationName} ${modelName}`, 10322 op: "gen_ai.chat", 10323 attributes: { 10324 ...getAgentNameFromMetadata(metadata), 10325 ...attributes, 10326 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.chat" 10327 } 10328 }, (span) => { 10329 spanMap.set(runId, span); 10330 return span; 10331 }); 10332 }, 10333 handleChatModelStart(llm, messages, runId, _parentRunId, extraParams, tags, metadata, _runName) { 10334 const invocationParams = getInvocationParams(tags); 10335 const attributes = extractChatModelRequestAttributes(llm, messages, recordInputs, enableTruncation, invocationParams, metadata); 10336 const toolDefsJson = extractToolDefinitions(extraParams); 10337 if (toolDefsJson) attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = toolDefsJson; 10338 const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]; 10339 const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]; 10340 startSpanManual({ 10341 name: `${operationName} ${modelName}`, 10342 op: "gen_ai.chat", 10343 attributes: { 10344 ...getAgentNameFromMetadata(metadata), 10345 ...attributes, 10346 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.chat" 10347 } 10348 }, (span) => { 10349 spanMap.set(runId, span); 10350 return span; 10351 }); 10352 }, 10353 handleLLMEnd(output, runId, _parentRunId, _tags, _extraParams) { 10354 const span = spanMap.get(runId); 10355 if (span?.isRecording()) { 10356 const attributes = extractLlmResponseAttributes(output, recordOutputs); 10357 if (attributes) span.setAttributes(attributes); 10358 exitSpan(runId); 10359 } 10360 }, 10361 handleLLMError(_error, runId) { 10362 const span = spanMap.get(runId); 10363 if (span?.isRecording()) { 10364 span.setStatus({ 10365 code: 2, 10366 message: "internal_error" 10367 }); 10368 exitSpan(runId); 10369 } 10370 }, 10371 handleChainStart(chain, inputs, runId, _parentRunId, _tags, metadata, _runType, runName) { 10372 if (metadata?.__sentry_langgraph__) return; 10373 const chainName = runName || chain.name || "unknown_chain"; 10374 const attributes = { 10375 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.langchain", 10376 "langchain.chain.name": chainName
10377 }; 10378 if (recordInputs) attributes["langchain.chain.inputs"] = JSON.stringify(inputs); 10379 startSpanManual({ 10380 name: `chain ${chainName}`, 10381 op: "gen_ai.invoke_agent", 10382 attributes: { 10383 ...attributes, 10384 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.invoke_agent" 10385 } 10386 }, (span) => { 10387 spanMap.set(runId, span); 10388 return span; 10389 }); 10390 }, 10391 handleChainEnd(outputs, runId) { 10392 const span = spanMap.get(runId); 10393 if (span?.isRecording()) { 10394 if (recordOutputs) span.setAttributes({ "langchain.chain.outputs": JSON.stringify(outputs) }); 10395 exitSpan(runId); 10396 } 10397 }, 10398 handleChainError(_error, runId) { 10399 const span = spanMap.get(runId); 10400 if (span?.isRecording()) { 10401 span.setStatus({ 10402 code: 2, 10403 message: "internal_error" 10404 }); 10405 exitSpan(runId); 10406 } 10407 }, 10408 handleToolStart(tool, input, runId, _parentRunId, _tags, metadata, runName) { 10409 if (metadata?.__sentry_langgraph__) return; 10410 const toolName = runName || tool.name || "unknown_tool"; 10411 const attributes = { 10412 ...getAgentNameFromMetadata(metadata), 10413 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, 10414 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "execute_tool", 10415 [GEN_AI_TOOL_NAME_ATTRIBUTE]: toolName 10416 }; 10417 if (recordInputs) attributes[GEN_AI_TOOL_INPUT_ATTRIBUTE] = input; 10418 startSpanManual({ 10419 name: `execute_tool ${toolName}`, 10420 op: "gen_ai.execute_tool", 10421 attributes: { 10422 ...attributes, 10423 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.execute_tool" 10424 } 10425 }, (span) => { 10426 spanMap.set(runId, span); 10427 return span; 10428 }); 10429 }, 10430 handleToolEnd(output, runId) { 10431 const span = spanMap.get(runId); 10432 if (span?.isRecording()) { 10433 if (recordOutputs) { 10434 const outputObj = output; 10435 const content = outputObj && typeof outputObj === "object" && "content" in outputObj ? outputObj.content : output; 10436 span.setAttributes({ [GEN_AI_TOOL_OUTPUT_ATTRIBUTE]: typeof content === "string" ? content : JSON.stringify(content) }); 10437 } 10438 exitSpan(runId); 10439 } 10440 }, 10441 handleToolError(_error, runId) { 10442 const span = spanMap.get(runId); 10443 if (span?.isRecording()) { 10444 span.setStatus({ 10445 code: 2, 10446 message: "internal_error" 10447 }); 10448 exitSpan(runId); 10449 } 10450 }, 10451 copy() { 10452 return handler; 10453 }, 10454 toJSON() { 10455 return { 10456 lc: 1, 10457 type: "not_implemented", 10458 id: handler.lc_id 10459 }; 10460 }, 10461 toJSONNotImplemented() { 10462 return { 10463 lc: 1, 10464 type: "not_implemented", 10465 id: handler.lc_id 10466 }; 10467 } 10468 }; 10469 return handler; 10470} 10471function init_langchain() { 10472 return (init_langchain = __esmMin((() => { 10473 init_semanticAttributes(); 10474 init_spanstatus(); 10475 init_trace(); 10476 init_gen_ai_attributes(); 10477 init_utils$2(); 10478 init_constants$5(); 10479 init_utils$6(); 10480 })))(); 10481} 10482//#endregion 10483//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langchain/embeddings.js 10484function inferSystemFromInstance(instance) { 10485 const name = instance.constructor?.name ?? ""; 10486 if (name.includes("OpenAI")) return "openai"; 10487 if (name.includes("Google")) return "google_genai"; 10488 if (name.includes("Mistral")) return "mistralai"; 10489 if (name.includes("Vertex")) return "google_vertexai"; 10490 if (name.includes("Bedrock")) return "aws_bedrock"; 10491 if (name.includes("Ollama")) return "ollama"; 10492 if (name.includes("Cloudflare")) return "cloudflare"; 10493 if (name.includes("Cohere")) return "cohere"; 10494 return "langchain"; 10495} 10496function extractEmbeddingAttributes(instance) { 10497 const embeddingsInstance = instance ?? {}; 10498 const attributes = { 10499 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, 10500 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, 10501 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "embeddings", 10502 [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: embeddingsInstance.model ?? "unknown" 10503 }; 10504 attributes[GEN_AI_SYSTEM_ATTRIBUTE] = inferSystemFromInstance(embeddingsInstance); 10505 if ("dimensions" in embeddingsInstance) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions; 10506 if ("encodingFormat" in embeddingsInstance) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat; 10507 return attributes; 10508} 10509function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options = {}) { 10510 const { recordInputs } = resolveAIRecordingOptions(options); 10511 const attributes = extractEmbeddingAttributes(instance); 10512 const modelName = attributes["gen_ai.request.model"] || "unknown"; 10513 if (recordInputs && input != null) attributes[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE] = typeof input === "string" ? input : JSON.stringify(input); 10514 return { 10515 name: `embeddings ${modelName}`, 10516 op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, 10517 attributes 10518 }; 10519} 10520function instrumentEmbeddingMethod(originalMethod, options = {}) { 10521 return new Proxy(originalMethod, { apply(target, thisArg, args) { 10522 return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, args[0], options), () => { 10523 return Reflect.apply(target, thisArg, args); 10524 }); 10525 } }); 10526} 10527function instrumentLangChainEmbeddings(instance, options) { 10528 const embeddingsInstance = instance;
10529 if (typeof embeddingsInstance.embedQuery === "function") embeddingsInstance.embedQuery = instrumentEmbeddingMethod(embeddingsInstance.embedQuery, options); 10530 if (typeof embeddingsInstance.embedDocuments === "function") embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(embeddingsInstance.embedDocuments, options); 10531 return instance; 10532} 10533function init_embeddings() { 10534 return (init_embeddings = __esmMin((() => { 10535 init_semanticAttributes(); 10536 init_trace(); 10537 init_gen_ai_attributes(); 10538 init_utils$2(); 10539 init_constants$5(); 10540 })))(); 10541} 10542//#endregion 10543//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langgraph/constants.js 10544var LANGGRAPH_ORIGIN; 10545function init_constants$6() { 10546 return (init_constants$6 = __esmMin((() => { 10547 LANGGRAPH_ORIGIN = "auto.ai.langgraph"; 10548 })))(); 10549} 10550//#endregion 10551//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js 10552function extractLLMFromParams(args) { 10553 const arg = args[0]; 10554 if (typeof arg !== "object" || !arg || !("llm" in arg) || !arg.llm || typeof arg.llm !== "object") return null; 10555 const llm = arg.llm; 10556 if (typeof llm.modelName !== "string" && typeof llm.model !== "string") return null; 10557 return llm; 10558} 10559function extractAgentNameFromParams(args) { 10560 const arg = args[0]; 10561 if (typeof arg === "object" && !!arg && "name" in arg && typeof arg.name === "string") return arg.name; 10562 return null; 10563} 10564function wrapToolsWithSpans(tools, options, agentName) { 10565 const SENTRY_WRAPPED = "__sentry_tool_wrapped__"; 10566 for (const tool of tools) { 10567 if (!tool || typeof tool !== "object") continue; 10568 const t = tool; 10569 const originalInvoke = t.invoke; 10570 if (typeof originalInvoke !== "function" || Object.prototype.hasOwnProperty.call(t, SENTRY_WRAPPED)) continue; 10571 const toolName = typeof t.name === "string" ? t.name : "unknown_tool"; 10572 const toolDescription = typeof t.description === "string" ? t.description : void 0; 10573 t.invoke = new Proxy(originalInvoke, { apply(target, thisArg, args) { 10574 const spanAttributes = { 10575 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN, 10576 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE, 10577 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "execute_tool", 10578 [GEN_AI_TOOL_NAME_ATTRIBUTE]: toolName, 10579 [GEN_AI_TOOL_TYPE_ATTRIBUTE]: "function" 10580 }; 10581 const callAgentName = args[1]?.metadata?.lc_agent_name ?? agentName; 10582 if (typeof callAgentName === "string") spanAttributes[GEN_AI_AGENT_NAME_ATTRIBUTE] = callAgentName; 10583 if (toolDescription) spanAttributes[GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE] = toolDescription; 10584 const input = args[0]; 10585 if (typeof input === "object" && !!input) { 10586 if ("id" in input && typeof input.id === "string") spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id; 10587 if (options.recordInputs) { 10588 const toolArgs = "args" in input && typeof input.args === "object" ? input.args : input; 10589 try { 10590 spanAttributes[GEN_AI_TOOL_INPUT_ATTRIBUTE] = JSON.stringify(toolArgs); 10591 } catch {} 10592 } 10593 } 10594 return startSpan({ 10595 op: GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE, 10596 name: `execute_tool ${toolName}`, 10597 attributes: spanAttributes 10598 }, async (span) => { 10599 try { 10600 const result = await Reflect.apply(target, thisArg, args); 10601 if (options.recordOutputs) try { 10602 const resultObj = result; 10603 const content = resultObj && typeof resultObj === "object" && "content" in resultObj ? resultObj.content : result; 10604 span.setAttribute(GEN_AI_TOOL_OUTPUT_ATTRIBUTE, typeof content === "string" ? content : JSON.stringify(content)); 10605 } catch {} 10606 return result; 10607 } catch (error) { 10608 span.setStatus({ 10609 code: 2, 10610 message: "internal_error" 10611 }); 10612 throw error; 10613 } 10614 }); 10615 } }); 10616 Object.defineProperty(t, SENTRY_WRAPPED, { 10617 value: true, 10618 enumerable: false 10619 }); 10620 } 10621 return tools; 10622} 10623function extractToolCalls(messages) { 10624 if (!messages || messages.length === 0) return null; 10625 const toolCalls = []; 10626 for (const message of messages) if (message && typeof message === "object") { 10627 const msgToolCalls = message.tool_calls; 10628 if (msgToolCalls && Array.isArray(msgToolCalls)) toolCalls.push(...msgToolCalls); 10629 } 10630 return toolCalls.length > 0 ? toolCalls : null; 10631} 10632function extractTokenUsageFromMessage(message) { 10633 const msg = message; 10634 let inputTokens = 0; 10635 let outputTokens = 0; 10636 let totalTokens = 0; 10637 if (msg.usage_metadata && typeof msg.usage_metadata === "object") { 10638 const usage = msg.usage_metadata; 10639 if (typeof usage.input_tokens === "number") inputTokens = usage.input_tokens; 10640 if (typeof usage.output_tokens === "number") outputTokens = usage.output_tokens; 10641 if (typeof usage.total_tokens === "number") totalTokens = usage.total_tokens; 10642 return { 10643 inputTokens, 10644 outputTokens, 10645 totalTokens 10646 }; 10647 } 10648 if (msg.response_metadata && typeof msg.response_metadata === "object") { 10649 const metadata = msg.response_metadata; 10650 if (metadata.tokenUsage && typeof metadata.tokenUsage === "object") { 10651 const tokenUsage = metadata.tokenUsage; 10652 if (typeof tokenUsage.promptTokens === "number") inputTokens = tokenUsage.promptTokens; 10653 if (typeof tokenUsage.completionTokens === "number") outputTokens = tokenUsage.completionTokens; 10654 if (typeof tokenUsage.totalTokens === "number") totalTokens = tokenUsage.totalTokens; 10655 } 10656 } 10657 return { 10658 inputTokens, 10659 outputTokens, 10660 totalTokens 10661 }; 10662} 10663function extractModelMetadata(span, message) { 10664 const msg = message; 10665 if (msg.response_metadata && typeof msg.response_metadata === "object") { 10666 const metadata = msg.response_metadata; 10667 if (metadata.model_name && typeof metadata.model_name === "string") span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, metadata.model_name); 10668 if (metadata.finish_reason && typeof metadata.finish_reason === "string") span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, [metadata.finish_reason]); 10669 } 10670} 10671function extractToolsFromCompiledGraph(compiledGraph) { 10672 if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) return null; 10673 const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools; 10674 if (!tools || !Array.isArray(tools) || tools.length === 0) return null; 10675 return tools.map((tool) => ({ 10676 name: tool.lc_kwargs?.name, 10677 description: tool.lc_kwargs?.description, 10678 schema: tool.lc_kwargs?.schema 10679 })); 10680} 10681function setResponseAttributes(span, inputMessages, result) { 10682 const outputMessages = result?.messages; 10683 if (!outputMessages || !Array.isArray(outputMessages)) return; 10684 const inputCount = inputMessages?.length ?? 0; 10685 const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : []; 10686 if (newMessages.length === 0) return; 10687 const toolCalls = extractToolCalls(newMessages); 10688 if (toolCalls) span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, JSON.stringify(toolCalls)); 10689 const normalizedNewMessages = normalizeLangChainMessages(newMessages); 10690 span.setAttribute(GEN_AI_RESPONSE_TEXT_ATTRIBUTE, JSON.stringify(normalizedNewMessages)); 10691 let totalInputTokens = 0; 10692 let totalOutputTokens = 0; 10693 let totalTokens = 0; 10694 for (const message of newMessages) { 10695 const tokens = extractTokenUsageFromMessage(message); 10696 totalInputTokens += tokens.inputTokens; 10697 totalOutputTokens += tokens.outputTokens; 10698 totalTokens += tokens.totalTokens; 10699 extractModelMetadata(span, message); 10700 } 10701 if (totalInputTokens > 0) span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, totalInputTokens); 10702 if (totalOutputTokens > 0) span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, totalOutputTokens); 10703 if (totalTokens > 0) span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, totalTokens); 10704} 10705function init_utils$7() { 10706 return (init_utils$7 = __esmMin((() => { 10707 init_semanticAttributes(); 10708 init_spanstatus(); 10709 init_trace(); 10710 init_gen_ai_attributes(); 10711 init_utils$6(); 10712 init_constants$6(); 10713 })))(); 10714} 10715//#endregion 10716//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/langgraph/index.js 10717function _INTERNAL_getLangGraphCreateAgentSpanOptions(agentName) { 10718 const attributes = { 10719 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN, 10720 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.create_agent", 10721 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "create_agent" 10722 }; 10723 if (agentName) attributes[GEN_AI_AGENT_NAME_ATTRIBUTE] = agentName; 10724 return { 10725 op: "gen_ai.create_agent", 10726 name: agentName ? `create_agent ${agentName}` : "create_agent", 10727 attributes 10728 }; 10729} 10730function instrumentStateGraphCompile(originalCompile, options) { 10731 if (Object.prototype.hasOwnProperty.call(originalCompile, SENTRY_PATCHED)) return originalCompile; 10732 const sentryHandler = createLangChainCallbackHandler(options); 10733 const wrapped = new Proxy(originalCompile, { apply(target, thisArg, args) { 10734 if (_insideCreateReactAgent) return Reflect.apply(target, thisArg, args); 10735 return startSpan(_INTERNAL_getLangGraphCreateAgentSpanOptions(), (span) => { 10736 try { 10737 const compiledGraph = Reflect.apply(target, thisArg, args); 10738 const compileOptions = args.length > 0 ? args[0] : {}; 10739 if (compileOptions?.name && typeof compileOptions.name === "string") { 10740 span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, compileOptions.name); 10741 span.updateName(`create_agent ${compileOptions.name}`); 10742 } 10743 const originalInvoke = compiledGraph.invoke; 10744 if (originalInvoke && typeof originalInvoke === "function") compiledGraph.invoke = instrumentCompiledGraphInvoke(originalInvoke.bind(compiledGraph), compiledGraph, compileOptions, options, void 0, sentryHandler); 10745 return compiledGraph; 10746 } catch (error) { 10747 span.setStatus({ 10748 code: 2, 10749 message: "internal_error" 10750 }); 10751 throw error; 10752 } 10753 }); 10754 } }); 10755 Object.defineProperty(wrapped, SENTRY_PATCHED, { 10756 value: true, 10757 enumerable: false 10758 }); 10759 return wrapped; 10760} 10761function instrumentCompiledGraphInvoke(originalInvoke, graphInstance, compileOptions, options, llm, sentryCallbackHandler) { 10762 return new Proxy(originalInvoke, { apply(target, thisArg, args) { 10763 const modelName = llm?.modelName ?? llm?.model; 10764 return startSpan({ 10765 op: "gen_ai.invoke_agent", 10766 name: "invoke_agent", 10767 attributes: { 10768 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN, 10769 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, 10770 [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "invoke_agent" 10771 } 10772 }, async (span) => { 10773 try { 10774 const graphName = compileOptions?.name; 10775 if (graphName && typeof graphName === "string") { 10776 span.setAttribute(GEN_AI_PIPELINE_NAME_ATTRIBUTE, graphName); 10777 span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, graphName); 10778 span.updateName(`invoke_agent ${graphName}`); 10779 } 10780 if (modelName) span.setAttribute(GEN_AI_REQUEST_MODEL_ATTRIBUTE, modelName); 10781 const threadId = ((args.length > 1 ? args[1] : void 0)?.configurable)?.thread_id; 10782 if (threadId && typeof threadId === "string") span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, threadId); 10783 if (sentryCallbackHandler) { 10784 const invokeConfig = args[1] ?? {}; 10785 args[1] = invokeConfig; 10786 invokeConfig.metadata = { 10787 ...invokeConfig.metadata ?? {}, 10788 __sentry_langgraph__: true, 10789 ...typeof graphName === "string" ? { lc_agent_name: graphName } : {} 10790 }; 10791 invokeConfig.callbacks = _INTERNAL_mergeLangChainCallbackHandler(invokeConfig.callbacks, sentryCallbackHandler); 10792 } 10793 const tools = extractToolsFromCompiledGraph(graphInstance); 10794 if (tools) span.setAttribute(GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, JSON.stringify(tools)); 10795 const recordInputs = options.recordInputs; 10796 const recordOutputs = options.recordOutputs; 10797 const inputMessages = args.length > 0 ? args[0]?.messages ?? [] : []; 10798 if (inputMessages && recordInputs) { 10799 const { systemInstructions, filteredMessages }
10799 = extractSystemInstructions(normalizeLangChainMessages(inputMessages)); 10800 if (systemInstructions) span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions); 10801 const enableTruncation = shouldEnableTruncation(options.enableTruncation); 10802 const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0; 10803 span.setAttributes({ 10804 [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages), 10805 [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength 10806 }); 10807 } 10808 const result = await Reflect.apply(target, thisArg, args); 10809 if (recordOutputs) setResponseAttributes(span, inputMessages ?? null, result); 10810 return result; 10811 } catch (error) { 10812 span.setStatus({ 10813 code: 2, 10814 message: "internal_error" 10815 }); 10816 throw error; 10817 } 10818 }); 10819 } }); 10820} 10821function instrumentCreateReactAgent(originalCreateReactAgent, options) { 10822 if (Object.prototype.hasOwnProperty.call(originalCreateReactAgent, SENTRY_PATCHED)) return originalCreateReactAgent; 10823 const resolvedOptions = resolveAIRecordingOptions(options); 10824 const sentryHandler = createLangChainCallbackHandler(resolvedOptions); 10825 const wrapped = new Proxy(originalCreateReactAgent, { apply(target, thisArg, args) { 10826 const llm = extractLLMFromParams(args); 10827 const agentName = extractAgentNameFromParams(args); 10828 const params = args[0]; 10829 if (params && Array.isArray(params.tools) && params.tools.length > 0) wrapToolsWithSpans(params.tools, resolvedOptions, agentName ?? void 0); 10830 _insideCreateReactAgent = true; 10831 let compiledGraph; 10832 try { 10833 compiledGraph = Reflect.apply(target, thisArg, args); 10834 } finally { 10835 _insideCreateReactAgent = false; 10836 } 10837 const originalInvoke = compiledGraph.invoke; 10838 if (originalInvoke && typeof originalInvoke === "function") { 10839 const compileOptions = {}; 10840 if (agentName) compileOptions.name = agentName; 10841 compiledGraph.invoke = instrumentCompiledGraphInvoke(originalInvoke.bind(compiledGraph), compiledGraph, compileOptions, resolvedOptions, llm, sentryHandler); 10842 } 10843 return compiledGraph; 10844 } }); 10845 Object.defineProperty(wrapped, SENTRY_PATCHED, { 10846 value: true, 10847 enumerable: false 10848 }); 10849 return wrapped; 10850} 10851function instrumentStateGraph(stateGraph, options) { 10852 stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, resolveAIRecordingOptions(options)); 10853 return stateGraph; 10854} 10855var _insideCreateReactAgent, SENTRY_PATCHED, instrumentLangGraph; 10856function init_langgraph() { 10857 return (init_langgraph = __esmMin((() => { 10858 init_semanticAttributes(); 10859 init_string(); 10860 init_spanstatus(); 10861 init_trace(); 10862 init_gen_ai_attributes(); 10863 init_utils$2(); 10864 init_langchain(); 10865 init_utils$6(); 10866 init_constants$6(); 10867 init_utils$7(); 10868 _insideCreateReactAgent = false; 10869 SENTRY_PATCHED = "__sentry_patched__"; 10870 instrumentLangGraph = instrumentStateGraph; 10871 })))(); 10872} 10873//#endregion 10874//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/envelope.js 10875function createStreamedSpanEnvelope(serializedSpans, dsc, client) { 10876 const options = client.getOptions(); 10877 const dsn = client.getDsn(); 10878 const tunnel = options.tunnel; 10879 const sdk = getSdkMetadataForEnvelopeHeader(options._metadata); 10880 const headers = { 10881 sent_at: new Date(safeDateNow()).toISOString(), 10882 ...dscHasRequiredProps(dsc) && { trace: dsc }, 10883 ...sdk && { sdk }, 10884 ...!!tunnel && dsn && { dsn: dsnToString(dsn) } 10885 }; 10886 const inferSetting = client.getDataCollectionOptions().userInfo ? "auto" : "never"; 10887 return createEnvelope(headers, [[{ 10888 type: "span", 10889 item_count: serializedSpans.length, 10890 content_type: "application/vnd.sentry.items.span.v2+json" 10891 }, { 10892 version: 2, 10893 ...isBrowser() && { ingest_settings: { 10894 infer_ip: inferSetting, 10895 infer_user_agent: inferSetting 10896 } }, 10897 items: serializedSpans 10898 }]]); 10899} 10900function dscHasRequiredProps(dsc) { 10901 return !!dsc.trace_id && !!dsc.public_key; 10902} 10903function init_envelope$4() { 10904 return (init_envelope$4 = __esmMin((() => { 10905 init_dsn(); 10906 init_envelope(); 10907 init_isBrowser(); 10908 init_randomSafeContext(); 10909 })))(); 10910} 10911//#endregion 10912//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/estimateSize.js 10913function estimateSerializedSpanSizeInBytes(span) { 10914 let weight = 156; 10915 weight += span.name.length * 2; 10916 weight += estimateTypedAttributesSizeInBytes(span.attributes); 10917 if (span.links && span.links.length > 0) { 10918 const attributes = span.links[0]?.attributes; 10919 const linkWeight = 100 + (attributes ? estimateTypedAttributesSizeInBytes(attributes) : 0); 10920 weight += linkWeight * span.links.length; 10921 } 10922 return weight; 10923} 10924function init_estimateSize() { 10925 return (init_estimateSize = __esmMin((() => { 10926 init_attributes(); 10927 })))(); 10928} 10929//#endregion 10930//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/tracing/spans/spanBuffer.js 10931var MAX_SPANS_PER_ENVELOPE, MAX_TRACE_WEIGHT_IN_BYTES, SpanBuffer; 10932function init_spanBuffer() { 10933 return (init_spanBuffer = __esmMin((() => { 10934 init_debug_build(); 10935 init_debug_logger(); 10936 init_dynamicSamplingContext(); 10937 init_envelope$4(); 10938 init_estimateSize();
10939 MAX_SPANS_PER_ENVELOPE = 1e3; 10940 MAX_TRACE_WEIGHT_IN_BYTES = 5e6; 10941 SpanBuffer = class { 10942 constructor(client, options) { 10943 this._traceBuckets = /* @__PURE__ */ new Map(); 10944 this._client = client; 10945 const { maxSpanLimit, flushInterval, maxTraceWeightInBytes } = options ?? {}; 10946 this._maxSpanLimit = maxSpanLimit && maxSpanLimit > 0 && maxSpanLimit <= MAX_SPANS_PER_ENVELOPE ? maxSpanLimit : MAX_SPANS_PER_ENVELOPE; 10947 this._flushInterval = flushInterval && flushInterval > 0 ? flushInterval : 5e3; 10948 this._maxTraceWeight = maxTraceWeightInBytes && maxTraceWeightInBytes > 0 ? maxTraceWeightInBytes : MAX_TRACE_WEIGHT_IN_BYTES; 10949 this._client.on("flush", () => { 10950 this.drain(); 10951 }); 10952 this._client.on("close", () => { 10953 this._traceBuckets.forEach((bucket) => { 10954 clearTimeout(bucket.timeout); 10955 }); 10956 this._traceBuckets.clear(); 10957 }); 10958 } 10959 /** 10960 * Add a span to the buffer. 10961 */ 10962 add(spanJSON) { 10963 const traceId = spanJSON.trace_id; 10964 let bucket = this._traceBuckets.get(traceId); 10965 if (!bucket) { 10966 bucket = { 10967 spans: /* @__PURE__ */ new Set(), 10968 size: 0, 10969 timeout: safeUnref(setTimeout(() => { 10970 this.flush(traceId); 10971 }, this._flushInterval)) 10972 }; 10973 this._traceBuckets.set(traceId, bucket); 10974 } 10975 bucket.spans.add(spanJSON); 10976 bucket.size += estimateSerializedSpanSizeInBytes(spanJSON); 10977 if (bucket.spans.size >= this._maxSpanLimit || bucket.size >= this._maxTraceWeight) this.flush(traceId); 10978 } 10979 /** 10980 * Drain and flush all buffered traces. 10981 */ 10982 drain() { 10983 if (!this._traceBuckets.size) return; 10984 DEBUG_BUILD$5 && debug$2.log(`Flushing span tree map with ${this._traceBuckets.size} traces`); 10985 this._traceBuckets.forEach((_, traceId) => { 10986 this.flush(traceId); 10987 }); 10988 } 10989 /** 10990 * Flush spans of a specific trace. 10991 * In contrast to {@link SpanBuffer.drain}, this method does not flush all traces, but only the one with the given traceId. 10992 */ 10993 flush(traceId) { 10994 const bucket = this._traceBuckets.get(traceId); 10995 if (!bucket) return; 10996 if (!bucket.spans.size) { 10997 this._removeTrace(traceId); 10998 return; 10999 } 11000 const spans = Array.from(bucket.spans); 11001 const segmentSpan = spans[0]?._segmentSpan; 11002 if (!segmentSpan) { 11003 DEBUG_BUILD$5 && debug$2.warn("No segment span reference found on span JSON, cannot compute DSC"); 11004 this._removeTrace(traceId); 11005 return; 11006 } 11007 const dsc = getDynamicSamplingContextFromSpan(segmentSpan); 11008 const cleanedSpans = spans.map((spanJSON) => { 11009 const { _segmentSpan, ...cleanSpanJSON } = spanJSON; 11010 return cleanSpanJSON; 11011 }); 11012 const envelope = createStreamedSpanEnvelope(cleanedSpans, dsc, this._client); 11013 DEBUG_BUILD$5 && debug$2.log(`Sending span envelope for trace ${traceId} with ${cleanedSpans.length} spans`); 11014 this._client.sendEnvelope(envelope).then(null, (reason) => { 11015 DEBUG_BUILD$5 && debug$2.error("Error while sending streamed span envelope:", reason); 11016 }); 11017 this._removeTrace(traceId); 11018 } 11019 _removeTrace(traceId) { 11020 const bucket = this._traceBuckets.get(traceId); 11021 if (bucket) clearTimeout(bucket.timeout); 11022 this._traceBuckets.delete(traceId); 11023 } 11024 }; 11025 })))(); 11026} 11027//#endregion 11028//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/breadcrumb-log-level.js 11029function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) { 11030 if (statusCode === void 0) return; 11031 else if (statusCode >= 400 && statusCode < 500) return "warning"; 11032 else if (statusCode >= 500) return "error"; 11033 else return; 11034} 11035//#endregion 11036//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/supports.js 11037function supportsHistory() { 11038 return "history" in WINDOW$7 && !!WINDOW$7.history; 11039} 11040function _isFetchSupported() { 11041 if (!("fetch" in WINDOW$7)) return false; 11042 try { 11043 new Headers(); 11044 new Request("data:,"); 11045 new Response(); 11046 return true; 11047 } catch { 11048 return false; 11049 } 11050} 11051function isNativeFunction(func) { 11052 return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); 11053} 11054function supportsNativeFetch() { 11055 if (typeof EdgeRuntime === "string") return true;
11056 if (!_isFetchSupported()) return false; 11057 if (isNativeFunction(WINDOW$7.fetch)) return true; 11058 let result = false; 11059 const doc = WINDOW$7.document; 11060 if (doc && typeof doc.createElement === "function") try { 11061 const sandbox = doc.createElement("iframe"); 11062 sandbox.hidden = true; 11063 doc.head.appendChild(sandbox); 11064 if (sandbox.contentWindow?.fetch) result = isNativeFunction(sandbox.contentWindow.fetch); 11065 doc.head.removeChild(sandbox); 11066 } catch (err) { 11067 DEBUG_BUILD$5 && debug$2.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err); 11068 } 11069 return result; 11070} 11071function supportsReportingObserver() { 11072 return "ReportingObserver" in WINDOW$7; 11073} 11074var WINDOW$7; 11075function init_supports() { 11076 return (init_supports = __esmMin((() => { 11077 init_debug_build(); 11078 init_debug_logger(); 11079 init_worldwide(); 11080 WINDOW$7 = GLOBAL_OBJ; 11081 })))(); 11082} 11083//#endregion 11084//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/instrument/fetch.js 11085function addFetchInstrumentationHandler(handler, skipNativeFetchCheck) { 11086 const type = "fetch"; 11087 const removeHandler = addHandler$1(type, handler); 11088 maybeInstrument(type, () => instrumentFetch(void 0, skipNativeFetchCheck)); 11089 return removeHandler; 11090} 11091function addFetchEndInstrumentationHandler(handler) { 11092 const type = "fetch-body-resolved"; 11093 const removeHandler = addHandler$1(type, handler); 11094 maybeInstrument(type, () => instrumentFetch(streamHandler)); 11095 return removeHandler; 11096} 11097function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) { 11098 if (skipNativeFetchCheck && !supportsNativeFetch()) return; 11099 fill(GLOBAL_OBJ, "fetch", function(originalFetch) { 11100 return function(...args) { 11101 const virtualError = /* @__PURE__ */ new Error(); 11102 const { method, url } = parseFetchArgs(args); 11103 const handlerData = { 11104 args, 11105 fetchData: { 11106 method, 11107 url 11108 }, 11109 startTimestamp: timestampInSeconds() * 1e3, 11110 virtualError, 11111 headers: getHeadersFromFetchArgs(args) 11112 }; 11113 if (!onFetchResolved) triggerHandlers$1("fetch", { ...handlerData }); 11114 return originalFetch.apply(GLOBAL_OBJ, args).then(async (response) => { 11115 if (onFetchResolved) onFetchResolved(response); 11116 else triggerHandlers$1("fetch", { 11117 ...handlerData, 11118 endTimestamp: timestampInSeconds() * 1e3, 11119 response 11120 }); 11121 return response; 11122 }, (error) => { 11123 triggerHandlers$1("fetch", { 11124 ...handlerData, 11125 endTimestamp: timestampInSeconds() * 1e3, 11126 error 11127 }); 11128 if (isError(error) && error.stack === void 0) { 11129 error.stack = virtualError.stack; 11130 addNonEnumerableProperty(error, "framesToPop", 1); 11131 } 11132 const enhanceOption = getClient()?.getOptions().enhanceFetchErrorMessages ?? "always"; 11133 if (enhanceOption !== false && isError(error) && error.name === "TypeError" && (error.message === "Failed to fetch" || error.message === "Load failed" || error.message === "NetworkError when attempting to fetch resource.")) try { 11134 const hostname = new URL(handlerData.fetchData.url).host; 11135 if (enhanceOption === "always") error.message = `${error.message} (${hostname})`; 11136 else addNonEnumerableProperty(error, "__sentry_fetch_url_host__", hostname); 11137 } catch {} 11138 throw error; 11139 }); 11140 }; 11141 }); 11142} 11143async function resolveResponse(res, onFinishedResolving) { 11144 if (res?.body) { 11145 const body = res.body; 11146 const responseReader = body.getReader(); 11147 const maxFetchDurationTimeout = setTimeout(() => { 11148 body.cancel().then(null, () => {}); 11149 }, 9e4); 11150 let readingActive = true; 11151 while (readingActive) { 11152 let chunkTimeout; 11153 try { 11154 chunkTimeout = setTimeout(() => { 11155 body.cancel().then(null, () => {}); 11156 }, 5e3); 11157 const { done } = await responseReader.read(); 11158 clearTimeout(chunkTimeout); 11159 if (done) { 11160 onFinishedResolving(); 11161 readingActive = false; 11162 } 11163 } catch { 11164 readingActive = false; 11165 } finally { 11166 clearTimeout(chunkTimeout); 11167 } 11168 } 11169 clearTimeout(maxFetchDurationTimeout); 11170 responseReader.releaseLock(); 11171 body.cancel().then(null, () => {}); 11172 } 11173} 11174function streamHandler(response) { 11175 let clonedResponseForResolving; 11176 try { 11177 clonedResponseForResolving = response.clone(); 11178 } catch { 11179 return; 11180 } 11181 resolveResponse(clonedResponseForResolving, () => { 11182 triggerHandlers$1("fetch-body-resolved", { 11183 endTimestamp: timestampInSeconds() * 1e3, 11184 response 11185 }); 11186 }); 11187} 11188function hasProp(obj, prop) { 11189 return isObjectLike(obj) && !!obj[prop]; 11190} 11191function getUrlFromResource(resource) { 11192 if (typeof resource === "string") return resource; 11193 if (!resource) return ""; 11194 if (hasProp(resource, "url")) return resource.url; 11195 if (resource.toString) return resource.toString(); 11196 return ""; 11197} 11198function parseFetchArgs(fetchArgs) { 11199 if (fetchArgs.length === 0) return { 11200 method: "GET", 11201 url: "" 11202 }; 11203 if (fetchArgs.length === 2) { 11204 const [resource, options] = fetchArgs; 11205 return { 11206 url: getUrlFromResource(resource), 11207 method: hasProp(options, "method") ? String(options.method).toUpperCase() : isRequest(resource) && hasProp(resource, "method") ? String(resource.method).toUpperCase() : "GET" 11208 }; 11209 } 11210 const arg = fetchArgs[0]; 11211 return { 11212 url: getUrlFromResource(arg), 11213 method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET" 11214 }; 11215} 11216function getHeadersFromFetchArgs(fetchArgs) { 11217 const [requestArgument, optionsArgument] = fetchArgs; 11218 try { 11219 if (typeof optionsArgument === "object" && optionsArgument !== null && "headers" in o
11219ptionsArgument && optionsArgument.headers) return new Headers(optionsArgument.headers); 11220 if (isRequest(requestArgument)) return new Headers(requestArgument.headers); 11221 } catch {} 11222} 11223function init_fetch$1() { 11224 return (init_fetch$1 = __esmMin((() => { 11225 init_currentScopes(); 11226 init_is(); 11227 init_object(); 11228 init_supports(); 11229 init_time(); 11230 init_worldwide(); 11231 init_handlers(); 11232 })))(); 11233} 11234//#endregion 11235//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/core/build/esm/utils/browser.js 11236function getLocationHref() { 11237 try { 11238 return WINDOW$6.document.location.href; 11239 } catch { 11240 return ""; 11241 } 11242} 11243function getComponentName(elem, maxTraverseHeight = 5) { 11244 if (!WINDOW$6.HTMLElement) return null; 11245 let currentElem = elem; 11246 for (let i = 0; i < maxTraverseHeight; i++) { 11247 if (!currentElem) return null; 11248 if (currentElem instanceof HTMLElement) { 11249 if (currentElem.dataset["sentryComponent"]) return currentElem.dataset["sentryComponent"]; 11250 if (currentElem.dataset["sentryElement"]) return currentElem.dataset["sentryElement"]; 11251 } 11252 currentElem = currentElem.parentNode; 11253 } 11254 return null; 11255} 11256var WINDOW$6; 11257function init_browser() { 11258 return (init_browser = __esmMin((() => { 11259 init_worldwide(); 11260 WINDOW$6 = GLOBAL_OBJ; 11261 })))(); 11262} 11263//#endregion 11264//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/feedback/build/npm/esm/index.js 11265function resolveFeedbackErrorMessage(code, messages) { 11266 return messages?.[code] ?? DEFAULT_MESSAGES[code]; 11267} 11268function createFeedbackError(code, messages) { 11269 return new Error(resolveFeedbackErrorMessage(code, messages)); 11270} 11271function isScreenshotSupported() { 11272 if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(NAVIGATOR$1.userAgent)) return false; 11273 if (/Macintosh/i.test(NAVIGATOR$1.userAgent) && NAVIGATOR$1.maxTouchPoints && NAVIGATOR$1.maxTouchPoints > 1) return false; 11274 if (!isSecureContext) return false; 11275 return true; 11276} 11277function mergeOptions(defaultOptions, optionOverrides) { 11278 return { 11279 ...defaultOptions, 11280 ...optionOverrides, 11281 tags: { 11282 ...defaultOptions.tags, 11283 ...optionOverrides.tags 11284 }, 11285 onFormOpen: () => { 11286 optionOverrides.onFormOpen?.(); 11287 defaultOptions.onFormOpen?.(); 11288 }, 11289 onFormClose: () => { 11290 optionOverrides.onFormClose?.(); 11291 defaultOptions.onFormClose?.(); 11292 }, 11293 onSubmitSuccess: (data, eventId) => { 11294 optionOverrides.onSubmitSuccess?.(data, eventId); 11295 defaultOptions.onSubmitSuccess?.(data, eventId); 11296 }, 11297 onSubmitError: (error) => { 11298 optionOverrides.onSubmitError?.(error); 11299 defaultOptions.onSubmitError?.(error); 11300 }, 11301 onFormSubmitted: () => { 11302 optionOverrides.onFormSubmitted?.(); 11303 defaultOptions.onFormSubmitted?.(); 11304 }, 11305 themeDark: { 11306 ...defaultOptions.themeDark, 11307 ...optionOverrides.themeDark 11308 }, 11309 themeLight: { 11310 ...defaultOptions.themeLight, 11311 ...optionOverrides.themeLight 11312 } 11313 }; 11314} 11315function createActorStyles(styleNonce) { 11316 const style = DOCUMENT.createElement("style"); 11317 style.textContent = ` 11318.widget__actor { 11319 position: fixed; 11320 z-index: var(--z-index); 11321 margin: var(--page-margin); 11322 inset: var(--actor-inset); 11323 11324 display: flex; 11325 align-items: center; 11326 gap: 8px; 11327 padding: 16px; 11328 11329 font-family: inherit; 11330 font-size: var(--font-size); 11331 font-weight: 600; 11332 line-height: 1.14em; 11333 text-decoration: none; 11334 11335 background: var(--actor-background, var(--background)); 11336 border-radius: var(--actor-border-radius, 1.7em/50%); 11337 border: var(--actor-border, var(--border));
11338 box-shadow: var(--actor-box-shadow, var(--box-shadow)); 11339 color: var(--actor-color, var(--foreground)); 11340 fill: var(--actor-color, var(--foreground)); 11341 cursor: pointer; 11342 opacity: 1; 11343 transition: transform 0.2s ease-in-out; 11344 transform: translate(0, 0) scale(1); 11345} 11346.widget__actor[aria-hidden="true"] { 11347 opacity: 0; 11348 pointer-events: none; 11349 visibility: hidden; 11350 transform: translate(0, 16px) scale(0.98); 11351} 11352 11353.widget__actor:hover { 11354 background: var(--actor-hover-background, var(--background)); 11355 filter: var(--interactive-filter); 11356} 11357 11358.widget__actor svg { 11359 width: 1.14em; 11360 height: 1.14em; 11361} 11362 11363@media (max-width: 600px) { 11364 .widget__actor span { 11365 display: none; 11366 } 11367} 11368`; 11369 if (styleNonce) style.setAttribute("nonce", styleNonce); 11370 return style; 11371} 11372function setAttributesNS(el, attributes) { 11373 Object.entries(attributes).forEach(([key, val]) => { 11374 el.setAttributeNS(null, key, val); 11375 }); 11376 return el; 11377} 11378function FeedbackIcon() { 11379 const createElementNS = (tagName) => WINDOW$5.document.createElementNS(XMLNS$2, tagName); 11380 const svg = setAttributesNS(createElementNS("svg"), { 11381 width: `${SIZE}`, 11382 height: `${SIZE}`, 11383 viewBox: `0 0 ${SIZE} ${SIZE}`, 11384 fill: "var(--actor-color, var(--foreground))" 11385 }); 11386 const g = setAttributesNS(createElementNS("g"), { clipPath: "url(#clip0_57_80)" }); 11387 const path = setAttributesNS(createElementNS("path"), { 11388 ["fill-rule"]: "evenodd", 11389 ["clip-rule"]: "evenodd", 11390 d: "M15.6622 15H12.3997C12.2129 14.9959 12.031 14.9396 11.8747 14.8375L8.04965 12.2H7.49956V19.1C7.4875 19.3348 7.3888 19.5568 7.22256 19.723C7.05632 19.8892 6.83435 19.9879 6.59956 20H2.04956C1.80193 19.9968 1.56535 19.8969 1.39023 19.7218C1.21511 19.5467 1.1153 19.3101 1.11206 19.0625V12.2H0.949652C0.824431 12.2017 0.700142 12.1783 0.584123 12.1311C0.468104 12.084 0.362708 12.014 0.274155 11.9255C0.185602 11.8369 0.115689 11.7315 0.0685419 11.6155C0.0213952 11.4995 -0.00202913 11.3752 -0.00034808 11.25V3.75C-0.00900498 3.62067 0.0092504 3.49095 0.0532651 3.36904C0.0972798 3.24712 0.166097 3.13566 0.255372 3.04168C0.344646 2.94771 0.452437 2.87327 0.571937 2.82307C0.691437 2.77286 0.82005 2.74798 0.949652 2.75H8.04965L11.8747 0.1625C12.031 0.0603649 12.2129 0.00407221 12.3997 0H15.6622C15.9098 0.00323746 16.1464 0.103049 16.3215 0.278167C16.4966 0.453286 16.5964 0.689866 16.5997 0.9375V3.25269C17.3969 3.42959 18.1345 3.83026 18.7211 4.41679C19.5322 5.22788 19.9878 6.32796 19.9878 7.47502C19.9878 8.62209 19.5322 9.72217 18.7211 10.5333C18.1345 11.1198 17.3969 11.5205 16.5997 11.6974V14.0125C16.6047 14.1393 16.5842 14.2659 16.5395 14.3847C16.4948 14.5035 16.4268 14.6121 16.3394 14.7042C16.252 14.7962 16.147 14.8698 16.0307 14.9206C15.9144 14.9714 15.7891 14.9984 15.6622 15ZM1.89695 10.325H1.88715V4.625H8.33715C8.52423 4.62301 8.70666 4.56654 8.86215 4.4625L12.6872 1.875H14.7247V13.125H12.6872L8.86215 10.4875C8.70666 10.3835 8.52423 10.327 8.33715 10.325H2.20217C2.15205 10.3167 2.10102 10.3125 2.04956 10.3125C1.9981 10.3125 1.94708 10.3167 1.89695 10.325ZM2.98706 12.2V18.1625H5.66206V12.2H2.98706ZM16.5997 9.93612V5.01393C16.6536 5.02355 16.7072 5.03495 16.7605 5.04814C17.1202 5.13709 17.4556 5.30487 17.7425 5.53934C18.0293 5.77381 18.2605 6.06912 18.4192 6.40389C18.578 6.73866 18.6603 7.10452 18.6603 7.47502C18.6603 7.84552 18.578 8.21139 18.4192 8.54616C18.2605 8.88093 18.0293 9.17624 17.7425 9.41071C17.4556 9.64518 17.1202 9.81296 16.7605 9.90191C16.7072 9.91509 16.6536 9.9265 16.5997 9.93612Z" 11391 }); 11392 svg.appendChild(g).appendChild(path); 11393 const speakerDefs = createElementNS("defs"); 11394 const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), { id: "clip0_57_80" }); 11395 const speakerRect = setAttributesNS(createElementNS("rect"), { 11396 width: `${SIZE}`, 11397 height: `${SIZE}`, 11398 fill: "white" 11399 }); 11400 speakerClipPathDef.appendChild(speakerRect); 11401 speakerDefs.appendChild(speakerClipPathDef); 11402 svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect); 11403 return svg; 11404} 11405function Actor({ triggerLabel, triggerAriaLabel, shadow, styleNonce }) { 11406 const el = DOCUMENT.createElement("button"); 11407 el.type = "button"; 11408 el.className = "widget__actor"; 11409 el.ariaHidden = "false"; 11410 el.ariaLabel = triggerAriaLabel || triggerLabel || TRIGGER_LABEL; 11411 el.appendChild(FeedbackIcon()); 11412 if (triggerLabel) { 11413 const label = DOCUMENT.createElement("span"); 11414 label.appendChild(DOCUMENT.createTextNode(triggerLabel)); 11415 el.appendChild(label); 11416 } 11417 const style = createActorStyles(styleNonce); 11418 return { 11419 el, 11420 appendToDom() { 11421 shadow.appendChild(style); 11422 shadow.appendChild(el); 11423 }, 11424 removeFromDom() { 11425 el.remove(); 11426 style.remove(); 11427 }, 11428 show() { 11429 el.ariaHidden = "false"; 11430 }, 11431 hide() { 11432 el.ariaHidden = "true"; 11433 } 11434 }; 11435} 11436function getThemedCssVariables(theme) { 11437 return ` 11438 --foreground: ${theme.foreground}; 11439 --background: ${theme.background}; 11440 --accent-foreground: ${theme.accentForeground};
11441 --accent-background: ${theme.accentBackground}; 11442 --success-color: ${theme.successColor}; 11443 --error-color: ${theme.errorColor}; 11444 --border: ${theme.border}; 11445 --box-shadow: ${theme.boxShadow}; 11446 --outline: ${theme.outline}; 11447 --interactive-filter: ${theme.interactiveFilter}; 11448 `; 11449} 11450function createMainStyles({ colorScheme, themeDark, themeLight, styleNonce }) { 11451 const style = DOCUMENT.createElement("style"); 11452 style.textContent = ` 11453:host { 11454 --font-family: system-ui, 'Helvetica Neue', Arial, sans-serif; 11455 --font-size: 14px; 11456 --z-index: 100000; 11457 11458 --page-margin: 16px; 11459 --inset: auto 0 0 auto; 11460 --actor-inset: var(--inset); 11461 11462 font-family: var(--font-family); 11463 font-size: var(--font-size); 11464 11465 ${colorScheme !== "system" ? `color-scheme: only ${colorScheme};` : ""} 11466 11467 ${getThemedCssVariables(colorScheme === "dark" ? { 11468 ...DEFAULT_DARK, 11469 ...themeDark 11470 } : { 11471 ...DEFAULT_LIGHT, 11472 ...themeLight 11473 })} 11474} 11475 11476${colorScheme === "system" ? ` 11477@media (prefers-color-scheme: dark) { 11478 :host { 11479 color-scheme: only dark; 11480 11481 ${getThemedCssVariables({ 11482 ...DEFAULT_DARK, 11483 ...themeDark 11484 })} 11485 } 11486}` : ""} 11487`; 11488 if (styleNonce) style.setAttribute("nonce", styleNonce); 11489 return style; 11490} 11491function getFeedback() { 11492 return getClient()?.getIntegrationByName("Feedback"); 11493} 11494function v$1(n, l) { 11495 for (var u in l) n[u] = l[u]; 11496 return n; 11497} 11498function p$1(n) { 11499 var l = n.parentNode; 11500 l && l.removeChild(n); 11501} 11502function y$1(l, u, t) { 11503 var i, o, r, f = {}; 11504 for (r in u) "key" == r ? i = u[r] : "ref" == r ? o = u[r] : f[r] = u[r]; 11505 if (arguments.length > 2 && (f.children = arguments.length > 3 ? n$2.call(arguments, 2) : t), "function" == typeof l && null != l.defaultProps) for (r in l.defaultProps) void 0 === f[r] && (f[r] = l.defaultProps[r]); 11506 return d$1(l, f, i, o, null); 11507} 11508function d$1(n, t, i, o, r) { 11509 var f = { 11510 type: n, 11511 props: t, 11512 key: i, 11513 ref: o, 11514 __k: null, 11515 __: null, 11516 __b: 0, 11517 __e: null, 11518 __d: void 0, 11519 __c: null, 11520 constructor: void 0, 11521 __v: null == r ? ++u$1 : r, 11522 __i: -1, 11523 __u: 0 11524 }; 11525 return null == r && null != l$1.vnode && l$1.vnode(f), f; 11526} 11527function g$1(n) { 11528 return n.children; 11529} 11530function b$1(n, l) { 11531 this.props = n, this.context = l; 11532} 11533function m$1(n, l) { 11534 if (null == l) return n.__ ? m$1(n.__, n.__i + 1) : null; 11535 for (var u; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) return u.__e; 11536 return "function" == typeof n.type ? m$1(n) : null; 11537} 11538function w$1(n, u, t) { 11539 var i, o = n.__v, r = o.__e, f = n.__P; 11540 if (f) return (i = v$1({}, o)).__v = o.__v + 1, l$1.vnode && l$1.vnode(i), M(f, i, o, n.__n, void 0 !== f.ownerSVGElement, 32 & o.__u ? [r] : null, u, null == r ? m$1(o) : r, !!(32 & o.__u), t), i.__.__k[i.__i] = i, i.__d = void 0, i.__e != r && k$1(i), i; 11541} 11542function k$1(n) { 11543 var l, u; 11544 if (null != (n = n.__) && null != n.__c) { 11545 for (n.__e = n.__c.base = null, l = 0; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) { 11546 n.__e = n.__c.base = u.__e; 11547 break; 11548 } 11549 return k$1(n); 11550 } 11551} 11552function x$1(n) { 11553 (!n.__d && (n.__d = true) && i$1$1.push(n) && !C$1.__r++ || o$1 !== l$1.debounceRendering) && ((o$1 = l$1.debounceRendering) || r$1)(C$1); 11554} 11555function C$1() { 11556 var n, u, t, o = [], r = []; 11557 for (i$1$1.sort(f$1); n = i$1$1.shift();) n.__d && (t = i$1$1.length, u = w$1(n, o, r) || u, 0 === t || i$1$1.length > t ? (j$1(o, u, r), r.length = o.length = 0, u = void 0, i$1$1.sort(f$1)) : u && l$1.__c && l$1.__c(u, s$1)); 11558 u && j$1(o, u, r), C$1.__r = 0; 11559} 11560function P$1(n, l, u, t, i, o, r, f, e, a, h) { 11561 var v, p, y, d, _, g = t && t.__k || s$1, b = l.length; 11562 for (u.__d = e, S(u, l, g), e = u.__d, v = 0; v < b; v++) null != (y = u.__k[v]) && "boolean" != typeof y && "function" != typeof y && (p = -1 === y.__i ? c$1 : g[y.__i] || c$1, y.__i = v, M(n, y, p, i, o, r, f, e, a, h), d = y.__e, y.ref && p.ref != y.ref && (p.ref && N(p.ref, null, y), h.push(y.ref, y.__c || d, y)), null == _ && null != d && (_ = d), 65536 & y.__u || p.__k === y.__k ? e = $(y, e, n) : "function" == typeof y.type && void 0 !== y.__d ? e = y.__d : d && (e = d.nextSibling), y.__d = void 0, y.__u &= -196609); 11563 u.__d = e, u.__e = _; 11564} 11565function S(n, l, u) { 11566 var t, i, o, r, f, e = l.length, c = u.length, s = c, a = 0; 11567 for (n.__k = [], t = 0; t < e; t++) null != (i = n.__k[t] = null == (i = l[t]) || "boolean" == typeof i || "function" == typeof i ? null : "string" == typeof i || "number" == typeof i || "bigint" == typeof i || i.constructor == String ? d$1(null, i, null, null, i) : h$1(i) ? d$1(g$1, { children: i }, null, null, null) : void 0 === i.constructor && i.__b > 0 ? d$1(i.type, i.props, i.key, i.ref ? i.ref : null, i.__v) : i) ? (i.__ = n, i.__b = n.__b + 1, f = I(i, u, r = t + a, s), i.__i = f, o = null, -1 !== f && (s--, (o = u[f]) && (o.__u |= 131072)), null == o || null === o.__v ? (-1 == f && a--, "function" != typeof i.type && (i.__u |= 65536)) : f !== r && (f === r + 1 ? a++ : f > r ? s > e - r ? a += f - r : a-- : a = f < r && f == r - 1 ? f - r : 0, f !== t + a && (i.__u |= 65536))) : (o = u[t]) && null == o.key && o.__e && (o.__e == n.__d && (n.__d = m$1(o)), O(o, o, false), u[t] = null, s--); 11568 if (s) for (t = 0; t < c; t++) null != (o = u[t]) && 0 == (131072 & o.__u) && (o.__e == n.__d && (n.__d = m$1(o)), O(o, o)); 11569} 11570function $(n, l, u) { 11571 var t, i; 11572 if ("function" == typeof n.type) { 11573 for (t = n.__k, i = 0; t && i < t.length; i++) t[i] && (t[i].__ = n, l = $(t[i], l, u)); 11574 return l; 11575 } 11576 n.__e != l && (u.insertBefore(n.__e, l || null), l = n.__e); 11577 do 11578 l = l && l.nextSibling; 11579 while (null != l && 8 === l.nodeType); 11580 return l; 11581} 11582function I(n, l, u, t) { 11583 var i = n.key, o = n.type, r = u - 1, f = u + 1, e = l[u]; 11584 if (null === e || e && i == e.key && o === e.type) return u; 11585 if (t > (null != e && 0 == (131072 & e.__u) ? 1 : 0)) for (; r >= 0 || f < l.length;) { 11586 if (r >= 0) { 11587 if ((e = l[r]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return r; 11588 r--; 11589 } 11590 if (f < l.length) { 11591 if ((e = l[f]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return f; 11592 f++; 11593 } 11594 } 11595 return -1; 11596} 11597function T$1(n, l, u) { 11598 "-" === l[0] ? n.setProperty(l, null == u ? "" : u) : n[l] = null == u ? "" : "number" != typeof u || a$1.test(l) ? u : u + "px"; 11599} 11600function A$1(n, l, u, t, i) { 11601 var o; 11602 n: if ("style" === l) if ("string" == typeof u) n.style.cssText = u; 11603 else { 11604 if ("string" == typeof t && (n.style.cssText = t = ""), t) for (l in t) u && l in u || T$1(n.style, l, ""); 11605 if (u) for (l in u) t && u[l] === t[l] || T$1(n.style, l, u[l]); 11606 } 11607 else if ("o" === l[0] && "n" === l[1]) o = l !== (l = l.replace(/(PointerCapture)$|Capture$/i, "$1")), l = l.toLowerCase() in n ? l.toLowerCase().slice(2) : l.slice(2), n.l || (n.l = {}), n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = Date.now(), n.addEventListener(l, o ? L : D$1, o)) : n.removeEventListener(l, o ? L : D$1, o); 11608 else { 11609 if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); 11610 else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && "role" !== l && l in n) try { 11611 n[l] = null == u ? "" : u; 11612 break n; 11613 } catch (n) {} 11614 "function" == typeof u || (null == u || false === u && "-" !== l[4] ? n.removeAttribute(l) : n.setAttribute(l, u)); 11615 } 11616} 11617function D$1(n) { 11618 if (this.l) { 11619 var u = this.l[n.type + false]; 11620 if (n.t) { 11621 if (n.t <= u.u) return; 11622 } else n.t = Date.now();
vendor: 6,116 bytes, lines 11623-11734
11623 return u(l$1.event ? l$1.event(n) : n); 11624 } 11625} 11626function L(n) { 11627 if (this.l) return this.l[n.type + true](l$1.event ? l$1.event(n) : n); 11628} 11629function M(n, u, t, i, o, r, f, e, c, s) { 11630 var a, p, y, d, _, m, w, k, x, C, S, $, H, I, T, A = u.type; 11631 if (void 0 !== u.constructor) return null; 11632 128 & t.__u && (c = !!(32 & t.__u), r = [e = u.__e = t.__e]), (a = l$1.__b) && a(u); 11633 n: if ("function" == typeof A) try { 11634 if (k = u.props, x = (a = A.contextType) && i[a.__c], C = a ? x ? x.props.value : a.__ : i, t.__c ? w = (p = u.__c = t.__c).__ = p.__E : ("prototype" in A && A.prototype.render ? u.__c = p = new A(k, C) : (u.__c = p = new b$1(k, C), p.constructor = A, p.render = q$1), x && x.sub(p), p.props = k, p.state || (p.state = {}), p.context = C, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), p.__s ?? (p.__s = p.state), null != A.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v$1({}, p.__s)), v$1(p.__s, A.getDerivedStateFromProps(k, p.__s))), d = p.props, _ = p.state, p.__v = u, y) null == A.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), null != p.componentDidMount && p.__h.push(p.componentDidMount); 11635 else { 11636 if (null == A.getDerivedStateFromProps && k !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(k, C), !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(k, p.__s, C) || u.__v === t.__v)) { 11637 for (u.__v !== t.__v && (p.props = k, p.state = p.__s, p.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.forEach(function(n) { 11638 n && (n.__ = u); 11639 }), S = 0; S < p._sb.length; S++) p.__h.push(p._sb[S]); 11640 p._sb = [], p.__h.length && f.push(p); 11641 break n; 11642 } 11643 null != p.componentWillUpdate && p.componentWillUpdate(k, p.__s, C), null != p.componentDidUpdate && p.__h.push(function() { 11644 p.componentDidUpdate(d, _, m); 11645 }); 11646 } 11647 if (p.context = C, p.props = k, p.__P = n, p.__e = !1, $ = l$1.__r, H = 0, "prototype" in A && A.prototype.render) { 11648 for (p.state = p.__s, p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), I = 0; I < p._sb.length; I++) p.__h.push(p._sb[I]); 11649 p._sb = []; 11650 } else do 11651 p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; 11652 while (p.__d && ++H < 25); 11653 p.state = p.__s, null != p.getChildContext && (i = v$1(v$1({}, i), p.getChildContext())), y || null == p.getSnapshotBeforeUpdate || (m = p.getSnapshotBeforeUpdate(d, _)), P$1(n, h$1(T = null != a && a.type === g$1 && null == a.key ? a.props.children : a) ? T : [T], u, t, i, o, r, f, e, c, s), p.base = u.__e, u.__u &= -161, p.__h.length && f.push(p), w && (p.__E = p.__ = null); 11654 } catch (n) { 11655 u.__v = null, c || null != r ? (u.__e = e, u.__u |= c ? 160 : 32, r[r.indexOf(e)] = null) : (u.__e = t.__e, u.__k = t.__k), l$1.__e(n, u, t); 11656 } 11657 else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = z$1(t.__e, u, t, i, o, r, f, c, s); 11658 (a = l$1.diffed) && a(u); 11659} 11660function j$1(n, u, t) { 11661 for (var i = 0; i < t.length; i++) N(t[i], t[++i], t[++i]); 11662 l$1.__c && l$1.__c(u, n), n.some(function(u) { 11663 try { 11664 n = u.__h, u.__h = [], n.some(function(n) { 11665 n.call(u); 11666 }); 11667 } catch (n) { 11668 l$1.__e(n, u.__v); 11669 } 11670 }); 11671} 11672function z$1(l, u, t, i, o, r, f, e, s) { 11673 var a, v, y, d, _, g, b, w = t.props, k = u.props, x = u.type; 11674 if ("svg" === x && (o = true), null != r) { 11675 for (a = 0; a < r.length; a++) if ((_ = r[a]) && "setAttribute" in _ == !!x && (x ? _.localName === x : 3 === _.nodeType)) { 11676 l = _, r[a] = null; 11677 break; 11678 } 11679 } 11680 if (null == l) { 11681 if (null === x) return document.createTextNode(k); 11682 l = o ? document.createElementNS("http://www.w3.org/2000/svg", x) : document.createElement(x, k.is && k), r = null, e = false; 11683 } 11684 if (null === x) w === k || e && l.data === k || (l.data = k); 11685 else { 11686 if (r = r && n$2.call(l.childNodes), w = t.props || c$1, !e && null != r) for (w = {}, a = 0; a < l.attributes.length; a++) w[(_ = l.attributes[a]).name] = _.value; 11687 for (a in w) _ = w[a], "children" == a || ("dangerouslySetInnerHTML" == a ? y = _ : "key" === a || a in k || A$1(l, a, null, _, o)); 11688 for (a in k) _ = k[a], "children" == a ? d = _ : "dangerouslySetInnerHTML" == a ? v = _ : "value" == a ? g = _ : "checked" == a ? b = _ : "key" === a || e && "function" != typeof _ || w[a] === _ || A$1(l, a, _, w[a], o); 11689 if (v) e || y && (v.__html === y.__html || v.__html === l.innerHTML) || (l.innerHTML = v.__html), u.__k = []; 11690 else if (y && (l.innerHTML = ""), P$1(l, h$1(d) ? d : [d], u, t, i, o && "foreignObject" !== x, r, f, r ? r[0] : t.__k && m$1(t, 0), e, s), null != r) for (a = r.length; a--;) null != r[a] && p$1(r[a]); 11691 e || (a = "value", void 0 !== g && (g !== l[a] || "progress" === x && !g || "option" === x && g !== w[a]) && A$1(l, a, g, w[a], false), a = "checked", void 0 !== b && b !== l[a] && A$1(l, a, b, w[a], false)); 11692 } 11693 return l; 11694} 11695function N(n, u, t) { 11696 try { 11697 "function" == typeof n ? n(u) : n.current = u; 11698 } catch (n) { 11699 l$1.__e(n, t); 11700 } 11701} 11702function O(n, u, t) { 11703 var i, o; 11704 if (l$1.unmount && l$1.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || N(i, null, u)), null != (i = n.__c)) { 11705 if (i.componentWillUnmount) try { 11706 i.componentWillUnmount(); 11707 } catch (n) { 11708 l$1.__e(n, u); 11709 } 11710 i.base = i.__P = null, n.__c = void 0; 11711 } 11712 if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && O(i[o], u, t || "function" != typeof n.type); 11713 t || null == n.__e || p$1(n.__e), n.__ = n.__e = n.__d = void 0; 11714} 11715function q$1(n, l, u) { 11716 return this.constructor(n, u); 11717} 11718function B$1(u, t, i) { 11719 var o, r, f, e; 11720 l$1.__ && l$1.__(u, t), r = (o = false) ? null : t.__k, f = [], e = [], M(t, u = t.__k = y$1(g$1, null, [u]), r || c$1, c$1, void 0 !== t.ownerSVGElement, r ? null : t.firstChild ? n$2.call(t.childNodes) : null, f, r ? r.__e : t.firstChild, o, e), u.__d = void 0, j$1(f, u, e); 11721} 11722function h(n, t) { 11723 e$1.__h && e$1.__h(r$2, n, o || t), o = 0; 11724 var u = r$2.__H || (r$2.__H = { 11725 __: [], 11726 __h: [] 11727 }); 11728 return n >= u.__.length && u.__.push({ __V: c }), u.__[n]; 11729} 11730function p(n) { 11731 return o = 1, y(D, n); 11732} 11733function y(n, u, i) { 11734 var o = h(t$2++, 2);
11735 if (o.t = n, !o.__c && (o.__ = [i ? i(u) : D(void 0, u), function(n) { 11736 var t = o.__N ? o.__N[0] : o.__[0], r = o.t(t, n); 11737 t !== r && (o.__N = [r, o.__[1]], o.__c.setState({})); 11738 }], o.__c = r$2, !r$2.u)) { 11739 var f = function(n, t, r) { 11740 if (!o.__c.__H) return true; 11741 var u = o.__c.__H.__.filter(function(n) { 11742 return !!n.__c; 11743 }); 11744 if (u.every(function(n) { 11745 return !n.__N; 11746 })) return !c || c.call(this, n, t, r); 11747 var i = false; 11748 return u.forEach(function(n) { 11749 if (n.__N) { 11750 var t = n.__[0]; 11751 n.__ = n.__N, n.__N = void 0, t !== n.__[0] && (i = true); 11752 } 11753 }), !(!i && o.__c.props === n) && (!c || c.call(this, n, t, r)); 11754 }; 11755 r$2.u = true; 11756 var c = r$2.shouldComponentUpdate, e = r$2.componentWillUpdate; 11757 r$2.componentWillUpdate = function(n, t, r) { 11758 if (this.__e) { 11759 var u = c; 11760 c = void 0, f(n, t, r), c = u; 11761 } 11762 e && e.call(this, n, t, r); 11763 }, r$2.shouldComponentUpdate = f; 11764 } 11765 return o.__N || o.__; 11766} 11767function _(n, u) { 11768 var i = h(t$2++, 3); 11769 !e$1.__s && C(i.__H, u) && (i.__ = n, i.i = u, r$2.__H.__h.push(i)); 11770} 11771function A(n, u) { 11772 var i = h(t$2++, 4); 11773 !e$1.__s && C(i.__H, u) && (i.__ = n, i.i = u, r$2.__h.push(i)); 11774} 11775function F(n) { 11776 return o = 5, q(function() { 11777 return { current: n }; 11778 }, []); 11779} 11780function T(n, t, r) { 11781 o = 6, A(function() { 11782 return "function" == typeof n ? (n(t()), function() { 11783 return n(null); 11784 }) : n ? (n.current = t(), function() { 11785 return n.current = null; 11786 }) : void 0; 11787 }, null == r ? r : r.concat(n)); 11788} 11789function q(n, r) { 11790 var u = h(t$2++, 7); 11791 return C(u.__H, r) ? (u.__V = n(), u.i = r, u.__h = n, u.__V) : u.__; 11792} 11793function x(n, t) { 11794 return o = 8, q(function() { 11795 return n; 11796 }, t); 11797} 11798function P(n) { 11799 var u = r$2.context[n.__c], i = h(t$2++, 9); 11800 return i.c = n, u ? (i.__ ?? (i.__ = true, u.sub(r$2)), u.props.value) : n.__; 11801} 11802function V(n, t) { 11803 e$1.useDebugValue && e$1.useDebugValue(t ? t(n) : n); 11804} 11805function b(n) { 11806 var u = h(t$2++, 10), i = p(); 11807 return u.__ = n, r$2.componentDidCatch || (r$2.componentDidCatch = function(n, t) { 11808 u.__ && u.__(n, t), i[1](n); 11809 }), [i[0], function() { 11810 i[1](void 0); 11811 }]; 11812} 11813function g() { 11814 var n = h(t$2++, 11); 11815 if (!n.__) { 11816 for (var u = r$2.__v; null !== u && !u.__m && null !== u.__;) u = u.__; 11817 var i = u.__m || (u.__m = [0, 0]); 11818 n.__ = "P" + i[0] + "-" + i[1]++; 11819 } 11820 return n.__; 11821} 11822function j() { 11823 for (var n; n = f.shift();) if (n.__P && n.__H) try { 11824 n.__H.__h.forEach(z), n.__H.__h.forEach(B), n.__H.__h = []; 11825 } catch (t) { 11826 n.__H.__h = [], e$1.__e(t, n.__v); 11827 } 11828} 11829function w(n) { 11830 var t, r = function() { 11831 clearTimeout(u), k && cancelAnimationFrame(t), setTimeout(n); 11832 }, u = setTimeout(r, 100); 11833 k && (t = requestAnimationFrame(r)); 11834} 11835function z(n) { 11836 var t = r$2, u = n.__c; 11837 "function" == typeof u && (n.__c = void 0, u()), r$2 = t; 11838} 11839function B(n) { 11840 var t = r$2; 11841 n.__c = n.__(), r$2 = t; 11842} 11843function C(n, t) { 11844 return !n || n.length !== t.length || t.some(function(t, r) { 11845 return t !== n[r]; 11846 }); 11847} 11848function D(n, t) { 11849 return "function" == typeof t ? t(n) : t; 11850} 11851function SentryLogo() { 11852 const createElementNS = (tagName) => DOCUMENT.createElementNS(XMLNS$1, tagName); 11853 const svg = setAttributesNS(createElementNS("svg"), { 11854 width: "32", 11855 height: "30", 11856 viewBox: "0 0 72 66", 11857 fill: "inherit" 11858 }); 11859 const path = setAttributesNS(createElementNS("path"), { 11860 transform: "translate(11, 11)", 11861 d: "M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z" 11862 }); 11863 svg.appendChild(path); 11864 return svg; 11865} 11866function DialogHeader({ options }) { 11867 const logoHtml = q(() => ({ __html: SentryLogo().outerHTML }), []); 11868 return /* @__PURE__ */ y$1("h2", { class: "dialog__header" }
11868, /* @__PURE__ */ y$1("span", { class: "dialog__title" }, options.formTitle), options.showBranding ? /* @__PURE__ */ y$1("a", { 11869 class: "brand-link", 11870 target: "_blank", 11871 href: "https://sentry.io/welcome/", 11872 title: "Powered by Sentry", 11873 rel: "noopener noreferrer", 11874 dangerouslySetInnerHTML: logoHtml 11875 }) : null); 11876} 11877function getMissingFields(feedback, props) { 11878 const emptyFields = []; 11879 if (props.isNameRequired && !feedback.name) emptyFields.push(props.nameLabel); 11880 if (props.isEmailRequired && !feedback.email) emptyFields.push(props.emailLabel); 11881 if (!feedback.message) emptyFields.push(props.messageLabel); 11882 return emptyFields; 11883} 11884function retrieveStringValue(formData, key) { 11885 const value = formData.get(key); 11886 if (typeof value === "string") return value.trim(); 11887 return ""; 11888} 11889function Form({ options, defaultEmail, defaultName, onFormClose, onSubmit, onSubmitSuccess, onSubmitError, showEmail, showName, screenshotInput }) { 11890 const { tags, addScreenshotButtonLabel, removeScreenshotButtonLabel, cancelButtonLabel, emailLabel, emailPlaceholder, isEmailRequired, isNameRequired, messageLabel, messagePlaceholder, nameLabel, namePlaceholder, submitButtonLabel, isRequiredLabel } = options; 11891 const [isSubmitting, setIsSubmitting] = p(false); 11892 const [error, setError] = p(null); 11893 const [showScreenshotInput, setShowScreenshotInput] = p(false); 11894 const ScreenshotInputComponent = screenshotInput?.input; 11895 const [screenshotError, setScreenshotError] = p(null); 11896 const onScreenshotError = x((error2) => { 11897 setScreenshotError(error2); 11898 setShowScreenshotInput(false); 11899 }, []); 11900 const hasAllRequiredFields = x((data) => { 11901 const missingFields = getMissingFields(data, { 11902 emailLabel, 11903 isEmailRequired, 11904 isNameRequired, 11905 messageLabel, 11906 nameLabel 11907 }); 11908 if (missingFields.length > 0) setError(`Please enter in the following required fields: ${missingFields.join(", ")}`); 11909 else setError(null); 11910 return missingFields.length === 0; 11911 }, [ 11912 emailLabel, 11913 isEmailRequired, 11914 isNameRequired, 11915 messageLabel, 11916 nameLabel 11917 ]); 11918 return /* @__PURE__ */ y$1("form", { 11919 class: "form", 11920 onSubmit: x(async (e) => { 11921 setIsSubmitting(true); 11922 try { 11923 e.preventDefault(); 11924 if (!(e.target instanceof HTMLFormElement)) return; 11925 const formData = new FormData(e.target); 11926 const attachment = await (screenshotInput && showScreenshotInput ? screenshotInput.value() : void 0); 11927 const data = { 11928 name: retrieveStringValue(formData, "name"), 11929 email: retrieveStringValue(formData, "email"), 11930 message: retrieveStringValue(formData, "message"), 11931 attachments: attachment ? [attachment] : void 0 11932 }; 11933 if (!hasAllRequiredFields(data)) return; 11934 try { 11935 onSubmitSuccess(data, await onSubmit({ 11936 name: data.name, 11937 email: data.email, 11938 message: data.message, 11939 source: FEEDBACK_WIDGET_SOURCE, 11940 tags 11941 }, { attachments: data.attachments })); 11942 } catch (error2) { 11943 DEBUG_BUILD$4 && debug$2.error(error2); 11944 const err = error2 instanceof Error ? error2 : new Error(String(error2)); 11945 setError(err.message); 11946 onSubmitError(err); 11947 } 11948 } finally { 11949 setIsSubmitting(false); 11950 } 11951 }, [ 11952 screenshotInput && showScreenshotInput, 11953 onSubmitSuccess, 11954 onSubmitError 11955 ]) 11956 }, ScreenshotInputComponent && showScreenshotInput ? /* @__PURE__ */ y$1(ScreenshotInputComponent, { onError: onScreenshotError }) : null, /* @__PURE__ */ y$1("fieldset", { 11957 class: "form__right", 11958 "data-sentry-feedback": true, 11959 disabled: isSubmitting 11960 }, /* @__PURE__ */ y$1("div", { class: "form__top" }, error ? /* @__PURE__ */ y$1("div", { class: "form__error-container" }, error) : null, showName ? /* @__PURE__ */ y$1("label", { 11961 for: "name", 11962 class: "form__label" 11963 }, /* @__PURE__ */ y$1(LabelText, { 11964 label: nameLabel, 11965 isRequiredLabel, 11966 isRequired: isNameRequired 11967 }
vendor: 6,254 bytes, lines 11967-12102
11967), /* @__PURE__ */ y$1("input", { 11968 class: "form__input", 11969 defaultValue: defaultName, 11970 id: "name", 11971 name: "name", 11972 placeholder: namePlaceholder, 11973 required: isNameRequired, 11974 type: "text" 11975 })) : /* @__PURE__ */ y$1("input", { 11976 "aria-hidden": true, 11977 value: defaultName, 11978 name: "name", 11979 type: "hidden" 11980 }), showEmail ? /* @__PURE__ */ y$1("label", { 11981 for: "email", 11982 class: "form__label" 11983 }, /* @__PURE__ */ y$1(LabelText, { 11984 label: emailLabel, 11985 isRequiredLabel, 11986 isRequired: isEmailRequired 11987 }), /* @__PURE__ */ y$1("input", { 11988 class: "form__input", 11989 defaultValue: defaultEmail, 11990 id: "email", 11991 name: "email", 11992 placeholder: emailPlaceholder, 11993 required: isEmailRequired, 11994 type: "email" 11995 })) : /* @__PURE__ */ y$1("input", { 11996 "aria-hidden": true, 11997 value: defaultEmail, 11998 name: "email", 11999 type: "hidden" 12000 }), /* @__PURE__ */ y$1("label", { 12001 for: "message", 12002 class: "form__label" 12003 }, /* @__PURE__ */ y$1(LabelText, { 12004 label: messageLabel, 12005 isRequiredLabel, 12006 isRequired: true 12007 }), /* @__PURE__ */ y$1("textarea", { 12008 autoFocus: true, 12009 class: "form__input form__input--textarea", 12010 id: "message", 12011 name: "message", 12012 placeholder: messagePlaceholder, 12013 required: true, 12014 rows: 5 12015 })), ScreenshotInputComponent ? /* @__PURE__ */ y$1("label", { 12016 for: "screenshot", 12017 class: "form__label" 12018 }, /* @__PURE__ */ y$1("button", { 12019 class: "btn btn--default", 12020 disabled: isSubmitting, 12021 type: "button", 12022 onClick: () => { 12023 setScreenshotError(null); 12024 setShowScreenshotInput((prev) => !prev); 12025 } 12026 }, showScreenshotInput ? removeScreenshotButtonLabel : addScreenshotButtonLabel), screenshotError ? /* @__PURE__ */ y$1("div", { class: "form__error-container" }, screenshotError.message) : null) : null), /* @__PURE__ */ y$1("div", { class: "btn-group" }, /* @__PURE__ */ y$1("button", { 12027 class: "btn btn--primary", 12028 disabled: isSubmitting, 12029 type: "submit" 12030 }, submitButtonLabel), /* @__PURE__ */ y$1("button", { 12031 class: "btn btn--default", 12032 disabled: isSubmitting, 12033 type: "button", 12034 onClick: onFormClose 12035 }, cancelButtonLabel)))); 12036} 12037function LabelText({ label, isRequired, isRequiredLabel }) { 12038 return /* @__PURE__ */ y$1("span", { class: "form__label__text" }, label, isRequired && /* @__PURE__ */ y$1("span", { class: "form__label__text--required" }, isRequiredLabel)); 12039} 12040function SuccessIcon() { 12041 const createElementNS = (tagName) => WINDOW$5.document.createElementNS(XMLNS, tagName); 12042 const svg = setAttributesNS(createElementNS("svg"), { 12043 width: `${WIDTH}`, 12044 height: `${HEIGHT}`, 12045 viewBox: `0 0 ${WIDTH} ${HEIGHT}`, 12046 fill: "inherit" 12047 }); 12048 const g = setAttributesNS(createElementNS("g"), { clipPath: "url(#clip0_57_156)" }); 12049 const path2 = setAttributesNS(createElementNS("path"), { 12050 ["fill-rule"]: "evenodd", 12051 ["clip-rule"]: "evenodd", 12052 d: "M3.55544 15.1518C4.87103 16.0308 6.41775 16.5 8 16.5C10.1217 16.5 12.1566 15.6571 13.6569 14.1569C15.1571 12.6566 16 10.6217 16 8.5C16 6.91775 15.5308 5.37103 14.6518 4.05544C13.7727 2.73985 12.5233 1.71447 11.0615 1.10897C9.59966 0.503466 7.99113 0.34504 6.43928 0.653721C4.88743 0.962403 3.46197 1.72433 2.34315 2.84315C1.22433 3.96197 0.462403 5.38743 0.153721 6.93928C-0.15496 8.49113 0.00346625 10.0997 0.608967 11.5615C1.21447 13.0233 2.23985 14.2727 3.55544 15.1518ZM4.40546 3.1204C5.46945 2.40946 6.72036 2.03 8 2.03C9.71595 2.03 11.3616 2.71166 12.575 3.92502C13.7883 5.13838 14.47 6.78405 14.47 8.5C14.47 9.77965 14.0905 11.0306 13.3796 12.0945C12.6687 13.1585 11.6582 13.9878 10.476 14.4775C9.29373 14.9672 7.99283 15.0953 6.73777 14.8457C5.48271 14.596 4.32987 13.9798 3.42502 13.075C2.52018 12.1701 1.90397 11.0173 1.65432 9.76224C1.40468 8.50718 1.5328 7.20628 2.0225 6.02404C2.5122 4.8418 3.34148 3.83133 4.40546 3.1204Z" 12053 }); 12054 const path = setAttributesNS(createElementNS("path"), { d: "M6.68775 12.4297C6.78586 12.4745 6.89218 12.4984 7 12.5C7.11275 12.4955 7.22315 12.4664 7.32337 12.4145C7.4236 12.3627 7.51121 12.2894 7.58 12.2L12 5.63999C12.0848 5.47724 12.1071 5.28902 12.0625 5.11098C12.0178 4.93294 11.9095 4.77744 11.7579 4.67392C11.6064 4.57041 11.4221 4.52608 11.24 4.54931C11.0579 4.57254 10.8907 4.66173 10.77 4.79999L6.88 10.57L5.13 8.56999C5.06508 8.49566 4.98613 8.43488 4.89768 8.39111C4.80922 8.34735 4.713 8.32148 4.61453 8.31498C4.51605 8.30847 4.41727 8.32147 4.32382 8.35322C4.23038 8.38497 4.14413 8.43484 4.07 8.49999C3.92511 8.63217 3.83692 8.81523 3.82387 9.01092C3.81083 9.2066 3.87393 9.39976 4 9.54999L6.43 12.24C6.50187 12.3204 6.58964 12.385 6.68775 12.4297Z" }); 12055 svg.appendChild(g).append(path, path2); 12056 const speakerDefs = createElementNS("defs"); 12057 const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), { id: "clip0_57_156" }); 12058 const speakerRect = setAttributesNS(createElementNS("rect"), { 12059 width: `${WIDTH}`, 12060 height: `${WIDTH}`, 12061 fill: "white", 12062 transform: "translate(0 0.5)" 12063 }); 12064 speakerClipPathDef.appendChild(speakerRect); 12065 speakerDefs.appendChild(speakerClipPathDef); 12066 svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect); 12067 return svg; 12068} 12069function Dialog({ open, onFormSubmitted, ...props }) { 12070 const options = props.options; 12071 const successIconHtml = q(() => ({ __html: SuccessIcon().outerHTML }), []); 12072 const [timeoutId, setTimeoutId] = p(null); 12073 const handleOnSuccessClick = x(() => { 12074 if (timeoutId) { 12075 clearTimeout(timeoutId); 12076 setTimeoutId(null); 12077 } 12078 onFormSubmitted(); 12079 }, [timeoutId]); 12080 const onSubmitSuccess = x((data, eventId) => { 12081 props.onSubmitSuccess(data, eventId); 12082 setTimeoutId(setTimeout(() => { 12083 onFormSubmitted(); 12084 setTimeoutId(null); 12085 }, SUCCESS_MESSAGE_TIMEOUT)); 12086 }, [onFormSubmitted]); 12087 return /* @__PURE__ */ y$1(g$1, null, timeoutId ? /* @__PURE__ */ y$1("div", { 12088 class: "success__position", 12089 onClick: handleOnSuccessClick 12090 }, /* @__PURE__ */ y$1("div", { class: "success__content" }, options.successMessageText, /* @__PURE__ */ y$1("span", { 12091 class: "success__icon", 12092 dangerouslySetInnerHTML: successIconHtml 12093 }))) : /* @__PURE__ */ y$1("dialog", { 12094 class: "dialog", 12095 onClick: options.onFormClose, 12096 open 12097 }, /* @__PURE__ */ y$1("div", { class: "dialog__position" }, /* @__PURE__ */ y$1("div", { 12098 class: "dialog__content", 12099 onClick: (e) => { 12100 e.stopPropagation(); 12101 } 12102 }, /* @__PURE__ */ y$1(DialogHeader, { options }
12102), /* @__PURE__ */ y$1(Form, { 12103 ...props, 12104 onSubmitSuccess 12105 }))))); 12106} 12107function createDialogStyles(styleNonce) { 12108 const style = DOCUMENT.createElement("style"); 12109 style.textContent = ` 12110:host { 12111 --dialog-inset: var(--inset); 12112} 12113 12114${DIALOG} 12115${DIALOG_HEADER} 12116${FORM} 12117${BUTTON} 12118${SUCCESS} 12119`; 12120 if (styleNonce) style.setAttribute("nonce", styleNonce); 12121 return style; 12122} 12123function getUser() { 12124 const currentUser = getCurrentScope().getUser(); 12125 const isolationUser = getIsolationScope().getUser(); 12126 const globalUser = getGlobalScope().getUser(); 12127 if (currentUser && Object.keys(currentUser).length) return currentUser; 12128 if (isolationUser && Object.keys(isolationUser).length) return isolationUser; 12129 return globalUser; 12130} 12131function IconCloseFactory({ h }) { 12132 return function IconClose() { 12133 return /* @__PURE__ */ h("svg", { 12134 "data-test-id": "icon-close", 12135 viewBox: "0 0 16 16", 12136 fill: "#2B2233", 12137 height: "25px", 12138 width: "25px" 12139 }, /* @__PURE__ */ h("circle", { 12140 r: "7", 12141 cx: "8", 12142 cy: "8", 12143 fill: "white" 12144 }), /* @__PURE__ */ h("path", { 12145 strokeWidth: "1.5", 12146 d: "M8,16a8,8,0,1,1,8-8A8,8,0,0,1,8,16ZM8,1.53A6.47,6.47,0,1,0,14.47,8,6.47,6.47,0,0,0,8,1.53Z" 12147 }), /* @__PURE__ */ h("path", { 12148 strokeWidth: "1.5", 12149 d: "M5.34,11.41a.71.71,0,0,1-.53-.22.74.74,0,0,1,0-1.06l5.32-5.32a.75.75,0,0,1,1.06,1.06L5.87,11.19A.74.74,0,0,1,5.34,11.41Z" 12150 }), /* @__PURE__ */ h("path", { 12151 strokeWidth: "1.5", 12152 d: "M10.66,11.41a.74.74,0,0,1-.53-.22L4.81,5.87A.75.75,0,0,1,5.87,4.81l5.32,5.32a.74.74,0,0,1,0,1.06A.71.71,0,0,1,10.66,11.41Z" 12153 })); 12154 }; 12155} 12156function createScreenshotInputStyles(styleNonce) { 12157 const style = DOCUMENT.createElement("style"); 12158 const surface200 = "#1A141F"; 12159 const gray100 = "#302735"; 12160 style.textContent = ` 12161.editor { 12162 display: flex; 12163 flex-grow: 1; 12164 flex-direction: column; 12165} 12166 12167.editor__image-container { 12168 justify-items: center; 12169 padding: 15px; 12170 position: relative; 12171 height: 100%; 12172 border-radius: var(--menu-border-radius, 6px); 12173 12174 background-color: ${surface200}; 12175 background-image: repeating-linear-gradient( 12176 -145deg, 12177 transparent, 12178 transparent 8px, 12179 ${surface200} 8px, 12180 ${surface200} 11px 12181 ), 12182 repeating-linear-gradient( 12183 -45deg, 12184 transparent, 12185 transparent 15px, 12186 ${gray100} 15px, 12187 ${gray100} 16px 12188 ); 12189} 12190 12191.editor__canvas-container { 12192 width: 100%; 12193 height: 100%; 12194 position: relative; 12195 display: flex; 12196 align-items: center; 12197 justify-content: center; 12198} 12199 12200.editor__canvas-container > * { 12201 object-fit: contain; 12202 position: absolute; 12203} 12204 12205.editor__tool-container { 12206 padding-top: 8px; 12207 display: flex; 12208 justify-content: center; 12209} 12210 12211.editor__tool-bar { 12212 display: flex; 12213 gap: 8px; 12214} 12215 12216.editor__tool { 12217 display: flex; 12218 padding: 8px 12px; 12219 justify-content: center; 12220 align-items: center; 12221 border: var(--button-border, var(--border)); 12222 border-radius: var(--button-border-radius, 6px); 12223 background: var(--button-background, var(--background)); 12224 color: var(--button-color, var(--foreground)); 12225} 12226 12227.editor__tool--active { 12228 background: var(--button-primary-background, var(--accent-background)); 12229 color: var(--button-primary-color, var(--accent-foreground)); 12230} 12231 12232.editor__rect { 12233 position: absolute; 12234 z-index: 2; 12235} 12236 12237.editor__rect button { 12238 opacity: 0; 12239 position: absolute; 12240 top: -12px; 12241 right: -12px; 12242 cursor: pointer; 12243 padding: 0; 12244 z-index: 3; 12245 border: none; 12246 background: none; 12247} 12248 12249.editor__rect:hover button { 12250 opacity: 1; 12251} 12252`; 12253 if (styleNonce) style.setAttribute("nonce", styleNonce); 12254 return style; 12255} 12256function ToolbarFactory({ h }) { 12257 return function Toolbar({ action, setAction, options }) { 12258 return /* @__PURE__ */ h("div", { class: "editor__tool-container" }, /* @__PURE__ */ h("div", { class: "editor__tool-bar" }, /* @__PURE__ */ h("button", { 12259 type: "button", 12260 class: `editor__tool ${action === "highlight" ? "editor__tool--active" : ""}`, 12261 onClick: () => { 12262 setAction(action === "highlight" ? "" : "highlight"); 12263 } 12264 }, options.highlightToolText), /* @__PURE__ */ h("button", { 12265 type: "button", 12266 class: `editor__tool ${action === "hide" ? "editor__tool--active" : ""}`, 12267 onClick: () => {
vendor: 7,736 bytes, lines 12268-12477
12268 setAction(action === "hide" ? "" : "hide"); 12269 } 12270 }, options.hideToolText))); 12271 }; 12272} 12273function useTakeScreenshotFactory({ hooks }) { 12274 function useDpi() { 12275 const [dpi, setDpi] = hooks.useState(WINDOW$5.devicePixelRatio ?? 1); 12276 hooks.useEffect(() => { 12277 const onChange = () => { 12278 setDpi(WINDOW$5.devicePixelRatio); 12279 }; 12280 const media = matchMedia(`(resolution: ${WINDOW$5.devicePixelRatio}dppx)`); 12281 media.addEventListener("change", onChange); 12282 return () => { 12283 media.removeEventListener("change", onChange); 12284 }; 12285 }, []); 12286 return dpi; 12287 } 12288 return function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }) { 12289 const dpi = useDpi(); 12290 hooks.useEffect(() => { 12291 const takeScreenshot = async () => { 12292 onBeforeScreenshot(); 12293 const stream = await NAVIGATOR$1.mediaDevices.getDisplayMedia({ 12294 video: { 12295 width: WINDOW$5.innerWidth * dpi, 12296 height: WINDOW$5.innerHeight * dpi 12297 }, 12298 audio: false, 12299 monitorTypeSurfaces: "exclude", 12300 preferCurrentTab: true, 12301 selfBrowserSurface: "include", 12302 surfaceSwitching: "exclude" 12303 }); 12304 const video = DOCUMENT.createElement("video"); 12305 await new Promise((resolve, reject) => { 12306 video.srcObject = stream; 12307 video.onloadedmetadata = () => { 12308 onScreenshot(video, dpi); 12309 stream.getTracks().forEach((track) => track.stop()); 12310 resolve(); 12311 }; 12312 video.play().catch(reject); 12313 }); 12314 onAfterScreenshot(); 12315 }; 12316 takeScreenshot().catch(onError); 12317 }, []); 12318 }; 12319} 12320function drawRect(command, ctx, color) { 12321 switch (command.type) { 12322 case "highlight": 12323 ctx.shadowColor = "rgba(0, 0, 0, 0.7)"; 12324 ctx.shadowBlur = 50; 12325 ctx.fillStyle = color; 12326 ctx.fillRect(command.x - 1, command.y - 1, command.w + 2, command.h + 2); 12327 ctx.clearRect(command.x, command.y, command.w, command.h); 12328 break; 12329 case "hide": 12330 ctx.fillStyle = "rgb(0, 0, 0)"; 12331 ctx.fillRect(command.x, command.y, command.w, command.h); 12332 } 12333} 12334function with2dContext(canvas, options, callback) { 12335 if (!canvas) return; 12336 const ctx = canvas.getContext("2d", options); 12337 if (!ctx) return; 12338 callback(canvas, ctx); 12339} 12340function paintImage(maybeDest, source) { 12341 with2dContext(maybeDest, { alpha: true }, (destCanvas, destCtx) => { 12342 destCtx.drawImage(source, 0, 0, source.width, source.height, 0, 0, destCanvas.width, destCanvas.height); 12343 }); 12344} 12345function paintForeground(maybeCanvas, strokeColor, drawCommands) { 12346 with2dContext(maybeCanvas, { alpha: true }, (canvas, ctx) => { 12347 if (drawCommands.length) { 12348 ctx.fillStyle = "rgba(0, 0, 0, 0.25)"; 12349 ctx.fillRect(0, 0, canvas.width, canvas.height); 12350 } 12351 drawCommands.forEach((command) => { 12352 drawRect(command, ctx, strokeColor); 12353 }); 12354 }); 12355} 12356function ScreenshotEditorFactory({ h: h2, hooks, outputBuffer, dialog, options }) { 12357 const useTakeScreenshot = useTakeScreenshotFactory({ hooks }); 12358 const Toolbar = ToolbarFactory({ h: h2 }); 12359 const IconClose = IconCloseFactory({ h: h2 }); 12360 const editorStyleInnerText = { __html: createScreenshotInputStyles(options.styleNonce).innerText }; 12361 const dialogStyle = dialog.el.style; 12362 const ScreenshotEditor = ({ screenshot }) => { 12363 const [action, setAction] = hooks.useState("highlight"); 12364 const [drawCommands, setDrawCommands] = hooks.useState([]); 12365 const measurementRef = hooks.useRef(null); 12366 const backgroundRef = hooks.useRef(null); 12367 const foregroundRef = hooks.useRef(null); 12368 const mouseRef = hooks.useRef(null); 12369 const [scaleFactor, setScaleFactor] = hooks.useState(1); 12370 const strokeColor = hooks.useMemo(() => { 12371 const sentryFeedback = DOCUMENT.getElementById(options.id); 12372 if (!sentryFeedback) return "white"; 12373 const computedStyle = getComputedStyle(sentryFeedback); 12374 return computedStyle.getPropertyValue("--button-primary-background") || computedStyle.getPropertyValue("--accent-background"); 12375 }, [options.id]); 12376 hooks.useLayoutEffect(() => { 12377 const handleResize = () => { 12378 const measurementDiv = measurementRef.current; 12379 if (!measurementDiv) return; 12380 with2dContext(screenshot.canvas, { alpha: false }, (canvas) => { 12381 const scale = Math.min(measurementDiv.clientWidth / canvas.width, measurementDiv.clientHeight / canvas.height); 12382 setScaleFactor(scale); 12383 }); 12384 if (measurementDiv.clientHeight === 0 || measurementDiv.clientWidth === 0) setTimeout(handleResize, 0); 12385 }; 12386 handleResize(); 12387 WINDOW$5.addEventListener("resize", handleResize); 12388 return () => { 12389 WINDOW$5.removeEventListener("resize", handleResize); 12390 }; 12391 }, [screenshot]); 12392 const setCanvasSize = hooks.useCallback((maybeCanvas, scale) => { 12393 with2dContext(maybeCanvas, { alpha: true }, (canvas, ctx) => { 12394 ctx.scale(scale, scale); 12395 canvas.width = screenshot.canvas.width; 12396 canvas.height = screenshot.canvas.height; 12397 }); 12398 }, [screenshot]); 12399 hooks.useEffect(() => { 12400 setCanvasSize(backgroundRef.current, screenshot.dpi); 12401 paintImage(backgroundRef.current, screenshot.canvas); 12402 }, [screenshot]); 12403 hooks.useEffect(() => { 12404 setCanvasSize(foregroundRef.current, screenshot.dpi); 12405 with2dContext(foregroundRef.current, { alpha: true }, (canvas, ctx) => { 12406 ctx.clearRect(0, 0, canvas.width, canvas.height); 12407 }); 12408 paintForeground(foregroundRef.current, strokeColor, drawCommands); 12409 }, [drawCommands, strokeColor]); 12410 hooks.useEffect(() => { 12411 setCanvasSize(outputBuffer, screenshot.dpi); 12412 paintImage(outputBuffer, screenshot.canvas); 12413 with2dContext(DOCUMENT.createElement("canvas"), { alpha: true }, (foreground, ctx) => { 12414 ctx.scale(screenshot.dpi, screenshot.dpi); 12415 foreground.width = screenshot.canvas.width; 12416 foreground.height = screenshot.canvas.height; 12417 paintForeground(foreground, strokeColor, drawCommands); 12418 paintImage(outputBuffer, foreground); 12419 }); 12420 }, [ 12421 drawCommands, 12422 screenshot, 12423 strokeColor 12424 ]); 12425 const handleMouseDown = (e) => { 12426 if (!action || !mouseRef.current) return; 12427 const boundingRect = mouseRef.current.getBoundingClientRect(); 12428 const startingPoint = { 12429 type: action, 12430 x: e.offsetX / scaleFactor, 12431 y: e.offsetY / scaleFactor 12432 }; 12433 const getDrawCommand = (startingPoint2, e2) => { 12434 const x = (e2.clientX - boundingRect.x) / scaleFactor; 12435 const y = (e2.clientY - boundingRect.y) / scaleFactor; 12436 return { 12437 type: startingPoint2.type, 12438 x: Math.min(startingPoint2.x, x), 12439 y: Math.min(startingPoint2.y, y), 12440 w: Math.abs(x - startingPoint2.x), 12441 h: Math.abs(y - startingPoint2.y) 12442 }; 12443 }; 12444 const handleMouseMove = (e2) => { 12445 with2dContext(foregroundRef.current, { alpha: true }, (canvas, ctx) => { 12446 ctx.clearRect(0, 0, canvas.width, canvas.height); 12447 }); 12448 paintForeground(foregroundRef.current, strokeColor, [...drawCommands, getDrawCommand(startingPoint, e2)]); 12449 }; 12450 const handleMouseUp = (e2) => { 12451 const drawCommand = getDrawCommand(startingPoint, e2); 12452 if (drawCommand.w * scaleFactor >= 1 && drawCommand.h * scaleFactor >= 1) setDrawCommands((prev) => [...prev, drawCommand]); 12453 DOCUMENT.removeEventListener("mousemove", handleMouseMove); 12454 DOCUMENT.removeEventListener("mouseup", handleMouseUp); 12455 }; 12456 DOCUMENT.addEventListener("mousemove", handleMouseMove); 12457 DOCUMENT.addEventListener("mouseup", handleMouseUp); 12458 }; 12459 const deleteRect = hooks.useCallback((index) => { 12460 return (e) => { 12461 e.preventDefault(); 12462 e.stopPropagation(); 12463 setDrawCommands((prev) => { 12464 const updatedRects = [...prev]; 12465 updatedRects.splice(index, 1); 12466 return updatedRects; 12467 }); 12468 }; 12469 }, []); 12470 const dimensions = { 12471 width: `${screenshot.canvas.width * scaleFactor}px`, 12472 height: `${screenshot.canvas.height * scaleFactor}px` 12473 }; 12474 const handleStopPropagation = (e) => { 12475 e.stopPropagation(); 12476 }; 12477 return /* @__PURE__ */ h2("div", { class: "editor" }
12477, /* @__PURE__ */ h2("style", { 12478 nonce: options.styleNonce, 12479 dangerouslySetInnerHTML: editorStyleInnerText 12480 }), /* @__PURE__ */ h2("div", { class: "editor__image-container" }, /* @__PURE__ */ h2("div", { 12481 class: "editor__canvas-container", 12482 ref: measurementRef 12483 }, /* @__PURE__ */ h2("canvas", { 12484 ref: backgroundRef, 12485 id: "background", 12486 style: dimensions 12487 }), /* @__PURE__ */ h2("canvas", { 12488 ref: foregroundRef, 12489 id: "foreground", 12490 style: dimensions 12491 }), /* @__PURE__ */ h2("div", { 12492 ref: mouseRef, 12493 onMouseDown: handleMouseDown, 12494 style: dimensions 12495 }, drawCommands.map((rect, index) => /* @__PURE__ */ h2("div", { 12496 key: index, 12497 class: "editor__rect", 12498 style: { 12499 top: `${rect.y * scaleFactor}px`, 12500 left: `${rect.x * scaleFactor}px`, 12501 width: `${rect.w * scaleFactor}px`, 12502 height: `${rect.h * scaleFactor}px` 12503 } 12504 }, /* @__PURE__ */ h2("button", { 12505 "aria-label": options.removeHighlightText, 12506 onClick: deleteRect(index), 12507 onMouseDown: handleStopPropagation, 12508 onMouseUp: handleStopPropagation, 12509 type: "button" 12510 }, /* @__PURE__ */ h2(IconClose, null))))))), /* @__PURE__ */ h2(Toolbar, { 12511 options, 12512 action, 12513 setAction 12514 })); 12515 }; 12516 return function Wrapper({ onError }) { 12517 const [screenshot, setScreenshot] = hooks.useState(); 12518 useTakeScreenshot({ 12519 onBeforeScreenshot: hooks.useCallback(() => { 12520 dialogStyle.display = "none"; 12521 }, []), 12522 onScreenshot: hooks.useCallback((screenshotVideo, dpi) => { 12523 with2dContext(DOCUMENT.createElement("canvas"), { alpha: false }, (canvas, ctx) => { 12524 ctx.scale(dpi, dpi); 12525 canvas.width = screenshotVideo.videoWidth; 12526 canvas.height = screenshotVideo.videoHeight; 12527 ctx.drawImage(screenshotVideo, 0, 0, canvas.width, canvas.height); 12528 setScreenshot({ 12529 canvas, 12530 dpi 12531 }); 12532 }); 12533 outputBuffer.width = screenshotVideo.videoWidth; 12534 outputBuffer.height = screenshotVideo.videoHeight; 12535 }, []), 12536 onAfterScreenshot: hooks.useCallback(() => { 12537 dialogStyle.display = "block"; 12538 }, []), 12539 onError: hooks.useCallback((error) => { 12540 dialogStyle.display = "block"; 12541 onError(error); 12542 }, []) 12543 }); 12544 if (screenshot) return /* @__PURE__ */ h2(ScreenshotEditor, { screenshot }); 12545 return /* @__PURE__ */ h2("div", null); 12546 }; 12547} 12548var WINDOW$5, DOCUMENT, NAVIGATOR$1, TRIGGER_LABEL, CANCEL_BUTTON_LABEL, SUBMIT_BUTTON_LABEL, CONFIRM_BUTTON_LABEL, FORM_TITLE, EMAIL_PLACEHOLDER, EMAIL_LABEL, MESSAGE_PLACEHOLDER, MESSAGE_LABEL, NAME_PLACEHOLDER, NAME_LABEL, SUCCESS_MESSAGE_TEXT, IS_REQUIRED_LABEL, ADD_SCREENSHOT_LABEL, REMOVE_SCREENSHOT_LABEL, HIGHLIGHT_TOOL_TEXT, HIDE_TOOL_TEXT, REMOVE_HIGHLIGHT_TEXT, ERROR_EMPTY_MESSAGE_TEXT, ERROR_NO_CLIENT_TEXT, ERROR_TIMEOUT_TEXT, ERROR_FORBIDDEN_TEXT, ERROR_GENERIC_TEXT, FEEDBACK_WIDGET_SOURCE, FEEDBACK_API_SOURCE, SUCCESS_MESSAGE_TIMEOUT, DEFAULT_MESSAGES, sendFeedback, DEBUG_BUILD$4, SIZE, XMLNS$2, PURPLE, DEFAULT_LIGHT, DEFAULT_DARK, buildFeedbackIntegration, n$2, l$1, u$1, i$1$1, o$1, r$1, f$1, c$1, s$1, a$1, h$1, t$2, r$2, u, i$2, o, f, c, e$1, a, v, l, m, s, d, k, hooks, XMLNS$1, WIDTH, HEIGHT, XMLNS, DIALOG, DIALOG_HEADER, FORM, BUTTON, SUCCESS, feedbackModalIntegration, feedbackScreenshotIntegration; 12549function init_esm() { 12550 return (init_esm = __esmMin((() => { 12551 init_worldwide(), init_currentScopes(), init_feedback(), init_browser(), init_isBrowser(), init_debug_logger(), init_integration(); 12552 WINDOW$5 = GLOBAL_OBJ; 12553 DOCUMENT = WINDOW$5.document; 12554 NAVIGATOR$1 = WINDOW$5.navigator; 12555 TRIGGER_LABEL = "Report a Bug"; 12556 CANCEL_BUTTON_LABEL = "Cancel"; 12557 SUBMIT_BUTTON_LABEL = "Send Bug Report"; 12558 CONFIRM_BUTTON_LABEL = "Confirm"; 12559 FORM_TITLE = "Report a Bug"; 12560 EMAIL_PLACEHOLDER = "[email protected]"; 12561 EMAIL_LABEL = "Email"; 12562 MESSAGE_PLACEHOLDER = "What's the bug? What did you expect?"; 12563 MESSAGE_LABEL = "Description"; 12564 NAME_PLACEHOLDER = "Your Name"; 12565 NAME_LABEL = "Name"; 12566 SUCCESS_MESSAGE_TEXT = "Thank you for your report!"; 12567 IS_REQUIRED_LABEL = "(required)"; 12568 ADD_SCREENSHOT_LABEL = "Add a screenshot"; 12569 REMOVE_SCREENSHOT_LABEL = "Remove screenshot"; 12570 HIGHLIGHT_TOOL_TEXT = "Highlight"; 12571 HIDE_TOOL_TEXT = "Hide"; 12572 REMOVE_HIGHLIGHT_TEXT = "Remove"; 12573 ERROR_EMPTY_MESSAGE_TEXT = "Unable to submit feedback with empty message"; 12574 ERROR_NO_CLIENT_TEXT = "No client setup, cannot send feedback."; 12575 ERROR_TIMEOUT_TEXT = "Unable to determine if Feedback was correctly sent."; 12576 ERROR_FORBIDDEN_TEXT = "Unable to send feedback. This could be because this domain is not in your list of allowed domains."; 12577 ERROR_GENERIC_TEXT = "Unable to send feedback. This could be because of network issues, or because you are using an ad-blocker."; 12578 FEEDBACK_WIDGET_SOURCE = "widget"; 12579 FEEDBACK_API_SOURCE = "api"; 12580 SUCCESS_MESSAGE_TIMEOUT = 5e3; 12581 DEFAULT_MESSAGES = { 12582 ERROR_EMPTY_MESSAGE: ERROR_EMPTY_MESSAGE_TEXT, 12583 ERROR_NO_CLIENT: ERROR_NO_CLIENT_TEXT, 12584 ERROR_TIMEOUT: ERROR_TIMEOUT_TEXT, 12585 ERROR_FORBIDDEN: ERROR_FORBIDDEN_TEXT, 12586 ERROR_GENERIC: ERROR_GENERIC_TEXT 12587 }; 12588 sendFeedback = (params, hint = { includeReplay: true }) => { 12589 const errorMessages = hint.errorMessages; 12590 if (!params.message) throw createFeedbackError("ERROR_EMPTY_MESSAGE", errorMessages); 12591 const client = getClient(); 12592 if (!client) throw createFeedbackError("ERROR_NO_CLIENT", errorMessages); 12593 if (params.tags && Object.keys(params.tags).length) getCurrentScope().setTags(params.tags); 12594 const eventId = captureFeedback({ 12595 source: FEEDBACK_API_SOURCE, 12596 url: getLocationHref(), 12597 ...params 12598 }, hint); 12599 return new Promise((resolve, reject) => { 12600 const timeout = setTimeout(() => { 12601 cleanup(); 12602 reject(resolveFeedbackErrorMessage("ERROR_TIMEOUT", errorMessages)); 12603 }, 3e4); 12604 const cleanup = client.on("afterSendEvent", (event, response) => { 12605 if (event.event_id !== eventId) return; 12606 clearTimeout(timeout); 12607 cleanup(); 12608 if (response?.statusCode && response.statusCode >= 200 && response.statusCode < 300) return resolve(eventId); 12609 if (response?.statusCode === 403) return reject(resolveFeedbackErrorMessage("ERROR_FORBIDDEN", errorMessages)); 12610 return reject(resolveFeedbackErrorMessage("ERROR_GENERIC", errorMessages)); 12611 }); 12612 }); 12613 }; 12614 DEBUG_BUILD$4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 12615 SIZE = 20; 12616 XMLNS$2 = "http://www.w3.org/2000/svg"; 12617 PURPLE = "rgba(88, 74, 192, 1)"; 12618 DEFAULT_LIGHT = { 12619 foreground: "#2b2233", 12620 background: "#ffffff", 12621 accentForeground: "white",
vendor: 5,011 bytes, lines 12622-12734
12622 accentBackground: PURPLE, 12623 successColor: "#268d75", 12624 errorColor: "#df3338", 12625 border: "1.5px solid rgba(41, 35, 47, 0.13)", 12626 boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)", 12627 outline: "1px auto var(--accent-background)", 12628 interactiveFilter: "brightness(95%)" 12629 }; 12630 DEFAULT_DARK = { 12631 foreground: "#ebe6ef", 12632 background: "#29232f", 12633 accentForeground: "white", 12634 accentBackground: PURPLE, 12635 successColor: "#2da98c", 12636 errorColor: "#f55459", 12637 border: "1.5px solid rgba(235, 230, 239, 0.15)", 12638 boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)", 12639 outline: "1px auto var(--accent-background)", 12640 interactiveFilter: "brightness(150%)" 12641 }; 12642 buildFeedbackIntegration = ({ lazyLoadIntegration, getModalIntegration, getScreenshotIntegration }) => { 12643 const feedbackIntegration = (({ id = "sentry-feedback", autoInject = true, showBranding = true, isEmailRequired = false, isNameRequired = false, showEmail = true, showName = true, enableScreenshot = true, useSentryUser = { 12644 email: "email", 12645 name: "username" 12646 }, tags, styleNonce, scriptNonce, colorScheme = "system", themeLight = {}, themeDark = {}, addScreenshotButtonLabel = ADD_SCREENSHOT_LABEL, cancelButtonLabel = CANCEL_BUTTON_LABEL, confirmButtonLabel = CONFIRM_BUTTON_LABEL, emailLabel = EMAIL_LABEL, emailPlaceholder = EMAIL_PLACEHOLDER, formTitle = FORM_TITLE, isRequiredLabel = IS_REQUIRED_LABEL, messageLabel = MESSAGE_LABEL, messagePlaceholder = MESSAGE_PLACEHOLDER, nameLabel = NAME_LABEL, namePlaceholder = NAME_PLACEHOLDER, removeScreenshotButtonLabel = REMOVE_SCREENSHOT_LABEL, submitButtonLabel = SUBMIT_BUTTON_LABEL, successMessageText = SUCCESS_MESSAGE_TEXT, triggerLabel = TRIGGER_LABEL, triggerAriaLabel = "", highlightToolText = HIGHLIGHT_TOOL_TEXT, hideToolText = HIDE_TOOL_TEXT, removeHighlightText = REMOVE_HIGHLIGHT_TEXT, errorEmptyMessageText = ERROR_EMPTY_MESSAGE_TEXT, errorNoClientText = ERROR_NO_CLIENT_TEXT, errorTimeoutText = ERROR_TIMEOUT_TEXT, errorForbiddenText = ERROR_FORBIDDEN_TEXT, errorGenericText = ERROR_GENERIC_TEXT, onFormOpen, onFormClose, onSubmitSuccess, onSubmitError, onFormSubmitted } = {}) => { 12647 const _options = { 12648 id, 12649 autoInject, 12650 showBranding, 12651 isEmailRequired, 12652 isNameRequired, 12653 showEmail, 12654 showName, 12655 enableScreenshot, 12656 useSentryUser, 12657 tags, 12658 styleNonce, 12659 scriptNonce, 12660 colorScheme, 12661 themeDark, 12662 themeLight, 12663 triggerLabel, 12664 triggerAriaLabel, 12665 cancelButtonLabel, 12666 submitButtonLabel, 12667 confirmButtonLabel, 12668 formTitle, 12669 emailLabel, 12670 emailPlaceholder, 12671 messageLabel, 12672 messagePlaceholder, 12673 nameLabel, 12674 namePlaceholder, 12675 successMessageText, 12676 isRequiredLabel, 12677 addScreenshotButtonLabel, 12678 removeScreenshotButtonLabel, 12679 highlightToolText, 12680 hideToolText, 12681 removeHighlightText, 12682 errorEmptyMessageText, 12683 errorNoClientText, 12684 errorTimeoutText, 12685 errorForbiddenText, 12686 errorGenericText, 12687 onFormClose, 12688 onFormOpen, 12689 onSubmitError, 12690 onSubmitSuccess, 12691 onFormSubmitted 12692 }; 12693 let _shadow = null; 12694 let _mainStyle = null; 12695 let _subscriptions = []; 12696 const _createShadow = (options) => { 12697 if (!_shadow) { 12698 const host = DOCUMENT.createElement("div"); 12699 host.id = String(options.id); 12700 DOCUMENT.body.appendChild(host); 12701 _shadow = host.attachShadow({ mode: "open" }); 12702 _mainStyle = createMainStyles(options); 12703 _shadow.appendChild(_mainStyle); 12704 } 12705 return _shadow; 12706 }; 12707 const _loadAndRenderDialog = async (options) => { 12708 const screenshotRequired = options.enableScreenshot && isScreenshotSupported(); 12709 let modalIntegration; 12710 let screenshotIntegration; 12711 try { 12712 modalIntegration = (getModalIntegration ? getModalIntegration() : await lazyLoadIntegration("feedbackModalIntegration", scriptNonce))(); 12713 addIntegration(modalIntegration); 12714 } catch { 12715 DEBUG_BUILD$4 && debug$2.error("[Feedback] Error when trying to load feedback integrations. Try using `feedbackSyncIntegration` in your `Sentry.init`."); 12716 throw new Error("[Feedback] Missing feedback modal integration!"); 12717 } 12718 try { 12719 const screenshotIntegrationFn = screenshotRequired ? getScreenshotIntegration ? getScreenshotIntegration() : await lazyLoadIntegration("feedbackScreenshotIntegration", scriptNonce) : void 0; 12720 if (screenshotIntegrationFn) { 12721 screenshotIntegration = screenshotIntegrationFn(); 12722 addIntegration(screenshotIntegration); 12723 } 12724 } catch { 12725 DEBUG_BUILD$4 && debug$2.error("[Feedback] Missing feedback screenshot integration. Proceeding without screenshots."); 12726 } 12727 const errorMessages = { 12728 ERROR_EMPTY_MESSAGE: options.errorEmptyMessageText, 12729 ERROR_NO_CLIENT: options.errorNoClientText, 12730 ERROR_TIMEOUT: options.errorTimeoutText, 12731 ERROR_FORBIDDEN: options.errorForbiddenText, 12732 ERROR_GENERIC: options.errorGenericText 12733 }; 12734 const wrappedSendFeedback = (params, hint) =>
12734 sendFeedback(params, { 12735 includeReplay: true, 12736 ...hint, 12737 errorMessages 12738 }); 12739 const dialog = modalIntegration.createDialog({ 12740 options: { 12741 ...options, 12742 onFormClose: () => { 12743 dialog?.close(); 12744 options.onFormClose?.(); 12745 }, 12746 onFormSubmitted: () => { 12747 dialog?.close(); 12748 options.onFormSubmitted?.(); 12749 } 12750 }, 12751 screenshotIntegration, 12752 sendFeedback: wrappedSendFeedback, 12753 shadow: _createShadow(options) 12754 }); 12755 return dialog; 12756 }; 12757 const _attachTo = (el, optionOverrides = {}) => { 12758 const mergedOptions = mergeOptions(_options, optionOverrides); 12759 const targetEl = typeof el === "string" ? DOCUMENT.querySelector(el) : typeof el.addEventListener === "function" ? el : null; 12760 if (!targetEl) { 12761 DEBUG_BUILD$4 && debug$2.error("[Feedback] Unable to attach to target element"); 12762 throw new Error("Unable to attach to target element"); 12763 } 12764 let dialog = null; 12765 const handleClick = async () => { 12766 if (!dialog) dialog = await _loadAndRenderDialog({ 12767 ...mergedOptions, 12768 onFormSubmitted: () => { 12769 dialog?.removeFromDom(); 12770 mergedOptions.onFormSubmitted?.(); 12771 } 12772 }); 12773 dialog.appendToDom(); 12774 dialog.open(); 12775 }; 12776 targetEl.addEventListener("click", handleClick); 12777 const unsubscribe = () => { 12778 _subscriptions = _subscriptions.filter((sub) => sub !== unsubscribe); 12779 dialog?.removeFromDom(); 12780 dialog = null; 12781 targetEl.removeEventListener("click", handleClick); 12782 };
12783 _subscriptions.push(unsubscribe); 12784 return unsubscribe; 12785 }; 12786 const _createActor = (optionOverrides = {}) => { 12787 const mergedOptions = mergeOptions(_options, optionOverrides); 12788 const shadow = _createShadow(mergedOptions); 12789 const actor = Actor({ 12790 triggerLabel: mergedOptions.triggerLabel, 12791 triggerAriaLabel: mergedOptions.triggerAriaLabel, 12792 shadow, 12793 styleNonce 12794 }); 12795 _attachTo(actor.el, { 12796 ...mergedOptions, 12797 onFormOpen() { 12798 actor.hide(); 12799 }, 12800 onFormClose() { 12801 actor.show(); 12802 }, 12803 onFormSubmitted() { 12804 actor.show(); 12805 } 12806 }); 12807 return actor; 12808 }; 12809 return { 12810 name: "Feedback", 12811 setupOnce() { 12812 if (!isBrowser() || !_options.autoInject) return; 12813 if (DOCUMENT.readyState === "loading") DOCUMENT.addEventListener("DOMContentLoaded", () => _createActor().appendToDom()); 12814 else _createActor().appendToDom(); 12815 }, 12816 /** 12817 * Adds click listener to the element to open a feedback dialog 12818 * 12819 * The returned function can be used to remove the click listener 12820 */ 12821 attachTo: _attachTo, 12822 /** 12823 * Creates a new widget which is composed of a Button which triggers a Dialog. 12824 * Accepts partial options to override any options passed to constructor. 12825 */ 12826 createWidget(optionOverrides = {}) { 12827 const actor = _createActor(mergeOptions(_options, optionOverrides)); 12828 actor.appendToDom(); 12829 return actor; 12830 }, 12831 /** 12832 * Creates a new Form which you can 12833 * Accepts partial options to override any options passed to constructor. 12834 */ 12835 async createForm(optionOverrides = {}) { 12836 return _loadAndRenderDialog(mergeOptions(_options, optionOverrides)); 12837 }, 12838 /** 12839 * Updates the color scheme of the feedback widget at runtime. 12840 */ 12841 setTheme(colorScheme2) { 12842 _options.colorScheme = colorScheme2; 12843 if (_shadow) { 12844 const newStyle = createMainStyles(_options); 12845 if (_mainStyle) _shadow.replaceChild(newStyle, _mainStyle); 12846 else _shadow.prepend(newStyle); 12847 _mainStyle = newStyle; 12848 } 12849 }, 12850 /** 12851 * Removes the Feedback integration (including host, shadow DOM, and all widgets) 12852 */ 12853 remove() { 12854 if (_shadow) { 12855 _shadow.parentElement?.remove(); 12856 _shadow = null; 12857 _mainStyle = null; 12858 } 12859 _subscriptions.forEach((sub) => sub()); 12860 _subscriptions = []; 12861 } 12862 }; 12863 }); 12864 return feedbackIntegration; 12865 }; 12866 c$1 = {}; 12867 s$1 = []; 12868 a$1 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i; 12869 h$1 = Array.isArray; 12870 n$2 = s$1.slice, l$1 = { __e: function(n, l, u, t) { 12871 for (var i, o, r; l = l.__;) if ((i = l.__c) && !i.__) try { 12872 if ((o = i.constructor) && null != o.getDerivedStateFromError && (i.setState(o.getDerivedStateFromError(n)), r = i.__d), null != i.componentDidCatch && (i.componentDidCatch(n, t || {}), r = i.__d), r) return i.__E = i; 12873 } catch (l) { 12874 n = l; 12875 } 12876 throw n; 12877 } }, u$1 = 0, b$1.prototype.setState = function(n, l) { 12878 var u = null != this.__s && this.__s !== this.state ? this.__s : this.__s = v$1({}, this.state); 12879 "function" == typeof n && (n = n(v$1({}, u), this.props)), n && v$1(u, n), null != n && this.__v && (l && this._sb.push(l), x$1(this)); 12880 }, b$1.prototype.forceUpdate = function(n) { 12881 this.__v && (this.__e = true, n && this.__h.push(n), x$1(this)); 12882 }, b$1.prototype.render = g$1, i$1$1 = [], r$1 = "function" == typeof Promise ? Promise.prototype.then.bind(Prom
12882ise.resolve()) : setTimeout, f$1 = function(n, l) { 12883 return n.__v.__b - l.__v.__b; 12884 }, C$1.__r = 0; 12885 o = 0; 12886 f = []; 12887 c = []; 12888 e$1 = l$1; 12889 a = e$1.__b; 12890 v = e$1.__r; 12891 l = e$1.diffed; 12892 m = e$1.__c; 12893 s = e$1.unmount; 12894 d = e$1.__; 12895 e$1.__b = function(n) { 12896 r$2 = null, a && a(n); 12897 }, e$1.__ = function(n, t) { 12898 t.__k && t.__k.__m && (n.__m = t.__k.__m), d && d(n, t); 12899 }, e$1.__r = function(n) { 12900 v && v(n), t$2 = 0; 12901 var i = (r$2 = n.__c).__H; 12902 i && (u === r$2 ? (i.__h = [], r$2.__h = [], i.__.forEach(function(n) { 12903 n.__N && (n.__ = n.__N), n.__V = c, n.__N = n.i = void 0; 12904 })) : (i.__h.forEach(z), i.__h.forEach(B), i.__h = [], t$2 = 0)), u = r$2; 12905 }, e$1.diffed = function(n) { 12906 l && l(n); 12907 var t = n.__c; 12908 t && t.__H && (t.__H.__h.length && (1 !== f.push(t) && i$2 === e$1.requestAnimationFrame || ((i$2 = e$1.requestAnimationFrame) || w)(j)), t.__H.__.forEach(function(n) { 12909 n.i && (n.__H = n.i), n.__V !== c && (n.__ = n.__V), n.i = void 0, n.__V = c; 12910 })), u = r$2 = null; 12911 }, e$1.__c = function(n, t) { 12912 t.some(function(n) { 12913 try { 12914 n.__h.forEach(z), n.__h = n.__h.filter(function(n) { 12915 return !n.__ || B(n); 12916 }); 12917 } catch (r) { 12918 t.some(function(n) { 12919 n.__h && (n.__h = []); 12920 }), t = [], e$1.__e(r, n.__v); 12921 } 12922 }), m && m(n, t); 12923 }, e$1.unmount = function(n) { 12924 s && s(n); 12925 var t, r = n.__c; 12926 r && r.__H && (r.__H.__.forEach(function(n) { 12927 try { 12928 z(n); 12929 } catch (n) { 12930 t = n; 12931 } 12932 }), r.__H = void 0, t && e$1.__e(t, r.__v)); 12933 }; 12934 k = "function" == typeof requestAnimationFrame; 12935 hooks = /*#__PURE__*/ Object.defineProperty({ 12936 __proto__: null, 12937 useCallback: x, 12938 useContext: P, 12939 useDebugValue: V, 12940 useEffect: _, 12941 useErrorBoundary: b, 12942 useId: g, 12943 useImperativeHandle: T, 12944 useLayoutEffect: A, 12945 useMemo: q, 12946 useReducer: y, 12947 useRef: F, 12948 useState: p 12949 }, Symbol.toStringTag, { value: "Module" }); 12950 XMLNS$1 = "http://www.w3.org/2000/svg"; 12951 WIDTH = 16; 12952 HEIGHT = 17; 12953 XMLNS = "http://www.w3.org/2000/svg"; 12954 DIALOG = ` 12955.dialog { 12956 position: fixed; 12957 z-index: var(--z-index); 12958 margin: 0; 12959 inset: 0; 12960 12961 display: flex; 12962 align-items: center; 12963 justify-content: center; 12964 padding: 0; 12965 height: 100vh; 12966 width: 100vw; 12967 12968 color: var(--dialog-color, var(--foreground)); 12969 fill: var(--dialog-color, var(--foreground)); 12970 line-height: 1.75em; 12971 12972 background-color: rgba(0, 0, 0, 0.05); 12973 border: none; 12974 inset: 0; 12975 opacity: 1; 12976 transition: opacity 0.2s ease-in-out; 12977} 12978 12979.dialog__position { 12980 position: fixed; 12981 z-index: var(--z-index); 12982 inset: var(--dialog-inset); 12983 padding: var(--page-margin); 12984 display: flex; 12985 max-height: calc(100vh - (2 * var(--page-margin))); 12986} 12987@media (max-width: 600px) { 12988 .dialog__position { 12989 inset: var(--page-margin); 12990 padding: 0; 12991 } 12992} 12993 12994.dialog__position:has(.editor) { 12995 inset: var(--page-margin); 12996 padding: 0; 12997} 12998 12999.dialog:not([open]) { 13000 opacity: 0; 13001 pointer-events: none; 13002 visibility: hidden; 13003} 13004.dialog:not([open]) .dialog__content { 13005 transform: translate(0, -16px) scale(0.98); 13006} 13007 13008.dialog__content { 13009 display: flex; 13010 flex-direction: column; 13011 gap: 16px; 13012 padding: var(--dialog-padding, 24px); 13013 max-width: 100%; 13014 width: 100%; 13015 max-height: 100%; 13016 overflow: auto; 13017 13018 background: var(--dialog-background, var(--background)); 13019 border-radius: var(--dialog-border-radius, 20px); 13020 border: var(--dialog-border, var(--border));
13021 box-shadow: var(--dialog-box-shadow, var(--box-shadow)); 13022 transform: translate(0, 0) scale(1); 13023 transition: transform 0.2s ease-in-out; 13024} 13025 13026`; 13027 DIALOG_HEADER = ` 13028.dialog__header { 13029 display: flex; 13030 gap: 4px; 13031 justify-content: space-between; 13032 font-weight: var(--dialog-header-weight, 600); 13033 margin: 0; 13034} 13035.dialog__title { 13036 align-self: center; 13037 width: var(--form-width, 272px); 13038} 13039 13040@media (max-width: 600px) { 13041 .dialog__title { 13042 width: auto; 13043 } 13044} 13045 13046.dialog__position:has(.editor) .dialog__title { 13047 width: auto; 13048} 13049 13050 13051.brand-link { 13052 display: inline-flex; 13053} 13054.brand-link:focus-visible { 13055 outline: var(--outline); 13056} 13057`; 13058 FORM = ` 13059.form { 13060 display: flex; 13061 overflow: auto; 13062 flex-direction: row; 13063 gap: 16px; 13064 flex: 1 0; 13065} 13066 13067.form fieldset { 13068 border: none; 13069 margin: 0; 13070 padding: 0; 13071} 13072 13073.form__right { 13074 flex: 0 0 auto; 13075 display: flex; 13076 overflow: auto; 13077 flex-direction: column; 13078 justify-content: space-between; 13079 gap: 20px; 13080 width: var(--form-width, 100%); 13081} 13082 13083.dialog__position:has(.editor) .form__right { 13084 width: var(--form-width, 272px); 13085} 13086 13087.form__top { 13088 display: flex; 13089 flex-direction: column; 13090 gap: 8px; 13091} 13092 13093.form__error-container { 13094 color: var(--error-color); 13095 fill: var(--error-color); 13096} 13097 13098.form__label { 13099 display: flex; 13100 flex-direction: column; 13101 gap: 4px; 13102 margin: 0px; 13103} 13104 13105.form__label__text { 13106 display: flex; 13107 gap: 4px; 13108 align-items: center; 13109} 13110 13111.form__label__text--required { 13112 font-size: 0.85em; 13113} 13114 13115.form__input { 13116 font-family: inherit; 13117 line-height: inherit; 13118 background: transparent; 13119 box-sizing: border-box; 13120 border: var(--input-border, var(--border)); 13121 border-radius: var(--input-border-radius, 6px); 13122 color: var(--input-color, inherit); 13123 fill: var(--input-color, inherit); 13124 font-size: var(--input-font-size, inherit); 13125 font-weight: var(--input-font-weight, 500); 13126 padding: 6px 12px; 13127} 13128 13129.form__input::placeholder { 13130 opacity: 0.65; 13131 color: var(--input-placeholder-color, inherit); 13132 filter: var(--interactive-filter); 13133} 13134 13135.form__input:focus-visible { 13136 outline: var(--input-focus-outline, var(--outline)); 13137} 13138 13139.form__input--textarea { 13140 font-family: inherit; 13141 resize: vertical; 13142} 13143 13144.error { 13145 color: var(--error-color); 13146 fill: var(--error-color); 13147} 13148`; 13149 BUTTON = ` 13150.btn-group { 13151 display: grid; 13152 gap: 8px; 13153} 13154 13155.btn { 13156 line-height: inherit; 13157 border: var(--button-border, var(--border)); 13158 border-radius: var(--button-border-radius, 6px); 13159 cursor: pointer; 13160 font-family: inherit; 13161 font-size: var(--button-font-size, inherit); 13162 font-weight: var(--button-font-weight, 600); 13163 padding: var(--button-padding, 6px 16px); 13164} 13165.btn[disabled] { 13166 opacity: 0.6; 13167 pointer-events: none; 13168} 13169 13170.btn--primary { 13171 color: var(--button-primary-color, var(--accent-foreground)); 13172 fill: var(--button-primary-color, var(--accent-foreground)); 13173 background: var(--button-primary-background, var(--accent-background)); 13174 border: var(--button-primary-border, var(--border)); 13175 border-radius: var(--button-primary-border-radius, 6px); 13176 font-weight: var(--button-primary-font-weight, 500); 13177} 13178.btn--primary:hover { 13179 color: var(--button-primary-hover-color, var(--accent-foreground)); 13180 fill: var(--button-primary-hover-color, var(--accent-foreground)); 13181 background: var(--button-primary-hover-background, var(--accent-background)); 13182 filter: var(--interactive-filter); 13183} 13184.btn--primary:focus-visible { 13185 background: var(--button-primary-hover-background, var(--accent-background)); 13186 filter: var(--interactive-filter); 13187 outline: var(--button-primary-focus-outline, var(--outline)); 13188} 13189 13190.btn--default { 13191 color: var(--button-color, var(--foreground)); 13192 fill: var(--button-color, var(--foreground)); 13193 background: var(--button-background, var(--background)); 13194 border: var(--button-border, var(--border)); 13195 border-radius: var(--button-border-radius, 6px); 13196 font-weight: var(--button-font-weight, 500); 13197} 13198.btn--default:hover { 13199 color: var(--button-color, var(--foreground)); 13200 fill: var(--button-color, var(--foreground)); 13201 background: var(--button-hover-background, var(--background)); 13202 filter: var(--interactive-filter); 13203} 13204.btn--default:focus-visible { 13205 background: var(--button-hover-background, var(--background)); 13206 filter: var(--interactive-filter); 13207 outline: var(--button-focus-outline, var(--outline)); 13208} 13209`; 13210 SUCCESS = ` 13211.success__position { 13212 position: fixed; 13213 inset: var(--dialog-inset); 13214 padding: var(--page-margin); 13215 z-index: var(--z-index); 13216} 13217.success__content { 13218 background: var(--success-background, var(--background)); 13219 border: var(--success-border, var(--border)); 13220 border-radius: var(--success-border-radius, 1.7em/50%);
13221 box-shadow: var(--success-box-shadow, var(--box-shadow)); 13222 font-weight: var(--success-font-weight, 600); 13223 color: var(--success-color); 13224 fill: var(--success-color); 13225 padding: 12px 24px; 13226 line-height: 1.75em; 13227 13228 display: grid; 13229 align-items: center; 13230 grid-auto-flow: column; 13231 gap: 6px; 13232 cursor: default; 13233} 13234 13235.success__icon { 13236 display: flex; 13237} 13238`; 13239 feedbackModalIntegration = (() => { 13240 return { 13241 name: "FeedbackModal", 13242 setupOnce() {}, 13243 createDialog: ({ options, screenshotIntegration, sendFeedback, shadow }) => { 13244 const shadowRoot = shadow; 13245 const userKey = options.useSentryUser; 13246 const user = getUser(); 13247 const el = DOCUMENT.createElement("div"); 13248 const style = createDialogStyles(options.styleNonce); 13249 let originalOverflow = ""; 13250 const dialog = { 13251 get el() { 13252 return el; 13253 }, 13254 appendToDom() { 13255 if (!shadowRoot.contains(style) && !shadowRoot.contains(el)) { 13256 shadowRoot.appendChild(style); 13257 shadowRoot.appendChild(el); 13258 } 13259 }, 13260 removeFromDom() { 13261 el.remove(); 13262 style.remove(); 13263 DOCUMENT.body.style.overflow = originalOverflow; 13264 }, 13265 open() { 13266 renderContent(true); 13267 options.onFormOpen?.(); 13268 getClient()?.emit("openFeedbackWidget"); 13269 originalOverflow = DOCUMENT.body.style.overflow; 13270 DOCUMENT.body.style.overflow = "hidden"; 13271 }, 13272 close() { 13273 renderContent(false); 13274 DOCUMENT.body.style.overflow = originalOverflow; 13275 } 13276 }; 13277 const screenshotInput = screenshotIntegration?.createInput({ 13278 h: y$1, 13279 hooks, 13280 dialog, 13281 options 13282 }); 13283 const renderContent = (open) => { 13284 B$1(/* @__PURE__ */ y$1(Dialog, { 13285 options, 13286 screenshotInput, 13287 showName: options.showName || options.isNameRequired, 13288 showEmail: options.showEmail || options.isEmailRequired, 13289 defaultName: String(userKey && user?.[userKey.name] || ""), 13290 defaultEmail: String(userKey && user?.[userKey.email] || ""), 13291 onFormClose: () => { 13292 renderContent(false); 13293 options.onFormClose?.(); 13294 }, 13295 onSubmit: sendFeedback, 13296 onSubmitSuccess: (data, eventId) => { 13297 renderContent(false); 13298 options.onSubmitSuccess?.(data, eventId); 13299 }, 13300 onSubmitError: (error) => { 13301 options.onSubmitError?.(error); 13302 }, 13303 onFormSubmitted: () => { 13304 options.onFormSubmitted?.(); 13305 }, 13306 open 13307 }), el); 13308 }; 13309 return dialog; 13310 } 13311 }; 13312 }); 13313 feedbackScreenshotIntegration = (() => { 13314 return { 13315 name: "FeedbackScreenshot", 13316 setupOnce() {}, 13317 createInput: ({ h, hooks, dialog, options }) => { 13318 const outputBuffer = DOCUMENT.createElement("canvas"); 13319 return { 13320 input: ScreenshotEditorFactory({ 13321 h, 13322 hooks, 13323 outputBuffer, 13324 dialog, 13325 options 13326 }), 13327 value: async () => { 13328 const blob = await new Promise((resolve) => { 13329 outputBuffer.toBlob(resolve, "image/png"); 13330 }); 13331 if (blob) return { 13332 data: new Uint8Array(await blob.arrayBuffer()), 13333 filename: "screenshot.png", 13334 contentType: "application/png" 13335 }; 13336 } 13337 }; 13338 } 13339 }; 13340 }); 13341 })))(); 13342} 13343//#endregion 13344//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/helpers.js 13345function shouldIgnoreOnError() { 13346 return ignoreOnError > 0; 13347} 13348function ignoreNextOnError() { 13349 ignoreOnError++; 13350 setTimeout(() => { 13351 ignoreOnError--; 13352 }); 13353} 13354function wrap(fn, options = {}) { 13355 function isFunction(fn2) { 13356 return typeof fn2 === "function"; 13357 } 13358 if (!isFunction(fn)) return fn; 13359 try { 13360 if (Object.prototype.hasOwnProperty.call(fn, "__sentry_wrapped__")) { 13361 const wrapper = fn.__sentry_wrapped__; 13362 if (typeof wrapper === "function") return wrapper; 13363 else return fn; 13364 } 13365 if (getOriginalFunction(fn)) return fn; 13366 } catch { 13367 return fn; 13368 } 13369 const sentryWrapped = function(...args) { 13370 GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) + 1; 13371 try { 13372 const wrappedArguments = args.map((arg) => wrap(arg, options)); 13373 return fn.apply(this, wrappedArguments); 13374 } catch (ex) { 13375 ignoreNextOnError(); 13376 withScope((scope) => { 13377 scope.addEventProcessor((event) => { 13378 if (options.mechanism) { 13379 addExceptionTypeValue(event, void 0, void 0); 13380 addExceptionMechanism(event, options.mechanism); 13381 } 13382 event.extra = { 13383 ...event.extra, 13384 arguments: args 13385 }; 13386 return event; 13387 }); 13388 captureException(ex); 13389 }); 13390 throw ex; 13391 } finally { 13392 GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) - 1; 13393 } 13394 }; 13395 try { 13396 for (const property in fn) if (Object.prototype.hasOwnProperty.call(fn, property)) sentryWrapped[property] = fn[property]; 13397 } catch {} 13398 markFunctionWrapped(sentryWrapped, fn); 13399 addNonEnumerableProperty(fn, "__sentry_wrapped__", sentryWrapped); 13400 try { 13401 if (Object.getOwnPropertyDescriptor(sentryWrapped, "name").configurable) Object.defineProperty(sentryWrapped, "name", { get() { 13402 return fn.name; 13403 } }); 13404 } catch {} 13405 return sentryWrapped; 13406} 13407function getHttpRequestData() { 13408 const url = getLocationHref(); 13409 const { referrer } = WINDOW$4.document || {}; 13410 const { userAgent }
13410 = WINDOW$4.navigator || {}; 13411 return { 13412 url, 13413 headers: { 13414 ...referrer && { Referer: referrer }, 13415 ...userAgent && { "User-Agent": userAgent } 13416 } 13417 }; 13418} 13419var WINDOW$4, ignoreOnError; 13420function init_helpers() { 13421 return (init_helpers = __esmMin((() => { 13422 init_worldwide(), init_object(), init_currentScopes(), init_misc(), init_exports(), init_browser(); 13423 WINDOW$4 = GLOBAL_OBJ; 13424 ignoreOnError = 0; 13425 })))(); 13426} 13427//#endregion 13428//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/utils/lazyLoadIntegration.js 13429function getBundleName(name) { 13430 return HYPHENATED_BUNDLES[name] || name.replace("Integration", "").toLowerCase(); 13431} 13432async function lazyLoadIntegration(name, scriptNonce) { 13433 const bundle = LAZY_LOADABLE_NAMES.includes(name) ? getBundleName(name) : void 0; 13434 const sentryOnWindow = WindowWithMaybeIntegration.Sentry = WindowWithMaybeIntegration.Sentry || {}; 13435 if (!bundle) throw new Error(`Cannot lazy load integration: ${name}`); 13436 const existing = sentryOnWindow[name]; 13437 if (typeof existing === "function" && !("_isShim" in existing)) return existing; 13438 const url = getScriptURL(bundle); 13439 const script = WINDOW$4.document.createElement("script"); 13440 script.src = url; 13441 script.crossOrigin = "anonymous"; 13442 script.referrerPolicy = "strict-origin"; 13443 if (scriptNonce) script.setAttribute("nonce", scriptNonce); 13444 const waitForLoad = new Promise((resolve, reject) => { 13445 script.addEventListener("load", () => resolve()); 13446 script.addEventListener("error", reject); 13447 }); 13448 const currentScript = WINDOW$4.document.currentScript; 13449 const parent = WINDOW$4.document.body || WINDOW$4.document.head || currentScript?.parentElement; 13450 if (parent) parent.appendChild(script); 13451 else throw new Error(`Could not find parent element to insert lazy-loaded ${name} script`); 13452 try { 13453 await waitForLoad; 13454 } catch { 13455 throw new Error(`Error when loading integration: ${name}`); 13456 } 13457 const integrationFn = sentryOnWindow[name]; 13458 if (typeof integrationFn !== "function") throw new Error(`Could not load integration: ${name}`); 13459 return integrationFn; 13460} 13461function getScriptURL(bundle) { 13462 const baseURL = getClient()?.getOptions()?.cdnBaseUrl || "https://browser.sentry-cdn.com"; 13463 return new URL(`/${SDK_VERSION}/${bundle}.min.js`, baseURL).toString(); 13464} 13465var LAZY_LOADABLE_NAMES, HYPHENATED_BUNDLES, WindowWithMaybeIntegration; 13466function init_lazyLoadIntegration() { 13467 return (init_lazyLoadIntegration = __esmMin((() => { 13468 init_currentScopes(), init_version(); 13469 init_helpers(); 13470 LAZY_LOADABLE_NAMES = [ 13471 "replayIntegration", 13472 "replayCanvasIntegration", 13473 "feedbackIntegration", 13474 "feedbackModalIntegration", 13475 "feedbackScreenshotIntegration", 13476 "captureConsoleIntegration", 13477 "contextLinesIntegration", 13478 "linkedErrorsIntegration", 13479 "dedupeIntegration", 13480 "extraErrorDataIntegration", 13481 "graphqlClientIntegration", 13482 "httpClientIntegration", 13483 "reportingObserverIntegration", 13484 "rewriteFramesIntegration", 13485 "browserProfilingIntegration", 13486 "moduleMetadataIntegration", 13487 "instrumentAnthropicAiClient", 13488 "instrumentOpenAiClient", 13489 "instrumentGoogleGenAIClient", 13490 "instrumentStateGraph", 13491 "instrumentLangGraph", 13492 "createLangChainCallbackHandler", 13493 "instrumentLangChainEmbeddings" 13494 ]; 13495 HYPHENATED_BUNDLES = { 13496 replayCanvasIntegration: "replay-canvas", 13497 feedbackModalIntegration: "feedback-modal", 13498 feedbackScreenshotIntegration: "feedback-screenshot" 13499 }; 13500 WindowWithMaybeIntegration = WINDOW$4; 13501 })))(); 13502} 13503//#endregion 13504//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/feedbackAsync.js 13505var feedbackAsyncIntegration; 13506function init_feedbackAsync() { 13507 return (init_feedbackAsync = __esmMin((() => { 13508 init_esm(); 13509 init_lazyLoadIntegration(); 13510 feedbackAsyncIntegration = buildFeedbackIntegration({ lazyLoadIntegration }); 13511 })))(); 13512} 13513//#endregion 13514//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/feedbackSync.js 13515var feedbackSyncIntegration; 13516function init_feedbackSync() { 13517 return (init_feedbackSync = __esmMin((() => { 13518 init_esm(); 13519 feedbackSyncIntegration = buildFeedbackIntegration({ 13520 getModalIntegration: () => feedbackModalIntegration, 13521 getScreenshotIntegration: () => feedbackScreenshotIntegration 13522 }); 13523 })))(); 13524} 13525//#endregion 13526//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/eventbuilder.js 13527function exceptionFromError(stackParser, ex) { 13528 const frames = parseStackFrames(stackParser, ex); 13529 const exception = { 13530 type: extractType(ex), 13531 value: extractMessage(ex) 13532 }; 13533 if (frames.length) exception.stacktrace = { frames }; 13534 if (exception.type === void 0 && exception.value === "") exception.value = "Unrecoverable error caught"; 13535 return exception; 13536} 13537function eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection) { 13538 const normalizeDepth = getClient()?.getOptions().normalizeDepth; 13539 const errorFromProp = getErrorPropertyFromObject(exception); 13540 const extra = { __serialized__: normalizeToSize(exception, normalizeDepth) }; 13541 if (errorFromProp) return { 13542 exception: { values: [exceptionFromError(stackParser, errorFromProp)] }, 13543 extra 13544 }; 13545 const event = { 13546 exception: { values: [{ 13547 type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? "UnhandledRejection" : "Error", 13548 value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) 13549 }] }, 13550 extra 13551 }; 13552 if (syntheticException) { 13553 const frames = parseStackFrames(stackParser, syntheticException); 13554 if (frames.length) event.exception.values[0].stacktrace = { frames }; 13555 } 13556 return event; 13557} 13558function eventFromError(stackParser, ex) { 13559 return { exception: { values: [exceptionFromError(stackParser, ex)] } }; 13560} 13561function parseStackFrames(stackParser, ex) { 13562 const stacktrace = ex.stacktrace || ex.stack || ""; 13563 const skipLines = getSkipFirstStackStringLines(ex); 13564 const framesToPop = getPopFirstTopFrames(ex); 13565 try { 13566 return stackParser(stacktrace, skipLines, framesToPop); 13567 } catch {} 13568 return []; 13569} 13570function getSkipFirstStackStringLines(ex) { 13571 if (ex && reactMinifiedRegexp.test(ex.message)) return 1; 13572 return 0; 13573} 13574function getPopFirstTopFrames(ex) { 13575 if (typeof ex.framesToPop === "number") return ex.framesToPop; 13576 return 0; 13577} 13578function isWebAssemblyException(exception) { 13579 if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") return exception instanceof WebAssembly.Exception; 13580 else return false;
13581} 13582function extractType(ex) { 13583 const name = ex?.name; 13584 if (!name && isWebAssemblyException(ex)) return ex.message && Array.isArray(ex.message) && ex.message.length == 2 ? ex.message[0] : "WebAssembly.Exception"; 13585 return name; 13586} 13587function extractMessage(ex) { 13588 const message = ex?.message; 13589 if (isWebAssemblyException(ex)) { 13590 if (Array.isArray(ex.message) && ex.message.length == 2) return ex.message[1]; 13591 return "wasm exception"; 13592 } 13593 if (!message) return "No error message"; 13594 if (message.error && typeof message.error.message === "string") return _enhanceErrorWithSentryInfo(message.error); 13595 return _enhanceErrorWithSentryInfo(ex); 13596} 13597function eventFromException(stackParser, exception, hint, attachStacktrace) { 13598 const event = eventFromUnknownInput(stackParser, exception, hint?.syntheticException || void 0, attachStacktrace); 13599 addExceptionMechanism(event); 13600 event.level = "error"; 13601 if (hint?.event_id) event.event_id = hint.event_id; 13602 return resolvedSyncPromise(event); 13603} 13604function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) { 13605 const event = eventFromString(stackParser, message, hint?.syntheticException || void 0, attachStacktrace); 13606 event.level = level; 13607 if (hint?.event_id) event.event_id = hint.event_id; 13608 return resolvedSyncPromise(event); 13609} 13610function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) { 13611 let event; 13612 if (isErrorEvent$3(exception) && exception.error) return eventFromError(stackParser, exception.error); 13613 if (isDOMError(exception) || isDOMException(exception)) { 13614 const domException = exception; 13615 if ("stack" in exception) { 13616 event = eventFromError(stackParser, exception); 13617 const firstException = event.exception?.values?.[0]; 13618 if (attachStacktrace && syntheticException && firstException && !firstException.stacktrace) { 13619 const frames = parseStackFrames(stackParser, syntheticException); 13620 if (frames.length) { 13621 firstException.stacktrace = { frames }; 13622 addExceptionMechanism(event, { synthetic: true }); 13623 } 13624 } 13625 } else { 13626 const name = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException"); 13627 const message = domException.message ? `${name}: ${domException.message}` : name; 13628 event = eventFromString(stackParser, message, syntheticException, attachStacktrace); 13629 addExceptionTypeValue(event, message); 13630 } 13631 if ("code" in domException) event.tags = { 13632 ...event.tags, 13633 "DOMException.code": `${domException.code}` 13634 }; 13635 return event; 13636 } 13637 if (isError(exception)) return eventFromError(stackParser, exception); 13638 if (isPlainObject(exception) || isEvent(exception)) { 13639 event = eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection); 13640 addExceptionMechanism(event, { synthetic: true }); 13641 return event; 13642 } 13643 event = eventFromString(stackParser, exception, syntheticException, attachStacktrace); 13644 addExceptionTypeValue(event, `${exception}`, void 0); 13645 addExceptionMechanism(event, { synthetic: true }); 13646 return event; 13647} 13648function eventFromString(stackParser, message, syntheticException, attachStacktrace) { 13649 const event = {}; 13650 if (attachStacktrace && syntheticException) { 13651 const frames = parseStackFrames(stackParser, syntheticException); 13652 if (frames.length) event.exception = { values: [{ 13653 value: message, 13654 stacktrace: { frames } 13655 }] }; 13656 addExceptionMechanism(event, { synthetic: true }); 13657 } 13658 if (isParameterizedString(message)) { 13659 const { __sentry_template_string__, __sentry_template_values__ } = message; 13660 event.logentry = { 13661 message: __sentry_template_string__, 13662 params: __sentry_template_values__ 13663 }; 13664 return event; 13665 } 13666 event.message = message; 13667 return event; 13668} 13669function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) { 13670 const keys = extractExceptionKeysForMessage(exception); 13671 const captureType = isUnhandledRejection ? "promise rejection" : "exception"; 13672 if (isErrorEvent$3(exception)) return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``; 13673 if (isEvent(exception)) return `Event \`${getObjectClassName(exception)}\` (type=${exception.type}) captured as ${captureType}`; 13674 return `Object captured as ${captureType} with keys: ${keys}`; 13675} 13676function getObjectClassName(obj) { 13677 try { 13678 const prototype = Object.getPrototypeOf(obj); 13679 return prototype ? prototype.constructor.name : void 0; 13680 } catch {} 13681} 13682function getErrorPropertyFromObject(obj) { 13683 return Object.values(obj).find(isError); 13684} 13685var reactMinifiedRegexp; 13686function init_eventbuilder$1() { 13687 return (init_eventbuilder$1 = __esmMin((() => { 13688 init_is(), init_misc(), init_currentScopes(), init_normalize(), init_object(), init_eventbuilder(), init_syncpromise(); 13689 reactMinifiedRegexp = /Minified React error #\d+;/i; 13690 })))(); 13691} 13692//#endregion 13693//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/client.js 13694function applyDefaultOptions(optionsArg) { 13695 return { 13696 release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW$4.SENTRY_RELEASE?.id, 13697 sendClientReports: true, 13698 parentSpanIsAlwaysRootSpan: true, 13699 ...optionsArg 13700 }; 13701} 13702var BrowserClient; 13703function init_client$1() { 13704 return (init_client$1 = __esmMin((() => { 13705 init_client(), init_sdkMetadata(); 13706 init_eventbuilder$1(); 13707 init_helpers(); 13708 BrowserClient = class extends Client { 13709 /** 13710 * Creates a new Browser SDK instance. 13711 * 13712 * @param options Configuration options for this SDK. 13713 */ 13714 constructor(options) { 13715 const opts = applyDefaultOptions(options); 13716 applySdkMetadata(opts, "browser", ["browser"], WINDOW$4.SENTRY_SDK_SOURCE || getSDKSource()); 13717 super(opts); 13718 const { userInfo } = this.getDataCollectionOptions(); 13719 if (opts._metadata?.sdk) opts._metadata.sdk.settings = { 13720 infer_ip: userInfo ? "auto" : "never", 13721 ...opts._metadata.sdk.settings 13722 }; 13723 const { sendClientReports } = this._options; 13724 if (WINDOW$4.document) WINDOW$4.document.addEventListener("visibilitychange", () => { 13725 if (WINDOW$4.document.visibilityState === "hidden") { 13726 if (sendClientReports) this._flushOutcomes(); 13727 queueMicrotask(() => { 13728 this.flush(); 13729 }); 13730 } 13731 }); 13732 if (userInfo) this.on("beforeSendSession", addAutoIpAddressToSession); 13733 } 13734 /** 13735 * @inheritDoc 13736 */ 13737 eventFromException(exception, hint) { 13738 return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace); 13739 } 13740 /** 13741 * @inheritDoc 13742 */ 13743 eventFromMessage(message, level = "info", hint) { 13744 return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace); 13745 } 13746 /** 13747 * @inheritDoc 13748 */ 13749 _prepareEvent(event, hint, currentScope, isolationScope) { 13750 event.platform = event.platform || "javascript"; 13751 return super._prepareEvent(event, hint, currentScope, isolationScope); 13752 } 13753 }; 13754 })))(); 13755} 13756//#endregion 13757//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/debug-build.js 13758var DEBUG_BUILD$3; 13759function init_debug_build$1() { 13760 return (init_debug_build$1 = __esmMin((() => { 13761 DEBUG_BUILD$3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 13762 })))(); 13763} 13764//#endregion 13765//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/types.js 13766var WINDOW$3; 13767function init_types() { 13768 return (init_types = __esmMin((() => { 13769 init_worldwide(); 13770 WINDOW$3 = GLOBAL_OBJ; 13771 })))(); 13772} 13773//#endregion 13774//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/bindReporter.js 13775var getRating, bindReporter; 13776function init_bindReporter() { 13777 return (init_bindReporter = __esmMin((() => { 13778 getRating = (value, thresholds) => { 13779 if (value > thresholds[1]) return "poor"; 13780 if (value > thresholds[0]) return "needs-improvement"; 13781 return "good"; 13782 }; 13783 bindReporter = (callback, metric, thresholds, reportAllChanges) => { 13784 let prevValue; 13785 let delta; 13786 return (forceReport) => { 13787 if (metric.value >= 0) { 13788 if (forceReport || reportAllChanges) { 13789 delta = metric.value - (prevValue ?? 0); 13790 if (delta || prevValue === void 0) { 13791 prevValue = metric.value; 13792 metric.delta = delta; 13793 metric.rating = getRating(metric.value, thresholds); 13794 callback(metric); 13795 } 13796 } 13797 } 13798 }; 13799 }; 13800 })))(); 13801} 13802//#endregion 13803//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/getNavigationEntry.js 13804var getNavigationEntry; 13805function init_getNavigationEntry() { 13806 return (init_getNavigationEntry = __esmMin((() => { 13807 init_types(); 13808 getNavigationEntry = (checkResponseStart = true) => { 13809 const navigationEntry = WINDOW$3.performance?.getEntriesByType?.("navigation")[0]; 13810 if (!checkResponseStart || navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now()) return navigationEntry; 13811 }; 13812 })))(); 13813} 13814//#endregion 13815//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/getActivationStart.js 13816var getActivationStart; 13817function init_getActivationStart() { 13818 return (init_getActivationStart = __esmMin((() => { 13819 init_getNavigationEntry(); 13820 getActivationStart = () => { 13821 return getNavigationEntry()?.activationStart ?? 0; 13822 }; 13823 })))(); 13824} 13825//#endregion 13826//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/globalListeners.js 13827function addPageListener(type, listener, options) { 13828 if (WINDOW$3.document) WINDOW$3.addEventListener(type, listener, options); 13829} 13830function removePageListener(type, listener, options) { 13831 if (WINDOW$3.document) WINDOW$3.removeEventListener(type, listener, options); 13832} 13833function init_globalListeners() { 13834 return (init_globalListeners = __esmMin((() => { 13835 init_types(); 13836 })))(); 13837} 13838//#endregion 13839//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/getVisibilityWatcher.js 13840function isPageHidden(event) { 13841 return event.type === "pagehide" || WINDOW$3.document?.visibilityState === "hidden"; 13842} 13843var firstHiddenTime, onHiddenFunctions, initHiddenTime, onVisibilityUpdate, getVisibilityWatcher; 13844function init_getVisibilityWatcher() { 13845 return (init_getVisibilityWatcher = __esmMin((() => { 13846 init_types(); 13847 init_getActivationStart(); 13848 init_globalListeners(); 13849 firstHiddenTime = -1; 13850 onHiddenFunctions = /* @__PURE__ */ new Set(); 13851 initHiddenTime = () => { 13852 return WINDOW$3.document?.visibilityState === "hidden" && !WINDOW$3.document?.prerendering ? 0 : Infinity; 13853 }; 13854 onVisibilityUpdate = (event) => { 13855 if (isPageHidden(event) && firstHiddenTime > -1) { 13856 if (event.type === "visibilitychange" || event.type === "pagehide") for (const onHiddenFunction of onHiddenFunctions) onHiddenFunction(); 13857 if (!isFinite(firstHiddenTime)) { 13858 firstHiddenTime = event.type === "visibilitychange" ? event.timeStamp : 0; 13859 removePageListener("prerenderingchange", onVisibilityUpdate, true); 13860 } 13861 } 13862 }; 13863 getVisibilityWatcher = () => { 13864 if (WINDOW$3.document && firstHiddenTime < 0) { 13865 const activationStart = getActivationStart(); 13866 firstHiddenTime = (!WINDOW$3.document.prerendering ? globalThis.performance.getEntriesByType("visibility-state").filter((e) => e.name === "hidden" && e.startTime > activationStart)[0]?.startTime : void 0) ?? initHiddenTime(); 13867 addPageListener("visibilitychange", onVisibilityUpdate, true); 13868 addPageListener("pagehide", onVisibilityUpdate, true); 13869 addPageListener("prerenderingchange", onVisibilityUpdate, true); 13870 } 13871 return { 13872 get firstHiddenTime() { 13873 return firstHiddenTime; 13874 }, 13875 onHidden(cb) { 13876 onHiddenFunctions.add(cb); 13877 } 13878 }; 13879 }; 13880 })))(); 13881} 13882//#endregion 13883//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/generateUniqueID.js 13884var generateUniqueID; 13885function init_generateUniqueID() { 13886 return (init_generateUniqueID = __esmMin((() => { 13887 generateUniqueID = () => { 13888 return `v5-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 0xe8d4a51000}`; 13889 }; 13890 })))(); 13891} 13892//#endregion 13893//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/initMetric.js 13894var initMetric; 13895function init_initMetric() { 13896 return (init_initMetric = __esmMin((() => { 13897 init_types(); 13898 init_generateUniqueID(); 13899 init_getActivationStart(); 13900 init_getNavigationEntry(); 13901 initMetric = (name, value = -1) => { 13902 const navEntry = getNavigationEntry(); 13903 let navigationType = "navigate"; 13904 if (navEntry) { 13905 if (WINDOW$3.document?.prerendering || getActivationStart() >
13905 0) navigationType = "prerender"; 13906 else if (WINDOW$3.document?.wasDiscarded) navigationType = "restore"; 13907 else if (navEntry.type) navigationType = navEntry.type.replace(/_/g, "-"); 13908 } 13909 return { 13910 name, 13911 value, 13912 rating: "good", 13913 delta: 0, 13914 entries: [], 13915 id: generateUniqueID(), 13916 navigationType 13917 }; 13918 }; 13919 })))(); 13920} 13921//#endregion 13922//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/initUnique.js 13923function initUnique(identityObj, ClassObj) { 13924 try { 13925 if (!instanceMap.get(identityObj)) instanceMap.set(identityObj, new ClassObj()); 13926 return instanceMap.get(identityObj); 13927 } catch (_e) { 13928 return new ClassObj(); 13929 } 13930} 13931var instanceMap; 13932function init_initUnique() { 13933 return (init_initUnique = __esmMin((() => { 13934 instanceMap = /* @__PURE__ */ new WeakMap(); 13935 })))(); 13936} 13937//#endregion 13938//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/LayoutShiftManager.js 13939var LayoutShiftManager; 13940function init_LayoutShiftManager() { 13941 return (init_LayoutShiftManager = __esmMin((() => { 13942 LayoutShiftManager = class { 13943 constructor() { 13944 this._sessionValue = 0; 13945 this._sessionEntries = []; 13946 } 13947 _processEntry(entry) { 13948 if (entry.hadRecentInput) return; 13949 const firstSessionEntry = this._sessionEntries[0]; 13950 const lastSessionEntry = this._sessionEntries[this._sessionEntries.length - 1]; 13951 if (this._sessionValue && firstSessionEntry && lastSessionEntry && entry.startTime - lastSessionEntry.startTime < 1e3 && entry.startTime - firstSessionEntry.startTime < 5e3) { 13952 this._sessionValue += entry.value; 13953 this._sessionEntries.push(entry); 13954 } else { 13955 this._sessionValue = entry.value; 13956 this._sessionEntries = [entry]; 13957 } 13958 this._onAfterProcessingUnexpectedShift?.(entry); 13959 } 13960 }; 13961 })))(); 13962} 13963//#endregion 13964//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/observe.js 13965var observe; 13966function init_observe() { 13967 return (init_observe = __esmMin((() => { 13968 observe = (type, callback, opts = {}) => { 13969 try { 13970 if (PerformanceObserver.supportedEntryTypes.includes(type)) { 13971 const po = new PerformanceObserver((list) => { 13972 Promise.resolve().then(() => { 13973 callback(list.getEntries()); 13974 }); 13975 }); 13976 po.observe({ 13977 type, 13978 buffered: true, 13979 ...opts 13980 }); 13981 return po; 13982 } 13983 } catch {} 13984 }; 13985 })))(); 13986} 13987//#endregion 13988//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/runOnce.js 13989var runOnce; 13990function init_runOnce() { 13991 return (init_runOnce = __esmMin((() => { 13992 runOnce = (cb) => { 13993 let called = false; 13994 return () => { 13995 if (!called) { 13996 cb(); 13997 called = true; 13998 } 13999 }; 14000 }; 14001 })))(); 14002} 14003//#endregion 14004//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/whenActivated.js 14005var whenActivated; 14006function init_whenActivated() { 14007 return (init_whenActivated = __esmMin((() => { 14008 init_types(); 14009 whenActivated = (callback) => { 14010 if (WINDOW$3.document?.prerendering) addEventListener("prerenderingchange", () => callback(), true); 14011 else callback(); 14012 }; 14013 })))(); 14014} 14015//#endregion 14016//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/onFCP.js 14017var FCPThresholds, onFCP; 14018function init_onFCP() { 14019 return (init_onFCP = __esmMin((() => { 14020 init_bindReporter(); 14021 init_getActivationStart(); 14022 init_getVisibilityWatcher(); 14023 init_initMetric(); 14024 init_observe(); 14025 init_whenActivated(); 14026 FCPThresholds = [1800, 3e3]; 14027 onFCP = (onReport, opts = {}) => { 14028 whenActivated(() => { 14029 const visibilityWatcher = getVisibilityWatcher(); 14030 const metric = initMetric("FCP"); 14031 let report; 14032 const handleEntries = (entries) => { 14033 for (const entry of entries) if (entry.name === "first-contentful-paint") { 14034 po.disconnect(); 14035 if (entry.startTime < visibilityWatcher.firstHiddenTime) { 14036 metric.value = Math.max(entry.startTime - getActivationStart(), 0); 14037 metric.entries.push(entry); 14038 report(true); 14039 } 14040 } 14041 }; 14042 const po = observe("paint", handleEntries); 14043 if (po) report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges); 14044 }); 14045 }; 14046 })))(); 14047} 14048//#endregion 14049//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/getCLS.js 14050var CLSThresholds, onCLS; 14051function init_getCLS() { 14052 return (init_getCLS = __esmMin((() => { 14053 init_types(); 14054 init_bindReporter(); 14055 init_getVisibilityWatcher(); 14056 init_initMetric(); 14057 init_initUnique(); 14058 init_LayoutShiftManager(); 14059 init_observe(); 14060 init_runOnce(); 14061 init_onFCP(); 14062 CLSThresholds = [.1, .25]; 14063 onCLS = (onReport, opts = {}) => { 14064 onFCP(runOnce(() => { 14065 const metric = initMetric("CLS", 0); 14066 let report; 14067 const visibilityWatcher = getVisibilityWatcher(); 14068 const layoutShiftManager = initUnique(opts, LayoutShiftManager); 14069 const handleEntries = (entries) => {
14070 for (const entry of entries) layoutShiftManager._processEntry(entry); 14071 if (layoutShiftManager._sessionValue > metric.value) { 14072 metric.value = layoutShiftManager._sessionValue; 14073 metric.entries = layoutShiftManager._sessionEntries; 14074 report(); 14075 } 14076 }; 14077 const po = observe("layout-shift", handleEntries); 14078 if (po) { 14079 report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges); 14080 visibilityWatcher.onHidden(() => { 14081 handleEntries(po.takeRecords()); 14082 report(true); 14083 }); 14084 WINDOW$3?.setTimeout?.(report); 14085 } 14086 })); 14087 }; 14088 })))(); 14089} 14090//#endregion 14091//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.js 14092var interactionCountEstimate, minKnownInteractionId, maxKnownInteractionId, updateEstimate, po, getInteractionCount, initInteractionCountPolyfill; 14093function init_interactionCountPolyfill() { 14094 return (init_interactionCountPolyfill = __esmMin((() => { 14095 init_observe(); 14096 interactionCountEstimate = 0; 14097 minKnownInteractionId = Infinity; 14098 maxKnownInteractionId = 0; 14099 updateEstimate = (entries) => { 14100 entries.forEach((e) => { 14101 if (e.interactionId) { 14102 minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId); 14103 maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId); 14104 interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0; 14105 } 14106 }); 14107 }; 14108 getInteractionCount = () => { 14109 return po ? interactionCountEstimate : performance.interactionCount || 0; 14110 }; 14111 initInteractionCountPolyfill = () => { 14112 if ("interactionCount" in performance || po) return; 14113 po = observe("event", updateEstimate, { 14114 type: "event", 14115 buffered: true, 14116 durationThreshold: 0 14117 }); 14118 }; 14119 })))(); 14120} 14121//#endregion 14122//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/InteractionManager.js 14123var MAX_INTERACTIONS_TO_CONSIDER, prevInteractionCount, getInteractionCountForNavigation, InteractionManager; 14124function init_InteractionManager() { 14125 return (init_InteractionManager = __esmMin((() => { 14126 init_interactionCountPolyfill(); 14127 MAX_INTERACTIONS_TO_CONSIDER = 10; 14128 prevInteractionCount = 0; 14129 getInteractionCountForNavigation = () => { 14130 return getInteractionCount() - prevInteractionCount; 14131 }; 14132 InteractionManager = class { 14133 constructor() { 14134 /** 14135 * A list of longest interactions on the page (by latency) sorted so the 14136 * longest one is first. The list is at most MAX_INTERACTIONS_TO_CONSIDER 14137 * long. 14138 */ 14139 this._longestInteractionList = []; 14140 /** 14141 * A mapping of longest interactions by their interaction ID. 14142 * This is used for faster lookup. 14143 */ 14144 this._longestInteractionMap = /* @__PURE__ */ new Map(); 14145 } 14146 _resetInteractions() { 14147 prevInteractionCount = getInteractionCount(); 14148 this._longestInteractionList.length = 0; 14149 this._longestInteractionMap.clear(); 14150 } 14151 /** 14152 * Returns the estimated p98 longest interaction based on the stored 14153 * interaction candidates and the interaction count for the current page. 14154 */ 14155 _estimateP98LongestInteraction() { 14156 const candidateInteractionIndex = Math.min(this._longestInteractionList.length - 1, Math.floor(getInteractionCountForNavigation() / 50)); 14157 return this._longestInteractionList[candidateInteractionIndex]; 14158 } 14159 /** 14160 * Takes a performance entry and adds it to the list of worst interactions 14161 * if its duration is long enough to make it among the worst. If the 14162 * entry is part of an existing interaction, it is merged and the latency 14163 * and entries list is updated as needed. 14164 */ 14165 _processEntry(entry) { 14166 this._onBeforeProcessingEntry?.(entry); 14167 if (!(entry.interactionId || entry.entryType === "first-input")) return; 14168 const minLongestInteraction = this._longestInteractionList.at(-1); 14169 let interaction = this._longestInteractionMap.get(entry.interactionId); 14170 if (interaction || this._longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER || entry.duration > minLongestInteraction._latency) { 14171 if (interaction) { 14172 if (entry.duration > interaction._latency) { 14173 interaction.entries = [entry]; 14174 interaction._latency = entry.duration; 14175 } else if (entry.duration === interaction._latency && entry.startTime === interaction.entries[0].startTime) interaction.entries.push(entry); 14176 } else { 14177 interaction = { 14178 id: entry.interactionId, 14179 entries: [entry], 14180 _latency: entry.duration 14181 }; 14182 this._longestInteractionMap.set(interaction.id, interaction); 14183 this._longestInteractionList.push(interaction); 14184 } 14185 this._longestInteractionList.sort((a, b) => b._latency - a._latency); 14186 if (this._longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) { 14187 const removedInteractions = this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER); 14188 for (const interaction2 of removedInteractions) this._longestInteractionMap.delete(interaction2.id); 14189 } 14190 this._onAfterProcessingINPCandidate?.(interaction); 14191 } 14192 } 14193 }; 14194 })))(); 14195} 14196//#endregion 14197//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/whenIdleOrHidden.js 14198var whenIdleOrHidden; 14199function init_whenIdleOrHidden() { 14200 return (init_whenIdleOrHidden = __esmMin((() => { 14201 init_types(); 14202 init_globalListeners(); 14203 init_runOnce(); 14204 whenIdleOrHidden = (cb) => { 14205 const rIC = WINDOW$3.requestIdleCallback || WINDOW$3.setTimeout; 14206 if (WINDOW$3.document?.visibilityState === "hidden") cb(); 14207 else { 14208 cb = runOnce(cb); 14209 addPageListener("visibilitychange", cb, { 14210 once: true, 14211 capture: true 14212 }); 14213 addPageListener("pagehide", cb, { 14214 once: true, 14215 capture: true 14216 }); 14217 rIC(() => { 14218 cb(); 14219 removePageListener("visibilitychange", cb, { capture: true }); 14220 removePageListener("pagehide", cb, { capture: true }); 14221 }); 14222 } 14223 }; 14224 })))(); 14225} 14226//#endregion 14227//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/getINP.js 14228var INPThresholds, DEFAULT_DURATION_THRESHOLD, onINP; 14229function init_getINP() { 14230 return (init_getINP = __esmMin((() => { 14231 init_bindReporter(); 14232 init_getVisibilityWatcher(); 14233 init_initMetric(); 14234 init_initUnique(); 14235 init_InteractionManager(); 14236 init_observe(); 14237 init_interactionCountPolyfill(); 14238 init_whenActivated(); 14239 init_whenIdleOrHidden(); 14240 INPThresholds = [200, 500]; 14241 DEFAULT_DURATION_THRESHOLD = 40; 14242 onINP = (onReport, opts = {}) => { 14243 if (!(globalThis.PerformanceEventTiming && "interactionId" in PerformanceEventTiming.prototype)) return; 14244 const visibilityWatcher = getVisibilityWatcher(); 14245 whenActivated(() => { 14246 initInteractionCountPolyfill(); 14247 const metric = initMetric("INP"); 14248 let report; 14249 const interactionManager = initUnique(opts, InteractionManager); 14250 const handleEntries = (entries) => { 14251 whenIdleOrHidden(() => {
14252 for (const entry of entries) interactionManager._processEntry(entry); 14253 const inp = interactionManager._estimateP98LongestInteraction(); 14254 if (inp && inp._latency !== metric.value) { 14255 metric.value = inp._latency; 14256 metric.entries = inp.entries; 14257 report(); 14258 } 14259 }); 14260 }; 14261 const po = observe("event", handleEntries, { durationThreshold: opts.durationThreshold ?? DEFAULT_DURATION_THRESHOLD }); 14262 report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges); 14263 if (po) { 14264 po.observe({ 14265 type: "first-input", 14266 buffered: true 14267 }); 14268 visibilityWatcher.onHidden(() => { 14269 handleEntries(po.takeRecords()); 14270 report(true); 14271 }); 14272 } 14273 }); 14274 }; 14275 })))(); 14276} 14277//#endregion 14278//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/LCPEntryManager.js 14279var LCPEntryManager; 14280function init_LCPEntryManager() { 14281 return (init_LCPEntryManager = __esmMin((() => { 14282 LCPEntryManager = class { 14283 _processEntry(entry) { 14284 this._onBeforeProcessingEntry?.(entry); 14285 } 14286 }; 14287 })))(); 14288} 14289//#endregion 14290//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/getLCP.js 14291var LCPThresholds, onLCP; 14292function init_getLCP() { 14293 return (init_getLCP = __esmMin((() => { 14294 init_bindReporter(); 14295 init_getActivationStart(); 14296 init_getVisibilityWatcher(); 14297 init_globalListeners(); 14298 init_initMetric(); 14299 init_initUnique(); 14300 init_LCPEntryManager(); 14301 init_observe(); 14302 init_runOnce(); 14303 init_whenActivated(); 14304 init_whenIdleOrHidden(); 14305 LCPThresholds = [2500, 4e3]; 14306 onLCP = (onReport, opts = {}) => { 14307 whenActivated(() => { 14308 const visibilityWatcher = getVisibilityWatcher(); 14309 const metric = initMetric("LCP"); 14310 let report; 14311 const lcpEntryManager = initUnique(opts, LCPEntryManager); 14312 const handleEntries = (entries) => { 14313 if (!opts.reportAllChanges) entries = entries.slice(-1); 14314 for (const entry of entries) { 14315 lcpEntryManager._processEntry(entry); 14316 if (entry.startTime < visibilityWatcher.firstHiddenTime) { 14317 metric.value = Math.max(entry.startTime - getActivationStart(), 0); 14318 metric.entries = [entry]; 14319 report(); 14320 } 14321 } 14322 }; 14323 const po = observe("largest-contentful-paint", handleEntries); 14324 if (po) { 14325 report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges); 14326 const stopListening = runOnce(() => { 14327 handleEntries(po.takeRecords()); 14328 po.disconnect(); 14329 report(true); 14330 }); 14331 const stopListeningWrapper = (event) => { 14332 if (event.isTrusted) { 14333 whenIdleOrHidden(stopListening); 14334 removePageListener(event.type, stopListeningWrapper, { capture: true }); 14335 } 14336 }; 14337 for (const type of [ 14338 "keydown", 14339 "click", 14340 "visibilitychange" 14341 ]) addPageListener(type, stopListeningWrapper, { capture: true }); 14342 } 14343 }); 14344 }; 14345 })))(); 14346} 14347//#endregion 14348//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/onTTFB.js 14349var TTFBThresholds, whenReady, onTTFB; 14350function init_onTTFB() { 14351 return (init_onTTFB = __esmMin((() => { 14352 init_types(); 14353 init_bindReporter(); 14354 init_getActivationStart(); 14355 init_getNavigationEntry(); 14356 init_initMetric(); 14357 init_whenActivated(); 14358 TTFBThresholds = [800, 1800]; 14359 whenReady = (callback) => { 14360 if (WINDOW$3.document?.prerendering) whenActivated(() => whenReady(callback)); 14361 else if (WINDOW$3.document?.readyState !== "complete") addEventListener("load", () => whenReady(callback), true); 14362 else setTimeout(callback); 14363 }; 14364 onTTFB = (onReport, opts = {}) => { 14365 const metric = initMetric("TTFB"); 14366 const report = bindReporter(onReport, metric, TTFBThresholds, opts.reportAllChanges); 14367 whenReady(() => { 14368 const navigationEntry = getNavigationEntry(); 14369 if (navigationEntry) { 14370 metric.value = Math.max(navigationEntry.responseStart - getActivationStart(), 0); 14371 metric.entries = [navigationEntry]; 14372 report(true); 14373 } 14374 }); 14375 }; 14376 })))(); 14377} 14378//#endregion 14379//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/instrument.js 14380function addClsInstrumentationHandler(callback, stopOnCallback = false) { 14381 return addMetricObserver("cls", callback, instrumentCls, _previousCls, stopOnCallback); 14382} 14383function addLcpInstrumentationHandler(callback, stopOnCallback = false) { 14384 return addMetricObserver("lcp", callback, instrumentLcp, _previousLcp, stopOnCallback); 14385} 14386function addTtfbInstrumentationHandler(callback) { 14387 return addMetricObserver("ttfb", callback, instrumentTtfb, _previousTtfb); 14388} 14389function addInpInstrumentationHandler(callback) { 14390 return addMetricObserver("inp", callback, instrumentInp, _previousInp); 14391} 14392function addPerformanceInstrumentationHandler(type, callback) { 14393 addHandler(type, callback); 14394 if (!instrumented[type]) { 14395 instrumentPerformanceObserver(type); 14396 instrumented[type] = true; 14397 } 14398 return getCleanupCallback(type, callback); 14399} 14400function triggerHandlers(type, data) { 14401 const typeHandlers = handlers$1[type]; 14402 if (!typeHandlers?.length) return; 14403 for (const handler of typeHandlers) try { 14404 handler(data); 14405 } catch (e) { 14406 DEBUG_BUILD$3 && debug$2.error(`Error while triggering instrumentation handler. 14407Type: ${type} 14408Name: ${getFunctionName(handler)} 14409Error:`, e); 14410 } 14411} 14412function instrumentCls() { 14413 return onCLS((metric) => { 14414 triggerHandlers("cls", { metric }); 14415 _previousCls = metric; 14416 }, { reportAllChanges: true }); 14417} 14418function instrumentLcp() { 14419 return onLCP((metric) => { 14420 triggerHandlers("lcp", { metric }); 14421 _previousLcp = metric; 14422 }, { reportAllChanges: true }); 14423} 14424function instrumentTtfb() { 14425 return onTTFB((metric) => { 14426 triggerHandlers("ttfb", { metric }); 14427 _previousTtfb = metric; 14428 }); 14429} 14430function instrumentInp() { 14431 return onINP((metric) => { 14432 triggerHandlers("inp", { metric }); 14433 _previousInp = metric; 14434 }); 14435} 14436function addMetricObserver(type, callback, instrumentFn, previousValue, stopOnCallback = false) { 14437 addHandler(type, callback); 14438 let stopListening; 14439 if (!instrumented[type]) { 14440 stopListening = instrumentFn(); 14441 instrumented[type] = true; 14442 } 14443 if (previousValue) callback({ metric: previousValue }); 14444 return getCleanupCallback(type, callback, stopOnCallback ? stopListening : void 0); 14445} 14446function instrumentPerformanceObserver(type) { 14447 const options = {}; 14448 if (type === "event") options.durationThreshold = 0; 14449 observe(type, (entries) => { 14450 triggerHandlers(type, { entries }); 14451 }, options); 14452} 14453function addHandler(type, handler) { 14454 handlers$1[type] = handlers$1[type] || []; 14455 handlers$1[type].push(handler); 14456} 14457function getCleanupCallback(type, callback, stopListening) { 14458 return () => { 14459 if (stopListening) stopListening(); 14460 const typeHandlers = handlers$1[type]; 14461 if (!typeHandlers) return; 14462 const index = typeHandlers.indexOf(callback); 14463 if (index !== -1) typeHandlers.splice(index, 1); 14464 }; 14465} 14466function isPerformanceEventTiming(entry) { 14467 return "duration" in entry; 14468} 14469var handlers$1, instrumented, _previousCls, _previousLcp, _previousTtfb, _previousInp; 14470function init_instrument() { 14471 return (init_instrument = __esmMin((() => { 14472 init_debug_logger(), init_stacktrace(); 14473 init_debug_build$1(); 14474 init_getCLS(); 14475 init_getINP(); 14476 init_getLCP(); 14477 init_observe(); 14478 init_onTTFB(); 14479 handlers$1 = {}; 14480 instrumented = {}; 14481 })))(); 14482} 14483//#endregion 14484//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/htmlTreeAsString.js 14485function _safeRead(el, prop, arg) { 14486 const fn = accessors[prop]; 14487 if (fn) try {
14488 return fn.call(el, arg); 14489 } catch {} 14490 const val = el[prop]; 14491 return typeof val === "function" ? val.call(el, arg) : val; 14492} 14493function htmlTreeAsString(elem, options = {}) { 14494 if (!elem) return "<unknown>"; 14495 try { 14496 let currentElem = elem; 14497 const MAX_TRAVERSE_HEIGHT = 5; 14498 const out = []; 14499 let height = 0; 14500 let len = 0; 14501 const separator = " > "; 14502 const sepLength = 3; 14503 let nextStr; 14504 const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; 14505 const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH; 14506 while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { 14507 nextStr = _htmlElementAsString(currentElem, keyAttrs); 14508 if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) break; 14509 out.push(nextStr); 14510 len += nextStr.length; 14511 currentElem = _safeRead(currentElem, "parentNode"); 14512 } 14513 return out.reverse().join(separator); 14514 } catch { 14515 return "<unknown>"; 14516 } 14517} 14518function _htmlElementAsString(el, keyAttrs) { 14519 const out = []; 14520 const tagName = _safeRead(el, "tagName"); 14521 if (!tagName) return ""; 14522 if (typeof HTMLElement !== "undefined") { 14523 if (el instanceof HTMLElement) { 14524 const dataset = _safeRead(el, "dataset"); 14525 if (dataset) { 14526 if (dataset["sentryComponent"]) return dataset["sentryComponent"]; 14527 if (dataset["sentryElement"]) return dataset["sentryElement"]; 14528 } 14529 } 14530 } 14531 out.push(tagName.toLowerCase()); 14532 const keyAttrPairs = keyAttrs?.length ? keyAttrs.filter((keyAttr) => _safeRead(el, "getAttribute", keyAttr)).map((keyAttr) => [keyAttr, _safeRead(el, "getAttribute", keyAttr)]) : null; 14533 if (keyAttrPairs?.length) keyAttrPairs.forEach((keyAttrPair) => { 14534 out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); 14535 }); 14536 else { 14537 const id = _safeRead(el, "id"); 14538 if (id) out.push(`#${id}`); 14539 const className = _safeRead(el, "className"); 14540 if (className && isString(className)) { 14541 const classes = className.split(/\s+/); 14542 for (const c of classes) out.push(`.${c}`); 14543 } 14544 } 14545 for (const k of [ 14546 "aria-label", 14547 "type", 14548 "name", 14549 "title", 14550 "alt" 14551 ]) { 14552 const attr = _safeRead(el, "getAttribute", k); 14553 if (attr) out.push(`[${k}="${attr}"]`); 14554 } 14555 return out.join(""); 14556} 14557var DEFAULT_MAX_STRING_LENGTH, accessors; 14558function init_htmlTreeAsString() { 14559 return (init_htmlTreeAsString = __esmMin((() => { 14560 init_is(); 14561 DEFAULT_MAX_STRING_LENGTH = 80; 14562 accessors = {}; 14563 try { 14564 if (typeof Node !== "undefined") accessors.parentNode = Object.getOwnPropertyDescriptor(Node.prototype, "parentNode").get; 14565 if (typeof Element !== "undefined") { 14566 accessors.tagName = Object.getOwnPropertyDescriptor(Element.prototype, "tagName").get; 14567 accessors.id = Object.getOwnPropertyDescriptor(Element.prototype, "id").get; 14568 accessors.className = Object.getOwnPropertyDescriptor(Element.prototype, "className").get; 14569 accessors.getAttribute = Element.prototype.getAttribute; 14570 } 14571 if (typeof HTMLElement !== "undefined") accessors.dataset = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "dataset").get; 14572 } catch {} 14573 })))(); 14574} 14575//#endregion 14576//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/web-vitals/lib/onHidden.js 14577var onHidden; 14578function init_onHidden() { 14579 return (init_onHidden = __esmMin((() => { 14580 init_types(); 14581 init_globalListeners(); 14582 onHidden = (cb) => { 14583 const onHiddenOrPageHide = (event) => { 14584 if (event.type === "pagehide" || WINDOW$3.document?.visibilityState === "hidden") cb(event); 14585 }; 14586 addPageListener("visibilitychange", onHiddenOrPageHide, { 14587 capture: true, 14588 once: true 14589 }); 14590 addPageListener("pagehide", onHiddenOrPageHide, { 14591 capture: true, 14592 once: true 14593 }); 14594 }; 14595 })))(); 14596} 14597//#endregion 14598//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/utils.js 14599function isMeasurementValue(value) { 14600 return typeof value === "number" && isFinite(value); 14601} 14602function startAndEndSpan(parentSpan, startTimeInSeconds, endTime, { ...ctx }) { 14603 const parentStartTime = spanToJSON(parentSpan).start_timestamp; 14604 if (parentStartTime && parentStartTime > startTimeInSeconds) { 14605 if (typeof parentSpan.updateStartTime === "function") parentSpan.updateStartTime(startTimeInSeconds); 14606 } 14607 return withActiveSpan(parentSpan, () => { 14608 const span = startInactiveSpan({ 14609 startTime: startTimeInSeconds, 14610 ...ctx 14611 });
14612 if (span) span.end(endTime); 14613 return span; 14614 }); 14615} 14616function startStandaloneWebVitalSpan(options) { 14617 const client = getClient(); 14618 if (!client) return; 14619 const { name, transaction, attributes: passedAttributes, startTime } = options; 14620 const { release, environment } = client.getOptions(); 14621 const { userInfo } = client.getDataCollectionOptions(); 14622 const replayId = client.getIntegrationByName("Replay")?.getReplayId(); 14623 const scope = getCurrentScope(); 14624 const user = scope.getUser(); 14625 const userDisplay = user !== void 0 ? user.email || user.id || user.ip_address : void 0; 14626 let profileId; 14627 try { 14628 profileId = scope.getScopeData().contexts.profile.profile_id; 14629 } catch {} 14630 return startInactiveSpan({ 14631 name, 14632 attributes: { 14633 release, 14634 environment, 14635 user: userDisplay || void 0, 14636 profile_id: profileId || void 0, 14637 replay_id: replayId || void 0, 14638 transaction, 14639 "user_agent.original": WINDOW$3.navigator?.userAgent, 14640 "client.address": userInfo ? "{{auto}}" : void 0, 14641 ...passedAttributes 14642 }, 14643 startTime, 14644 experimental: { standalone: true } 14645 }); 14646} 14647function getBrowserPerformanceAPI() { 14648 return WINDOW$3.addEventListener && WINDOW$3.performance; 14649} 14650function msToSec(time) { 14651 return time / 1e3; 14652} 14653function extractNetworkProtocol(nextHopProtocol) { 14654 let name = "unknown"; 14655 let version = "unknown"; 14656 let _name = ""; 14657 for (const char of nextHopProtocol) { 14658 if (char === "/") { 14659 [name, version] = nextHopProtocol.split("/"); 14660 break; 14661 } 14662 if (!isNaN(Number(char))) { 14663 name = _name === "h" ? "http" : _name; 14664 version = nextHopProtocol.split(_name)[1]; 14665 break; 14666 } 14667 _name += char; 14668 } 14669 if (_name === nextHopProtocol) name = _name; 14670 return { 14671 name, 14672 version 14673 }; 14674} 14675function supportsWebVital(entryType) { 14676 try { 14677 return PerformanceObserver.supportedEntryTypes.includes(entryType); 14678 } catch { 14679 return false; 14680 } 14681} 14682function listenForWebVitalReportEvents(client, collectorCallback) { 14683 let pageloadSpan; 14684 let collected = false; 14685 function _runCollectorCallbackOnce(event) { 14686 if (!collected && pageloadSpan) collectorCallback(event, pageloadSpan.spanContext().spanId, pageloadSpan); 14687 collected = true; 14688 } 14689 onHidden(() => { 14690 _runCollectorCallbackOnce("pagehide"); 14691 }); 14692 const unsubscribeStartNavigation = client.on("beforeStartNavigationSpan", (_, options) => { 14693 if (!options?.isRedirect) { 14694 _runCollectorCallbackOnce("navigation"); 14695 unsubscribeStartNavigation(); 14696 unsubscribeAfterStartPageLoadSpan(); 14697 } 14698 }); 14699 const unsubscribeAfterStartPageLoadSpan = client.on("afterStartPageLoadSpan", (span) => { 14700 pageloadSpan = span; 14701 unsubscribeAfterStartPageLoadSpan(); 14702 }); 14703} 14704function init_utils$8() { 14705 return (init_utils$8 = __esmMin((() => { 14706 init_spanUtils(), init_trace(), init_currentScopes(); 14707 init_types(); 14708 init_onHidden(); 14709 })))(); 14710} 14711//#endregion 14712//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/cls.js 14713function trackClsAsStandaloneSpan(client) { 14714 let standaloneCLsValue = 0; 14715 let standaloneClsEntry; 14716 if (!supportsWebVital("layout-shift")) return; 14717 const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => { 14718 const entry = metric.entries[metric.entries.length - 1]; 14719 if (!entry) return; 14720 standaloneCLsValue = metric.value; 14721 standaloneClsEntry = entry; 14722 }, true); 14723 listenForWebVitalReportEvents(client, (reportEvent, pageloadSpanId) => { 14724 _sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId, reportEvent); 14725 cleanupClsHandler(); 14726 }); 14727} 14728function _sendStandaloneClsSpan(clsValue, entry, pageloadSpanId, reportEvent) { 14729 DEBUG_BUILD$3 && debug$2.log(`Sending CLS span (${clsValue})`); 14730 const startTime = entry ? msToSec((browserPerformanceTimeOrigin() || 0) + entry.startTime) : timestampInSeconds(); 14731 const routeName = getCurrentScope().getScopeData().transactionName; 14732 const name = entry ? htmlTreeAsString(entry.sources[0]?.node) : "Layout shift"; 14733 const attributes = { 14734 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.cls", 14735 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "ui.webvital.cls", 14736 [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: 0, 14737 "sentry.pageload.span_id": pageloadSpanId, 14738 "sentry.report_event": reportEvent 14739 };
14740 if (entry?.sources) entry.sources.forEach((source, index) => { 14741 attributes[`cls.source.${index + 1}`] = htmlTreeAsString(source.node); 14742 }); 14743 const span = startStandaloneWebVitalSpan({ 14744 name, 14745 transaction: routeName, 14746 attributes, 14747 startTime 14748 }); 14749 if (span) { 14750 span.addEvent("cls", { 14751 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "", 14752 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue 14753 }); 14754 span.end(startTime); 14755 } 14756} 14757function init_cls() { 14758 return (init_cls = __esmMin((() => { 14759 init_debug_logger(), init_time(), init_currentScopes(), init_semanticAttributes(); 14760 init_debug_build$1(); 14761 init_htmlTreeAsString(); 14762 init_instrument(); 14763 init_utils$8(); 14764 })))(); 14765} 14766//#endregion 14767//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/lcp.js 14768function isValidLcpMetric(lcpValue) { 14769 return lcpValue != null && lcpValue > 0 && lcpValue <= 6e4; 14770} 14771function trackLcpAsStandaloneSpan(client) { 14772 let standaloneLcpValue = 0; 14773 let standaloneLcpEntry; 14774 if (!supportsWebVital("largest-contentful-paint")) return; 14775 const cleanupLcpHandler = addLcpInstrumentationHandler(({ metric }) => { 14776 const entry = metric.entries[metric.entries.length - 1]; 14777 if (!entry || !isValidLcpMetric(metric.value)) return; 14778 standaloneLcpValue = metric.value; 14779 standaloneLcpEntry = entry; 14780 }, true); 14781 listenForWebVitalReportEvents(client, (reportEvent, pageloadSpanId) => { 14782 _sendStandaloneLcpSpan(standaloneLcpValue, standaloneLcpEntry, pageloadSpanId, reportEvent); 14783 cleanupLcpHandler(); 14784 }); 14785} 14786function _sendStandaloneLcpSpan(lcpValue, entry, pageloadSpanId, reportEvent) { 14787 if (!isValidLcpMetric(lcpValue)) return; 14788 DEBUG_BUILD$3 && debug$2.log(`Sending LCP span (${lcpValue})`); 14789 const startTime = msToSec((browserPerformanceTimeOrigin() || 0) + (entry?.startTime || 0)); 14790 const routeName = getCurrentScope().getScopeData().transactionName; 14791 const name = entry ? htmlTreeAsString(entry.element) : "Largest contentful paint"; 14792 const attributes = { 14793 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.lcp", 14794 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "ui.webvital.lcp", 14795 [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: 0, 14796 "sentry.pageload.span_id": pageloadSpanId, 14797 "sentry.report_event": reportEvent 14798 }; 14799 if (entry) { 14800 entry.element && (attributes["lcp.element"] = htmlTreeAsString(entry.element)); 14801 entry.id && (attributes["lcp.id"] = entry.id); 14802 entry.url && (attributes["lcp.url"] = entry.url); 14803 entry.loadTime != null && (attributes["lcp.loadTime"] = entry.loadTime); 14804 entry.renderTime != null && (attributes["lcp.renderTime"] = entry.renderTime); 14805 entry.size != null && (attributes["lcp.size"] = entry.size); 14806 } 14807 const span = startStandaloneWebVitalSpan({ 14808 name, 14809 transaction: routeName, 14810 attributes, 14811 startTime 14812 }); 14813 if (span) { 14814 span.addEvent("lcp", { 14815 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "millisecond", 14816 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: lcpValue 14817 }); 14818 span.end(startTime); 14819 } 14820} 14821function init_lcp() { 14822 return (init_lcp = __esmMin((() => { 14823 init_debug_logger(), init_time(), init_currentScopes(), init_semanticAttributes(); 14824 init_debug_build$1(); 14825 init_htmlTreeAsString(); 14826 init_instrument(); 14827 init_utils$8(); 14828 })))(); 14829} 14830//#endregion 14831//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/resourceTiming.js 14832function getAbsoluteTime$1(time) { 14833 return time ? ((browserPerformanceTimeOrigin() || performance.timeOrigin) + time) / 1e3 : time; 14834} 14835function resourceTimingToSpanAttributes(resourceTiming) { 14836 const timingSpanData = {}; 14837 if (resourceTiming.nextHopProtocol != void 0) { 14838 const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol); 14839 timingSpanData["network.protocol.version"] = version; 14840 timingSpanData["network.protocol.name"] = name; 14841 } 14842 if (!(browserPerformanceTimeOrigin() || getBrowserPerformanceAPI()?.timeOrigin)) return timingSpanData; 14843 return dropUndefinedKeysFromObject({ 14844 ...timingSpanData, 14845 "http.request.redirect_start": getAbsoluteTime$1(resourceTiming.redirectStart), 14846 "http.request.redirect_end": getAbsoluteTime$1(resourceTiming.redirectEnd), 14847 "http.request.worker_start": getAbsoluteTime$1(resourceTiming.workerStart), 14848 "http.request.fetch_start": getAbsoluteTime$1(resourceTiming.fetchStart), 14849 "http.request.domain_lookup_start": getAbsoluteTime$1(resourceTiming.domainLookupStart), 14850 "http.request.domain_lookup_end": getAbsoluteTime$1(resourceTiming.domainLookupEnd), 14851 "http.request.connect_start": getAbsoluteTime$1(resourceTiming.connectStart), 14852 "http.request.secure_connection_start": getAbsoluteTime$1(resourceTiming.secureConnectionStart), 14853 "http.request.connection_end": getAbsoluteTime$1(resourceTiming.connectEnd), 14854 "http.request.request_start": getAbsoluteTime$1(resourceTiming.requestStart), 14855 "http.request.response_start": getAbsoluteTime$1(resourceTiming.responseStart), 14856 "http.request.response_end": getAbsoluteTime$1(resourceTiming.responseEnd), 14857 "http.request.time_to_first_byte": resourceTiming.responseStart != null ? resourceTiming.responseStart / 1e3 : void 0 14858 }); 14859} 14860function dropUndefinedKeysFromObject(attrs) { 14861 return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null)); 14862} 14863function init_resourceTiming() { 14864 return (init_resourceTiming = __esmMin((() => { 14865 init_time(); 14866 init_utils$8(); 14867 })))(); 14868} 14869//#endregion 14870//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/browserMetrics.js 14871function startTrackingWebVitals({ recordClsStandaloneSpans, recordLcpStandaloneSpans, client }) { 14872 const performance = getBrowserPerformanceAPI(); 14873 if (performance && browserPerformanceTimeOrigin()) { 14874 if (performance.mark) WINDOW$3.performance.mark("sentry-tracing-init");
14875 const lcpCleanupCallback = recordLcpStandaloneSpans ? trackLcpAsStandaloneSpan(client) : recordLcpStandaloneSpans === false ? _trackLCP() : void 0; 14876 const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan(client) : recordClsStandaloneSpans === false ? _trackCLS() : void 0; 14877 const ttfbCleanupCallback = _trackTtfb(); 14878 const fpFcpCleanupCallback = _trackFpFcp(); 14879 return () => { 14880 ttfbCleanupCallback(); 14881 fpFcpCleanupCallback(); 14882 lcpCleanupCallback?.(); 14883 clsCleanupCallback?.(); 14884 }; 14885 } 14886 return () => void 0; 14887} 14888function startTrackingLongTasks() { 14889 addPerformanceInstrumentationHandler("longtask", ({ entries }) => { 14890 const parent = getActiveSpan(); 14891 if (!parent) return; 14892 const { op: parentOp, start_timestamp: parentStartTimestamp } = spanToJSON(parent); 14893 for (const entry of entries) { 14894 const startTime = msToSec(browserPerformanceTimeOrigin() + entry.startTime); 14895 const duration = msToSec(entry.duration); 14896 if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) continue; 14897 startAndEndSpan(parent, startTime, startTime + duration, { 14898 name: "Main UI thread blocked", 14899 op: "ui.long-task", 14900 attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } 14901 }); 14902 } 14903 }); 14904} 14905function startTrackingLongAnimationFrames() { 14906 new PerformanceObserver((list) => { 14907 const parent = getActiveSpan(); 14908 if (!parent) return; 14909 for (const entry of list.getEntries()) { 14910 if (!entry.scripts[0]) continue; 14911 const startTime = msToSec(browserPerformanceTimeOrigin() + entry.startTime); 14912 const { start_timestamp: parentStartTimestamp, op: parentOp } = spanToJSON(parent); 14913 if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) continue; 14914 const duration = msToSec(entry.duration); 14915 const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" }; 14916 const { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = entry.scripts[0]; 14917 attributes["browser.script.invoker"] = invoker; 14918 attributes["browser.script.invoker_type"] = invokerType; 14919 if (sourceURL) attributes["code.filepath"] = sourceURL; 14920 if (sourceFunctionName) attributes["code.function"] = sourceFunctionName; 14921 if (sourceCharPosition !== -1) attributes["browser.script.source_char_position"] = sourceCharPosition; 14922 startAndEndSpan(parent, startTime, startTime + duration, { 14923 name: "Main UI thread blocked", 14924 op: "ui.long-animation-frame", 14925 attributes 14926 }); 14927 } 14928 }).observe({ 14929 type: "long-animation-frame", 14930 buffered: true 14931 }); 14932} 14933function startTrackingInteractions() { 14934 addPerformanceInstrumentationHandler("event", ({ entries }) => { 14935 const parent = getActiveSpan(); 14936 if (!parent) return; 14937 for (const entry of entries) if (entry.name === "click") { 14938 const startTime = msToSec(browserPerformanceTimeOrigin() + entry.startTime); 14939 const duration = msToSec(entry.duration); 14940 const spanOptions = { 14941 name: htmlTreeAsString(entry.target), 14942 op: `ui.interaction.${entry.name}`, 14943 startTime, 14944 attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } 14945 }; 14946 const componentName = getComponentName(entry.target); 14947 if (componentName) spanOptions.attributes["ui.component_name"] = componentName; 14948 startAndEndSpan(parent, startTime, startTime + duration, spanOptions); 14949 } 14950 }); 14951} 14952function _trackCLS() { 14953 return addClsInstrumentationHandler(({ metric }) => { 14954 const entry = metric.entries[metric.entries.length - 1]; 14955 if (!entry) return; 14956 _measurements["cls"] = { 14957 value: metric.value, 14958 unit: "" 14959 }; 14960 _clsEntry = entry; 14961 }, true); 14962} 14963function _trackLCP() { 14964 return addLcpInstrumentationHandler(({ metric }) => { 14965 const entry = metric.entries[metric.entries.length - 1]; 14966 if (!entry || !isValidLcpMetric(metric.value)) return; 14967 _measurements["lcp"] = { 14968 value: metric.value, 14969 unit: "millisecond" 14970 }; 14971 _lcpEntry = entry; 14972 }, true); 14973} 14974function _trackTtfb() { 14975 return addTtfbInstrumentationHandler(({ metric }) => { 14976 if (!metric.entries[metric.entries.length - 1]) return; 14977 _measurements["ttfb"] = { 14978 value: metric.value, 14979 unit: "millisecond" 14980 }; 14981 }); 14982} 14983function _trackFpFcp() { 14984 return addPerformanceInstrumentationHandler("paint", ({ entries }) => { 14985 const firstHidden = getVisibilityWatcher();
14986 for (const entry of entries) { 14987 const shouldRecord = entry.startTime < firstHidden.firstHiddenTime; 14988 if (entry.name === "first-paint" && shouldRecord) _measurements["fp"] = { 14989 value: entry.startTime, 14990 unit: "millisecond" 14991 }; 14992 if (entry.name === "first-contentful-paint" && shouldRecord) _measurements["fcp"] = { 14993 value: entry.startTime, 14994 unit: "millisecond" 14995 }; 14996 } 14997 }); 14998} 14999function addPerformanceEntries(span, options) { 15000 const performance = getBrowserPerformanceAPI(); 15001 const origin = browserPerformanceTimeOrigin(); 15002 if (!performance?.getEntries || !origin) return; 15003 const { spanStreamingEnabled, ignorePerformanceApiSpans, ignoreResourceSpans } = options; 15004 const timeOrigin = msToSec(origin); 15005 const performanceEntries = performance.getEntries(); 15006 const { op, start_timestamp: transactionStartTime } = spanToJSON(span); 15007 performanceEntries.slice(_performanceCursor).forEach((entry) => { 15008 const startTime = msToSec(entry.startTime); 15009 const duration = msToSec(Math.max(0, entry.duration)); 15010 if (op === "navigation" && transactionStartTime && timeOrigin + startTime < transactionStartTime) return; 15011 switch (entry.entryType) { 15012 case "navigation": 15013 _addNavigationSpans(span, entry, timeOrigin); 15014 break; 15015 case "mark": 15016 case "paint": 15017 case "measure": 15018 _addMeasureSpans(span, entry, startTime, duration, timeOrigin, ignorePerformanceApiSpans); 15019 break; 15020 case "resource": _addResourceSpans(span, entry, entry.name, startTime, duration, timeOrigin, ignoreResourceSpans); 15021 } 15022 }); 15023 _performanceCursor = Math.max(performanceEntries.length - 1, 0); 15024 _trackNavigator(span, spanStreamingEnabled); 15025} 15026function addWebVitalsToSpan(span, options) { 15027 const origin = browserPerformanceTimeOrigin(); 15028 if (!getBrowserPerformanceAPI()?.getEntries || !origin) { 15029 resetWebVitalState(); 15030 return; 15031 } 15032 const { spanStreamingEnabled, recordClsOnPageloadSpan, recordLcpOnPageloadSpan } = options; 15033 const timeOrigin = msToSec(origin); 15034 if (spanToJSON(span).op === "pageload") { 15035 _addTtfbRequestTimeToMeasurements(_measurements); 15036 if (spanStreamingEnabled) { 15037 const setAttr = (shortWebVitalName, value, customAttrName) => { 15038 const attrKey = customAttrName ?? `browser.web_vital.${shortWebVitalName}.value`; 15039 span.setAttribute(attrKey, value); 15040 DEBUG_BUILD$3 && debug$2.log("Setting web vital attribute", { [attrKey]: value }, "on pageload span"); 15041 }; 15042 [ 15043 "ttfb", 15044 "fp", 15045 "fcp" 15046 ].forEach((measurementName) => { 15047 if (_measurements[measurementName]) setAttr(measurementName, _measurements[measurementName].value); 15048 }); 15049 if (_measurements["ttfb.requestTime"]) setAttr("ttfb.requestTime", _measurements["ttfb.requestTime"].value, "browser.web_vital.ttfb.request_time"); 15050 } else { 15051 if (!recordClsOnPageloadSpan) delete _measurements.cls; 15052 if (!recordLcpOnPageloadSpan) delete _measurements.lcp; 15053 Object.entries(_measurements).forEach(([measurementName, measurement]) => { 15054 setMeasurement(measurementName, measurement.value, measurement.unit, span); 15055 }); 15056 _setWebVitalAttributes(span, options); 15057 } 15058 span.setAttribute(spanStreamingEnabled ? "browser.performance.time_origin" : "performance.timeOrigin", timeOrigin); 15059 span.setAttribute(spanStreamingEnabled ? "browser.performance.navigation.activation_start" : "performance.activationStart", getActivationStart()); 15060 } 15061 resetWebVitalState(); 15062} 15063function resetWebVitalState() { 15064 _lcpEntry = void 0; 15065 _clsEntry = void 0; 15066 _measurements = {}; 15067} 15068function isReact19MeasureEntry(entry) { 15069 if (entry?.entryType !== "measure") return; 15070 try { 15071 return entry.detail.devtools.track === "Components ⚛"; 15072 } catch { 15073 return; 15074 } 15075} 15076function _addMeasureSpans(span, entry, startTime, duration, timeOrigin, ignorePerformanceApiSpans) { 15077 if (isReact19MeasureEntry(entry)) return; 15078 if (["mark", "measure"].includes(entry.entryType) && stringMatchesSomePattern(entry.name, ignorePerformanceApiSpans)) return; 15079 const navEntry = getNavigationEntry(false); 15080 const requestTime = msToSec(navEntry ? navEntry.requestStart : 0); 15081 const measureStartTimestamp = timeOrigin + Math.max(startTime, requestTime); 15082 const startTimeStamp = timeOrigin + startTime; 15083 const measureEndTimestamp = startTimeStamp + duration; 15084 const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics" }; 15085 if (measureStartTimestamp !== startTimeStamp) { 15086 attributes["sentry.browser.measure_happened_before_request"] = true; 15087 attributes["sentry.browser.measure_start_time"] = measureStartTimestamp; 15088 } 15089 _addDetailToSpanAttributes(attributes, entry); 15090 if (measureStartTimestamp <= measureEndTimestamp) startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, { 15091 name: entry.name, 15092 op: entry.entryType, 15093 attributes 15094 }); 15095} 15096function _addDetailToSpanAttributes(attributes, performanceMeasure) { 15097 try { 15098 const detail = performanceMeasure.detail; 15099 if (!detail) return; 15100 if (typeof detail === "object") { 15101 for (const [key, value] of Object.entries(detail)) if (value && isPrimitive(value)) attributes[`sentry.browser.measure.detail.${key}`] = value; 15102 else if (value !== void 0) try { 15103 attributes[`sentry.browser.measure.detail.${key}`] = JSON.stringify(value); 15104 } catch {} 15105 return; 15106 } 15107 if (isPrimitive(detail)) { 15108 attributes["sentry.browser.measure.detail"] = detail; 15109 return; 15110 } 15111 try { 15112 attributes["sentry.browser.measure.detail"] = JSON.stringify(detail); 15113 } catch {} 15114 } catch {} 15115} 15116function _addNavigationSpans(span, entry, timeOrigin) { 15117 [ 15118 "unloadEvent", 15119 "redirect", 15120 "domContentLoadedEvent", 15121 "loadEvent", 15122 "connect" 15123 ].forEach((event) => { 15124 _addPerformanceNavigationTiming(span, entry, event, timeOrigin); 15125 }); 15126 _addPerformanceNavigationTiming(span, entry, "secureConnection", timeOrigin, "TLS/SSL"); 15127 _addPerformanceNavigationTiming(span, entry, "fetch", timeOrigin, "cache"); 15128 _addPerformanceNavigationTiming(span, entry, "domainLookup", timeOrigin, "DNS"); 15129 _addRequest(span, entry, timeOrigin); 15130} 15131function _addPerformanceNavigationTiming(span, entry, event, timeOrigin, name = event) { 15132 const end = entry[_getEndPropertyNameForNavigationTiming(event)]; 15133 const start = entry[`${event}Start`]; 15134 if (!start || !end) return; 15135 startAndEndSpan(span, timeOrigin + msToSec(start), timeOrigin + msToSec(end), { 15136 op: `browser.${name}`, 15137 name: entry.name, 15138 attributes: { 15139 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics", 15140 ...event === "redirect" && entry.redirectCount != null ? { "http.redirect_count": entry.redirectCount } : {} 15141 } 15142 }); 15143} 15144function _getEndPropertyNameForNavigationTiming(event) { 15145 if (event === "secureConnection") return "connectEnd"; 15146 if (event === "fetch") return "domainLookupStart"; 15147 return `${event}End`; 15148} 15149function _addRequest(span, entry, timeOrigin) { 15150 const requestStartTimestamp = timeOrigin + msToSec(entry.requestStart); 15151 const responseEndTimestamp = timeOrigin + msToSec(entry.responseEnd); 15152 const responseStartTimestamp = timeOrigin + msToSec(entry.responseStart); 15153 if (entry.responseEnd) { 15154 startAndEndSpan(span, requestStartTimestamp, responseEndTimestamp, { 15155 op: "browser.request", 15156 name: entry.name, 15157 attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } 15158 }); 15159 startAndEndSpan(span, responseStartTimestamp, responseEndTimestamp, { 15160 op: "browser.response", 15161 name: entry.name, 15162 attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } 15163 }); 15164 } 15165} 15166function _addResourceSpans(span, entry, resourceUrl, startTime, duration, timeOrigin, ignoredResourceSpanOps) { 15167 if (entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch") return; 15168 const op = entry.initiatorType ? `resource.${entry.initiatorType}` : "resource.other"; 15169 if (ignoredResourceSpanOps?.includes(op)) return; 15170 const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics" }; 15171 const parsedUrl = parseUrl(resourceUrl); 15172 if (parsedUrl.protocol) attributes["url.scheme"] = parsedUrl.protocol.split(":").pop(); 15173 if (parsedUrl.host) attributes["server.address"] = parsedUrl.host; 15174 attributes["url.same_origin"] = resourceUrl.includes(WINDOW$3.location.origin); 15175 attributes[Yu] = resourceUrl; 15176 _setResourceRequestAttributes(entry, attributes, [ 15177 ["responseStatus", "http.response.status_code"], 15178 ["transferSize", "http.response_transfer_size"], 15179 ["encodedBodySize", "http.response_content_length"], 15180 ["decodedBodySize", "http.decoded_response_content_length"], 15181 ["renderBlockingStatus", "resource.render_blocking_status"], 15182 ["deliveryType", "http.response_delivery_type"] 15183 ]); 15184 const attributesWithResourceTiming = { 15185 ...attributes, 15186 ...resourceTimingToSpanAttributes(entry) 15187 }; 15188 const startTimestamp = timeOrigin + startTime; 15189 startAndEndSpan(span, startTimestamp, startTimestamp + duration, { 15190 name: resourceUrl.replace(WINDOW$3.location.origin, ""), 15191 op, 15192 attributes: attributesWithResourceTiming 15193 }); 15194} 15195function _trackNavigator(span, spanStreamingEnabled) { 15196 const navigator = WINDOW$3.navigator; 15197 if (!navigator) return; 15198 const connection = navigator.connection; 15199 if (connection) { 15200 if (connection.effectiveType) span.setAttribute(spanStreamingEnabled ? "network.connection.effective_type" : "effectiveConnectionType", connection.effectiveType); 15201 if (connection.type) span.setAttribute(spanStreamingEnabled ? "network.connection.type" : "connectionType", connection.type); 15202 if (isMeasurementValue(connection.rtt)) { 15203 if (spanStreamingEnabled) span.setAttribute("network.connection.rtt", connection.rtt);
15204 else if (spanToJSON(span).op === "pageload") setMeasurement("connection.rtt", connection.rtt, "millisecond"); 15205 } 15206 } 15207 if (isMeasurementValue(navigator.deviceMemory)) { 15208 if (spanStreamingEnabled) span.setAttribute("device.memory.estimated_capacity", navigator.deviceMemory); 15209 else span.setAttribute("deviceMemory", `${navigator.deviceMemory} GB`); 15210 } 15211 if (isMeasurementValue(navigator.hardwareConcurrency)) { 15212 if (spanStreamingEnabled) span.setAttribute("device.processor_count", navigator.hardwareConcurrency); 15213 else span.setAttribute("hardwareConcurrency", String(navigator.hardwareConcurrency)); 15214 } 15215} 15216function _setWebVitalAttributes(span, options) { 15217 if (_lcpEntry && options.recordLcpOnPageloadSpan) { 15218 if (_lcpEntry.element) span.setAttribute("lcp.element", htmlTreeAsString(_lcpEntry.element)); 15219 if (_lcpEntry.id) span.setAttribute("lcp.id", _lcpEntry.id); 15220 if (_lcpEntry.url) span.setAttribute("lcp.url", _lcpEntry.url.trim().slice(0, 200)); 15221 if (_lcpEntry.loadTime != null) span.setAttribute("lcp.loadTime", _lcpEntry.loadTime); 15222 if (_lcpEntry.renderTime != null) span.setAttribute("lcp.renderTime", _lcpEntry.renderTime); 15223 span.setAttribute("lcp.size", _lcpEntry.size); 15224 } 15225 if (_clsEntry?.sources && options.recordClsOnPageloadSpan) _clsEntry.sources.forEach((source, index) => span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node))); 15226} 15227function _setResourceRequestAttributes(entry, attributes, properties) { 15228 properties.forEach(([entryKey, attributeKey]) => { 15229 const entryVal = entry[entryKey]; 15230 if (entryVal != null && (typeof entryVal === "number" && entryVal < MAX_INT_AS_BYTES || typeof entryVal === "string")) attributes[attributeKey] = entryVal; 15231 }); 15232} 15233function _addTtfbRequestTimeToMeasurements(_measurements2) { 15234 const navEntry = getNavigationEntry(false); 15235 if (!navEntry) return; 15236 const { responseStart, requestStart } = navEntry; 15237 if (requestStart <= responseStart) _measurements2["ttfb.requestTime"] = { 15238 value: responseStart - requestStart, 15239 unit: "millisecond" 15240 }; 15241} 15242var MAX_INT_AS_BYTES, _performanceCursor, _measurements, _lcpEntry, _clsEntry; 15243function init_browserMetrics() { 15244 return (init_browserMetrics = __esmMin((() => { 15245 init_time(), init_spanUtils(), init_measurement(), init_url(), init_string(), init_debug_logger(), init_semanticAttributes(), init_is(), init_browser(); 15246 init_htmlTreeAsString(); 15247 init_types(); 15248 init_cls(); 15249 init_instrument(); 15250 init_lcp(); 15251 init_resourceTiming(); 15252 init_utils$8(); 15253 init_getActivationStart(); 15254 init_getNavigationEntry(); 15255 init_getVisibilityWatcher(); 15256 init_debug_build$1(); 15257 init_attributes$1(); 15258 MAX_INT_AS_BYTES = 2147483647; 15259 _performanceCursor = 0; 15260 _measurements = {}; 15261 })))(); 15262} 15263//#endregion 15264//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/elementTiming.js 15265var INTEGRATION_NAME$13, _elementTimingIntegration, elementTimingIntegration; 15266function init_elementTiming() { 15267 return (init_elementTiming = __esmMin((() => { 15268 init_integration(), init_time(), init_public_api$1(); 15269 init_instrument(); 15270 init_utils$8(); 15271 INTEGRATION_NAME$13 = "ElementTiming"; 15272 _elementTimingIntegration = (() => { 15273 return { 15274 name: INTEGRATION_NAME$13, 15275 setup() { 15276 if (!getBrowserPerformanceAPI() || !browserPerformanceTimeOrigin()) return; 15277 addPerformanceInstrumentationHandler("element", ({ entries }) => { 15278 for (const entry of entries) { 15279 const elementEntry = entry; 15280 if (!elementEntry.identifier) continue; 15281 const identifier = elementEntry.identifier; 15282 const paintType = elementEntry.name; 15283 const renderTime = elementEntry.renderTime; 15284 const loadTime = elementEntry.loadTime; 15285 const metricAttributes = { 15286 "sentry.origin": "auto.ui.browser.element_timing", 15287 "ui.element.identifier": identifier 15288 }; 15289 if (paintType) metricAttributes["ui.element.paint_type"] = paintType; 15290 if (elementEntry.id) metricAttributes["ui.element.id"] = elementEntry.id; 15291 if (elementEntry.element) metricAttributes["ui.element.type"] = elementEntry.element.tagName.toLowerCase(); 15292 if (elementEntry.url) metricAttributes["ui.element.url"] = elementEntry.url;
15293 if (elementEntry.naturalWidth) metricAttributes["ui.element.width"] = elementEntry.naturalWidth; 15294 if (elementEntry.naturalHeight) metricAttributes["ui.element.height"] = elementEntry.naturalHeight; 15295 if (renderTime > 0) distribution(`ui.element.render_time`, renderTime, { 15296 unit: "millisecond", 15297 attributes: metricAttributes 15298 }); 15299 if (loadTime > 0) distribution(`ui.element.load_time`, loadTime, { 15300 unit: "millisecond", 15301 attributes: metricAttributes 15302 }); 15303 } 15304 }); 15305 } 15306 }; 15307 }); 15308 elementTimingIntegration = defineIntegration(_elementTimingIntegration); 15309 })))(); 15310} 15311//#endregion 15312//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/inp.js 15313function startTrackingINP() { 15314 if (getBrowserPerformanceAPI() && browserPerformanceTimeOrigin()) { 15315 const inpCallback = _trackINP(); 15316 return () => { 15317 inpCallback(); 15318 }; 15319 } 15320 return () => void 0; 15321} 15322function _trackINP() { 15323 return addInpInstrumentationHandler(_onInp); 15324} 15325function getCachedInteractionContext(interactionId) { 15326 return interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : void 0; 15327} 15328function registerInpInteractionListener() { 15329 const interactionEvents = Object.keys(INP_ENTRY_MAP); 15330 if (isBrowser()) interactionEvents.forEach((eventType) => { 15331 WINDOW$3.addEventListener(eventType, captureElementFromEvent, { 15332 capture: true, 15333 passive: true 15334 }); 15335 }); 15336 function captureElementFromEvent(event) { 15337 const target = event.target; 15338 if (!target) return; 15339 const elementName = htmlTreeAsString(target); 15340 const timestamp = Math.round(event.timeStamp); 15341 ELEMENT_NAME_TIMESTAMP_MAP.set(timestamp, elementName); 15342 if (ELEMENT_NAME_TIMESTAMP_MAP.size > 50) { 15343 const firstKey = ELEMENT_NAME_TIMESTAMP_MAP.keys().next().value; 15344 if (firstKey !== void 0) ELEMENT_NAME_TIMESTAMP_MAP.delete(firstKey); 15345 } 15346 } 15347 function resolveElementNameFromEntry(entry) { 15348 const timestamp = Math.round(entry.startTime); 15349 let elementName = ELEMENT_NAME_TIMESTAMP_MAP.get(timestamp); 15350 if (!elementName) for (let offset = -5; offset <= 5; offset++) { 15351 const nearbyName = ELEMENT_NAME_TIMESTAMP_MAP.get(timestamp + offset); 15352 if (nearbyName) { 15353 elementName = nearbyName; 15354 break; 15355 } 15356 } 15357 return elementName || "<unknown>"; 15358 } 15359 const handleEntries = ({ entries }) => { 15360 const activeSpan = getActiveSpan(); 15361 const activeRootSpan = activeSpan && getRootSpan(activeSpan); 15362 entries.forEach((entry) => { 15363 if (!isPerformanceEventTiming(entry)) return; 15364 const interactionId = entry.interactionId; 15365 if (interactionId == null) return; 15366 if (INTERACTIONS_SPAN_MAP.has(interactionId)) return; 15367 const elementName = entry.target ? htmlTreeAsString(entry.target) : resolveElementNameFromEntry(entry); 15368 if (LAST_INTERACTIONS.length > 10) { 15369 const last = LAST_INTERACTIONS.shift(); 15370 INTERACTIONS_SPAN_MAP.delete(last); 15371 } 15372 LAST_INTERACTIONS.push(interactionId); 15373 INTERACTIONS_SPAN_MAP.set(interactionId, { 15374 span: activeRootSpan, 15375 elementName 15376 }); 15377 }); 15378 }; 15379 addPerformanceInstrumentationHandler("event", handleEntries); 15380 addPerformanceInstrumentationHandler("first-input", handleEntries); 15381} 15382var LAST_INTERACTIONS, INTERACTIONS_SPAN_MAP, ELEMENT_NAME_TIMESTAMP_MAP, INP_ENTRY_MAP, _onInp; 15383function init_inp() { 15384 return (init_inp = __esmMin((() => { 15385 init_isBrowser(), init_time(), init_spanUtils(), init_currentScopes(), init_semanticAttributes(); 15386 init_htmlTreeAsString(); 15387 init_types(); 15388 init_instrument(); 15389 init_utils$8(); 15390 LAST_INTERACTIONS = []; 15391 INTERACTIONS_SPAN_MAP = /* @__PURE__ */ new Map(); 15392 ELEMENT_NAME_TIMESTAMP_MAP = /* @__PURE__ */ new Map(); 15393 INP_ENTRY_MAP = { 15394 click: "click", 15395 pointerdown: "click", 15396 pointerup: "click", 15397 mousedown: "click", 15398 mouseup: "click", 15399 touchstart: "click", 15400 touchend: "click", 15401 mouseover: "hover", 15402 mouseout: "hover", 15403 mouseenter: "hover", 15404 mouseleave: "hover", 15405 pointerover: "hover", 15406 pointerout: "hover", 15407 pointerenter: "hover", 15408 pointerleave: "hover", 15409 dragstart: "drag", 15410 dragend: "drag", 15411 drag: "drag", 15412 dragenter: "drag", 15413 dragleave: "drag", 15414 dragover: "drag", 15415 drop: "drag", 15416 keydown: "press", 15417 keyup: "press", 15418 keypress: "press",
15419 input: "press" 15420 }; 15421 _onInp = ({ metric }) => { 15422 if (metric.value == void 0) return; 15423 const duration = msToSec(metric.value); 15424 if (duration > 60) return; 15425 const entry = metric.entries.find((entry2) => entry2.duration === metric.value && INP_ENTRY_MAP[entry2.name]); 15426 if (!entry) return; 15427 const { interactionId } = entry; 15428 const interactionType = INP_ENTRY_MAP[entry.name]; 15429 const startTime = msToSec(browserPerformanceTimeOrigin() + entry.startTime); 15430 const activeSpan = getActiveSpan(); 15431 const rootSpan = activeSpan ? getRootSpan(activeSpan) : void 0; 15432 const cachedInteractionContext = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : void 0; 15433 const spanToUse = cachedInteractionContext?.span || rootSpan; 15434 const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope().getScopeData().transactionName; 15435 const span = startStandaloneWebVitalSpan({ 15436 name: cachedInteractionContext?.elementName || htmlTreeAsString(entry.target), 15437 transaction: routeName, 15438 attributes: { 15439 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.inp", 15440 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`, 15441 [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration 15442 }, 15443 startTime 15444 }); 15445 if (span) { 15446 span.addEvent("inp", { 15447 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "millisecond", 15448 [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value 15449 }); 15450 span.end(startTime + duration); 15451 } 15452 }; 15453 })))(); 15454} 15455//#endregion 15456//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/metrics/webVitalSpans.js 15457function _emitWebVitalSpan(options) { 15458 const { name, op, origin, metricName, value, attributes: passedAttributes, parentSpan, reportEvent, startTime, endTime } = options; 15459 const routeName = getCurrentScope().getScopeData().transactionName; 15460 const attributes = { 15461 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin, 15462 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op, 15463 [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: 0, 15464 [`browser.web_vital.${metricName}.value`]: value, 15465 [Xc]: routeName, 15466 [Lc]: routeName, 15467 "user_agent.original": WINDOW$3.navigator?.userAgent, 15468 ...passedAttributes 15469 }; 15470 if (parentSpan && spanToStreamedSpanJSON(parentSpan).attributes?.["sentry.op"] === "pageload") attributes["sentry.pageload.span_id"] = parentSpan.spanContext().spanId; 15471 if (reportEvent) attributes[`browser.web_vital.${metricName}.report_event`] = reportEvent; 15472 const span = startInactiveSpan({ 15473 name, 15474 attributes, 15475 startTime, 15476 parentSpan 15477 }); 15478 if (span) span.end(endTime ?? startTime); 15479} 15480function trackLcpAsSpan(client) { 15481 let lcpValue = 0; 15482 let lcpEntry; 15483 if (!supportsWebVital("largest-contentful-paint")) return; 15484 const cleanupLcpHandler = addLcpInstrumentationHandler(({ metric }) => { 15485 const entry = metric.entries[metric.entries.length - 1]; 15486 if (!entry || !isValidLcpMetric(metric.value)) return; 15487 lcpValue = metric.value; 15488 lcpEntry = entry; 15489 }, true); 15490 listenForWebVitalReportEvents(client, (reportEvent, _, pageloadSpan) => { 15491 _sendLcpSpan(lcpValue, lcpEntry, pageloadSpan, reportEvent); 15492 cleanupLcpHandler(); 15493 }); 15494} 15495function _sendLcpSpan(lcpValue, entry, pageloadSpan, reportEvent) { 15496 if (!isValidLcpMetric(lcpValue)) return; 15497 DEBUG_BUILD$3 && debug$2.log(`Sending LCP span (${lcpValue})`); 15498 const performanceTimeOrigin = browserPerformanceTimeOrigin() || 0; 15499 const timeOrigin = msToSec(performanceTimeOrigin); 15500 const endTime = msToSec(performanceTimeOrigin + (entry?.startTime || 0)); 15501 const name = entry ? htmlTreeAsString(entry.element) : "Largest contentful paint"; 15502 const attributes = {}; 15503 entry?.element && (attributes["browser.web_vital.lcp.element"] = htmlTreeAsString(entry.element)); 15504 entry?.id && (attributes["browser.web_vital.lcp.id"] = entry.id); 15505 entry?.url && (attributes["browser.web_vital.lcp.url"] = entry.url); 15506 entry?.loadTime != null && (attributes["browser.web_vital.lcp.load_time"] = entry.loadTime); 15507 entry?.renderTime != null && (attributes["browser.web_vital.lcp.render_time"] = entry.renderTime); 15508 entry?.size != null && (attributes["browser.web_vital.lcp.size"] = entry.size); 15509 _emitWebVitalSpan({ 15510 name, 15511 op: "ui.webvital.lcp", 15512 origin: "auto.http.browser.lcp", 15513 metricName: "lcp", 15514 value: lcpValue, 15515 attributes, 15516 parentSpan: pageloadSpan, 15517 reportEvent, 15518 startTime: timeOrigin, 15519 endTime 15520 }); 15521} 15522function trackClsAsSpan(client) { 15523 let clsValue = 0; 15524 let clsEntry; 15525 if (!supportsWebVital("layout-shift")) return; 15526 const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => { 15527 const entry = metric.entries[metric.entries.length - 1]; 15528 if (!entry) return; 15529 clsValue = metric.value; 15530 clsEntry = entry; 15531 }, true); 15532 listenForWebVitalReportEvents(client, (reportEvent, _, pageloadSpan) => { 15533 _sendClsSpan(clsValue, clsEntry, pageloadSpan, reportEvent); 15534 cleanupClsHandler(); 15535 }); 15536} 15537function _sendClsSpan(clsValue, entry, pageloadSpan, reportEvent) { 15538 DEBUG_BUILD$3 && debug$2.log(`Sending CLS span (${clsValue})`); 15539 const startTime = entry ? msToSec((browserPerformanceTimeOrigin() || 0) + entry.startTime) : timestampInSeconds(); 15540 const name = entry ? htmlTreeAsString(entry.sources[0]?.node) : "Layout shift"; 15541 const attributes = {};
15542 if (entry?.sources) entry.sources.forEach((source, index) => { 15543 attributes[`browser.web_vital.cls.source.${index + 1}`] = htmlTreeAsString(source.node); 15544 }); 15545 _emitWebVitalSpan({ 15546 name, 15547 op: "ui.webvital.cls", 15548 origin: "auto.http.browser.cls", 15549 metricName: "cls", 15550 value: clsValue, 15551 attributes, 15552 parentSpan: pageloadSpan, 15553 reportEvent, 15554 startTime 15555 }); 15556} 15557function trackInpAsSpan() { 15558 if (!getBrowserPerformanceAPI() || !browserPerformanceTimeOrigin()) return; 15559 const onInp = ({ metric }) => { 15560 if (metric.value == null) return; 15561 if (msToSec(metric.value) > 60) return; 15562 const entry = metric.entries.find((e) => e.duration === metric.value && INP_ENTRY_MAP[e.name]); 15563 if (!entry) return; 15564 _sendInpSpan(metric.value, entry); 15565 }; 15566 addInpInstrumentationHandler(onInp); 15567} 15568function _sendInpSpan(inpValue, entry) { 15569 DEBUG_BUILD$3 && debug$2.log(`Sending INP span (${inpValue})`); 15570 const startTime = msToSec(browserPerformanceTimeOrigin() + entry.startTime); 15571 const duration = msToSec(inpValue); 15572 const interactionType = INP_ENTRY_MAP[entry.name]; 15573 const cachedContext = getCachedInteractionContext(entry.interactionId); 15574 const activeSpan = getActiveSpan(); 15575 const rootSpan = activeSpan ? getRootSpan(activeSpan) : void 0; 15576 const spanToUse = cachedContext?.span || rootSpan; 15577 const routeName = spanToUse ? spanToStreamedSpanJSON(spanToUse).name : getCurrentScope().getScopeData().transactionName; 15578 _emitWebVitalSpan({ 15579 name: cachedContext?.elementName || htmlTreeAsString(entry.target), 15580 op: `ui.interaction.${interactionType}`, 15581 origin: "auto.http.browser.inp", 15582 metricName: "inp", 15583 value: inpValue, 15584 attributes: { 15585 [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration, 15586 [Xc]: routeName, 15587 [Lc]: routeName 15588 }, 15589 startTime, 15590 endTime: startTime + duration, 15591 parentSpan: spanToUse 15592 }); 15593} 15594function init_webVitalSpans() { 15595 return (init_webVitalSpans = __esmMin((() => { 15596 init_time(), init_debug_logger(), init_currentScopes(), init_spanUtils(), init_semanticAttributes(), init_trace(); 15597 init_debug_build$1(); 15598 init_htmlTreeAsString(); 15599 init_types(); 15600 init_inp(); 15601 init_instrument(); 15602 init_lcp(); 15603 init_utils$8(); 15604 init_attributes$1(); 15605 })))(); 15606} 15607//#endregion 15608//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/instrument/dom.js 15609function addClickKeypressInstrumentationHandler(handler) { 15610 const type = "dom"; 15611 addHandler$1(type, handler); 15612 maybeInstrument(type, instrumentDOM); 15613} 15614function instrumentDOM() { 15615 if (!WINDOW$3.document) return; 15616 const triggerDOMHandler = triggerHandlers$1.bind(null, "dom"); 15617 const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); 15618 WINDOW$3.document.addEventListener("click", globalDOMEventHandler, false); 15619 WINDOW$3.document.addEventListener("keypress", globalDOMEventHandler, false); 15620 ["EventTarget", "Node"].forEach((target) => { 15621 const proto = WINDOW$3[target]?.prototype; 15622 if (!proto?.hasOwnProperty?.("addEventListener")) return; 15623 fill(proto, "addEventListener", function(originalAddEventListener) { 15624 return function(type, listener, options) { 15625 if (type === "click" || type == "keypress") try { 15626 const handlers = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {}; 15627 const handlerForType = handlers[type] = handlers[type] || { refCount: 0 }; 15628 if (!handlerForType.handler) { 15629 const handler = makeDOMEventHandler(triggerDOMHandler); 15630 handlerForType.handler = handler; 15631 originalAddEventListener.call(this, type, handler, options); 15632 } 15633 handlerForType.refCount++; 15634 } catch {} 15635 return originalAddEventListener.call(this, type, listener, options); 15636 }; 15637 }); 15638 fill(proto, "removeEventListener", function(originalRemoveEventListener) { 15639 return function(type, listener, options) { 15640 if (type === "click" || type == "keypress") try { 15641 const handlers = this.__sentry_instrumentation_handlers__ || {}; 15642 const handlerForType = handlers[type]; 15643 if (handlerForType) { 15644 handlerForType.refCount--; 15645 if (handlerForType.refCount <= 0) { 15646 originalRemoveEventListener.call(this, type, handlerForType.handler, options); 15647 handlerForType.handler = void 0; 15648 delete handlers[type]; 15649 } 15650 if (Object.keys(handlers).length === 0) delete this.__sentry_instrumentation_handlers__; 15651 } 15652 } catch {} 15653 return originalRemoveEventListener.call(this, type, listener, options); 15654 }; 15655 }); 15656 }); 15657} 15658function isSimilarToLastCapturedEvent(event) { 15659 if (event.type !== lastCapturedEventType) return false;
15660 try { 15661 if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) return false; 15662 } catch {} 15663 return true; 15664} 15665function shouldSkipDOMEvent(eventType, target) { 15666 if (eventType !== "keypress") return false; 15667 if (!target?.tagName) return true; 15668 if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) return false; 15669 return true; 15670} 15671function makeDOMEventHandler(handler, globalListener = false) { 15672 return (event) => { 15673 if (!event || event["_sentryCaptured"]) return; 15674 const target = getEventTarget$1(event); 15675 if (shouldSkipDOMEvent(event.type, target)) return; 15676 addNonEnumerableProperty(event, "_sentryCaptured", true); 15677 if (target && !target._sentryId) addNonEnumerableProperty(target, "_sentryId", uuid4()); 15678 const name = event.type === "keypress" ? "input" : event.type; 15679 if (!isSimilarToLastCapturedEvent(event)) { 15680 handler({ 15681 event, 15682 name, 15683 global: globalListener 15684 }); 15685 lastCapturedEventType = event.type; 15686 lastCapturedEventTargetId = target ? target._sentryId : void 0; 15687 } 15688 clearTimeout(debounceTimerID); 15689 debounceTimerID = WINDOW$3.setTimeout(() => { 15690 lastCapturedEventTargetId = void 0; 15691 lastCapturedEventType = void 0; 15692 }, DEBOUNCE_DURATION); 15693 }; 15694} 15695function getEventTarget$1(event) { 15696 try { 15697 return event.target; 15698 } catch { 15699 return null; 15700 } 15701} 15702var DEBOUNCE_DURATION, debounceTimerID, lastCapturedEventType, lastCapturedEventTargetId; 15703function init_dom() { 15704 return (init_dom = __esmMin((() => { 15705 init_handlers(), init_object(), init_misc(); 15706 init_types(); 15707 DEBOUNCE_DURATION = 1e3; 15708 })))(); 15709} 15710//#endregion 15711//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/instrument/history.js 15712function addHistoryInstrumentationHandler(handler) { 15713 const type = "history"; 15714 addHandler$1(type, handler); 15715 maybeInstrument(type, instrumentHistory); 15716} 15717function instrumentHistory() { 15718 WINDOW$3.addEventListener("popstate", () => { 15719 const to = WINDOW$3.location.href; 15720 const from = lastHref; 15721 lastHref = to; 15722 if (from === to) return; 15723 triggerHandlers$1("history", { 15724 from, 15725 to 15726 }); 15727 }); 15728 if (!supportsHistory()) return; 15729 function historyReplacementFunction(originalHistoryFunction) { 15730 return function(...args) { 15731 const url = args.length > 2 ? args[2] : void 0; 15732 if (url) { 15733 const from = lastHref; 15734 const to = getAbsoluteUrl$1(String(url)); 15735 lastHref = to; 15736 if (from === to) return originalHistoryFunction.apply(this, args); 15737 triggerHandlers$1("history", { 15738 from, 15739 to 15740 }); 15741 } 15742 return originalHistoryFunction.apply(this, args); 15743 }; 15744 } 15745 fill(WINDOW$3.history, "pushState", historyReplacementFunction); 15746 fill(WINDOW$3.history, "replaceState", historyReplacementFunction); 15747} 15748function getAbsoluteUrl$1(urlOrPath) { 15749 try { 15750 return new URL(urlOrPath, WINDOW$3.location.origin).toString(); 15751 } catch { 15752 return urlOrPath; 15753 } 15754} 15755var lastHref; 15756function init_history() { 15757 return (init_history = __esmMin((() => { 15758 init_handlers(), init_supports(), init_object(); 15759 init_types(); 15760 })))(); 15761} 15762//#endregion 15763//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/getNativeImplementation.js 15764function getNativeImplementation(name) { 15765 const cached = cachedImplementations$3[name]; 15766 if (cached) return cached; 15767 let impl = WINDOW$3[name]; 15768 if (isNativeFunction(impl)) return cachedImplementations$3[name] = impl.bind(WINDOW$3); 15769 const document = WINDOW$3.document; 15770 if (document && typeof document.createElement === "function") try { 15771 const sandbox = document.createElement("iframe"); 15772 sandbox.hidden = true; 15773 document.head.appendChild(sandbox); 15774 const contentWindow = sandbox.contentWindow; 15775 if (contentWindow?.[name]) impl = contentWindow[name]; 15776 document.head.removeChild(sandbox); 15777 } catch (e) { 15778 DEBUG_BUILD$3 && debug$2.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e); 15779 } 15780 if (!impl) return impl; 15781 return cachedImplementations$3[name] = impl.bind(WINDOW$3); 15782} 15783function clearCachedImplementation(name) { 15784 cachedImplementations$3[name] = void 0; 15785} 15786function setTimeout$3(...rest) { 15787 return getNativeImplementation("setTimeout")(...rest); 15788} 15789var cachedImplementations$3; 15790function init_getNativeImplementation() { 15791 return (init_getNativeImplementation = __esmMin((() => { 15792 init_supports(), init_debug_logger(); 15793 init_debug_build$1(); 15794 init_types(); 15795 cachedImplementations$3 = {}; 15796 })))(); 15797} 15798//#endregion 15799//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/instrument/xhr.js 15800function addXhrInstrumentationHandler(handler) { 15801 const type = "xhr"; 15802 addHandler$1(type, handler); 15803 maybeInstrument(type, instrumentXHR); 15804} 15805function instrumentXHR() { 15806 if (!WINDOW$3.XMLHttpRequest) return; 15807 const xhrproto = XMLHttpRequest.prototype; 15808 xhrproto.open = new Proxy(xhrproto.open, { apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) { 15809 const virtualError = /* @__PURE__ */ new Error(); 15810 const startTimestamp = timestampInSeconds() * 1e3; 15811 const method = isString(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : void 0; 15812 const url = parseXhrUrlArg(xhrOpenArgArray[1]); 15813 if (!method || !url) return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); 15814 xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = { 15815 method, 15816 url, 15817 request_headers: {} 15818 };
15819 if (method === "POST" && url.match(/sentry_key/)) xhrOpenThisArg.__sentry_own_request__ = true; 15820 const onreadystatechangeHandler = () => { 15821 const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY]; 15822 if (!xhrInfo) return; 15823 if (xhrOpenThisArg.readyState === 4) { 15824 try { 15825 xhrInfo.status_code = xhrOpenThisArg.status; 15826 } catch {} 15827 triggerHandlers$1("xhr", { 15828 endTimestamp: timestampInSeconds() * 1e3, 15829 startTimestamp, 15830 xhr: xhrOpenThisArg, 15831 virtualError 15832 }); 15833 xhrOpenThisArg.removeEventListener("readystatechange", onreadystatechangeHandler); 15834 } 15835 }; 15836 if ("onreadystatechange" in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === "function") xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, { apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) { 15837 onreadystatechangeHandler(); 15838 return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray); 15839 } }); 15840 else xhrOpenThisArg.addEventListener("readystatechange", onreadystatechangeHandler); 15841 xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, { apply(originalSetRequestHeader, setRequestHeaderThisArg, setRequestHeaderArgArray) { 15842 const [header, value] = setRequestHeaderArgArray; 15843 const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY]; 15844 if (xhrInfo && isString(header) && isString(value)) xhrInfo.request_headers[header.toLowerCase()] = value; 15845 return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray); 15846 } }); 15847 return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); 15848 } }); 15849 xhrproto.send = new Proxy(xhrproto.send, { apply(originalSend, sendThisArg, sendArgArray) { 15850 const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY]; 15851 if (!sentryXhrData) return originalSend.apply(sendThisArg, sendArgArray); 15852 if (sendArgArray[0] !== void 0) sentryXhrData.body = sendArgArray[0]; 15853 triggerHandlers$1("xhr", { 15854 startTimestamp: timestampInSeconds() * 1e3, 15855 xhr: sendThisArg 15856 }); 15857 return originalSend.apply(sendThisArg, sendArgArray); 15858 } }); 15859} 15860function parseXhrUrlArg(url) { 15861 if (isString(url)) return url; 15862 try { 15863 return url.toString(); 15864 } catch {} 15865} 15866var SENTRY_XHR_DATA_KEY; 15867function init_xhr() { 15868 return (init_xhr = __esmMin((() => { 15869 init_handlers(), init_time(), init_is(); 15870 init_types(); 15871 SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__"; 15872 })))(); 15873} 15874//#endregion 15875//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/networkUtils.js 15876function serializeFormData(formData) { 15877 return new URLSearchParams(formData).toString(); 15878} 15879function getBodyString(body, _debug = debug$2) { 15880 try { 15881 if (typeof body === "string") return [body]; 15882 if (body instanceof URLSearchParams) return [body.toString()]; 15883 if (body instanceof FormData) return [serializeFormData(body)]; 15884 if (!body) return [void 0]; 15885 } catch (error) { 15886 DEBUG_BUILD$3 && _debug.error(error, "Failed to serialize body", body); 15887 return [void 0, "BODY_PARSE_ERROR"]; 15888 } 15889 DEBUG_BUILD$3 && _debug.log("Skipping network body because of body type", body); 15890 return [void 0, "UNPARSEABLE_BODY_TYPE"]; 15891} 15892function getFetchRequestArgBody(fetchArgs = []) { 15893 if (fetchArgs.length >= 2 && fetchArgs[1] && typeof fetchArgs[1] === "object" && "body" in fetchArgs[1]) return fetchArgs[1].body; 15894 if (fetchArgs.length >= 1 && fetchArgs[0] instanceof Request) { 15895 const originalBody = fetchArgs[0][ORIGINAL_REQ_BODY]; 15896 if (originalBody !== void 0) return originalBody; 15897 return; 15898 } 15899} 15900function parseXhrResponseHeaders(xhr) { 15901 let headers; 15902 try { 15903 headers = xhr.getAllResponseHeaders(); 15904 } catch (error) { 15905 DEBUG_BUILD$3 && debug$2.error(error, "Failed to get xhr response headers", xhr); 15906 return {}; 15907 } 15908 if (!headers) return {}; 15909 return headers.split("\r\n").reduce((acc, line) => { 15910 const [key, value] = line.split(": "); 15911 if (value) acc[key.toLowerCase()] = value; 15912 return acc; 15913 }, {}); 15914} 15915var ORIGINAL_REQ_BODY; 15916function init_networkUtils() { 15917 return (init_networkUtils = __esmMin((() => { 15918 init_debug_logger(); 15919 init_debug_build$1(); 15920 ORIGINAL_REQ_BODY = /* @__PURE__ */ Symbol.for("sentry__originalRequestBody"); 15921 })))(); 15922} 15923//#endregion 15924//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/is.js 15925function isElement$2(wat) { 15926 if (typeof Element === "undefined") return false;
15927 try { 15928 return wat instanceof Element; 15929 } catch { 15930 return false; 15931 } 15932} 15933//#endregion 15934//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser-utils/build/esm/instrument/location.js 15935function getAbsoluteUrl(urlOrPath) { 15936 try { 15937 return new URL(urlOrPath, WINDOW$3.location.origin).toString(); 15938 } catch { 15939 return urlOrPath; 15940 } 15941} 15942function init_location() { 15943 return (init_location = __esmMin((() => { 15944 init_types(); 15945 })))(); 15946} 15947//#endregion 15948//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/transports/fetch.js 15949function makeFetchTransport(options, nativeFetch = getNativeImplementation("fetch")) { 15950 let pendingBodySize = 0; 15951 let pendingCount = 0; 15952 async function makeRequest(request) { 15953 const requestSize = request.body.length; 15954 pendingBodySize += requestSize; 15955 pendingCount++; 15956 const requestOptions = { 15957 body: request.body, 15958 method: "POST", 15959 referrerPolicy: "strict-origin", 15960 headers: options.headers, 15961 keepalive: pendingBodySize <= 6e4 && pendingCount < 15, 15962 ...options.fetchOptions 15963 }; 15964 try { 15965 const response = await nativeFetch(options.url, requestOptions); 15966 return { 15967 statusCode: response.status, 15968 headers: { 15969 "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"), 15970 "retry-after": response.headers.get("Retry-After") 15971 } 15972 }; 15973 } catch (e) { 15974 clearCachedImplementation("fetch"); 15975 throw e; 15976 } finally { 15977 pendingBodySize -= requestSize; 15978 pendingCount--; 15979 } 15980 } 15981 return createTransport(options, makeRequest, makePromiseBuffer(options.bufferSize || DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE)); 15982} 15983var DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE; 15984function init_fetch$2() { 15985 return (init_fetch$2 = __esmMin((() => { 15986 init_base(), init_promisebuffer(); 15987 init_getNativeImplementation(); 15988 DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE = 40; 15989 })))(); 15990} 15991//#endregion 15992//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/debug-build.js 15993var DEBUG_BUILD$2; 15994function init_debug_build$2() { 15995 return (init_debug_build$2 = __esmMin((() => { 15996 DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 15997 })))(); 15998} 15999//#endregion 16000//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/profiling/index.js 16001function startProfiler() { 16002 const client = getClient(); 16003 if (!client) { 16004 DEBUG_BUILD$2 && debug$2.warn("No Sentry client available, profiling is not started"); 16005 return; 16006 } 16007 if (!client.getIntegrationByName("BrowserProfiling")) { 16008 DEBUG_BUILD$2 && debug$2.warn("BrowserProfiling integration is not available"); 16009 return; 16010 } 16011 client.emit("startUIProfiler"); 16012} 16013function stopProfiler() { 16014 const client = getClient(); 16015 if (!client) { 16016 DEBUG_BUILD$2 && debug$2.warn("No Sentry client available, profiling is not started"); 16017 return; 16018 } 16019 if (!client.getIntegrationByName("BrowserProfiling")) { 16020 DEBUG_BUILD$2 && debug$2.warn("ProfilingIntegration is not available"); 16021 return; 16022 } 16023 client.emit("stopUIProfiler"); 16024} 16025var uiProfiler; 16026function init_profiling() { 16027 return (init_profiling = __esmMin((() => { 16028 init_currentScopes(), init_debug_logger(); 16029 init_debug_build$2(); 16030 uiProfiler = { 16031 startProfiler, 16032 stopProfiler 16033 }; 16034 })))(); 16035} 16036//#endregion 16037//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/stack-parsers.js 16038function createFrame(filename, func, lineno, colno) { 16039 const frame = { 16040 filename, 16041 function: func === "<anonymous>" ? "?" : func, 16042 in_app: true 16043 }; 16044 if (lineno !== void 0) frame.lineno = lineno; 16045 if (colno !== void 0) frame.colno = colno; 16046 return frame; 16047} 16048var OPERA10_PRIORITY, OPERA11_PRIORITY, CHROME_PRIORITY, WINJS_PRIORITY, GECKO_PRIORITY, chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeDataUriRegex, chromeStackParserFn, chromeStackLineParser, geckoREgex, geckoEvalRegex, gecko, geckoStackLineParser, winjsRegex, winjs, winjsStackLineParser, opera10Regex, opera10, opera10StackLineParser, opera11Regex, opera11, opera11StackLineParser, defaultStackLineParsers, defaultStackParser, extractSafariExtensionDetail
16048s; 16049function init_stack_parsers() { 16050 return (init_stack_parsers = __esmMin((() => { 16051 init_stacktrace(); 16052 OPERA10_PRIORITY = 10; 16053 OPERA11_PRIORITY = 20; 16054 CHROME_PRIORITY = 30; 16055 WINJS_PRIORITY = 40; 16056 GECKO_PRIORITY = 50; 16057 chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; 16058 chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; 16059 chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; 16060 chromeDataUriRegex = /at (.+?) ?\(data:(.+?),/; 16061 chromeStackParserFn = (line) => { 16062 const dataUriMatch = line.match(chromeDataUriRegex); 16063 if (dataUriMatch) return { 16064 filename: `<data:${dataUriMatch[2]}>`, 16065 function: dataUriMatch[1] 16066 }; 16067 const noFnParts = chromeRegexNoFnName.exec(line); 16068 if (noFnParts) { 16069 const [, filename, line2, col] = noFnParts; 16070 return createFrame(filename, "?", +line2, +col); 16071 } 16072 const parts = chromeRegex.exec(line); 16073 if (parts) { 16074 if (parts[2]?.indexOf("eval") === 0) { 16075 const subMatch = chromeEvalRegex.exec(parts[2]); 16076 if (subMatch) { 16077 parts[2] = subMatch[1]; 16078 parts[3] = subMatch[2]; 16079 parts[4] = subMatch[3]; 16080 } 16081 } 16082 const [func, filename] = extractSafariExtensionDetails(parts[1] || "?", parts[2]); 16083 return createFrame(filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0); 16084 } 16085 }; 16086 chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn]; 16087 geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; 16088 geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; 16089 gecko = (line) => { 16090 const parts = geckoREgex.exec(line); 16091 if (parts) { 16092 if (parts[3] && parts[3].indexOf(" > eval") > -1) { 16093 const subMatch = geckoEvalRegex.exec(parts[3]); 16094 if (subMatch) { 16095 parts[1] = parts[1] || "eval"; 16096 parts[3] = subMatch[1]; 16097 parts[4] = subMatch[2]; 16098 parts[5] = ""; 16099 } 16100 } 16101 let filename = parts[3]; 16102 let func = parts[1] || "?"; 16103 [func, filename] = extractSafariExtensionDetails(func, filename); 16104 return createFrame(filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0); 16105 } 16106 }; 16107 geckoStackLineParser = [GECKO_PRIORITY, gecko]; 16108 winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i; 16109 winjs = (line) => { 16110 const parts = winjsRegex.exec(line); 16111 return parts ? createFrame(parts[2], parts[1] || "?", +parts[3], parts[4] ? +parts[4] : void 0) : void 0; 16112 }; 16113 winjsStackLineParser = [WINJS_PRIORITY, winjs]; 16114 opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i; 16115 opera10 = (line) => { 16116 const parts = opera10Regex.exec(line); 16117 return parts ? createFrame(parts[2], parts[3] || "?", +parts[1]) : void 0; 16118 }; 16119 opera10StackLineParser = [OPERA10_PRIORITY, opera10]; 16120 opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i; 16121 opera11 = (line) => { 16122 const parts = opera11Regex.exec(line); 16123 return parts ? createFrame(parts[5], parts[3] || parts[4] || "?", +parts[1], +parts[2]) : void 0; 16124 }; 16125 opera11StackLineParser = [OPERA11_PRIORITY, opera11]; 16126 defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser]; 16127 defaultStackParser = createStackParser(...defaultStackLineParsers); 16128 extractSafariExtensionDetails = (func, filename) => { 16129 const isSafariExtension = func.indexOf("safari-extension") !== -1; 16130 const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1; 16131 return isSafariExtension || isSafariWebExtension ? [func.indexOf("@") !== -1 ? func.split("@")[0] : "?", isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`] : [func, filename]; 16132 }; 16133 })))(); 16134} 16135//#endregion 16136//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/userfeedback.js 16137function createUserFeedbackEnvelope(feedback, { metadata, tunnel, dsn }) { 16138 return createEnvelope({ 16139 event_id: feedback.event_id, 16140 sent_at: (/* @__PURE__ */ new Date()).toISOString(), 16141 ...metadata?.sdk && { sdk: { 16142 name: metadata.sdk.name, 16143 version: metadata.sdk.version 16144 } }, 16145 ...!!tunnel && !!dsn && { dsn: dsnToString(dsn) } 16146 }, [createUserFeedbackEnvelopeItem(feedback)]); 16147} 16148function createUserFeedbackEnvelopeItem(feedback) { 16149 return [{ type: "user_report" }, feedback]; 16150} 16151function init_userfeedback() { 16152 return (init_userfeedback = __esmMin((() => { 16153 init_dsn(), init_envelope(); 16154 })))(); 16155} 16156//#endregion 16157//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/breadcrumbs.js 16158function _getSentryBreadcrumbHandler(client) { 16159 return function addSentryBreadcrumb(event) { 16160 if (getClient() !== client) return; 16161 addBreadcrumb({ 16162 category: `sentry.${event.type === "transaction" ? "transaction" : "event"}`, 16163 event_id: event.event_id, 16164 level: event.level, 16165 message: getEventDescription(event) 16166 }, { event }); 16167 }; 16168} 16169function _getDomBreadcrumbHandler(client, dom) { 16170 return function _innerDomBreadcrumb(handlerData) { 16171 if (getClient() !== client) return; 16172 let target; 16173 let componentName; 16174 let keyAttrs = typeof dom === "object" ? dom.serializeAttribute : void 0; 16175 let maxStringLength = typeof dom === "object" && typeof dom.maxStringLength === "number" ? dom.maxStringLength : void 0; 16176 if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) { 16177 DEBUG_BUILD$2 && debug$2.warn(`\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`); 16178 maxStringLength = MAX_ALLOWED_STRING_LENGTH; 16179 } 16180 if (typeof keyAttrs === "string") keyAttrs = [keyAttrs]; 16181 try { 16182 const event = handlerData.event; 16183 const element = _isEvent(event) ? event.target : event; 16184 target = htmlTreeAsString(element, { 16185 keyAttrs, 16186 maxStringLength 16187 }); 16188 componentName = getComponentName(element); 16189 } catch { 16190 target = "<unknown>"; 16191 } 16192 if (target.length === 0) return; 16193 const breadcrumb = { 16194 category: `ui.${handlerData.name}`, 16195 message: target 16196 };
16197 if (componentName) breadcrumb.data = { "ui.component_name": componentName }; 16198 addBreadcrumb(breadcrumb, { 16199 event: handlerData.event, 16200 name: handlerData.name, 16201 global: handlerData.global 16202 }); 16203 }; 16204} 16205function _getConsoleBreadcrumbHandler(client) { 16206 return function _consoleBreadcrumb(handlerData) { 16207 if (getClient() !== client) return; 16208 const breadcrumb = { 16209 category: "console", 16210 data: { 16211 arguments: handlerData.args, 16212 logger: "console" 16213 }, 16214 level: severityLevelFromString(handlerData.level), 16215 message: safeJoin(handlerData.args, " ") 16216 }; 16217 if (handlerData.level === "assert") { 16218 if (handlerData.args[0] === false) { 16219 breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`; 16220 breadcrumb.data.arguments = handlerData.args.slice(1); 16221 } else return; 16222 } 16223 addBreadcrumb(breadcrumb, { 16224 input: handlerData.args, 16225 level: handlerData.level 16226 }); 16227 }; 16228} 16229function _getXhrBreadcrumbHandler(client) { 16230 return function _xhrBreadcrumb(handlerData) { 16231 if (getClient() !== client) return; 16232 const { startTimestamp, endTimestamp } = handlerData; 16233 const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY]; 16234 if (!startTimestamp || !endTimestamp || !sentryXhrData) return; 16235 const { method, url, status_code, body } = sentryXhrData; 16236 const data = { 16237 method, 16238 url, 16239 status_code 16240 }; 16241 const hint = { 16242 xhr: handlerData.xhr, 16243 input: body, 16244 startTimestamp, 16245 endTimestamp 16246 }; 16247 const breadcrumb = { 16248 category: "xhr", 16249 data, 16250 type: "http", 16251 level: getBreadcrumbLogLevelFromHttpStatusCode(status_code) 16252 }; 16253 client.emit("beforeOutgoingRequestBreadcrumb", breadcrumb, hint); 16254 addBreadcrumb(breadcrumb, hint); 16255 }; 16256} 16257function _getFetchBreadcrumbHandler(client) { 16258 return function _fetchBreadcrumb(handlerData) { 16259 if (getClient() !== client) return; 16260 const { startTimestamp, endTimestamp } = handlerData; 16261 if (!endTimestamp) return; 16262 if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") return; 16263 if (handlerData.error) { 16264 const hint = { 16265 data: handlerData.error, 16266 input: handlerData.args, 16267 startTimestamp, 16268 endTimestamp 16269 }; 16270 const breadcrumb = { 16271 category: "fetch", 16272 data: handlerData.fetchData, 16273 level: "error", 16274 type: "http" 16275 }; 16276 client.emit("beforeOutgoingRequestBreadcrumb", breadcrumb, hint); 16277 addBreadcrumb(breadcrumb, hint); 16278 } else { 16279 const response = handlerData.response; 16280 const data = { 16281 ...handlerData.fetchData, 16282 status_code: response?.status 16283 }; 16284 const hint = { 16285 input: handlerData.args, 16286 response, 16287 startTimestamp, 16288 endTimestamp 16289 }; 16290 const breadcrumb = { 16291 category: "fetch", 16292 data, 16293 type: "http", 16294 level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code) 16295 }; 16296 client.emit("beforeOutgoingRequestBreadcrumb", breadcrumb, hint); 16297 addBreadcrumb(breadcrumb, hint); 16298 } 16299 }; 16300} 16301function _getHistoryBreadcrumbHandler(client) { 16302 return function _historyBreadcrumb(handlerData) { 16303 if (getClient() !== client) return; 16304 let from = handlerData.from; 16305 let to = handlerData.to; 16306 const parsedLoc = parseUrl(WINDOW$4.location.href); 16307 let parsedFrom = from ? parseUrl(from) : void 0; 16308 const parsedTo = parseUrl(to); 16309 if (!parsedFrom?.path) parsedFrom = parsedLoc; 16310 if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) to = parsedTo.relative; 16311 if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) from = parsedFrom.relative; 16312 addBreadcrumb({ 16313 category: "navigation", 16314 data: { 16315 from, 16316 to 16317 } 16318 }); 16319 }; 16320} 16321function _isEvent(event) { 16322 return !!event && !!event.target; 16323} 16324var MAX_ALLOWED_STRING_LENGTH, INTEGRATION_NAME$12, _breadcrumbsIntegration, breadcrumbsIntegration; 16325function init_breadcrumbs$1() { 16326 return (init_breadcrumbs$1 = __esmMin((() => { 16327 init_integration(), init_console(), init_fetch$1(), init_currentScopes(), init_string(), init_breadcrumbs(), init_debug_logger(), init_browser(), init_url(), init_misc(); 16328 init_dom(), init_xhr(), init_history(), init_htmlTreeAsString(); 16329 init_debug_build$2(); 16330 init_helpers(); 16331 MAX_ALLOWED_STRING_LENGTH = 1024; 16332 INTEGRATION_NAME$12 = "Breadcrumbs"; 16333 _breadcrumbsIntegration = ((options = {}) => { 16334 const _options = { 16335 console: true, 16336 dom: true, 16337 fetch: true, 16338 history: true, 16339 sentry: true, 16340 xhr: true, 16341 ...options 16342 }; 16343 return { 16344 name: INTEGRATION_NAME$12, 16345 setup(client) { 16346 if (_options.console) addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client)); 16347 if (_options.dom) addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom)); 16348 if (_options.xhr) addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client)); 16349 if (_options.fetch) addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client)); 16350 if (_options.history) addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client)); 16351 if (_options.sentry) client.on("beforeSendEvent", _getSentryBreadcrumbHandler(client)); 16352 } 16353 }; 16354 }); 16355 breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration); 16356 })))(); 16357} 16358//#endregion 16359//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/browserapierrors.js 16360function _wrapTimeFunction(original) { 16361 return function(...args) { 16362 const originalCallback = args[0]; 16363 args[0] = wrap(originalCallback, { mechanism: { 16364 handled: false, 16365 type: `auto.browser.browserapierrors.${getFunctionName(original)}` 16366 } }); 16367 return original.apply(this, args); 16368 }; 16369} 16370function _wrapRAF(original) { 16371 return function(callback) { 16372 return original.apply(this, [wrap(callback, { mechanism: { 16373 data: { handler: getFunctionName(original) }, 16374 handled: false, 16375 type: "auto.browser.browserapierrors.requestAnimationFrame" 16376 } })]); 16377 }; 16378} 16379function _wrapXHR$1(originalSend) { 16380 return function(...args) { 16381 const xhr = this; 16382 [ 16383 "onload", 16384 "onerror", 16385 "onprogress", 16386 "onreadystatechange" 16387 ].forEach((prop) => { 16388 if (prop in xhr && typeof xhr[prop] === "function") fill(xhr, prop, function(original) { 16389 const wrapOptions = { mechanism: { 16390 data: { handler: getFunctionName(original) }, 16391 handled: false, 16392 type: `auto.browser.browserapierrors.xhr.${prop}` 16393 } }; 16394 const originalFunction = getOriginalFunction(original); 16395 if (originalFunction) wrapOptions.mechanism.data.handler = getFunctionName(originalFunction); 16396 return wrap(original, wrapOptions); 16397 }); 16398 }); 16399 return originalSend.apply(this, args); 16400 }; 16401} 16402function _wrapEventTarget(target, integrationOptions) { 16403 const proto = WINDOW$4[target]?.prototype; 16404 if (!proto?.hasOwnProperty?.("addEventListener")) return; 16405 fill(proto, "addEventListener", function(original) { 16406 return function(eventName, fn, options) { 16407 try { 16408 if (isEventListenerObject(fn)) fn.handleEvent = wrap(fn.handleEvent, { mechanism: { 16409 data: { 16410 handler: getFunctionName(fn), 16411 target 16412 }, 16413 handled: false, 16414 type: "auto.browser.browserapierrors.handleEvent" 16415 } }); 16416 } catch {} 16417 if (integrationOptions.unregisterOriginalCallbacks) unregisterOriginalCallback(this, eventName, fn); 16418 return original.apply(this, [ 16419 eventName, 16420 wrap(fn, { mechanism: { 16421 data: { 16422 handler: getFunctionName(fn), 16423 target 16424 }, 16425 handled: false, 16426 type: "auto.browser.browserapierrors.addEventListener" 16427 } }), 16428 options 16429 ]); 16430 }; 16431 }); 16432 fill(proto, "removeEventListener", function(originalRemoveEventListener) { 16433 return function(eventName, fn, options) { 16434 try { 16435 if (Object.prototype.hasOwnProperty.call(fn, "__sentry_wrapped__")) { 16436 const originalEventHandler = fn.__sentry_wrapped__; 16437 if (originalEventHandler) originalRemoveEventListener.call(this, eventName, originalEventHandler, options); 16438 } 16439 } catch {} 16440 return originalRemoveEventListener.call(this, eventName, fn, options); 16441 }; 16442 }); 16443} 16444function isEventListenerObject(obj) { 16445 return typeof obj.handleEvent === "function"; 16446} 16447function unregisterOriginalCallback(target, eventName, fn) { 16448 if (target && typeof target === "object" && "removeEventListener" in target && typeof target.removeEventListener === "function") target.removeEventListener(eventName, fn); 16449} 16450var DEFAULT_EVENT_TARGET, INTEGRATION_NAME$11, _browserApiErrorsIntegration, browserApiErrorsIntegration; 16451function init_browserapierrors() { 16452 return (init_browserapierrors = __esmMin((() => { 16453 init_integration(), init_object(), init_stacktrace(); 16454 init_helpers(); 16455 DEFAULT_EVENT_TARGET = "EventTarget,Window,Node,ApplicationCache,AudioTrackList,BroadcastChannel,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDB
16455Request,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(","); 16456 INTEGRATION_NAME$11 = "BrowserApiErrors"; 16457 _browserApiErrorsIntegration = ((options = {}) => { 16458 const _options = { 16459 XMLHttpRequest: true, 16460 eventTarget: true, 16461 requestAnimationFrame: true, 16462 setInterval: true, 16463 setTimeout: true, 16464 unregisterOriginalCallbacks: false, 16465 ...options 16466 }; 16467 return { 16468 name: INTEGRATION_NAME$11, 16469 setupOnce() { 16470 if (_options.setTimeout) fill(WINDOW$4, "setTimeout", _wrapTimeFunction); 16471 if (_options.setInterval) fill(WINDOW$4, "setInterval", _wrapTimeFunction); 16472 if (_options.requestAnimationFrame) fill(WINDOW$4, "requestAnimationFrame", _wrapRAF); 16473 if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW$4) fill(XMLHttpRequest.prototype, "send", _wrapXHR$1); 16474 const eventTargetOption = _options.eventTarget; 16475 if (eventTargetOption) (Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET).forEach((target) => _wrapEventTarget(target, _options)); 16476 } 16477 }; 16478 }); 16479 browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration); 16480 })))(); 16481} 16482//#endregion 16483//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/browsersession.js 16484var browserSessionIntegration; 16485function init_browsersession() { 16486 return (init_browsersession = __esmMin((() => { 16487 init_integration(), init_debug_logger(), init_exports(), init_currentScopes(); 16488 init_whenIdleOrHidden(), init_history(); 16489 init_debug_build$2(); 16490 init_helpers(); 16491 browserSessionIntegration = defineIntegration((options = {}) => { 16492 const lifecycle = options.lifecycle ?? "route"; 16493 return { 16494 name: "BrowserSession", 16495 setupOnce() { 16496 if (typeof WINDOW$4.document === "undefined") { 16497 DEBUG_BUILD$2 && debug$2.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."); 16498 return; 16499 } 16500 startSession({ ignoreDuration: true }); 16501 let initialSessionSent = false; 16502 whenIdleOrHidden(() => { 16503 if (!initialSessionSent) { 16504 captureSession(); 16505 initialSessionSent = true; 16506 } 16507 }); 16508 const isolationScope = getIsolationScope(); 16509 let previousUser = isolationScope.getUser(); 16510 isolationScope.addScopeListener((scope) => { 16511 const maybeNewUser = scope.getUser(); 16512 if (previousUser?.id !== maybeNewUser?.id || previousUser?.ip_address !== maybeNewUser?.ip_address) { 16513 previousUser = maybeNewUser; 16514 if (initialSessionSent) captureSession(); 16515 } 16516 }); 16517 if (lifecycle === "route") addHistoryInstrumentationHandler(({ from, to }) => { 16518 if (from !== to) { 16519 startSession({ ignoreDuration: true }); 16520 captureSession(); 16521 initialSessionSent = true; 16522 } 16523 }); 16524 } 16525 }; 16526 }); 16527 })))(); 16528} 16529//#endregion 16530//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/culturecontext.js 16531function getCultureContext() { 16532 try { 16533 const intl = WINDOW$4.Intl; 16534 if (!intl) return; 16535 const options = intl.DateTimeFormat().resolvedOptions(); 16536 return { 16537 locale: options.locale, 16538 timezone: options.timeZone, 16539 calendar: options.calendar 16540 }; 16541 } catch { 16542 return; 16543 } 16544} 16545var INTEGRATION_NAME$10, _cultureContextIntegration, cultureContextIntegration; 16546function init_culturecontext() { 16547 return (init_culturecontext = __esmMin((() => { 16548 init_integration(), init_captureSpan(); 16549 init_helpers(); 16550 INTEGRATION_NAME$10 = "CultureContext"; 16551 _cultureContextIntegration = (() => { 16552 return { 16553 name: INTEGRATION_NAME$10, 16554 preprocessEvent(event) { 16555 const culture = getCultureContext(); 16556 if (culture) event.contexts = { 16557 ...event.contexts, 16558 culture: { 16559 ...culture, 16560 ...event.contexts?.culture 16561 } 16562 }; 16563 }, 16564 processSegmentSpan(span) { 16565 const culture = getCultureContext(); 16566 if (culture) safeSetSpanJSONAttributes(span, { 16567 "culture.locale": culture.locale, 16568 "culture.timezone": culture.timezone, 16569 "culture.calendar": culture.calendar 16570 }); 16571 } 16572 }; 16573 }); 16574 cultureContextIntegration = defineIntegration(_cultureContextIntegration); 16575 })))(); 16576} 16577//#endregion 16578//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/globalhandlers.js 16579function _installGlobalOnErrorHandler(client) { 16580 addGlobalErrorInstrumentationHandler((data) => { 16581 const { stackParser, attachStacktrace } = getOptions(); 16582 if (getClient() !== client || shouldIgnoreOnError()) return; 16583 const { msg, url, line, column, error } = data; 16584 const event = _enhanceEventWithInitialFrame(eventFromUnknownInput(stackParser, error || msg, void 0, attachStacktrace, false), url, line, column); 16585 event.level = "error"; 16586 captureEvent(event, { 16587 originalException: error, 16588 mechanism: { 16589 handled: false, 16590 type: "auto.browser.global_handlers.onerror" 16591 } 16592 }); 16593 }); 16594} 16595function _installGlobalOnUnhandledRejectionHandler(client) { 16596 addGlobalUnhandledRejectionInstrumentationHandler((e) => { 16597 const { stackParser, attachStacktrace } = getOptions(); 16598 if (getClient() !== client || shouldIgnoreOnError()) return; 16599 const error = _getUnhandledRejectionError(e); 16600 const event = isPrimitive(error) ? _eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(stackParser, error, void 0, attachStacktrace, true); 16601 event.level = "error"; 16602 captureEvent(event, { 16603 originalException: error, 16604 mechanism: { 16605 handled: false, 16606 type: "auto.browser.global_handlers.onunhandledrejection" 16607 } 16608 }); 16609 }); 16610} 16611function _getUnhandledRejectionError(error) { 16612 if (isPrimitive(error)) return error; 16613 try { 16614 if ("reason" in error) return error.reason; 16615 if ("detail" in error && "reason" in error.detail) return error.detail.reason; 16616 } catch {} 16617 return error; 16618} 16619function _eventFromRejectionWithPrimitive(reason) { 16620 return { exception: { values: [{
16621 type: "UnhandledRejection", 16622 value: `Non-Error promise rejection captured with value: ${String(reason)}` 16623 }] } }; 16624} 16625function _enhanceEventWithInitialFrame(event, url, lineno, colno) { 16626 const e = event.exception = event.exception || {}; 16627 const ev = e.values = e.values || []; 16628 const ev0 = ev[0] = ev[0] || {}; 16629 const ev0s = ev0.stacktrace = ev0.stacktrace || {}; 16630 const ev0sf = ev0s.frames = ev0s.frames || []; 16631 if (ev0sf.length === 0) ev0sf.push({ 16632 colno, 16633 lineno, 16634 filename: getFilenameFromUrl(url) ?? getLocationHref(), 16635 function: "?", 16636 in_app: true 16637 }); 16638 return event; 16639} 16640function globalHandlerLog(type) { 16641 DEBUG_BUILD$2 && debug$2.log(`Global Handler attached: ${type}`); 16642} 16643function getOptions() { 16644 return getClient()?.getOptions() || { 16645 stackParser: () => [], 16646 attachStacktrace: false 16647 }; 16648} 16649function getFilenameFromUrl(url) { 16650 if (!isString(url) || url.length === 0) return; 16651 if (url.startsWith("data:")) return `<${stripDataUrlContent(url, false)}>`; 16652 return url; 16653} 16654var INTEGRATION_NAME$9, _globalHandlersIntegration, globalHandlersIntegration; 16655function init_globalhandlers() { 16656 return (init_globalhandlers = __esmMin((() => { 16657 init_integration(), init_globalError(), init_currentScopes(), init_exports(), init_debug_logger(), init_globalUnhandledRejection(), init_is(), init_stacktrace(), init_browser(), init_url(); 16658 init_debug_build$2(); 16659 init_eventbuilder$1(); 16660 init_helpers(); 16661 INTEGRATION_NAME$9 = "GlobalHandlers"; 16662 _globalHandlersIntegration = ((options = {}) => { 16663 const _options = { 16664 onerror: true, 16665 onunhandledrejection: true, 16666 ...options 16667 }; 16668 return { 16669 name: INTEGRATION_NAME$9, 16670 setupOnce() { 16671 Error.stackTraceLimit = 50; 16672 }, 16673 setup(client) { 16674 if (_options.onerror) { 16675 _installGlobalOnErrorHandler(client); 16676 globalHandlerLog("onerror"); 16677 } 16678 if (_options.onunhandledrejection) { 16679 _installGlobalOnUnhandledRejectionHandler(client); 16680 globalHandlerLog("onunhandledrejection"); 16681 } 16682 } 16683 }; 16684 }); 16685 globalHandlersIntegration = defineIntegration(_globalHandlersIntegration); 16686 })))(); 16687} 16688//#endregion 16689//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/httpcontext.js 16690var httpContextIntegration; 16691function init_httpcontext() { 16692 return (init_httpcontext = __esmMin((() => { 16693 init_integration(), init_captureSpan(); 16694 init_helpers(); 16695 init_attributes$1(); 16696 httpContextIntegration = defineIntegration(() => { 16697 return { 16698 name: "HttpContext", 16699 preprocessEvent(event) { 16700 if (!WINDOW$4.navigator && !WINDOW$4.location && !WINDOW$4.document) return; 16701 const reqData = getHttpRequestData(); 16702 const headers = { 16703 ...reqData.headers, 16704 ...event.request?.headers 16705 }; 16706 event.request = { 16707 ...reqData, 16708 ...event.request, 16709 headers 16710 }; 16711 }, 16712 processSpan(span) { 16713 if (!WINDOW$4.navigator && !WINDOW$4.location && !WINDOW$4.document) return; 16714 const reqData = getHttpRequestData(); 16715 safeSetSpanJSONAttributes(span, { 16716 [Qu]: reqData.headers["User-Agent"], 16717 ...span.is_segment && { 16718 ["url.full"]: span.attributes?.["sentry.op"] !== "http.client" ? reqData.url : void 0, 16719 [`http.request.header.referer`]: reqData.headers["Referer"] 16720 } 16721 }); 16722 } 16723 }; 16724 }); 16725 })))(); 16726} 16727//#endregion 16728//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/linkederrors.js 16729var DEFAULT_KEY, DEFAULT_LIMIT, INTEGRATION_NAME$8, _linkedErrorsIntegration, linkedErrorsIntegration; 16730function init_linkederrors() { 16731 return (init_linkederrors = __esmMin((() => { 16732 init_integration(), init_aggregate_errors(); 16733 init_eventbuilder$1(); 16734 DEFAULT_KEY = "cause"; 16735 DEFAULT_LIMIT = 5; 16736 INTEGRATION_NAME$8 = "LinkedErrors"; 16737 _linkedErrorsIntegration = ((options = {}) => { 16738 const limit = options.limit || DEFAULT_LIMIT; 16739 const key = options.key || DEFAULT_KEY; 16740 return { 16741 name: INTEGRATION_NAME$8, 16742 preprocessEvent(event, hint, client) { 16743 applyAggregateErrorsToEvent(exceptionFromError, client.getOptions().stackParser, key, limit, event, hint); 16744 } 16745 }; 16746 }); 16747 linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration); 16748 })))(); 16749} 16750//#endregion 16751//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/normalizeStringifyValue.js 16752function normalizeStringifyValue$1(value) { 16753 if (typeof window !== "undefined" && value === window) return "[Window]"; 16754 if (typeof document !== "undefined" && value === document) return "[Document]"; 16755 if (isElement$2(value)) { 16756 const objName = getConstructorName(value); 16757 if (HTML_ELEMENT_CONSTRUCTOR_NAME_REGEX.test(objName)) return `[HTMLElement: ${htmlTreeAsString(value)}]`; 16758 } 16759} 16760function getConstructorName(value) { 16761 const prototype = Object.getPrototypeOf(value); 16762 return prototype?.constructor ? prototype.constructor.name : "null prototype"; 16763} 16764var HTML_ELEMENT_CONSTRUCTOR_NAME_REGEX; 16765function init_normalizeStringifyValue() { 16766 return (init_normalizeStringifyValue = __esmMin((() => { 16767 init_htmlTreeAsString(); 16768 HTML_ELEMENT_CONSTRUCTOR_NAME_REGEX = /^HTML(\w*)Element$/; 16769 })))(); 16770} 16771//#endregion 16772//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/utils/detectBrowserExtension.js 16773function checkAndWarnIfIsEmbeddedBrowserExtension() { 16774 if (_isEmbeddedBrowserExtension()) { 16775 if (DEBUG_BUILD$2) consoleSandbox(() => { 16776 console.error("[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/"); 16777 }); 16778 return true; 16779 } 16780 return false;
16781} 16782function _isEmbeddedBrowserExtension() { 16783 if (typeof WINDOW$4.window === "undefined") return false; 16784 const _window = WINDOW$4; 16785 if (_window.nw) return false; 16786 if (!(_window["chrome"] || _window["browser"])?.runtime?.id) return false; 16787 const href = getLocationHref(); 16788 return !(WINDOW$4 === WINDOW$4.top && /^(?:chrome-extension|moz-extension|ms-browser-extension|safari-web-extension):\/\//.test(href)); 16789} 16790function init_detectBrowserExtension() { 16791 return (init_detectBrowserExtension = __esmMin((() => { 16792 init_debug_logger(), init_browser(); 16793 init_debug_build$2(); 16794 init_helpers(); 16795 })))(); 16796} 16797//#endregion 16798//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/sdk.js 16799function getDefaultIntegrations(_options) { 16800 return [ 16801 inboundFiltersIntegration(), 16802 functionToStringIntegration(), 16803 conversationIdIntegration(), 16804 browserApiErrorsIntegration(), 16805 breadcrumbsIntegration(), 16806 globalHandlersIntegration(), 16807 linkedErrorsIntegration(), 16808 dedupeIntegration(), 16809 httpContextIntegration(), 16810 cultureContextIntegration(), 16811 browserSessionIntegration() 16812 ]; 16813} 16814function init$1(options = {}) { 16815 const shouldDisableBecauseIsBrowserExtenstion = !options.skipBrowserExtensionCheck && checkAndWarnIfIsEmbeddedBrowserExtension(); 16816 let defaultIntegrations = options.defaultIntegrations == null ? getDefaultIntegrations() : options.defaultIntegrations; 16817 const clientOptions = { 16818 ...options, 16819 enabled: shouldDisableBecauseIsBrowserExtenstion ? false : options.enabled, 16820 stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), 16821 integrations: getIntegrationsToSetup({ 16822 integrations: options.integrations, 16823 defaultIntegrations 16824 }), 16825 transport: options.transport || makeFetchTransport 16826 }; 16827 setNormalizeStringifier(normalizeStringifyValue$1); 16828 return initAndBind(BrowserClient, clientOptions); 16829} 16830function forceLoad() {} 16831function onLoad(callback) { 16832 callback(); 16833} 16834function init_sdk$1() { 16835 return (init_sdk$1 = __esmMin((() => { 16836 init_eventFilters(), init_functiontostring(), init_conversationId(), init_dedupe(), init_integration(), init_stacktrace(), init_normalize(), init_sdk(); 16837 init_client$1(); 16838 init_breadcrumbs$1(); 16839 init_browserapierrors(); 16840 init_browsersession(); 16841 init_culturecontext(); 16842 init_globalhandlers(); 16843 init_httpcontext(); 16844 init_linkederrors(); 16845 init_stack_parsers(); 16846 init_fetch$2(); 16847 init_normalizeStringifyValue(); 16848 init_detectBrowserExtension(); 16849 })))(); 16850} 16851//#endregion 16852//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/report-dialog.js 16853function showReportDialog(options = {}) { 16854 const optionalDocument = WINDOW$4.document; 16855 const injectionPoint = optionalDocument?.head || optionalDocument?.body; 16856 if (!injectionPoint) { 16857 DEBUG_BUILD$2 && debug$2.error("[showReportDialog] Global document not defined"); 16858 return; 16859 } 16860 const scope = getCurrentScope(); 16861 const dsn = getClient()?.getDsn(); 16862 if (!dsn) { 16863 DEBUG_BUILD$2 && debug$2.error("[showReportDialog] DSN not configured"); 16864 return; 16865 } 16866 const mergedOptions = { 16867 ...options, 16868 user: { 16869 ...scope.getUser(), 16870 ...options.user 16871 }, 16872 eventId: options.eventId || lastEventId() 16873 }; 16874 const script = WINDOW$4.document.createElement("script"); 16875 script.async = true; 16876 script.crossOrigin = "anonymous"; 16877 script.src = getReportDialogEndpoint(dsn, mergedOptions); 16878 const { onLoad, onClose } = mergedOptions; 16879 if (onLoad) script.onload = onLoad; 16880 if (onClose) { 16881 const reportDialogClosedMessageHandler = (event) => { 16882 if (event.data === "__sentry_reportdialog_closed__") try { 16883 onClose(); 16884 } finally { 16885 WINDOW$4.removeEventListener("message", reportDialogClosedMessageHandler); 16886 } 16887 }; 16888 WINDOW$4.addEventListener("message", reportDialogClosedMessageHandler); 16889 } 16890 injectionPoint.appendChild(script); 16891} 16892function init_report_dialog() { 16893 return (init_report_dialog = __esmMin((() => { 16894 init_debug_logger(), init_currentScopes(), init_exports(), init_api(); 16895 init_debug_build$2(); 16896 init_helpers(); 16897 })))(); 16898} 16899//#endregion 16900//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/reportingobserver.js 16901var WINDOW$2, INTEGRATION_NAME$7, SETUP_CLIENTS, _reportingObserverIntegration, reportingObserverIntegration; 16902function init_reportingobserver() { 16903 return (init_reportingobserver = __esmMin((() => { 16904 init_integration(), init_supports(), init_worldwide(), init_currentScopes(), init_exports(); 16905 WINDOW$2 = GLOBAL_OBJ; 16906 INTEGRATION_NAME$7 = "ReportingObserver"; 16907 SETUP_CLIENTS = /* @__PURE__ */ new WeakMap(); 16908 _reportingObserverIntegration = ((options = {}) => { 16909 const types = options.types || [ 16910 "crash", 16911 "deprecation", 16912 "intervention" 16913 ]; 16914 function handler(reports) { 16915 if (!SETUP_CLIENTS.has(getClient())) return; 16916 for (const report of reports) withScope((scope) => { 16917 scope.setExtra("url", report.url); 16918 const label = `ReportingObserver [${report.type}]`; 16919 let details = "No details available"; 16920 if (report.body) { 16921 const plainBody = {}; 16922 for (const prop in report.body) plainBody[prop] = report.body[prop]; 16923 scope.setExtra("body", plainBody); 16924 if (report.type === "crash") { 16925 const body = report.body; 16926 details = [body.crashId || "", body.reason || ""].join(" ").trim() || details; 16927 } else details = report.body.message || details; 16928 } 16929 captureMessage(`${label}: ${details}`); 16930 }); 16931 } 16932 return { 16933 name: INTEGRATION_NAME$7, 16934 setupOnce() { 16935 if (!supportsReportingObserver()) return; 16936 new WINDOW$2.ReportingObserver(handler, { 16937 buffered: true, 16938 types 16939 }).observe(); 16940 }, 16941 setup(client) { 16942 SETUP_CLIENTS.set(client, true); 16943 } 16944 }; 16945 }); 16946 reportingObserverIntegration = defineIntegration(_reportingObserverIntegration); 16947 })))(); 16948} 16949//#endregion 16950//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/httpclient.js 16951function _fetchResponseHandler(options, requestInfo, response, requestInit, error) { 16952 if (_shouldCaptureResponse(options, response.status, response.url)) {
16953 const request = _getRequest(requestInfo, requestInit); 16954 let requestHeaders, responseHeaders, requestCookies, responseCookies; 16955 const dc = _getDataCollectionSettings(); 16956 if (dc.requestHeaders !== false) requestHeaders = filterKeyValueData(_extractFetchHeaders(request.headers), dc.requestHeaders); 16957 if (dc.responseHeaders !== false) responseHeaders = filterKeyValueData(_extractFetchHeaders(response.headers), dc.responseHeaders); 16958 if (dc.cookies !== false) { 16959 const reqCookieStr = request.headers.get("Cookie") || void 0; 16960 if (reqCookieStr) { 16961 const filtered = filterCookies(reqCookieStr, dc.cookies); 16962 if (typeof filtered === "object") requestCookies = filtered; 16963 } 16964 const resCookieStr = response.headers.get("Set-Cookie") || void 0; 16965 if (resCookieStr) { 16966 const filtered = filterCookies(resCookieStr, dc.cookies); 16967 if (typeof filtered === "object") responseCookies = filtered; 16968 } 16969 } 16970 captureEvent(_createEvent({ 16971 url: request.url, 16972 method: request.method, 16973 status: response.status, 16974 requestHeaders, 16975 responseHeaders, 16976 requestCookies, 16977 responseCookies, 16978 error, 16979 type: "fetch" 16980 })); 16981 } 16982} 16983function _xhrResponseHandler(options, xhr, method, headers, error) { 16984 if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) { 16985 let requestHeaders, responseCookies, responseHeaders; 16986 const dc = _getDataCollectionSettings(); 16987 if (dc.cookies !== false) try { 16988 const cookieString = xhr.getResponseHeader("Set-Cookie") || xhr.getResponseHeader("set-cookie") || void 0; 16989 if (cookieString) { 16990 const filtered = filterCookies(cookieString, dc.cookies); 16991 if (typeof filtered === "object") responseCookies = filtered; 16992 } 16993 } catch {} 16994 if (dc.responseHeaders !== false) try { 16995 responseHeaders = filterKeyValueData(_getXHRResponseHeaders(xhr), dc.responseHeaders); 16996 } catch {} 16997 if (dc.requestHeaders !== false) requestHeaders = filterKeyValueData(headers, dc.requestHeaders); 16998 captureEvent(_createEvent({ 16999 url: xhr.responseURL, 17000 method, 17001 status: xhr.status, 17002 requestHeaders, 17003 responseHeaders, 17004 responseCookies, 17005 error, 17006 type: "xhr" 17007 })); 17008 } 17009} 17010function _getResponseSizeFromHeaders(headers) { 17011 if (headers) { 17012 const contentLength = headers["Content-Length"] || headers["content-length"]; 17013 if (contentLength) return parseInt(contentLength, 10); 17014 } 17015} 17016function _extractFetchHeaders(headers) { 17017 const result = {}; 17018 headers.forEach((value, key) => { 17019 result[key] = value; 17020 }); 17021 return result; 17022} 17023function _getXHRResponseHeaders(xhr) { 17024 const headers = xhr.getAllResponseHeaders(); 17025 if (!headers) return {}; 17026 return headers.split("\r\n").reduce((acc, line) => { 17027 const [key, value] = line.split(": "); 17028 if (key && value) acc[key] = value; 17029 return acc; 17030 }, {}); 17031} 17032function _isInGivenRequestTargets(failedRequestTargets, target) { 17033 return failedRequestTargets.some((givenRequestTarget) => { 17034 if (typeof givenRequestTarget === "string") return target.includes(givenRequestTarget); 17035 return givenRequestTarget.test(target); 17036 }); 17037} 17038function _isInGivenStatusRanges(failedRequestStatusCodes, status) { 17039 return failedRequestStatusCodes.some((range) => { 17040 if (typeof range === "number") return range === status; 17041 return status >= range[0] && status <= range[1]; 17042 }); 17043} 17044function _wrapFetch(client, options) { 17045 if (!supportsNativeFetch()) return; 17046 addFetchInstrumentationHandler((handlerData) => { 17047 if (getClient() !== client) return; 17048 const { response, args, error, virtualError } = handlerData; 17049 const [requestInfo, requestInit] = args; 17050 if (!response) return; 17051 _fetchResponseHandler(options, requestInfo, response, requestInit, error || virtualError); 17052 }, false); 17053} 17054function _wrapXHR(client, options) { 17055 if (!("XMLHttpRequest" in GLOBAL_OBJ)) return; 17056 addXhrInstrumentationHandler((handlerData) => { 17057 if (getClient() !== client) return; 17058 const { error, virtualError } = handlerData; 17059 const xhr = handlerData.xhr; 17060 const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY]; 17061 if (!sentryXhrData) return; 17062 const { method, request_headers: headers } = sentryXhrData; 17063 try { 17064 _xhrResponseHandler(options, xhr, method, headers, error || virtualError); 17065 } catch (e) { 17066 DEBUG_BUILD$2 && debug$2.warn("Error while extracting response event form XHR response", e); 17067 } 17068 }); 17069} 17070function _shouldCaptureResponse(options, status, url) { 17071 return _isInGivenStatusRanges(options.failedRequestStatusCodes, status) && _isInGivenRequestTargets(options.failedRequestTargets, url) && !isSentryRequestUrl(url, getClient()); 17072} 17073function _createEvent(data) { 17074 const client = getClient(); 17075 const virtualStackTrace = client && data.error && data.error instanceof Error ? data.error.stack : void 0; 17076 const stack = virtualStackTrace && client ? client.getOptions().stackParser(virtualStackTrace, 0, 1) : void 0; 17077 const message = `HTTP Client Error with status code: ${data.status}`; 17078 const event = { 17079 message, 17080 exception: { values: [{ 17081 type: "Error", 17082 value: message, 17083 stacktrace: stack ? { frames: stack } : void 0 17084 }] }, 17085 request: { 17086 url: data.url, 17087 method: data.method, 17088 headers: data.requestHeaders, 17089 cookies: data.requestCookies 17090 }, 17091 contexts: { response: { 17092 status_code: data.status, 17093 headers: data.responseHeaders, 17094 cookies: data.responseCookies, 17095 body_size: _getResponseSizeFromHeaders(data.responseHeaders) 17096 } } 17097 }; 17098 addExceptionMechanism(event, { 17099 type: `auto.http.client.${data.type}`, 17100 handled: false 17101 }); 17102 return event; 17103}
17104function _getRequest(requestInfo, requestInit) { 17105 if (!requestInit && requestInfo instanceof Request) return requestInfo; 17106 if (requestInfo instanceof Request && requestInfo.bodyUsed) return requestInfo; 17107 return new Request(requestInfo, requestInit); 17108} 17109function _getDataCollectionSettings() { 17110 const client = getClient(); 17111 if (!client) return { 17112 cookies: false, 17113 requestHeaders: false, 17114 responseHeaders: false 17115 }; 17116 const options = client.getOptions(); 17117 if (options.dataCollection == null) { 17118 const enabled = Boolean(options.sendDefaultPii); 17119 return { 17120 cookies: enabled, 17121 requestHeaders: enabled, 17122 responseHeaders: enabled 17123 }; 17124 } 17125 const { cookies, httpHeaders } = client.getDataCollectionOptions(); 17126 return { 17127 cookies, 17128 requestHeaders: httpHeaders.request, 17129 responseHeaders: httpHeaders.response 17130 }; 17131} 17132var INTEGRATION_NAME$6, _httpClientIntegration, httpClientIntegration; 17133function init_httpclient() { 17134 return (init_httpclient = __esmMin((() => { 17135 init_integration(), init_supports(), init_fetch$1(), init_currentScopes(), init_worldwide(), init_debug_logger(), init_filterKeyValueData(), init_filterCookies(), init_exports(), init_isSentryRequestUrl(), init_misc(); 17136 init_xhr(); 17137 init_debug_build$2(); 17138 INTEGRATION_NAME$6 = "HttpClient"; 17139 _httpClientIntegration = ((options = {}) => { 17140 const _options = { 17141 failedRequestStatusCodes: [[500, 599]], 17142 failedRequestTargets: [/.*/], 17143 ...options 17144 }; 17145 return { 17146 name: INTEGRATION_NAME$6, 17147 setup(client) { 17148 _wrapFetch(client, _options); 17149 _wrapXHR(client, _options); 17150 } 17151 }; 17152 }); 17153 httpClientIntegration = defineIntegration(_httpClientIntegration); 17154 })))(); 17155} 17156//#endregion 17157//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/contextlines.js 17158function addSourceContext(event, contextLines) { 17159 const doc = WINDOW$1.document; 17160 const htmlFilename = WINDOW$1.location && stripUrlQueryAndFragment(WINDOW$1.location.href); 17161 if (!doc || !htmlFilename) return event; 17162 const exceptions = event.exception?.values; 17163 if (!exceptions?.length) return event; 17164 const html = doc.documentElement.innerHTML; 17165 if (!html) return event; 17166 const htmlLines = [ 17167 "<!DOCTYPE html>", 17168 "<html>", 17169 ...html.split("\n"), 17170 "</html>" 17171 ]; 17172 exceptions.forEach((exception) => { 17173 const stacktrace = exception.stacktrace; 17174 if (stacktrace?.frames) stacktrace.frames = stacktrace.frames.map((frame) => applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines)); 17175 }); 17176 return event; 17177} 17178function applySourceContextToFrame(frame, htmlLines, htmlFilename, linesOfContext) { 17179 if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) return frame; 17180 addContextToFrame(htmlLines, frame, linesOfContext); 17181 return frame; 17182} 17183var WINDOW$1, DEFAULT_LINES_OF_CONTEXT, INTEGRATION_NAME$5, _contextLinesIntegration, contextLinesIntegration; 17184function init_contextlines() { 17185 return (init_contextlines = __esmMin((() => { 17186 init_integration(), init_worldwide(), init_url(), init_misc(); 17187 WINDOW$1 = GLOBAL_OBJ; 17188 DEFAULT_LINES_OF_CONTEXT = 7; 17189 INTEGRATION_NAME$5 = "ContextLines"; 17190 _contextLinesIntegration = ((options = {}) => { 17191 return { 17192 name: INTEGRATION_NAME$5, 17193 processEvent(event, _hint, client) { 17194 return addSourceContext(event, options.frameContextLines ?? client?.getDataCollectionOptions().frameContextLines ?? DEFAULT_LINES_OF_CONTEXT); 17195 } 17196 }; 17197 }); 17198 contextLinesIntegration = defineIntegration(_contextLinesIntegration); 17199 })))(); 17200} 17201//#endregion 17202//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/graphqlClient.js 17203function _updateSpanWithGraphQLData(client, options) { 17204 client.on("beforeOutgoingRequestSpan", (span, hint) => { 17205 const spanAttributes = spanToJSON(span).data || {}; 17206 if (!(spanAttributes["sentry.op"] === "http.client")) return; 17207 const httpUrl = spanAttributes["url.full"] || spanAttributes["http.url"] || spanAttributes["url"]; 17208 const httpMethod = spanAttributes["http.request.method"] || spanAttributes["http.method"]; 17209 if (!isString(httpUrl) || !isString(httpMethod)) return; 17210 const { endpoints } = options;
17211 const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints); 17212 const payload = getRequestPayloadXhrOrFetch(hint); 17213 if (isTracedGraphqlEndpoint && payload) { 17214 const graphqlBody = getGraphQLRequestPayload(payload); 17215 if (graphqlBody) { 17216 const operationInfo = _getGraphQLOperation(graphqlBody); 17217 span.updateName(`${httpMethod} ${httpUrl} (${operationInfo})`); 17218 if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) span.setAttribute(qa, graphqlBody.query); 17219 if (isPersistedRequest(graphqlBody)) { 17220 span.setAttribute("graphql.persisted_query.hash.sha256", graphqlBody.extensions.persistedQuery.sha256Hash); 17221 span.setAttribute("graphql.persisted_query.version", graphqlBody.extensions.persistedQuery.version); 17222 } 17223 } 17224 } 17225 }); 17226} 17227function _updateBreadcrumbWithGraphQLData(client, options) { 17228 client.on("beforeOutgoingRequestBreadcrumb", (breadcrumb, handlerData) => { 17229 const { category, type, data } = breadcrumb; 17230 if (type === "http" && (category === "fetch" || category === "xhr")) { 17231 const httpUrl = data?.url; 17232 const { endpoints } = options; 17233 const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints); 17234 const payload = getRequestPayloadXhrOrFetch(handlerData); 17235 if (isTracedGraphqlEndpoint && data && payload) { 17236 const graphqlBody = getGraphQLRequestPayload(payload); 17237 if (!data.graphql && graphqlBody) { 17238 data["graphql.operation"] = _getGraphQLOperation(graphqlBody); 17239 if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) data[qa] = graphqlBody.query; 17240 if (isPersistedRequest(graphqlBody)) { 17241 data["graphql.persisted_query.hash.sha256"] = graphqlBody.extensions.persistedQuery.sha256Hash; 17242 data["graphql.persisted_query.version"] = graphqlBody.extensions.persistedQuery.version; 17243 } 17244 } 17245 } 17246 } 17247 }); 17248} 17249function _getGraphQLOperation(requestBody) { 17250 if (isPersistedRequest(requestBody)) return `persisted ${requestBody.operationName}`; 17251 if (isStandardRequest(requestBody)) { 17252 const { query: graphqlQuery, operationName: graphqlOperationName } = requestBody; 17253 const { operationName = graphqlOperationName, operationType } = parseGraphQLQuery(graphqlQuery); 17254 return operationName ? `${operationType} ${operationName}` : `${operationType}`; 17255 } 17256 return "unknown"; 17257} 17258function getRequestPayloadXhrOrFetch(hint) { 17259 const isXhr = "xhr" in hint; 17260 let body; 17261 if (isXhr) { 17262 const sentryXhrData = hint.xhr[SENTRY_XHR_DATA_KEY]; 17263 body = sentryXhrData && getBodyString(sentryXhrData.body)[0]; 17264 } else body = getBodyString(getFetchRequestArgBody(hint.input))[0]; 17265 return body; 17266} 17267function parseGraphQLQuery(query) { 17268 const namedQueryRe = /^(?:\s*)(query|mutation|subscription)(?:\s*)(\w+)(?:\s*)[{(]/; 17269 const unnamedQueryRe = /^(?:\s*)(query|mutation|subscription)(?:\s*)[{(]/; 17270 const namedMatch = query.match(namedQueryRe); 17271 if (namedMatch) return { 17272 operationType: namedMatch[1], 17273 operationName: namedMatch[2] 17274 }; 17275 const unnamedMatch = query.match(unnamedQueryRe); 17276 if (unnamedMatch) return { 17277 operationType: unnamedMatch[1], 17278 operationName: void 0 17279 }; 17280 return { 17281 operationType: void 0, 17282 operationName: void 0 17283 }; 17284} 17285function isStandardRequest(payload) { 17286 return isObjectLike(payload) && typeof payload.query === "string"; 17287} 17288function isPersistedRequest(payload) { 17289 return isObjectLike(payload) && typeof payload.operationName === "string" && isObjectLike(payload.extensions) && isObjectLike(payload.extensions.persistedQuery) && typeof payload.extensions.persistedQuery.sha256Hash === "string" && typeof payload.extensions.persistedQuery.version === "number"; 17290} 17291function getGraphQLRequestPayload(payload) { 17292 try { 17293 const requestBody = JSON.parse(payload); 17294 if (isStandardRequest(requestBody) || isPersistedRequest(requestBody)) return requestBody; 17295 return; 17296 } catch { 17297 return; 17298 } 17299} 17300var INTEGRATION_NAME$4, _graphqlClientIntegration, graphqlClientIntegration; 17301function init_graphqlClient() { 17302 return (init_graphqlClient = __esmMin((() => { 17303 init_integration(), init_spanUtils(), init_semanticAttributes(), init_is(), init_string(); 17304 init_xhr(), init_networkUtils(); 17305 init_attributes$1(); 17306 INTEGRATION_NAME$4 = "GraphQLClient"; 17307 _graphqlClientIntegration = ((options) => { 17308 return { 17309 name: INTEGRATION_NAME$4, 17310 setup(client) { 17311 _updateSpanWithGraphQLData(client, options); 17312 _updateBreadcrumbWithGraphQLData(client, options); 17313 } 17314 }; 17315 }); 17316 graphqlClientIntegration = defineIntegration(_graphqlClientIntegration); 17317 })))(); 17318} 17319//#endregion 17320//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/view-hierarchy.js 17321var viewHierarchyIntegration; 17322function init_view_hierarchy() { 17323 return (init_view_hierarchy = __esmMin((() => { 17324 init_integration(), init_browser(); 17325 init_helpers(); 17326 viewHierarchyIntegration = defineIntegration((options = {}) => { 17327 const skipHtmlTags = ["script"]; 17328 function walk(element, windows, depth = 0) { 17329 if (!element) return; 17330 const children = "shadowRoot" in element && element.shadowRoot ? element.shadowRoot.children : element.children; 17331 for (const child of children) { 17332 if (!(child instanceof HTMLElement)) continue; 17333 const componentName = getComponentName(child, 1) || void 0; 17334 const tagName = child.tagName.toLowerCase(); 17335 if (skipHtmlTags.includes(tagName)) continue; 17336 const result = options.onElement?.({ 17337 element: child, 17338 componentName, 17339 tagName, 17340 depth 17341 }) || {}; 17342 if (result === "skip") continue; 17343 if (result === "children") { 17344 walk(child, windows, depth + 1); 17345 continue; 17346 } 17347 const { x, y, width, height } = child.getBoundingClientRect(); 17348 const window = { 17349 identifier: child.id || void 0, 17350 type: componentName || tagName, 17351 visible: true,
17352 alpha: 1, 17353 height, 17354 width, 17355 x, 17356 y, 17357 ...result 17358 }; 17359 window.children = []; 17360 walk(child, window.children, depth + 1); 17361 windows.push(window); 17362 } 17363 } 17364 return { 17365 name: "ViewHierarchy", 17366 processEvent: (event, hint) => { 17367 if (event.type !== void 0 || options.shouldAttach?.(event, hint) === false) return event; 17368 const root = { 17369 rendering_system: "DOM", 17370 positioning: "absolute", 17371 windows: [] 17372 }; 17373 walk(options.rootElement?.() || WINDOW$4.document.body, root.windows); 17374 const attachment = { 17375 filename: "view-hierarchy.json", 17376 attachmentType: "event.view_hierarchy", 17377 contentType: "application/json", 17378 data: JSON.stringify(root) 17379 }; 17380 hint.attachments = hint.attachments || []; 17381 hint.attachments.push(attachment); 17382 return event; 17383 } 17384 }; 17385 }); 17386 })))(); 17387} 17388//#endregion 17389//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/replay/build/npm/esm/index.js 17390function isElement$1(n) { 17391 return n.nodeType === n.ELEMENT_NODE; 17392} 17393function isShadowRoot(n) { 17394 const host = n?.host; 17395 return Boolean(host?.shadowRoot === n); 17396} 17397function isNativeShadowDom(shadowRoot) { 17398 return Object.prototype.toString.call(shadowRoot) === "[object ShadowRoot]"; 17399} 17400function fixBrowserCompatibilityIssuesInCSS(cssText) { 17401 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;"); 17402 return cssText; 17403} 17404function escapeImportStatement(rule) { 17405 const { cssText } = rule; 17406 if (cssText.split("\"").length < 3) return cssText; 17407 const statement = ["@import", `url(${JSON.stringify(rule.href)})`]; 17408 if (rule.layerName === "") statement.push(`layer`); 17409 else if (rule.layerName) statement.push(`layer(${rule.layerName})`); 17410 if (rule.supportsText) statement.push(`supports(${rule.supportsText})`); 17411 if (rule.media.length) statement.push(rule.media.mediaText); 17412 return statement.join(" ") + ";"; 17413} 17414function stringifyStylesheet(s) { 17415 try { 17416 const rules = s.rules || s.cssRules; 17417 return rules ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join("")) : null; 17418 } catch (error) { 17419 return null; 17420 } 17421} 17422function fixAllCssProperty(rule) { 17423 let styles = ""; 17424 for (let i2 = 0; i2 < rule.style.length; i2++) { 17425 const styleDeclaration = rule.style; 17426 const attribute = styleDeclaration[i2]; 17427 const isImportant = styleDeclaration.getPropertyPriority(attribute); 17428 styles += `${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant ? ` !important` : ""};`; 17429 } 17430 return `${rule.selectorText} { ${styles} }`; 17431} 17432function stringifyRule(rule) { 17433 let importStringified; 17434 if (isCSSImportRule(rule)) try { 17435 importStringified = stringifyStylesheet(rule.styleSheet) || escapeImportStatement(rule); 17436 } catch (error) {} 17437 else if (isCSSStyleRule(rule)) { 17438 let cssText = rule.cssText; 17439 const needsSafariColonFix = rule.selectorText.includes(":"); 17440 const needsAllFix = typeof rule.style["all"] === "string" && rule.style["all"]; 17441 if (needsAllFix) cssText = fixAllCssProperty(rule); 17442 if (needsSafariColonFix) cssText = fixSafariColons(cssText); 17443 if (needsSafariColonFix || needsAllFix) return cssText; 17444 } 17445 return importStringified || rule.cssText; 17446} 17447function fixSafariColons(cssStringified) { 17448 return cssStringified.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm, "$1\\$2"); 17449} 17450function isCSSImportRule(rule) { 17451 return "styleSheet" in rule; 17452} 17453function isCSSStyleRule(rule) { 17454 return "selectorText" in rule; 17455} 17456function createMirror$1() { 17457 return new Mirror$1(); 17458} 17459function shouldMaskInput({ maskInputOptions, tagName, type }) { 17460 if (tagName === "OPTION") tagName = "SELECT"; 17461 return Boolean(maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === "password" || tagName === "INPUT" && !type && maskInputOptions["text"]); 17462} 17463function maskInputValue({ isMasked, element, value, maskInputFn }) { 17464 let text = value || ""; 17465 if (!isMasked) return text; 17466 if (maskInputFn) text = maskInputFn(text, element); 17467 return "*".repeat(text.length); 17468} 17469function toLowerCase(str) { 17470 return str.toLowerCase(); 17471} 17472function toUpperCase(str) { 17473 return str.toUpperCase(); 17474} 17475function is2DCanvasBlank(canvas) { 17476 const ctx = canvas.getContext("2d"); 17477 if (!ctx) return true; 17478 const chunkSize = 50; 17479 for (let x = 0; x < canvas.width; x += chunkSize) for (let y = 0; y < canvas.height; y += chunkSize) { 17480 const getImageData = ctx.getImageData; 17481 const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData; 17482 if (new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer).some((pixel) => pixel !== 0)) return false;
17483 } 17484 return true; 17485} 17486function getInputType(element) { 17487 const type = element.type; 17488 return element.hasAttribute("data-rr-is-password") ? "password" : type ? toLowerCase(type) : null; 17489} 17490function getInputValue(el, tagName, type) { 17491 if (tagName === "INPUT" && (type === "radio" || type === "checkbox")) return el.getAttribute("value") || ""; 17492 return el.value; 17493} 17494function extractFileExtension(path, baseURL) { 17495 let url; 17496 try { 17497 url = new URL(path, baseURL ?? window.location.href); 17498 } catch (err) { 17499 return null; 17500 } 17501 return url.pathname.match(/\.([0-9a-z]+)(?:$)/i)?.[1] ?? null; 17502} 17503function getImplementation$1(name) { 17504 const cached = cachedImplementations$1[name]; 17505 if (cached) return cached; 17506 const document2 = window.document; 17507 let impl = window[name]; 17508 if (document2 && typeof document2.createElement === "function") try { 17509 const sandbox = document2.createElement("iframe"); 17510 sandbox.hidden = true; 17511 document2.head.appendChild(sandbox); 17512 const contentWindow = sandbox.contentWindow; 17513 if (contentWindow && contentWindow[name]) impl = contentWindow[name]; 17514 document2.head.removeChild(sandbox); 17515 } catch (e) {} 17516 return cachedImplementations$1[name] = impl.bind(window); 17517} 17518function setTimeout$1$1(...rest) { 17519 return getImplementation$1("setTimeout")(...rest); 17520} 17521function clearTimeout$1(...rest) { 17522 return getImplementation$1("clearTimeout")(...rest); 17523} 17524function getIFrameContentDocument$1(iframe) { 17525 try { 17526 return iframe.contentDocument; 17527 } catch {} 17528} 17529function getIFrameContentWindow$1(iframe) { 17530 try { 17531 return iframe.contentWindow; 17532 } catch {} 17533} 17534function genId() { 17535 return _id++; 17536} 17537function getValidTagName(element) { 17538 if (element instanceof HTMLFormElement) return "form"; 17539 const processedTagName = toLowerCase(element.tagName); 17540 if (tagNameRegex.test(processedTagName)) return "div"; 17541 return processedTagName; 17542} 17543function extractOrigin(url) { 17544 let origin = ""; 17545 if (url.indexOf("//") > -1) origin = url.split("/").slice(0, 3).join("/"); 17546 else origin = url.split("/")[0]; 17547 origin = origin.split("?")[0]; 17548 return origin; 17549} 17550function filterCSSPropertiesFromInlineStyle(cssText, ignoredProperties) { 17551 if (!cssText || ignoredProperties.size === 0) return cssText; 17552 try { 17553 const properties = cssText.split(";"); 17554 const filteredProperties = []; 17555 for (let property of properties) { 17556 property = property.trim(); 17557 if (!property) continue; 17558 const colonIndex = property.indexOf(":"); 17559 if (colonIndex === -1) { 17560 filteredProperties.push(property); 17561 continue; 17562 } 17563 const propertyName = property.slice(0, colonIndex).trim(); 17564 if (!ignoredProperties.has(propertyName)) filteredProperties.push(property); 17565 } 17566 return filteredProperties.join("; ") + (filteredProperties.length > 0 && cssText.endsWith(";") ? ";" : ""); 17567 } catch (error) { 17568 console.warn("Error filtering CSS properties:", error); 17569 return cssText; 17570 } 17571} 17572function absoluteToStylesheet(cssText, href) { 17573 return (cssText || "").replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => { 17574 const filePath = path1 || path2 || path3; 17575 const maybeQuote = quote1 || quote2 || ""; 17576 if (!filePath) return origin; 17577 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) return `url(${maybeQuote}${filePath}${maybeQuote})`; 17578 if (DATA_URI.test(filePath)) return `url(${maybeQuote}${filePath}${maybeQuote})`; 17579 if (filePath[0] === "/") return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`; 17580 const stack = href.split("/"); 17581 const parts = filePath.split("/"); 17582 stack.pop(); 17583 for (const part of parts) if (part === ".") continue; 17584 else if (part === "..") stack.pop(); 17585 else stack.push(part); 17586 return `url(${maybeQuote}${stack.join("/")}${maybeQuote})`; 17587 }); 17588} 17589function getAbsoluteSrcsetString(doc, attributeValue) { 17590 if (attributeValue.trim() === "") return attributeValue; 17591 let pos = 0; 17592 function collectCharacters(regEx) { 17593 let chars2; 17594 const match = regEx.exec(attributeValue.substring(pos)); 17595 if (match) { 17596 chars2 = match[0]; 17597 pos += chars2.length; 17598 return chars2; 17599 } 17600 return ""; 17601 } 17602 const output = []; 17603 while (true) { 17604 collectCharacters(SRCSET_COMMAS_OR_SPACES); 17605 if (pos >= attributeValue.length) break; 17606 let url = collectCharacters(SRCSET_NOT_SPACES); 17607 if (url.slice(-1) === ",") { 17608 url = absoluteToDoc(doc, url.substring(0, url.length - 1)); 17609 output.push(url); 17610 } else { 17611 let descriptorsStr = ""; 17612 url = absoluteToDoc(doc, url); 17613 let inParens = false;
17614 while (true) { 17615 const c = attributeValue.charAt(pos); 17616 if (c === "") { 17617 output.push((url + descriptorsStr).trim()); 17618 break; 17619 } else if (!inParens) { 17620 if (c === ",") { 17621 pos += 1; 17622 output.push((url + descriptorsStr).trim()); 17623 break; 17624 } else if (c === "(") inParens = true; 17625 } else if (c === ")") inParens = false; 17626 descriptorsStr += c; 17627 pos += 1; 17628 } 17629 } 17630 } 17631 return output.join(", "); 17632} 17633function absoluteToDoc(doc, attributeValue) { 17634 if (!attributeValue || attributeValue.trim() === "") return attributeValue; 17635 return getHref(doc, attributeValue); 17636} 17637function isSVGElement(el) { 17638 return Boolean(el.tagName === "svg" || el.ownerSVGElement); 17639} 17640function getHref(doc, customHref) { 17641 let a = cachedDocument.get(doc); 17642 if (!a) { 17643 a = doc.createElement("a"); 17644 cachedDocument.set(doc, a); 17645 } 17646 if (!customHref) customHref = ""; 17647 else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) return customHref; 17648 a.setAttribute("href", customHref); 17649 return a.href; 17650} 17651function transformAttribute(doc, tagName, name, value, element, maskAttributeFn, ignoreCSSAttributes) { 17652 if (!value) return value; 17653 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) return absoluteToDoc(doc, value); 17654 else if (name === "xlink:href" && value[0] !== "#") return absoluteToDoc(doc, value); 17655 else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) return absoluteToDoc(doc, value); 17656 else if (name === "srcset") return getAbsoluteSrcsetString(doc, value); 17657 else if (name === "style") { 17658 let processedStyle = absoluteToStylesheet(value, getHref(doc)); 17659 if (ignoreCSSAttributes && ignoreCSSAttributes.size > 0) processedStyle = filterCSSPropertiesFromInlineStyle(processedStyle, ignoreCSSAttributes); 17660 return processedStyle; 17661 } else if (tagName === "object" && name === "data") return absoluteToDoc(doc, value); 17662 if (typeof maskAttributeFn === "function") return maskAttributeFn(name, value, element); 17663 return value; 17664} 17665function ignoreAttribute(tagName, name, _value) { 17666 return (tagName === "video" || tagName === "audio") && name === "autoplay"; 17667} 17668function _isBlockedElement(element, blockClass, blockSelector, unblockSelector) { 17669 try { 17670 if (unblockSelector && element.matches(unblockSelector)) return false; 17671 if (typeof blockClass === "string") { 17672 if (element.classList.contains(blockClass)) return true; 17673 } else for (let eIndex = element.classList.length; eIndex--;) { 17674 const className = element.classList[eIndex]; 17675 if (blockClass.test(className)) return true; 17676 } 17677 if (blockSelector) return element.matches(blockSelector); 17678 } catch (e) {} 17679 return false; 17680} 17681function elementClassMatchesRegex$1(el, regex) { 17682 for (let eIndex = el.classList.length; eIndex--;) { 17683 const className = el.classList[eIndex]; 17684 if (regex.test(className)) return true; 17685 } 17686 return false; 17687} 17688function distanceToMatch$1(node, matchPredicate, limit = Infinity, distance = 0) { 17689 if (!node) return -1; 17690 if (node.nodeType !== node.ELEMENT_NODE) return -1; 17691 if (distance > limit) return -1; 17692 if (matchPredicate(node)) return distance; 17693 return distanceToMatch$1(node.parentNode, matchPredicate, limit, distance + 1); 17694} 17695function createMatchPredicate$1(className, selector) { 17696 return (node) => { 17697 const el = node; 17698 if (el === null) return false; 17699 try { 17700 if (className) { 17701 if (typeof className === "string") { 17702 if (el.matches(`.${className}`)) return true; 17703 } else if (elementClassMatchesRegex$1(el, className)) return true; 17704 } 17705 if (selector && el.matches(selector)) return true; 17706 return false; 17707 } catch { 17708 return false; 17709 } 17710 }; 17711} 17712function needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) { 17713 try { 17714 const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement; 17715 if (el === null) return false; 17716 if (el.tagName === "INPUT") { 17717 const autocomplete = el.getAttribute("autocomplete"); 17718 if ([ 17719 "current-password", 17720 "new-password", 17721 "cc-number", 17722 "cc-exp", 17723 "cc-exp-month", 17724 "cc-exp-year", 17725 "cc-csc" 17726 ].includes(autocomplete)) return true; 17727 } 17728 let maskDistance = -1; 17729 let unmaskDistance = -1; 17730 if (maskAllText) { 17731 unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector)); 17732 if (unmaskDistance < 0) return true; 17733 maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity); 17734 } else { 17735 maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector)); 17736 if (maskDistance < 0) return false;
17737 unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity); 17738 } 17739 return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText; 17740 } catch (e) {} 17741 return !!maskAllText; 17742} 17743function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) { 17744 const win = getIFrameContentWindow$1(iframeEl); 17745 if (!win) return; 17746 let fired = false; 17747 let readyState; 17748 try { 17749 readyState = win.document.readyState; 17750 } catch (error) { 17751 return; 17752 } 17753 if (readyState !== "complete") { 17754 const timer = setTimeout$1$1(() => { 17755 if (!fired) { 17756 listener(); 17757 fired = true; 17758 } 17759 }, iframeLoadTimeout); 17760 iframeEl.addEventListener("load", () => { 17761 clearTimeout$1(timer); 17762 fired = true; 17763 listener(); 17764 }); 17765 return; 17766 } 17767 const blankUrl = "about:blank"; 17768 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") { 17769 setTimeout$1$1(listener, 0); 17770 return iframeEl.addEventListener("load", listener); 17771 } 17772 iframeEl.addEventListener("load", listener); 17773} 17774function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) { 17775 let fired = false; 17776 let styleSheetLoaded; 17777 try { 17778 styleSheetLoaded = link.sheet; 17779 } catch (error) { 17780 styleSheetLoaded = null; 17781 } 17782 if (styleSheetLoaded) return; 17783 const timer = setTimeout$1$1(() => { 17784 if (!fired) { 17785 listener(); 17786 fired = true; 17787 } 17788 }, styleSheetLoadTimeout); 17789 link.addEventListener("load", () => { 17790 clearTimeout$1(timer); 17791 fired = true; 17792 listener(); 17793 }); 17794} 17795function serializeNode(n, options) { 17796 const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, ignoreCSSAttributes } = options; 17797 const rootId = getRootId(doc, mirror); 17798 switch (n.nodeType) { 17799 case n.DOCUMENT_NODE: if (n.compatMode !== "CSS1Compat") return { 17800 type: NodeType$1.Document, 17801 childNodes: [], 17802 compatMode: n.compatMode 17803 }; 17804 else return { 17805 type: NodeType$1.Document, 17806 childNodes: [] 17807 }; 17808 case n.DOCUMENT_TYPE_NODE: return { 17809 type: NodeType$1.DocumentType, 17810 name: n.name, 17811 publicId: n.publicId, 17812 systemId: n.systemId, 17813 rootId 17814 }; 17815 case n.ELEMENT_NODE: return serializeElementNode(n, { 17816 doc, 17817 blockClass, 17818 blockSelector, 17819 unblockSelector, 17820 inlineStylesheet, 17821 maskAttributeFn, 17822 maskInputOptions, 17823 maskInputFn, 17824 dataURLOptions, 17825 inlineImages, 17826 recordCanvas, 17827 keepIframeSrcFn, 17828 newlyAddedElement, 17829 rootId, 17830 maskTextClass, 17831 unmaskTextClass, 17832 maskTextSelector, 17833 unmaskTextSelector, 17834 ignoreCSSAttributes 17835 }); 17836 case n.TEXT_NODE: return serializeTextNode(n, { 17837 doc, 17838 maskAllText, 17839 maskTextClass, 17840 unmaskTextClass, 17841 maskTextSelector, 17842 unmaskTextSelector, 17843 maskTextFn, 17844 maskInputOptions, 17845 maskInputFn, 17846 rootId 17847 }); 17848 case n.CDATA_SECTION_NODE: return { 17849 type: NodeType$1.CDATA, 17850 textContent: "", 17851 rootId 17852 }; 17853 case n.COMMENT_NODE: return { 17854 type: NodeType$1.Comment, 17855 textContent: n.textContent || "", 17856 rootId 17857 }; 17858 default: return false; 17859 } 17860} 17861function getRootId(doc, mirror) { 17862 if (!mirror.hasNode(doc)) return void 0; 17863 const docId = mirror.getId(doc); 17864 return docId === 1 ? void 0 : docId; 17865} 17866function serializeTextNode(n, options) { 17867 const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId } = options; 17868 const parentTagName = n.parentNode && n.parentNode.tagName; 17869 let textContent = n.textContent; 17870 const isStyle = parentTagName === "STYLE" ? true : void 0; 17871 const isScript = parentTagName === "SCRIPT" ? true : void 0; 17872 const isTextarea = parentTagName === "TEXTAREA" ? true : void 0; 17873 if (isStyle && textContent) { 17874 try { 17875 if (n.nextSibling || n.previousSibling) {} else if (n.parentNode.sheet?.cssRules) textContent = stringifyStylesheet(n.parentNode.sheet); 17876 } catch (err) { 17877 console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n); 17878 } 17879 textContent = absoluteToStylesheet(textContent, getHref(options.doc)); 17880 } 17881 if (isScript) textContent = "SCRIPT_PLACEHOLDER"; 17882 const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText); 17883 if (!isStyle && !isScript && !isTextarea && textContent && forceMask) textContent = maskTextFn ? maskTextFn(textContent, n.parentElement) : textContent.replace(/[\S]/g, "*"); 17884 if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) textContent = maskInputFn ? maskInputFn(textContent, n.parentNode) : textContent.replace(/[\S]/g, "*"); 17885 if (parentTagName === "OPTION" && textContent) textContent = maskInputValue({ 17886 isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({ 17887 type: null, 17888 tagName: parentTagName, 17889 maskInputOptions 17890 })), 17891 element: n, 17892 value: textContent, 17893 maskInputFn 17894 }); 17895 return { 17896 type: NodeType$1.Text, 17897 textContent: textContent || "", 17898 isStyle, 17899 rootId 17900 }; 17901} 17902function serializeElementNode(n, options) { 17903 const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, ignoreCSSAttributes } = options; 17904 const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector); 17905 const tagName = getValidTagName(n); 17906 let attributes2 = {}; 17907 const len = n.attributes.length; 17908 for (let i2 = 0; i2 < len; i2++) { 17909 const attr = n.attributes[i2]; 17910 if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) attributes2[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.n
17910ame), attr.value, n, maskAttributeFn, ignoreCSSAttributes); 17911 } 17912 if (tagName === "link" && inlineStylesheet) { 17913 const stylesheet = Array.from(doc.styleSheets).find((s) => { 17914 return s.href === n.href; 17915 }); 17916 let cssText = null; 17917 if (stylesheet) cssText = stringifyStylesheet(stylesheet); 17918 if (cssText) { 17919 attributes2.rel = null; 17920 attributes2.href = null; 17921 attributes2.crossorigin = null; 17922 attributes2._cssText = absoluteToStylesheet(cssText, stylesheet.href); 17923 } 17924 } 17925 if (tagName === "style" && n.sheet && !(n.innerText || n.textContent || "").trim().length) { 17926 const cssText = stringifyStylesheet(n.sheet); 17927 if (cssText) attributes2._cssText = absoluteToStylesheet(cssText, getHref(doc)); 17928 } 17929 if (tagName === "input" || tagName === "textarea" || tagName === "select" || tagName === "option") { 17930 const el = n; 17931 const type = getInputType(el); 17932 const value = getInputValue(el, toUpperCase(tagName), type); 17933 const checked = el.checked; 17934 if (type !== "submit" && type !== "button" && value) { 17935 const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({ 17936 type, 17937 tagName: toUpperCase(tagName), 17938 maskInputOptions 17939 })); 17940 attributes2.value = maskInputValue({ 17941 isMasked: forceMask, 17942 element: el, 17943 value, 17944 maskInputFn 17945 }); 17946 } 17947 if (checked) attributes2.checked = checked; 17948 } 17949 if (tagName === "option") { 17950 if (n.selected && !maskInputOptions["select"]) attributes2.selected = true; 17951 else delete attributes2.selected; 17952 } 17953 if (tagName === "canvas" && recordCanvas) { 17954 if (n.__context === "2d") { 17955 if (!is2DCanvasBlank(n)) attributes2.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality); 17956 } else if (!("__context" in n)) { 17957 const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality); 17958 const blankCanvas = doc.createElement("canvas"); 17959 blankCanvas.width = n.width; 17960 blankCanvas.height = n.height; 17961 if (canvasDataURL !== blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality)) attributes2.rr_dataURL = canvasDataURL; 17962 } 17963 } 17964 if (tagName === "img" && inlineImages) { 17965 if (!canvasService) { 17966 canvasService = doc.createElement("canvas"); 17967 canvasCtx = canvasService.getContext("2d"); 17968 } 17969 const image = n; 17970 const imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>"; 17971 const priorCrossOrigin = image.crossOrigin; 17972 const recordInlineImage = () => { 17973 image.removeEventListener("load", recordInlineImage); 17974 try { 17975 canvasService.width = image.naturalWidth; 17976 canvasService.height = image.naturalHeight; 17977 canvasCtx.drawImage(image, 0, 0); 17978 attributes2.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality); 17979 } catch (err) { 17980 if (image.crossOrigin !== "anonymous") { 17981 image.crossOrigin = "anonymous"; 17982 if (image.complete && image.naturalWidth !== 0) recordInlineImage(); 17983 else image.addEventListener("load", recordInlineImage); 17984 return; 17985 } else console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`); 17986 } 17987 if (image.crossOrigin === "anonymous") priorCrossOrigin ? attributes2.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin"); 17988 }; 17989 if (image.complete && image.naturalWidth !== 0) recordInlineImage(); 17990 else image.addEventListener("load", recordInlineImage); 17991 } 17992 if (tagName === "audio" || tagName === "video") { 17993 attributes2.rr_mediaState = n.paused ? "paused" : "played"; 17994 attributes2.rr_mediaCurrentTime = n.currentTime; 17995 } 17996 if (!newlyAddedElement) { 17997 if (n.scrollLeft) attributes2.rr_scrollLeft = n.scrollLeft; 17998 if (n.scrollTop) attributes2.rr_scrollTop = n.scrollTop; 17999 } 18000 if (needBlock) { 18001 const { width, height } = n.getBoundingClientRect(); 18002 attributes2 = { 18003 class: attributes2.class, 18004 rr_width: `${width}px`, 18005 rr_height: `${height}px` 18006 }; 18007 } 18008 if (tagName === "iframe" && !keepIframeSrcFn(attributes2.src)) { 18009 if (!needBlock && !getIFrameContentDocument$1(n)) attributes2.rr_src = attributes2.src; 18010 delete attributes2.src; 18011 } 18012 let isCustomElement; 18013 try { 18014 if (customElements.get(tagName)) isCustomElement = true; 18015 } catch (e) {} 18016 return { 18017 type: NodeType$1.Element, 18018 tagName, 18019 attributes: attributes2, 18020 childNodes: [], 18021 isSVG: isSVGElement(n) || void 0, 18022 needBlock,
18023 rootId, 18024 isCustom: isCustomElement 18025 }; 18026} 18027function lowerIfExists(maybeAttr) { 18028 if (maybeAttr === void 0 || maybeAttr === null) return ""; 18029 else return maybeAttr.toLowerCase(); 18030} 18031function slimDOMExcluded(sn, slimDOMOptions) { 18032 if (slimDOMOptions.comment && sn.type === NodeType$1.Comment) return true; 18033 else if (sn.type === NodeType$1.Element) { 18034 if (slimDOMOptions.script && (sn.tagName === "script" || sn.tagName === "link" && (sn.attributes.rel === "preload" || sn.attributes.rel === "modulepreload") || sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) return true; 18035 else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) return true; 18036 else if (sn.tagName === "meta") { 18037 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) return true; 18038 else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) return true; 18039 else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) return true; 18040 else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) return true; 18041 else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) return true; 18042 else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) return true; 18043 } 18044 } 18045 return false; 18046} 18047function serializeNodeWithId(n, options) { 18048 const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5e3, onBlockedImageLoad, onStylesheetLoad, stylesheetLoadTimeout = 5e3, keepIframeSrcFn = () => false, newlyAddedElement = false, ignoreCSSAttributes } = options; 18049 let { preserveWhiteSpace = true } = options; 18050 const _serializedNode = serializeNode(n, { 18051 doc, 18052 mirror, 18053 blockClass, 18054 blockSelector, 18055 maskAllText, 18056 unblockSelector, 18057 maskTextClass, 18058 unmaskTextClass, 18059 maskTextSelector, 18060 unmaskTextSelector, 18061 inlineStylesheet, 18062 maskInputOptions, 18063 maskAttributeFn, 18064 maskTextFn, 18065 maskInputFn, 18066 dataURLOptions, 18067 inlineImages, 18068 recordCanvas, 18069 keepIframeSrcFn, 18070 newlyAddedElement, 18071 ignoreCSSAttributes 18072 }); 18073 if (!_serializedNode) { 18074 console.warn(n, "not serialized"); 18075 return null; 18076 } 18077 let id; 18078 if (mirror.hasNode(n)) id = mirror.getId(n); 18079 else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$1.Text && !_serializedNode.isStyle && !_serializedNode.textContent.trim().length) id = IGNORED_NODE; 18080 else id = genId(); 18081 const serializedNode2 = Object.assign(_serializedNode, { id }); 18082 mirror.add(n, serializedNode2); 18083 if (id === IGNORED_NODE) return null; 18084 if (onSerialize) onSerialize(n); 18085 let recordChild = !skipChild; 18086 if (serializedNode2.type === NodeType$1.Element) { 18087 recordChild = recordChild && !serializedNode2.needBlock; 18088 const shadowRoot = n.shadowRoot; 18089 if (shadowRoot && isNativeShadowDom(shadowRoot)) serializedNode2.isShadowHost = true; 18090 } 18091 if ((serializedNode2.type === NodeType$1.Document || serializedNode2.type === NodeType$1.Element) && recordChild) { 18092 if (slimDOMOptions.headWhitespace && serializedNode2.type === NodeType$1.Element && serializedNode2.tagName === "head") preserveWhiteSpace = false;
18093 const bypassOptions = { 18094 doc, 18095 mirror, 18096 blockClass, 18097 blockSelector, 18098 maskAllText, 18099 unblockSelector, 18100 maskTextClass, 18101 unmaskTextClass, 18102 maskTextSelector, 18103 unmaskTextSelector, 18104 skipChild, 18105 inlineStylesheet, 18106 maskInputOptions, 18107 maskAttributeFn, 18108 maskTextFn, 18109 maskInputFn, 18110 slimDOMOptions, 18111 dataURLOptions, 18112 inlineImages, 18113 recordCanvas, 18114 preserveWhiteSpace, 18115 onSerialize, 18116 onIframeLoad, 18117 iframeLoadTimeout, 18118 onBlockedImageLoad, 18119 onStylesheetLoad, 18120 stylesheetLoadTimeout, 18121 keepIframeSrcFn, 18122 ignoreCSSAttributes 18123 }; 18124 const childNodes = n.childNodes ? Array.from(n.childNodes) : []; 18125 for (const childN of childNodes) { 18126 const serializedChildNode = serializeNodeWithId(childN, bypassOptions); 18127 if (serializedChildNode) serializedNode2.childNodes.push(serializedChildNode); 18128 } 18129 if (isElement$1(n) && n.shadowRoot) for (const childN of Array.from(n.shadowRoot.childNodes)) { 18130 const serializedChildNode = serializeNodeWithId(childN, bypassOptions); 18131 if (serializedChildNode) { 18132 isNativeShadowDom(n.shadowRoot) && (serializedChildNode.isShadow = true); 18133 serializedNode2.childNodes.push(serializedChildNode); 18134 } 18135 } 18136 } 18137 if (n.parentNode && isShadowRoot(n.parentNode) && isNativeShadowDom(n.parentNode)) serializedNode2.isShadow = true; 18138 if (serializedNode2.type === NodeType$1.Element && serializedNode2.tagName === "iframe" && !serializedNode2.needBlock) onceIframeLoaded(n, () => { 18139 const iframeDoc = getIFrameContentDocument$1(n); 18140 if (iframeDoc && onIframeLoad) { 18141 const serializedIframeNode = serializeNodeWithId(iframeDoc, { 18142 doc: iframeDoc, 18143 mirror, 18144 blockClass, 18145 blockSelector, 18146 unblockSelector, 18147 maskAllText, 18148 maskTextClass, 18149 unmaskTextClass, 18150 maskTextSelector, 18151 unmaskTextSelector, 18152 skipChild: false, 18153 inlineStylesheet, 18154 maskInputOptions, 18155 maskAttributeFn, 18156 maskTextFn, 18157 maskInputFn, 18158 slimDOMOptions, 18159 dataURLOptions, 18160 inlineImages, 18161 recordCanvas, 18162 preserveWhiteSpace, 18163 onSerialize, 18164 onIframeLoad, 18165 iframeLoadTimeout, 18166 onStylesheetLoad, 18167 stylesheetLoadTimeout, 18168 keepIframeSrcFn, 18169 ignoreCSSAttributes 18170 }); 18171 if (serializedIframeNode) onIframeLoad(n, serializedIframeNode); 18172 } 18173 }, iframeLoadTimeout); 18174 if (serializedNode2.type === NodeType$1.Element && serializedNode2.tagName === "img" && !n.complete && serializedNode2.needBlock) { 18175 const image = n; 18176 const updateImageDimensions = () => { 18177 if (image.isConnected && !image.complete && onBlockedImageLoad) try { 18178 const rect = image.getBoundingClientRect(); 18179 if (rect.width > 0 && rect.height > 0) onBlockedImageLoad(image, serializedNode2, rect); 18180 } catch (error) {} 18181 image.removeEventListener("load", updateImageDimensions); 18182 }; 18183 if (image.isConnected) image.addEventListener("load", updateImageDimensions); 18184 } 18185 if (serializedNode2.type === NodeType$1.Element && serializedNode2.tagName === "link" && typeof serializedNode2.attributes.rel === "string" && (serializedNode2.attributes.rel === "stylesheet" || serializedNode2.attributes.rel === "preload" && typeof serializedNode2.attributes.href === "string" && extractFileExtension(serializedNode2.attributes.href) === "css")) onceStylesheetLoaded(n, () => { 18186 if (onStylesheetLoad) { 18187 const serializedLinkNode = serializeNodeWithId(n, { 18188 doc, 18189 mirror, 18190 blockClass, 18191 blockSelector, 18192 unblockSelector, 18193 maskAllText, 18194 maskTextClass, 18195 unmaskTextClass, 18196 maskTextSelector, 18197 unmaskTextSelector, 18198 skipChild: false, 18199 inlineStylesheet, 18200 maskInputOptions, 18201 maskAttributeFn, 18202 maskTextFn, 18203 maskInputFn, 18204 slimDOMOptions, 18205 dataURLOptions, 18206 inlineImages, 18207 recordCanvas, 18208 preserveWhiteSpace, 18209 onSerialize, 18210 onIframeLoad, 18211 iframeLoadTimeout, 18212 onStylesheetLoad, 18213 stylesheetLoadTimeout, 18214 keepIframeSrcFn, 18215 ignoreCSSAttributes 18216 }); 18217 if (serializedLinkNode) onStylesheetLoad(n, serializedLinkNode); 18218 } 18219 }, stylesheetLoadTimeout); 18220 if (serializedNode2.type === NodeType$1.Element) delete serializedNode2.needBlock; 18221 return serializedNode2; 18222} 18223function snapshot(n, options) { 18224 const { mirror = new Mirror$1(), blockClass = "rr-block", blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onBlockedImageLoad, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, ignoreCSSAttributes = /* @__PURE__ */ new Set([]) } = options || {}; 18225 return serializeNodeWithId(n, { 18226 doc: n, 18227 mirror, 18228 blockClass, 18229 blockSelector, 18230 unblockSelector, 18231 maskAllText, 18232 maskTextClass, 18233 unmaskTextClass, 18234 maskTextSelector, 18235 unmaskTextSelector,
18236 skipChild: false, 18237 inlineStylesheet, 18238 maskInputOptions: maskAllInputs === true ? { 18239 color: true, 18240 date: true, 18241 "datetime-local": true, 18242 email: true, 18243 month: true, 18244 number: true, 18245 range: true, 18246 search: true, 18247 tel: true, 18248 text: true, 18249 time: true, 18250 url: true, 18251 week: true, 18252 textarea: true, 18253 select: true 18254 } : maskAllInputs === false ? {} : maskAllInputs, 18255 maskAttributeFn, 18256 maskTextFn, 18257 maskInputFn, 18258 slimDOMOptions: slimDOM === true || slimDOM === "all" ? { 18259 script: true, 18260 comment: true, 18261 headFavicon: true, 18262 headWhitespace: true, 18263 headMetaDescKeywords: slimDOM === "all", 18264 headMetaSocial: true, 18265 headMetaRobots: true, 18266 headMetaHttpEquiv: true, 18267 headMetaAuthorship: true, 18268 headMetaVerification: true 18269 } : slimDOM === false ? {} : slimDOM, 18270 dataURLOptions, 18271 inlineImages, 18272 recordCanvas, 18273 preserveWhiteSpace, 18274 onSerialize, 18275 onIframeLoad, 18276 iframeLoadTimeout, 18277 onBlockedImageLoad, 18278 onStylesheetLoad, 18279 stylesheetLoadTimeout, 18280 keepIframeSrcFn, 18281 newlyAddedElement: false, 18282 ignoreCSSAttributes 18283 }); 18284} 18285function on(type, fn, target = document) { 18286 const options = { 18287 capture: true, 18288 passive: true 18289 }; 18290 target.addEventListener(type, fn, options); 18291 return () => target.removeEventListener(type, fn, options); 18292} 18293function throttle$1(func, wait, options = {}) { 18294 let timeout = null; 18295 let previous = 0; 18296 return function(...args) { 18297 const now = Date.now(); 18298 if (!previous && options.leading === false) previous = now; 18299 const remaining = wait - (now - previous); 18300 const context = this; 18301 if (remaining <= 0 || remaining > wait) { 18302 if (timeout) { 18303 clearTimeout$2(timeout); 18304 timeout = null; 18305 } 18306 previous = now; 18307 func.apply(context, args); 18308 } else if (!timeout && options.trailing !== false) timeout = setTimeout$2(() => { 18309 previous = options.leading === false ? 0 : Date.now(); 18310 timeout = null; 18311 func.apply(context, args); 18312 }, remaining); 18313 }; 18314} 18315function hookSetter$1(target, key, d, isRevoked, win = window) { 18316 const original = win.Object.getOwnPropertyDescriptor(target, key); 18317 win.Object.defineProperty(target, key, isRevoked ? d : { set(value) { 18318 setTimeout$2(() => { 18319 d.set.call(this, value); 18320 }, 0); 18321 if (original && original.set) original.set.call(this, value); 18322 } }); 18323 return () => hookSetter$1(target, key, original || {}, true); 18324} 18325function patch$1(source, name, replacement) { 18326 try { 18327 if (!(name in source)) return () => {}; 18328 const original = source[name]; 18329 const wrapped = replacement(original); 18330 if (typeof wrapped === "function") { 18331 wrapped.prototype = wrapped.prototype || {}; 18332 Object.defineProperties(wrapped, { __rrweb_original__: { 18333 enumerable: false, 18334 value: original 18335 } }); 18336 } 18337 source[name] = wrapped; 18338 return () => { 18339 source[name] = original; 18340 }; 18341 } catch { 18342 return () => {}; 18343 } 18344} 18345function getWindowScroll(win) { 18346 const doc = win.document; 18347 return { 18348 left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc?.documentElement.scrollLeft || doc?.body?.parentElement?.scrollLeft || doc?.body?.scrollLeft || 0, 18349 top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : doc?.documentElement.scrollTop || doc?.body?.parentElement?.scrollTop || doc?.body?.scrollTop || 0 18350 }; 18351} 18352function getWindowHeight() { 18353 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight; 18354} 18355function getWindowWidth() { 18356 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth; 18357} 18358function closestElementOfNode$1(node) { 18359 if (!node) return null; 18360 try { 18361 return node.nodeType === node.ELEMENT_NODE ? node : node.parentElement; 18362 } catch (error) { 18363 return null; 18364 } 18365} 18366function isBlocked$1(node, blockClass, blockSelector, unblockSelector, checkAncestors) { 18367 if (!node) return false; 18368 const el = closestElementOfNode$1(node); 18369 if (!el) return false; 18370 const blockedPredicate = createMatchPredicate$1(blockClass, blockSelector); 18371 if (!checkAncestors) { 18372 const isUnblocked = unblockSelector && el.matches(unblockSelector); 18373 return blockedPredicate(el) && !isUnblocked; 18374 } 18375 const blockDistance = distanceToMatch$1(el, blockedPredicate); 18376 let unblockDistance = -1; 18377 if (blockDistance < 0) return false;
18378 if (unblockSelector) unblockDistance = distanceToMatch$1(el, createMatchPredicate$1(null, unblockSelector)); 18379 if (blockDistance > -1 && unblockDistance < 0) return true; 18380 return blockDistance < unblockDistance; 18381} 18382function isSerialized(n, mirror) { 18383 return mirror.getId(n) !== -1; 18384} 18385function isIgnored(n, mirror) { 18386 return mirror.getId(n) === IGNORED_NODE; 18387} 18388function isAncestorRemoved(target, mirror) { 18389 if (isShadowRoot(target)) return false; 18390 const id = mirror.getId(target); 18391 if (!mirror.has(id)) return true; 18392 if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) return false; 18393 if (!target.parentNode) return true; 18394 return isAncestorRemoved(target.parentNode, mirror); 18395} 18396function legacy_isTouchEvent(event) { 18397 return Boolean(event.changedTouches); 18398} 18399function polyfill(win = window) { 18400 if ("NodeList" in win && !win.NodeList.prototype.forEach) win.NodeList.prototype.forEach = Array.prototype.forEach; 18401 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) win.DOMTokenList.prototype.forEach = Array.prototype.forEach; 18402 if (!Node.prototype.contains) Node.prototype.contains = (...args) => { 18403 let node = args[0]; 18404 if (!(0 in args)) throw new TypeError("1 argument is required"); 18405 do 18406 if (this === node) return true; 18407 while (node = node && node.parentNode); 18408 return false; 18409 }; 18410} 18411function isSerializedIframe(n, mirror) { 18412 return Boolean(n.nodeName === "IFRAME" && mirror.getMeta(n)); 18413} 18414function isSerializedStylesheet(n, mirror) { 18415 return Boolean(n.nodeName === "LINK" && n.nodeType === n.ELEMENT_NODE && n.getAttribute && n.getAttribute("rel") === "stylesheet" && mirror.getMeta(n)); 18416} 18417function hasShadowRoot(n) { 18418 return Boolean(n?.shadowRoot); 18419} 18420function getShadowHost(n) { 18421 let shadowHost = null; 18422 if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE && n.getRootNode().host) shadowHost = n.getRootNode().host; 18423 return shadowHost; 18424} 18425function getRootShadowHost(n) { 18426 let rootShadowHost = n; 18427 let shadowHost; 18428 while (shadowHost = getShadowHost(rootShadowHost)) rootShadowHost = shadowHost; 18429 return rootShadowHost; 18430} 18431function shadowHostInDom(n) { 18432 const doc = n.ownerDocument; 18433 if (!doc) return false; 18434 const shadowHost = getRootShadowHost(n); 18435 return doc.contains(shadowHost); 18436} 18437function inDom(n) { 18438 const doc = n.ownerDocument; 18439 if (!doc) return false; 18440 return doc.contains(n) || shadowHostInDom(n); 18441} 18442function getImplementation$2(name) { 18443 const cached = cachedImplementations$2[name]; 18444 if (cached) return cached; 18445 const document2 = window.document; 18446 let impl = window[name]; 18447 if (document2 && typeof document2.createElement === "function") try { 18448 const sandbox = document2.createElement("iframe"); 18449 sandbox.hidden = true; 18450 document2.head.appendChild(sandbox); 18451 const contentWindow = sandbox.contentWindow; 18452 if (contentWindow && contentWindow[name]) impl = contentWindow[name]; 18453 document2.head.removeChild(sandbox); 18454 } catch (e) {} 18455 return cachedImplementations$2[name] = impl.bind(window); 18456} 18457function onRequestAnimationFrame$1(...rest) { 18458 return getImplementation$2("requestAnimationFrame")(...rest); 18459} 18460function setTimeout$2(...rest) { 18461 return getImplementation$2("setTimeout")(...rest); 18462} 18463function clearTimeout$2(...rest) { 18464 return getImplementation$2("clearTimeout")(...rest); 18465} 18466function registerErrorHandler$1(handler) { 18467 errorHandler$1 = handler; 18468} 18469function unregisterErrorHandler() { 18470 errorHandler$1 = void 0; 18471} 18472function getIFrameContentDocument(iframe) { 18473 try { 18474 return iframe.contentDocument; 18475 } catch (e2) {} 18476} 18477function getIFrameContentWindow(iframe) { 18478 try { 18479 return iframe.contentWindow; 18480 } catch (e2) {} 18481} 18482function isNodeInLinkedList(n2) { 18483 return "__ln" in n2; 18484} 18485function deepDelete(addsSet, n2) { 18486 addsSet.delete(n2); 18487 n2.childNodes?.forEach((childN) => deepDelete(addsSet, childN)); 18488} 18489function isParentRemoved(removes, n2, mirror2) { 18490 if (removes.length === 0) return false; 18491 return _isParentRemoved(removes, n2, mirror2); 18492} 18493function _isParentRemoved(removes, n2, mirror2) { 18494 let node = n2.parentNode; 18495 while (node) { 18496 const parentId = mirror2.getId(node); 18497 if (removes.some((r2) => r2.id === parentId)) return true; 18498 node = node.parentNode; 18499 } 18500 return false;
18501} 18502function isAncestorInSet(set, n2) { 18503 if (set.size === 0) return false; 18504 return _isAncestorInSet(set, n2); 18505} 18506function _isAncestorInSet(set, n2) { 18507 const { parentNode } = n2; 18508 if (!parentNode) return false; 18509 if (set.has(parentNode)) return true; 18510 return _isAncestorInSet(set, parentNode); 18511} 18512function getEventTarget(event) { 18513 try { 18514 if ("composedPath" in event) { 18515 const path = event.composedPath(); 18516 if (path.length) return path[0]; 18517 } else if ("path" in event && event.path.length) return event.path[0]; 18518 } catch {} 18519 return event && event.target; 18520} 18521function initMutationObserver(options, rootEl) { 18522 const mutationBuffer = new MutationBuffer(); 18523 mutationBuffers.push(mutationBuffer); 18524 mutationBuffer.init(options); 18525 let mutationObserverCtor = window.MutationObserver || window.__rrMutationObserver; 18526 const angularZoneSymbol = window?.Zone?.__symbol__?.("MutationObserver"); 18527 if (angularZoneSymbol && window[angularZoneSymbol]) mutationObserverCtor = window[angularZoneSymbol]; 18528 const observer = new mutationObserverCtor(callbackWrapper$1((mutations) => { 18529 if (options.onMutation && options.onMutation(mutations) === false) return; 18530 mutationBuffer.processMutations.bind(mutationBuffer)(mutations); 18531 })); 18532 observer.observe(rootEl, { 18533 attributes: true, 18534 attributeOldValue: true, 18535 characterData: true, 18536 characterDataOldValue: true, 18537 childList: true, 18538 subtree: true 18539 }); 18540 return observer; 18541} 18542function initMoveObserver({ mousemoveCb, sampling, doc, mirror: mirror2 }) { 18543 if (sampling.mousemove === false) return () => {}; 18544 const threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50; 18545 const callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500; 18546 let positions = []; 18547 let timeBaseline; 18548 const wrappedCb = throttle$1(callbackWrapper$1((source) => { 18549 const totalOffset = Date.now() - timeBaseline; 18550 mousemoveCb(positions.map((p) => { 18551 p.timeOffset -= totalOffset; 18552 return p; 18553 }), source); 18554 positions = []; 18555 timeBaseline = null; 18556 }), callbackThreshold); 18557 const updatePosition = callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => { 18558 const target = getEventTarget(evt); 18559 const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt; 18560 if (!timeBaseline) timeBaseline = nowTimestamp(); 18561 positions.push({ 18562 x: clientX, 18563 y: clientY, 18564 id: mirror2.getId(target), 18565 timeOffset: nowTimestamp() - timeBaseline 18566 }); 18567 wrappedCb(typeof DragEvent !== "undefined" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove); 18568 }), threshold, { trailing: false })); 18569 const handlers = [ 18570 on("mousemove", updatePosition, doc), 18571 on("touchmove", updatePosition, doc), 18572 on("drag", updatePosition, doc) 18573 ]; 18574 return callbackWrapper$1(() => { 18575 handlers.forEach((h) => h()); 18576 }); 18577} 18578function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) { 18579 if (sampling.mouseInteraction === false) return () => {}; 18580 const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction; 18581 const handlers = []; 18582 let currentPointerType = null; 18583 const getHandler = (eventKey) => { 18584 return (event) => { 18585 const target = getEventTarget(event); 18586 if (isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) return; 18587 let pointerType = null; 18588 let thisEventKey = eventKey; 18589 if ("pointerType" in event) { 18590 switch (event.pointerType) { 18591 case "mouse": 18592 pointerType = PointerTypes.Mouse; 18593 break; 18594 case "touch": 18595 pointerType = PointerTypes.Touch; 18596 break; 18597 case "pen": pointerType = PointerTypes.Pen; 18598 } 18599 if (pointerType === PointerTypes.Touch) { 18600 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) thisEventKey = "TouchStart"; 18601 else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) thisEventKey = "TouchEnd"; 18602 } else if (pointerType === PointerTypes.Pen); 18603 } else if (legacy_isTouchEvent(event)) pointerType = PointerTypes.Touch; 18604 if (pointerType !== null) { 18605 currentPointerType = pointerType; 18606 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) pointerType = null; 18607 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) { 18608 pointerType = currentPointerType; 18609 currentPointerType = null; 18610 } 18611 const e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event; 18612 if (!e2) return; 18613 const id = mirror2.getId(target); 18614 const { clientX, clientY } = e2; 18615 callbackWrapper$1(mouseInteractionCb)({ 18616 type: MouseInteractions[thisEventKey], 18617 id, 18618 x: clientX, 18619 y: clientY, 18620 ...pointerType !== null && { pointerType } 18621 }); 18622 }; 18623 }; 18624 Object.keys(MouseInteractions).filter((key) => Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false).forEach((eventKey) => { 18625 let eventName = toLowerCase(eventKey); 18626 const handler = getHandler(eventKey); 18627 if (window.PointerEvent) switch (MouseInteractions[eventKey]) { 18628 case MouseInteractions.MouseDown: 18629 case MouseInteractions.MouseUp: 18630 eventName = eventName.replace("mouse", "pointer"); 18631 break; 18632 case MouseInteractions.TouchStart: 18633 case MouseInteractions.TouchEnd: return; 18634 } 18635 handlers.push(on(eventName, handler, doc)); 18636 }); 18637 return callbackWrapper$1(() => {
18638 handlers.forEach((h) => h()); 18639 }); 18640} 18641function initScrollObserver({ scrollCb, doc, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) { 18642 return on("scroll", callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => { 18643 const target = getEventTarget(evt); 18644 if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) return; 18645 const id = mirror2.getId(target); 18646 if (target === doc && doc.defaultView) { 18647 const scrollLeftTop = getWindowScroll(doc.defaultView); 18648 scrollCb({ 18649 id, 18650 x: scrollLeftTop.left, 18651 y: scrollLeftTop.top 18652 }); 18653 } else scrollCb({ 18654 id, 18655 x: target.scrollLeft, 18656 y: target.scrollTop 18657 }); 18658 }), sampling.scroll || 100)), doc); 18659} 18660function initViewportResizeObserver({ viewportResizeCb }, { win }) { 18661 let lastH = -1; 18662 let lastW = -1; 18663 return on("resize", callbackWrapper$1(throttle$1(callbackWrapper$1(() => { 18664 const height = getWindowHeight(); 18665 const width = getWindowWidth(); 18666 if (lastH !== height || lastW !== width) { 18667 viewportResizeCb({ 18668 width: Number(width), 18669 height: Number(height) 18670 }); 18671 lastH = height; 18672 lastW = width; 18673 } 18674 }), 200)), win); 18675} 18676function initInputObserver({ inputCb, doc, mirror: mirror2, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector }) { 18677 function eventHandler(event) { 18678 let target = getEventTarget(event); 18679 const userTriggered = event.isTrusted; 18680 const tagName = target && toUpperCase(target.tagName); 18681 if (tagName === "OPTION") target = target.parentElement; 18682 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) return; 18683 const el = target; 18684 if (el.classList.contains(ignoreClass) || ignoreSelector && el.matches(ignoreSelector)) return; 18685 const type = getInputType(target); 18686 let text = getInputValue(el, tagName, type); 18687 let isChecked = false; 18688 const isInputMasked = shouldMaskInput({ 18689 maskInputOptions, 18690 tagName, 18691 type 18692 }); 18693 const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked); 18694 if (type === "radio" || type === "checkbox") isChecked = target.checked; 18695 text = maskInputValue({ 18696 isMasked: forceMask, 18697 element: target, 18698 value: text, 18699 maskInputFn 18700 }); 18701 cbWithDedup(target, userTriggeredOnInput ? { 18702 text, 18703 isChecked, 18704 userTriggered 18705 } : { 18706 text, 18707 isChecked 18708 }); 18709 const name = target.name; 18710 if (type === "radio" && name && isChecked) doc.querySelectorAll(`input[type="radio"][name="${name}"]`).forEach((el2) => { 18711 if (el2 !== target) { 18712 const text2 = maskInputValue({ 18713 isMasked: forceMask, 18714 element: el2, 18715 value: getInputValue(el2, tagName, type), 18716 maskInputFn 18717 }); 18718 cbWithDedup(el2, userTriggeredOnInput ? { 18719 text: text2, 18720 isChecked: !isChecked, 18721 userTriggered: false 18722 } : { 18723 text: text2, 18724 isChecked: !isChecked 18725 }); 18726 } 18727 }); 18728 } 18729 function cbWithDedup(target, v2) { 18730 const lastInputValue = lastInputValueMap.get(target); 18731 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) { 18732 lastInputValueMap.set(target, v2); 18733 const id = mirror2.getId(target); 18734 callbackWrapper$1(inputCb)({ 18735 ...v2, 18736 id 18737 }); 18738 } 18739 }
18740 const handlers = (sampling.input === "last" ? ["change"] : ["input", "change"]).map((eventName) => on(eventName, callbackWrapper$1(eventHandler), doc)); 18741 const currentWindow = doc.defaultView; 18742 if (!currentWindow) return () => { 18743 handlers.forEach((h) => h()); 18744 }; 18745 const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value"); 18746 const hookProperties = [ 18747 [currentWindow.HTMLInputElement.prototype, "value"], 18748 [currentWindow.HTMLInputElement.prototype, "checked"], 18749 [currentWindow.HTMLSelectElement.prototype, "value"], 18750 [currentWindow.HTMLTextAreaElement.prototype, "value"], 18751 [currentWindow.HTMLSelectElement.prototype, "selectedIndex"], 18752 [currentWindow.HTMLOptionElement.prototype, "selected"] 18753 ]; 18754 if (propertyDescriptor && propertyDescriptor.set) handlers.push(...hookProperties.map((p) => hookSetter$1(p[0], p[1], { set() { 18755 callbackWrapper$1(eventHandler)({ 18756 target: this, 18757 isTrusted: false 18758 }); 18759 } }, false, currentWindow))); 18760 return callbackWrapper$1(() => { 18761 handlers.forEach((h) => h()); 18762 }); 18763} 18764function getNestedCSSRulePositions(rule) { 18765 const positions = []; 18766 function recurse(childRule, pos) { 18767 if (hasNestedCSSRule("CSSGroupingRule") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule("CSSMediaRule") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule("CSSSupportsRule") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule("CSSConditionRule") && childRule.parentRule instanceof CSSConditionRule) { 18768 const index = Array.from(childRule.parentRule.cssRules).indexOf(childRule); 18769 pos.unshift(index); 18770 } else if (childRule.parentStyleSheet) { 18771 const index = Array.from(childRule.parentStyleSheet.cssRules).indexOf(childRule); 18772 pos.unshift(index); 18773 } 18774 return pos; 18775 } 18776 return recurse(rule, positions); 18777} 18778function getIdAndStyleId(sheet, mirror2, styleMirror) { 18779 let id, styleId; 18780 if (!sheet) return {}; 18781 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode); 18782 else styleId = styleMirror.getId(sheet); 18783 return { 18784 styleId, 18785 id 18786 }; 18787} 18788function initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) { 18789 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) return () => {}; 18790 const insertRule = win.CSSStyleSheet.prototype.insertRule; 18791 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18792 const [rule, index] = argumentsList; 18793 const { id, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); 18794 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18795 id, 18796 styleId, 18797 adds: [{ 18798 rule, 18799 index 18800 }] 18801 }); 18802 return target.apply(thisArg, argumentsList); 18803 }) }); 18804 const deleteRule = win.CSSStyleSheet.prototype.deleteRule; 18805 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18806 const [index] = argumentsList; 18807 const { id, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); 18808 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18809 id, 18810 styleId, 18811 removes: [{ index }] 18812 }); 18813 return target.apply(thisArg, argumentsList); 18814 }) }); 18815 let replace; 18816 if (win.CSSStyleSheet.prototype.replace) { 18817 replace = win.CSSStyleSheet.prototype.replace; 18818 win.CSSStyleSheet.prototype.replace = new Proxy(replace, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18819 const [text] = argumentsList; 18820 const { id, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); 18821 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18822 id, 18823 styleId, 18824 replace: text 18825 }); 18826 return target.apply(thisArg, argumentsList); 18827 }) }); 18828 } 18829 let replaceSync; 18830 if (win.CSSStyleSheet.prototype.replaceSync) { 18831 replaceSync = win.CSSStyleSheet.prototype.replaceSync; 18832 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18833 const [text] = argumentsList; 18834 const { id, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); 18835 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18836 id, 18837 styleId, 18838 replaceSync: text 18839 }); 18840 return target.apply(thisArg, argumentsList); 18841 }) }); 18842 } 18843 const supportedNestedCSSRuleTypes = {}; 18844 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule; 18845 else { 18846 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule; 18847 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule; 18848 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule; 18849 } 18850 const unmodifiedFunctions = {};
18851 Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => { 18852 unmodifiedFunctions[typeKey] = { 18853 insertRule: type.prototype.insertRule, 18854 deleteRule: type.prototype.deleteRule 18855 }; 18856 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18857 const [rule, index] = argumentsList; 18858 const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror); 18859 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18860 id, 18861 styleId, 18862 adds: [{ 18863 rule, 18864 index: [...getNestedCSSRulePositions(thisArg), index || 0] 18865 }] 18866 }); 18867 return target.apply(thisArg, argumentsList); 18868 }) }); 18869 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18870 const [index] = argumentsList; 18871 const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror); 18872 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({ 18873 id, 18874 styleId, 18875 removes: [{ index: [...getNestedCSSRulePositions(thisArg), index] }] 18876 }); 18877 return target.apply(thisArg, argumentsList); 18878 }) }); 18879 }); 18880 return callbackWrapper$1(() => { 18881 win.CSSStyleSheet.prototype.insertRule = insertRule; 18882 win.CSSStyleSheet.prototype.deleteRule = deleteRule; 18883 replace && (win.CSSStyleSheet.prototype.replace = replace); 18884 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync); 18885 Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => { 18886 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule; 18887 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule; 18888 }); 18889 }); 18890} 18891function initAdoptedStyleSheetObserver({ mirror: mirror2, stylesheetManager }, host) { 18892 let hostId = null; 18893 if (host.nodeName === "#document") hostId = mirror2.getId(host); 18894 else hostId = mirror2.getId(host.host); 18895 const patchTarget = host.nodeName === "#document" ? host.defaultView?.Document : host.ownerDocument?.defaultView?.ShadowRoot; 18896 const originalPropertyDescriptor = patchTarget?.prototype ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, "adoptedStyleSheets") : void 0; 18897 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return () => {}; 18898 Object.defineProperty(host, "adoptedStyleSheets", { 18899 configurable: originalPropertyDescriptor.configurable, 18900 enumerable: originalPropertyDescriptor.enumerable, 18901 get() { 18902 return originalPropertyDescriptor.get?.call(this); 18903 }, 18904 set(sheets) { 18905 const result = originalPropertyDescriptor.set?.call(this, sheets); 18906 if (hostId !== null && hostId !== -1) try { 18907 stylesheetManager.adoptStyleSheets(sheets, hostId); 18908 } catch (e2) {} 18909 return result; 18910 } 18911 }); 18912 return callbackWrapper$1(() => { 18913 Object.defineProperty(host, "adoptedStyleSheets", { 18914 configurable: originalPropertyDescriptor.configurable, 18915 enumerable: originalPropertyDescriptor.enumerable, 18916 get: originalPropertyDescriptor.get, 18917 set: originalPropertyDescriptor.set 18918 }); 18919 }); 18920} 18921function initStyleDeclarationObserver({ styleDeclarationCb, mirror: mirror2, ignoreCSSAttributes, stylesheetManager }, { win }) { 18922 const setProperty = win.CSSStyleDeclaration.prototype.setProperty; 18923 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18924 const [property, value, priority] = argumentsList; 18925 if (ignoreCSSAttributes.has(property)) return setProperty.apply(thisArg, [ 18926 property, 18927 value, 18928 priority 18929 ]); 18930 const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror2, stylesheetManager.styleMirror); 18931 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({ 18932 id, 18933 styleId, 18934 set: { 18935 property, 18936 value, 18937 priority 18938 }, 18939 index: getNestedCSSRulePositions(thisArg.parentRule) 18940 }); 18941 return target.apply(thisArg, argumentsList); 18942 }) }); 18943 const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty; 18944 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { 18945 const [property] = argumentsList; 18946 if (ignoreCSSAttributes.has(property)) return removeProperty.apply(thisArg, [property]); 18947 const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror2, stylesheetManager.styleMirror); 18948 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({ 18949 id, 18950 styleId, 18951 remove: { property }, 18952 index: getNestedCSSRulePositions(thisArg.parentRule) 18953 }); 18954 return target.apply(thisArg, argumentsList); 18955 }) }); 18956 return callbackWrapper$1(() => { 18957 win.CSSStyleDeclaration.prototype.setProperty = setProperty; 18958 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty; 18959 }); 18960} 18961function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror: mirror2, sampling, doc }) { 18962 const handler = callbackWrapper$1((type) => throttle$1(callbackWrapper$1((event) => { 18963 const target = getEventTarget(event); 18964 if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) return; 18965 const { currentTime, volume, muted, playbackRate } = target; 18966 mediaInteractionCb({ 18967 type, 18968 id: mirror2.getId(target), 18969 currentTime, 18970 volume, 18971 muted, 18972 playbackRate 18973 }); 18974 }), sampling.media || 500)); 18975 const handlers = [
18976 on("play", handler(MediaInteractions.Play), doc), 18977 on("pause", handler(MediaInteractions.Pause), doc), 18978 on("seeked", handler(MediaInteractions.Seeked), doc), 18979 on("volumechange", handler(MediaInteractions.VolumeChange), doc), 18980 on("ratechange", handler(MediaInteractions.RateChange), doc) 18981 ]; 18982 return callbackWrapper$1(() => { 18983 handlers.forEach((h) => h()); 18984 }); 18985} 18986function initFontObserver({ fontCb, doc }) { 18987 const win = doc.defaultView; 18988 if (!win) return () => {}; 18989 const handlers = []; 18990 const fontMap = /* @__PURE__ */ new WeakMap(); 18991 const originalFontFace = win.FontFace; 18992 win.FontFace = function FontFace2(family, source, descriptors) { 18993 const fontFace = new originalFontFace(family, source, descriptors); 18994 fontMap.set(fontFace, { 18995 family, 18996 buffer: typeof source !== "string", 18997 descriptors, 18998 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source))) 18999 }); 19000 return fontFace; 19001 }; 19002 const restoreHandler = patch$1(doc.fonts, "add", function(original) { 19003 return function(fontFace) { 19004 setTimeout$2(callbackWrapper$1(() => { 19005 const p = fontMap.get(fontFace); 19006 if (p) { 19007 fontCb(p); 19008 fontMap.delete(fontFace); 19009 } 19010 }), 0); 19011 return original.apply(this, [fontFace]); 19012 }; 19013 }); 19014 handlers.push(() => { 19015 win.FontFace = originalFontFace; 19016 }); 19017 handlers.push(restoreHandler); 19018 return callbackWrapper$1(() => { 19019 handlers.forEach((h) => h()); 19020 }); 19021} 19022function initSelectionObserver(param) { 19023 const { doc, mirror: mirror2, blockClass, blockSelector, unblockSelector, selectionCb } = param; 19024 let collapsed = true; 19025 const updateSelection = callbackWrapper$1(() => { 19026 const selection = doc.getSelection(); 19027 if (!selection || collapsed && selection?.isCollapsed) return; 19028 collapsed = selection.isCollapsed || false; 19029 const ranges = []; 19030 const count = selection.rangeCount || 0; 19031 for (let i2 = 0; i2 < count; i2++) { 19032 const { startContainer, startOffset, endContainer, endOffset } = selection.getRangeAt(i2); 19033 if (isBlocked$1(startContainer, blockClass, blockSelector, unblockSelector, true) || isBlocked$1(endContainer, blockClass, blockSelector, unblockSelector, true)) continue; 19034 ranges.push({ 19035 start: mirror2.getId(startContainer), 19036 startOffset, 19037 end: mirror2.getId(endContainer), 19038 endOffset 19039 }); 19040 } 19041 selectionCb({ ranges }); 19042 }); 19043 updateSelection(); 19044 return on("selectionchange", updateSelection); 19045} 19046function initCustomElementObserver({ doc, customElementCb }) { 19047 const win = doc.defaultView; 19048 if (!win || !win.customElements) return () => {}; 19049 return patch$1(win.customElements, "define", function(original) { 19050 return function(name, constructor, options) { 19051 try { 19052 customElementCb({ define: { name } }); 19053 } catch (e2) {} 19054 return original.apply(this, [ 19055 name, 19056 constructor, 19057 options 19058 ]); 19059 }; 19060 }); 19061} 19062function initObservers(o2, _hooks = {}) { 19063 const currentWindow = o2.doc.defaultView; 19064 if (!currentWindow) return () => {}; 19065 let mutationObserver; 19066 if (o2.recordDOM) mutationObserver = initMutationObserver(o2, o2.doc); 19067 const mousemoveHandler = initMoveObserver(o2); 19068 const mouseInteractionHandler = initMouseInteractionObserver(o2); 19069 const scrollHandler = initScrollObserver(o2); 19070 const viewportResizeHandler = initViewportResizeObserver(o2, { win: currentWindow }); 19071 const inputHandler = initInputObserver(o2); 19072 const mediaInteractionHandler = initMediaInteractionObserver(o2); 19073 let styleSheetObserver = () => {}; 19074 let adoptedStyleSheetObserver = () => {}; 19075 let styleDeclarationObserver = () => {}; 19076 let fontObserver = () => {}; 19077 if (o2.recordDOM) { 19078 styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow }); 19079 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc); 19080 styleDeclarationObserver = initStyleDeclarationObserver(o2, { win: currentWindow }); 19081 if (o2.collectFonts) fontObserver = initFontObserver(o2); 19082 } 19083 const selectionObserver = initSelectionObserver(o2); 19084 const customElementObserver = initCustomElementObserver(o2); 19085 const pluginHandlers = []; 19086 for (const plugin of o2.plugins) pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options)); 19087 return callbackWrapper$1(() => {
19088 mutationBuffers.forEach((b) => b.reset()); 19089 mutationObserver?.disconnect(); 19090 mousemoveHandler(); 19091 mouseInteractionHandler(); 19092 scrollHandler(); 19093 viewportResizeHandler(); 19094 inputHandler(); 19095 mediaInteractionHandler(); 19096 styleSheetObserver(); 19097 adoptedStyleSheetObserver(); 19098 styleDeclarationObserver(); 19099 fontObserver(); 19100 selectionObserver(); 19101 customElementObserver(); 19102 pluginHandlers.forEach((h) => h()); 19103 }); 19104} 19105function hasNestedCSSRule(prop) { 19106 return typeof window[prop] !== "undefined"; 19107} 19108function canMonkeyPatchNestedCSSRule(prop) { 19109 return Boolean(typeof window[prop] !== "undefined" && window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype); 19110} 19111function record(options = {}) { 19112 const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = "rr-block", blockSelector = null, unblockSelector = null, ignoreClass = "rr-ignore", ignoreSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load", userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = /* @__PURE__ */ new Set([]), errorHandler, onMutation, getCanvasManager } = options; 19113 registerErrorHandler$1(errorHandler); 19114 const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true; 19115 let passEmitsToParent = false; 19116 if (!inEmittingFrame) try { 19117 if (window.parent.document) passEmitsToParent = false; 19118 } catch (e2) { 19119 passEmitsToParent = true; 19120 } 19121 if (inEmittingFrame && !emit) throw new Error("emit function is required"); 19122 if (!inEmittingFrame && !passEmitsToParent) return () => {}; 19123 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) sampling.mousemove = mousemoveWait; 19124 mirror.reset(); 19125 const maskInputOptions = maskAllInputs === true ? { 19126 color: true, 19127 date: true, 19128 "datetime-local": true, 19129 email: true, 19130 month: true, 19131 number: true, 19132 range: true, 19133 search: true, 19134 tel: true, 19135 text: true, 19136 time: true, 19137 url: true, 19138 week: true, 19139 textarea: true, 19140 select: true, 19141 radio: true, 19142 checkbox: true 19143 } : _maskInputOptions !== void 0 ? _maskInputOptions : {}; 19144 const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? { 19145 script: true, 19146 comment: true, 19147 headFavicon: true, 19148 headWhitespace: true, 19149 headMetaSocial: true, 19150 headMetaRobots: true, 19151 headMetaHttpEquiv: true, 19152 headMetaVerification: true, 19153 headMetaAuthorship: _slimDOMOptions === "all", 19154 headMetaDescKeywords: _slimDOMOptions === "all" 19155 } : _slimDOMOptions ? _slimDOMOptions : {}; 19156 polyfill(); 19157 let lastFullSnapshotEvent; 19158 let incrementalSnapshotCount = 0; 19159 const eventProcessor = (e2) => { 19160 for (const plugin of plugins || []) if (plugin.eventProcessor) e2 = plugin.eventProcessor(e2); 19161 if (packFn && !passEmitsToParent) e2 = packFn(e2); 19162 return e2; 19163 }; 19164 wrappedEmit = (r2, isCheckout) => { 19165 const e2 = r2; 19166 e2.timestamp = nowTimestamp(); 19167 if (mutationBuffers[0]?.isFrozen() && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) mutationBuffers.forEach((buf) => buf.unfreeze()); 19168 if (inEmittingFrame) emit?.(eventProcessor(e2), isCheckout); 19169 else if (passEmitsToParent) { 19170 const message = { 19171 type: "rrweb", 19172 event: eventProcessor(e2), 19173 origin: window.location.origin, 19174 isCheckout 19175 }; 19176 window.parent.postMessage(message, "*"); 19177 } 19178 if (e2.type === EventType.FullSnapshot) { 19179 lastFullSnapshotEvent = e2; 19180 incrementalSnapshotCount = 0; 19181 } else if (e2.type === EventType.IncrementalSnapshot) { 19182 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) return; 19183 incrementalSnapshotCount++; 19184 const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth; 19185 const exceedTime = checkoutEveryNms && lastFullSnapshotEvent && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms; 19186 if (exceedCount || exceedTime) takeFullSnapshot2(true); 19187 } 19188 }; 19189 const wrappedMutationEmit = (m) => { 19190 wrappedEmit({ 19191 type: EventType.IncrementalSnapshot, 19192 data: { 19193 source: IncrementalSource.Mutation, 19194 ...m 19195 } 19196 }); 19197 }; 19198 const wrappedScrollEmit = (p) => wrappedEmit({ 19199 type: EventType.IncrementalSnapshot, 19200 data: { 19201 source: IncrementalSource.Scroll, 19202 ...p 19203 } 19204 }); 19205 const wrappedCanvasMutationEmit = (p) => wrappedEmit({ 19206 type: EventType.IncrementalSnapshot, 19207 data: { 19208 source: IncrementalSource.CanvasMutation, 19209 ...p 19210 } 19211 }); 19212 const wrappedAdoptedStyleSheetEmit = (a2) => wrappedEmit({ 19213 type: EventType.IncrementalSnapshot, 19214 data: { 19215 source: IncrementalSource.AdoptedStyleSheet, 19216 ...a2 19217 } 19218 }); 19219 const stylesheetManager = new StylesheetManager({ 19220 mutationCb: wrappedMutationEmit, 19221 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit 19222 }); 19223 const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === "boolean" && __RRWEB_EXCLUDE_IFRAME__ ? new IframeManagerNoop() : new IframeManager({ 19224 mirror, 19225 mutationCb: wrappedMutationEmit, 19226 stylesheetManager, 19227 recordCrossOriginIframes, 19228 wrappedEmit 19229 }); 19230 for (const plugin of plugins || []) if (plugin.getMirror) plugin.getMirror({ 19231 nodeMirror: mirror, 19232 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror, 19233 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror 19234 }); 19235 const processedNodeManager = new ProcessedNodeManager(); 19236 const canvasManager = _getCanvasManager(getCanvasManager, { 19237 mirror, 19238 win: window, 19239 mutationCb: (p) => wrappedEmit({ 19240 type: EventType.IncrementalSnapshot, 19241 data: { 19242 source: IncrementalSource.CanvasMutation, 19243 ...p 19244 } 19245 }), 19246 recordCanvas, 19247 blockClass, 19248 blockSelector, 19249 unblockSelector, 19250 maxCanvasSize, 19251 sampling: sampling["canvas"], 19252 dataURLOptions, 19253 errorHandler 19254 }); 19255 const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === "boolean" && __RRWEB_EXCLUDE_SHADOW_DOM__ ? new ShadowDomManagerNoop() : new ShadowDomManager({ 19256 mutationCb: wrappedMutationEmit, 19257 scrollCb: wrappedScrollEmit, 19258 bypassOptions: { 19259 onMutation, 19260 blockClass, 19261 blockSelector, 19262 unblockSelector, 19263 maskAllText, 19264 maskTextClass, 19265 unmaskTextClass, 19266 maskTextSelector, 19267 unmaskTextSelector, 19268 inlineStylesheet, 19269 maskInputOptions, 19270 dataURLOptions, 19271 maskAttributeFn, 19272 maskTextFn, 19273 maskInputFn, 19274 recordCanvas, 19275 inlineImages, 19276 sampling, 19277 slimDOMOptions, 19278 iframeManager, 19279 stylesheetManager, 19280 canvasManager, 19281 keepIframeSrcFn,
19282 processedNodeManager, 19283 ignoreCSSAttributes 19284 }, 19285 mirror 19286 }); 19287 const takeFullSnapshot2 = (isCheckout = false) => { 19288 if (!recordDOM) return; 19289 wrappedEmit({ 19290 type: EventType.Meta, 19291 data: { 19292 href: window.location.href, 19293 width: getWindowWidth(), 19294 height: getWindowHeight() 19295 } 19296 }, isCheckout); 19297 stylesheetManager.reset(); 19298 shadowDomManager.init(); 19299 mutationBuffers.forEach((buf) => buf.lock()); 19300 const node = snapshot(document, { 19301 mirror, 19302 blockClass, 19303 blockSelector, 19304 unblockSelector, 19305 maskAllText, 19306 maskTextClass, 19307 unmaskTextClass, 19308 maskTextSelector, 19309 unmaskTextSelector, 19310 inlineStylesheet, 19311 maskAllInputs: maskInputOptions, 19312 maskAttributeFn, 19313 maskInputFn, 19314 maskTextFn, 19315 slimDOM: slimDOMOptions, 19316 dataURLOptions, 19317 recordCanvas, 19318 inlineImages, 19319 onSerialize: (n2) => { 19320 if (isSerializedIframe(n2, mirror)) iframeManager.addIframe(n2); 19321 if (isSerializedStylesheet(n2, mirror)) stylesheetManager.trackLinkElement(n2); 19322 if (hasShadowRoot(n2)) shadowDomManager.addShadowRoot(n2.shadowRoot, document); 19323 }, 19324 onIframeLoad: (iframe, childSn) => { 19325 iframeManager.attachIframe(iframe, childSn); 19326 const contentWindow = getIFrameContentWindow(iframe); 19327 if (contentWindow) canvasManager.addWindow(contentWindow); 19328 shadowDomManager.observeAttachShadow(iframe); 19329 }, 19330 onStylesheetLoad: (linkEl, childSn) => { 19331 stylesheetManager.attachLinkElement(linkEl, childSn); 19332 }, 19333 onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => { 19334 wrappedMutationEmit({ 19335 adds: [], 19336 removes: [], 19337 texts: [], 19338 attributes: [{ 19339 id: serializedNode.id, 19340 attributes: { style: { 19341 width: `${width}px`, 19342 height: `${height}px` 19343 } } 19344 }] 19345 }); 19346 }, 19347 keepIframeSrcFn, 19348 ignoreCSSAttributes 19349 }); 19350 if (!node) return console.warn("Failed to snapshot the document"); 19351 wrappedEmit({ 19352 type: EventType.FullSnapshot, 19353 data: { 19354 node, 19355 initialOffset: getWindowScroll(window) 19356 } 19357 }); 19358 mutationBuffers.forEach((buf) => buf.unlock()); 19359 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document)); 19360 }; 19361 _takeFullSnapshot = takeFullSnapshot2; 19362 try { 19363 const handlers = []; 19364 const observe = (doc) => { 19365 return callbackWrapper$1(initObservers)({ 19366 onMutation, 19367 mutationCb: wrappedMutationEmit, 19368 mousemoveCb: (positions, source) => wrappedEmit({ 19369 type: EventType.IncrementalSnapshot, 19370 data: { 19371 source, 19372 positions 19373 } 19374 }), 19375 mouseInteractionCb: (d) => wrappedEmit({ 19376 type: EventType.IncrementalSnapshot, 19377 data: { 19378 source: IncrementalSource.MouseInteraction, 19379 ...d 19380 } 19381 }), 19382 scrollCb: wrappedScrollEmit, 19383 viewportResizeCb: (d) => wrappedEmit({ 19384 type: EventType.IncrementalSnapshot, 19385 data: { 19386 source: IncrementalSource.ViewportResize, 19387 ...d 19388 } 19389 }), 19390 inputCb: (v2) => wrappedEmit({ 19391 type: EventType.IncrementalSnapshot, 19392 data: { 19393 source: IncrementalSource.Input, 19394 ...v2 19395 } 19396 }), 19397 mediaInteractionCb: (p) => wrappedEmit({ 19398 type: EventType.IncrementalSnapshot, 19399 data: { 19400 source: IncrementalSource.MediaInteraction, 19401 ...p 19402 } 19403 }), 19404 styleSheetRuleCb: (r2) => wrappedEmit({ 19405 type: EventType.IncrementalSnapshot, 19406 data: { 19407 source: IncrementalSource.StyleSheetRule, 19408 ...r2 19409 } 19410 }), 19411 styleDeclarationCb: (r2) => wrappedEmit({ 19412 type: EventType.IncrementalSnapshot, 19413 data: { 19414 source: IncrementalSource.StyleDeclaration, 19415 ...r2 19416 } 19417 }), 19418 canvasMutationCb: wrappedCanvasMutationEmit, 19419 fontCb: (p) => wrappedEmit({ 19420 type: EventType.IncrementalSnapshot, 19421 data: { 19422 source: IncrementalSource.Font, 19423 ...p 19424 } 19425 }), 19426 selectionCb: (p) => { 19427 wrappedEmit({ 19428 type: EventType.IncrementalSnapshot, 19429 data: { 19430 source: IncrementalSource.Selection, 19431 ...p 19432 } 19433 }); 19434 }, 19435 customElementCb: (c2) => { 19436 wrappedEmit({ 19437 type: EventType.IncrementalSnapshot, 19438 data: { 19439 source: IncrementalSource.CustomElement, 19440 ...c2 19441 } 19442 }); 19443 }, 19444 blockClass, 19445 ignoreClass, 19446 ignoreSelector, 19447 maskAllText, 19448 maskTextClass, 19449 unmaskTextClass, 19450 maskTextSelector, 19451 unmaskTextSelector, 19452 maskInputOptions, 19453 inlineStylesheet, 19454 sampling, 19455 recordDOM, 19456 recordCanvas, 19457 inlineImages,
19458 userTriggeredOnInput, 19459 collectFonts, 19460 doc, 19461 maskAttributeFn, 19462 maskInputFn, 19463 maskTextFn, 19464 keepIframeSrcFn, 19465 blockSelector, 19466 unblockSelector, 19467 slimDOMOptions, 19468 dataURLOptions, 19469 mirror, 19470 iframeManager, 19471 stylesheetManager, 19472 shadowDomManager, 19473 processedNodeManager, 19474 canvasManager, 19475 ignoreCSSAttributes, 19476 plugins: plugins?.filter((p) => p.observer)?.map((p) => ({ 19477 observer: p.observer, 19478 options: p.options, 19479 callback: (payload) => wrappedEmit({ 19480 type: EventType.Plugin, 19481 data: { 19482 plugin: p.name, 19483 payload 19484 } 19485 }) 19486 })) || [] 19487 }, {}); 19488 }; 19489 iframeManager.addLoadListener((iframeEl) => { 19490 try { 19491 handlers.push(observe(iframeEl.contentDocument)); 19492 } catch (error) { 19493 console.warn(error); 19494 } 19495 }); 19496 const init = () => { 19497 takeFullSnapshot2(); 19498 handlers.push(observe(document)); 19499 }; 19500 if (document.readyState === "interactive" || document.readyState === "complete") init(); 19501 else { 19502 handlers.push(on("DOMContentLoaded", () => { 19503 wrappedEmit({ 19504 type: EventType.DomContentLoaded, 19505 data: {} 19506 }); 19507 if (recordAfter === "DOMContentLoaded") init(); 19508 })); 19509 handlers.push(on("load", () => { 19510 wrappedEmit({ 19511 type: EventType.Load, 19512 data: {} 19513 }); 19514 if (recordAfter === "load") init(); 19515 }, window)); 19516 } 19517 return () => { 19518 handlers.forEach((h) => h()); 19519 processedNodeManager.destroy(); 19520 _takeFullSnapshot = void 0; 19521 unregisterErrorHandler(); 19522 }; 19523 } catch (error) { 19524 console.warn(error); 19525 } 19526} 19527function takeFullSnapshot(isCheckout) { 19528 if (!_takeFullSnapshot) throw new Error("please take full snapshot after start recording"); 19529 _takeFullSnapshot(isCheckout); 19530} 19531function _getCanvasManager(getCanvasManagerFn, options) { 19532 try { 19533 return getCanvasManagerFn ? getCanvasManagerFn(options) : new CanvasManagerNoop(); 19534 } catch { 19535 console.warn("Unable to initialize CanvasManager"); 19536 return new CanvasManagerNoop(); 19537 } 19538} 19539function timestampToMs(timestamp) { 19540 return timestamp > 9999999999 ? timestamp : timestamp * 1e3; 19541} 19542function timestampToS(timestamp) { 19543 return timestamp > 9999999999 ? timestamp / 1e3 : timestamp; 19544} 19545function addBreadcrumbEvent(replay, breadcrumb) { 19546 if (breadcrumb.category === "sentry.transaction") return; 19547 if (["ui.click", "ui.input"].includes(breadcrumb.category)) replay.triggerUserActivity(); 19548 else replay.checkAndHandleExpiredSession(); 19549 replay.addUpdate(() => { 19550 replay.throttledAddEvent({ 19551 type: EventType.Custom, 19552 timestamp: (breadcrumb.timestamp || 0) * 1e3, 19553 data: { 19554 tag: "breadcrumb", 19555 payload: normalize(breadcrumb, 10, 1e3) 19556 } 19557 }); 19558 return breadcrumb.category === "console"; 19559 }); 19560} 19561function getClosestInteractive(element) { 19562 return element.closest(INTERACTIVE_SELECTOR) || element; 19563} 19564function getClickTargetNode(event) { 19565 const target = getTargetNode(event); 19566 if (!target || !(target instanceof Element)) return target; 19567 return getClosestInteractive(target); 19568} 19569function getTargetNode(event) { 19570 if (isEventWithTarget(event)) return event.target; 19571 return event; 19572} 19573function isEventWithTarget(event) { 19574 return isObjectLike(event) && "target" in event; 19575} 19576function onWindowOpen(cb) { 19577 if (!handlers) { 19578 handlers = []; 19579 monkeyPatchWindowOpen(); 19580 } 19581 handlers.push(cb); 19582 return () => { 19583 const pos = handlers ? handlers.indexOf(cb) : -1; 19584 if (pos > -1) handlers.splice(pos, 1); 19585 }; 19586} 19587function monkeyPatchWindowOpen() { 19588 fill(WINDOW, "open", function(originalWindowOpen) { 19589 return function(...args) { 19590 if (handlers) try { 19591 handlers.forEach((handler) => handler()); 19592 } catch {} 19593 return originalWindowOpen.apply(WINDOW, args); 19594 }; 19595 }); 19596} 19597function handleClick(clickDetector, clickBreadcrumb, node) { 19598 clickDetector.handleClick(clickBreadcrumb, node); 19599} 19600function ignoreElement(node, ignoreSelector) { 19601 if (!SLOW_CLICK_TAGS.includes(node.tagName)) return true; 19602 if (node.tagName === "INPUT" && !["submit", "button"].includes(node.getAttribute("type") || "")) return true; 19603 if (node.tagName === "A" && (node.hasAttribute("download") || node.hasAttribute("target") && node.getAttribute("target") !== "_self")) return true; 19604 if (ignoreSelector && node.matches(ignoreSelector)) return true; 19605 return false;
19606} 19607function isClickBreadcrumb(breadcrumb) { 19608 return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === "number" && breadcrumb.timestamp); 19609} 19610function nowInSeconds() { 19611 return Date.now() / 1e3; 19612} 19613function updateClickDetectorForRecordingEvent(clickDetector, event) { 19614 try { 19615 if (!isIncrementalEvent(event)) return; 19616 const { source } = event.data; 19617 if (IncrementalMutationSources.has(source)) clickDetector.registerMutation(event.timestamp); 19618 if (source === IncrementalSource.Scroll) clickDetector.registerScroll(event.timestamp); 19619 if (isIncrementalMouseInteraction(event)) { 19620 const { type, id } = event.data; 19621 const node = record.mirror.getNode(id); 19622 if (node instanceof HTMLElement && type === MouseInteractions.Click) clickDetector.registerClick(node); 19623 } 19624 } catch {} 19625} 19626function isIncrementalEvent(event) { 19627 return event.type === ReplayEventTypeIncrementalSnapshot; 19628} 19629function isIncrementalMouseInteraction(event) { 19630 return event.data.source === IncrementalSource.MouseInteraction; 19631} 19632function createBreadcrumb(breadcrumb) { 19633 return { 19634 timestamp: Date.now() / 1e3, 19635 type: "default", 19636 ...breadcrumb 19637 }; 19638} 19639function getAttributesToRecord(attributes) { 19640 const obj = {}; 19641 if (!attributes["data-sentry-component"] && attributes["data-sentry-element"]) attributes["data-sentry-component"] = attributes["data-sentry-element"]; 19642 for (const key in attributes) if (ATTRIBUTES_TO_RECORD.has(key)) { 19643 let normalizedKey = key; 19644 if (key === "data-testid" || key === "data-test-id") normalizedKey = "testId"; 19645 obj[normalizedKey] = attributes[key]; 19646 } 19647 return obj; 19648} 19649function getBaseDomBreadcrumb(target, message) { 19650 const nodeId = record.mirror.getId(target); 19651 const node = nodeId && record.mirror.getNode(nodeId); 19652 const meta = node && record.mirror.getMeta(node); 19653 const element = meta && isElement(meta) ? meta : null; 19654 return { 19655 message, 19656 data: element ? { 19657 nodeId, 19658 node: { 19659 id: nodeId, 19660 tagName: element.tagName, 19661 textContent: Array.from(element.childNodes).map((node2) => node2.type === NodeType.Text && node2.textContent).filter(Boolean).map((text) => text.trim()).join(""), 19662 attributes: getAttributesToRecord(element.attributes) 19663 } 19664 } : {} 19665 }; 19666} 19667function handleDom(handlerData) { 19668 const { target, message } = getDomTarget(handlerData); 19669 return createBreadcrumb({ 19670 category: `ui.${handlerData.name}`, 19671 ...getBaseDomBreadcrumb(target, message) 19672 }); 19673} 19674function getDomTarget(handlerData) { 19675 const isClick = handlerData.name === "click"; 19676 let message; 19677 let target = null; 19678 try { 19679 target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event); 19680 message = htmlTreeAsString(target, { maxStringLength: 200 }) || "<unknown>"; 19681 } catch { 19682 message = "<unknown>"; 19683 } 19684 return { 19685 target, 19686 message 19687 }; 19688} 19689function isElement(node) { 19690 return node.type === NodeType.Element; 19691} 19692function handleKeyboardEvent(replay, event) { 19693 if (!replay.isEnabled()) return; 19694 replay.updateUserActivity(); 19695 const breadcrumb = getKeyboardBreadcrumb(event); 19696 if (!breadcrumb) return; 19697 addBreadcrumbEvent(replay, breadcrumb); 19698} 19699function getKeyboardBreadcrumb(event) { 19700 const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event; 19701 if (!target || isInputElement(target) || !key) return null; 19702 const hasModifierKey = metaKey || ctrlKey || altKey; 19703 const isCharacterKey = key.length === 1; 19704 if (!hasModifierKey && isCharacterKey) return null; 19705 const message = htmlTreeAsString(target, { maxStringLength: 200 }) || "<unknown>"; 19706 return createBreadcrumb({ 19707 category: "ui.keyDown", 19708 message, 19709 data: { 19710 ...getBaseDomBreadcrumb(target, message).data, 19711 metaKey, 19712 shiftKey, 19713 ctrlKey, 19714 altKey, 19715 key 19716 } 19717 }); 19718} 19719function isInputElement(target) { 19720 return target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable; 19721} 19722function webVitalHandler(getter, replay) { 19723 return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric)); 19724} 19725function createPerformanceEntries(entries) { 19726 return entries.map(createPerformanceEntry).filter(Boolean); 19727} 19728function createPerformanceEntry(entry) { 19729 const entryType = ENTRY_TYPES[entry.entryType];
19730 if (!entryType) return null; 19731 return entryType(entry); 19732} 19733function getAbsoluteTime(time) { 19734 return ((browserPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1e3; 19735} 19736function createPaintEntry(entry) { 19737 const { duration, entryType, name, startTime } = entry; 19738 const start = getAbsoluteTime(startTime); 19739 return { 19740 type: entryType, 19741 name, 19742 start, 19743 end: start + duration, 19744 data: void 0 19745 }; 19746} 19747function createNavigationEntry(entry) { 19748 const { entryType, name, decodedBodySize, duration, domComplete, encodedBodySize, domContentLoadedEventStart, domContentLoadedEventEnd, domInteractive, loadEventStart, loadEventEnd, redirectCount, startTime, transferSize, type } = entry; 19749 if (duration === 0) return null; 19750 return { 19751 type: `${entryType}.${type}`, 19752 start: getAbsoluteTime(startTime), 19753 end: getAbsoluteTime(domComplete), 19754 name, 19755 data: { 19756 size: transferSize, 19757 decodedBodySize, 19758 encodedBodySize, 19759 duration, 19760 domInteractive, 19761 domContentLoadedEventStart, 19762 domContentLoadedEventEnd, 19763 loadEventStart, 19764 loadEventEnd, 19765 domComplete, 19766 redirectCount 19767 } 19768 }; 19769} 19770function createResourceEntry(entry) { 19771 const { entryType, initiatorType, name, responseEnd, startTime, decodedBodySize, encodedBodySize, responseStatus, transferSize } = entry; 19772 if (["fetch", "xmlhttprequest"].includes(initiatorType)) return null; 19773 return { 19774 type: `${entryType}.${initiatorType}`, 19775 start: getAbsoluteTime(startTime), 19776 end: getAbsoluteTime(responseEnd), 19777 name, 19778 data: { 19779 size: transferSize, 19780 statusCode: responseStatus, 19781 decodedBodySize, 19782 encodedBodySize 19783 } 19784 }; 19785} 19786function getLargestContentfulPaint(metric) { 19787 const lastEntry = metric.entries[metric.entries.length - 1]; 19788 return getWebVital(metric, "largest-contentful-paint", lastEntry?.element ? [lastEntry.element] : void 0); 19789} 19790function isLayoutShift(entry) { 19791 return entry.sources !== void 0; 19792} 19793function getCumulativeLayoutShift(metric) { 19794 const layoutShifts = []; 19795 const nodes = []; 19796 for (const entry of metric.entries) if (isLayoutShift(entry)) { 19797 const nodeIds = []; 19798 for (const source of entry.sources) if (source.node) { 19799 nodes.push(source.node); 19800 const nodeId = record.mirror.getId(source.node); 19801 if (nodeId) nodeIds.push(nodeId); 19802 } 19803 layoutShifts.push({ 19804 value: entry.value, 19805 nodeIds: nodeIds.length ? nodeIds : void 0 19806 }); 19807 } 19808 return getWebVital(metric, "cumulative-layout-shift", nodes, layoutShifts); 19809} 19810function getInteractionToNextPaint(metric) { 19811 const lastEntry = metric.entries[metric.entries.length - 1]; 19812 return getWebVital(metric, "interaction-to-next-paint", lastEntry?.target ? [lastEntry.target] : void 0); 19813} 19814function getWebVital(metric, name, nodes, attributions) { 19815 const value = metric.value; 19816 const rating = metric.rating; 19817 const end = getAbsoluteTime(value); 19818 return { 19819 type: "web-vital", 19820 name, 19821 start: end, 19822 end, 19823 data: { 19824 value, 19825 size: value, 19826 rating, 19827 nodeIds: nodes ? nodes.map((node) => record.mirror.getId(node)) : void 0, 19828 attributions 19829 } 19830 }; 19831} 19832function setupPerformanceObserver(replay) { 19833 function addPerformanceEntry(entry) { 19834 if (!replay.performanceEntries.includes(entry)) replay.performanceEntries.push(entry); 19835 } 19836 function onEntries({ entries }) { 19837 entries.forEach(addPerformanceEntry); 19838 } 19839 const clearCallbacks = []; 19840 [ 19841 "navigation", 19842 "paint", 19843 "resource" 19844 ].forEach((type) => { 19845 clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries)); 19846 }); 19847 clearCallbacks.push(addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)), addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)), addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay))); 19848 return () => { 19849 clearCallbacks.forEach((clearCallback) => clearCallback()); 19850 }; 19851} 19852function e() { 19853 const e2 = new Blob([t$1], { type: "text/javascript" }); 19854 return URL.createObjectURL(e2); 19855} 19856function _addBreadcrumb(message, level = "info") { 19857 addBreadcrumb({ 19858 category: "console", 19859 data: { logger: "replay" }, 19860 level, 19861 message: `${PREFIX}${message}` 19862 }, { level }); 19863} 19864function makeReplayDebugLogger() { 19865 let _capture = false;
19866 let _trace = false; 19867 const _debug = { 19868 exception: () => void 0, 19869 infoTick: () => void 0, 19870 setConfig: (opts) => { 19871 _capture = !!opts.captureExceptions; 19872 _trace = !!opts.traceInternals; 19873 } 19874 }; 19875 if (DEBUG_BUILD$1) { 19876 CONSOLE_LEVELS.forEach((name) => { 19877 _debug[name] = (...args) => { 19878 debug$2[name](PREFIX, ...args); 19879 if (_trace) _addBreadcrumb(args.join(""), severityLevelFromString(name)); 19880 }; 19881 }); 19882 _debug.exception = (error, ...message) => { 19883 if (message.length && _debug.error) _debug.error(...message); 19884 debug$2.error(PREFIX, error); 19885 if (_capture) captureException(error, { mechanism: { 19886 handled: true, 19887 type: "auto.function.replay.debug" 19888 } }); 19889 else if (_trace) _addBreadcrumb(error, "error"); 19890 }; 19891 _debug.infoTick = (...args) => { 19892 debug$2.log(PREFIX, ...args); 19893 if (_trace) setTimeout(() => _addBreadcrumb(args[0]), 0); 19894 }; 19895 } else CONSOLE_LEVELS.forEach((name) => { 19896 _debug[name] = () => void 0; 19897 }); 19898 return _debug; 19899} 19900function createEventBuffer({ useCompression, workerUrl: customWorkerUrl }) { 19901 if (useCompression && window.Worker) { 19902 const worker = _loadWorker(customWorkerUrl); 19903 if (worker) return worker; 19904 } 19905 DEBUG_BUILD$1 && debug.log("Using simple buffer"); 19906 return new EventBufferArray(); 19907} 19908function _loadWorker(customWorkerUrl) { 19909 try { 19910 const workerUrl = customWorkerUrl || _getWorkerUrl(); 19911 if (!workerUrl) return; 19912 DEBUG_BUILD$1 && debug.log(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ""}`); 19913 const worker = new Worker(workerUrl); 19914 return new EventBufferProxy(worker); 19915 } catch (error) { 19916 DEBUG_BUILD$1 && debug.exception(error, "Failed to create compression worker"); 19917 } 19918} 19919function _getWorkerUrl() { 19920 if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === "undefined" || !__SENTRY_EXCLUDE_REPLAY_WORKER__) return e(); 19921 return ""; 19922} 19923function hasSessionStorage() { 19924 try { 19925 return "sessionStorage" in WINDOW && !!WINDOW.sessionStorage; 19926 } catch { 19927 return false; 19928 } 19929} 19930function clearSession(replay) { 19931 deleteSession(); 19932 replay.session = void 0; 19933} 19934function deleteSession() { 19935 if (!hasSessionStorage()) return; 19936 try { 19937 WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY); 19938 } catch {} 19939} 19940function isSampled(sampleRate) { 19941 if (sampleRate === void 0) return false; 19942 return Math.random() < sampleRate; 19943} 19944function saveSession(session) { 19945 if (!hasSessionStorage()) return; 19946 try { 19947 WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session)); 19948 } catch {} 19949} 19950function makeSession(session) { 19951 const now = Date.now(); 19952 return { 19953 id: session.id || uuid4(), 19954 started: session.started || now, 19955 lastActivity: session.lastActivity || now, 19956 segmentId: session.segmentId || 0, 19957 sampled: session.sampled, 19958 previousSessionId: session.previousSessionId, 19959 dirty: session.dirty || false 19960 }; 19961} 19962function getSessionSampleType(sessionSampleRate, allowBuffering) { 19963 return isSampled(sessionSampleRate) ? "session" : allowBuffering ? "buffer" : false; 19964} 19965function createSession({ sessionSampleRate, allowBuffering, stickySession = false }, { previousSessionId } = {}) { 19966 const session = makeSession({ 19967 sampled: getSessionSampleType(sessionSampleRate, allowBuffering), 19968 previousSessionId 19969 }); 19970 if (stickySession) saveSession(session); 19971 return session; 19972} 19973function fetchSession() { 19974 if (!hasSessionStorage()) return null; 19975 try { 19976 const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY); 19977 if (!sessionStringFromStorage) return null; 19978 const sessionObj = JSON.parse(sessionStringFromStorage); 19979 DEBUG_BUILD$1 && debug.infoTick("Loading existing session"); 19980 return makeSession(sessionObj); 19981 } catch { 19982 return null; 19983 } 19984} 19985function isExpired(initialTime, expiry, targetTime = +/* @__PURE__ */ new Date()) { 19986 if (initialTime === null || expiry === void 0 || expiry < 0) return true; 19987 if (expiry === 0) return false; 19988 return initialTime + expiry <= targetTime; 19989} 19990function isSessionExpired(session, { maxReplayDuration, sessionIdleExpire, targetTime = Date.now() }) { 19991 return isExpired(session.started, maxReplayDuration, targetTime) || isExpired(session.lastActivity, sessionIdleExpire, targetTime); 19992} 19993function shouldRefreshSession(session, { sessionIdleExpire, maxReplayDuration }) { 19994 if (!isSessionExpired(session, { 19995 sessionIdleExpire, 19996 maxReplayDuration 19997 })) return false;
19998 if (session.sampled === "buffer" && session.segmentId === 0) return false; 19999 return true; 20000} 20001function loadOrCreateSession({ sessionIdleExpire, maxReplayDuration, previousSessionId }, sessionOptions) { 20002 const existingSession = sessionOptions.stickySession && fetchSession(); 20003 if (!existingSession) { 20004 DEBUG_BUILD$1 && debug.infoTick("Creating new session"); 20005 return createSession(sessionOptions, { previousSessionId }); 20006 } 20007 if (!shouldRefreshSession(existingSession, { 20008 sessionIdleExpire, 20009 maxReplayDuration 20010 })) return existingSession; 20011 DEBUG_BUILD$1 && debug.infoTick("Session in sessionStorage is expired, creating new one..."); 20012 return createSession(sessionOptions, { previousSessionId: existingSession.id }); 20013} 20014function isCustomEvent(event) { 20015 return event.type === EventType.Custom; 20016} 20017function addEventSync(replay, event, isCheckout) { 20018 if (!shouldAddEvent(replay, event)) return false; 20019 _addEvent(replay, event, isCheckout); 20020 return true; 20021} 20022function addEvent(replay, event, isCheckout) { 20023 if (!shouldAddEvent(replay, event)) return Promise.resolve(null); 20024 return _addEvent(replay, event, isCheckout); 20025} 20026async function _addEvent(replay, event, isCheckout) { 20027 const { eventBuffer } = replay; 20028 if (!eventBuffer || eventBuffer.waitForCheckout && !isCheckout) return null; 20029 const isBufferMode = replay.recordingMode === "buffer"; 20030 try { 20031 if (isCheckout && isBufferMode) eventBuffer.clear(); 20032 if (isCheckout) { 20033 eventBuffer.hasCheckout = true; 20034 eventBuffer.waitForCheckout = false; 20035 } 20036 const eventAfterPossibleCallback = maybeApplyCallback(event, replay.getOptions().beforeAddRecordingEvent); 20037 if (!eventAfterPossibleCallback) return; 20038 return await eventBuffer.addEvent(eventAfterPossibleCallback); 20039 } catch (error) { 20040 if (!replay.isEnabled()) { 20041 replay.handleException(error); 20042 return null; 20043 } 20044 const isExceeded = error && error instanceof EventBufferSizeExceededError; 20045 const reason = isExceeded ? "eventBufferOverflow" : "eventBufferError"; 20046 const client = getClient(); 20047 if (client) { 20048 const dropReason = isExceeded ? "buffer_overflow" : "internal_sdk_error"; 20049 client.recordDroppedEvent(dropReason, "replay"); 20050 } 20051 if (isExceeded && isBufferMode) { 20052 eventBuffer.clear(); 20053 eventBuffer.waitForCheckout = true; 20054 return null; 20055 } 20056 replay.handleException(error); 20057 await replay.stop({ reason }); 20058 } 20059} 20060function shouldAddEvent(replay, event) { 20061 if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) return false; 20062 const timestampInMs = timestampToMs(event.timestamp);
20063 if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) return false; 20064 if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) { 20065 DEBUG_BUILD$1 && debug.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`); 20066 return false; 20067 } 20068 return true; 20069} 20070function maybeApplyCallback(event, callback) { 20071 try { 20072 if (typeof callback === "function" && isCustomEvent(event)) return callback(event); 20073 } catch (error) { 20074 DEBUG_BUILD$1 && debug.exception(error, "An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."); 20075 return null; 20076 } 20077 return event; 20078} 20079function addSegmentDetailsToContext(replay, traceId, segmentName) { 20080 const replayContext = replay.getContext(); 20081 if (traceId && replayContext.traceIds.size < MAX_CONTEXT_VALUES) replayContext.traceIds.add(traceId); 20082 if (segmentName && replayContext.segmentNames.size < MAX_CONTEXT_VALUES) replayContext.segmentNames.add(segmentName); 20083} 20084function handleProcessSegmentSpan(replay) { 20085 return (spanJSON) => { 20086 if (!replay.isEnabled()) return; 20087 addSegmentDetailsToContext(replay, spanJSON.trace_id, spanJSON.name || void 0); 20088 }; 20089} 20090function isErrorEvent(event) { 20091 return !event.type; 20092} 20093function isTransactionEvent(event) { 20094 return event.type === "transaction"; 20095} 20096function isReplayEvent(event) { 20097 return event.type === "replay_event"; 20098} 20099function isFeedbackEvent(event) { 20100 return event.type === "feedback"; 20101} 20102function handleAfterSendEvent(replay) { 20103 return (event, sendResponse) => { 20104 if (!replay.isEnabled() || !isErrorEvent(event) && !isTransactionEvent(event)) return; 20105 const statusCode = sendResponse.statusCode; 20106 if (!statusCode || statusCode < 200 || statusCode >= 300) return; 20107 if (isTransactionEvent(event)) { 20108 handleTransactionEvent(replay, event); 20109 return; 20110 } 20111 handleErrorEvent(replay, event); 20112 }; 20113} 20114function handleTransactionEvent(replay, event) { 20115 addSegmentDetailsToContext(replay, event.contexts?.trace?.trace_id, event.transaction); 20116} 20117function handleErrorEvent(replay, event) { 20118 const replayContext = replay.getContext(); 20119 if (event.event_id && replayContext.errorIds.size < 100) replayContext.errorIds.add(event.event_id); 20120 if (replay.recordingMode !== "buffer" || !event.tags?.replayId) return; 20121 const { beforeErrorSampling } = replay.getOptions(); 20122 if (typeof beforeErrorSampling === "function" && !beforeErrorSampling(event)) return; 20123 setTimeout$3(async () => { 20124 try { 20125 await replay.sendBufferedReplayOrFlush(); 20126 } catch (err) { 20127 replay.handleException(err); 20128 } 20129 }); 20130} 20131function handleBeforeSendEvent(replay) { 20132 return (event) => { 20133 if (!replay.isEnabled() || !isErrorEvent(event)) return; 20134 handleHydrationError(replay, event); 20135 }; 20136} 20137function handleHydrationError(replay, event) { 20138 const exceptionValue = event.exception?.values?.[0]?.value; 20139 if (typeof exceptionValue !== "string") return; 20140 if (exceptionValue.match(/(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/) || exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)) addBreadcrumbEvent(replay, createBreadcrumb({ 20141 category: "replay.hydrate-error", 20142 data: { url: getLocationHref() } 20143 })); 20144} 20145function handleBreadcrumbs(replay) { 20146 const client = getClient(); 20147 if (!client) return; 20148 client.on("beforeAddBreadcrumb", (breadcrumb) => beforeAddBreadcrumb(replay, breadcrumb)); 20149} 20150function beforeAddBreadcrumb(replay, breadcrumb) { 20151 if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) return; 20152 const result = normalizeBreadcrumb(breadcrumb); 20153 if (result) addBreadcrumbEvent(replay, result); 20154} 20155function normalizeBreadcrumb(breadcrumb) { 20156 if (!isBreadcrumbWithCategory(breadcrumb) || [ 20157 "fetch", 20158 "xhr", 20159 "sentry.event", 20160 "sentry.transaction" 20161 ].includes(breadcrumb.category) || breadcrumb.category.startsWith("ui.")) return null; 20162 if (breadcrumb.category === "console") return normalizeConsoleBreadcrumb(breadcrumb); 20163 return createBreadcrumb(breadcrumb); 20164} 20165function normalizeConsoleBreadcrumb(breadcrumb) { 20166 const args = breadcrumb.data?.arguments; 20167 if (!Array.isArray(args) || args.length === 0) return createBreadcrumb(breadcrumb); 20168 let isTruncated = false;
20169 const normalizedArgs = args.map((arg) => { 20170 if (!arg) return arg; 20171 if (typeof arg === "string") { 20172 if (arg.length > CONSOLE_ARG_MAX_SIZE) { 20173 isTruncated = true; 20174 return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}\u2026`; 20175 } 20176 return arg; 20177 } 20178 if (typeof arg === "object") try { 20179 const normalizedArg = normalize(arg, 7); 20180 if (JSON.stringify(normalizedArg).length > CONSOLE_ARG_MAX_SIZE) { 20181 isTruncated = true; 20182 return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}\u2026`; 20183 } 20184 return normalizedArg; 20185 } catch {} 20186 return arg; 20187 }); 20188 return createBreadcrumb({ 20189 ...breadcrumb, 20190 data: { 20191 ...breadcrumb.data, 20192 arguments: normalizedArgs, 20193 ...isTruncated ? { _meta: { warnings: ["CONSOLE_ARG_TRUNCATED"] } } : {} 20194 } 20195 }); 20196} 20197function isBreadcrumbWithCategory(breadcrumb) { 20198 return !!breadcrumb.category; 20199} 20200function isRrwebError(event, hint) { 20201 if (event.type || !event.exception?.values?.length) return false; 20202 if (hint.originalException?.__rrweb__) return true; 20203 return false; 20204} 20205function resetReplayIdOnDynamicSamplingContext() { 20206 const dsc = getCurrentScope().getPropagationContext().dsc; 20207 if (dsc) delete dsc.replay_id; 20208 const activeSpan = getActiveSpan(); 20209 if (activeSpan) { 20210 const dsc2 = getDynamicSamplingContextFromSpan(activeSpan); 20211 delete dsc2.replay_id; 20212 } 20213} 20214function setReplayIdOnDynamicSamplingContext(replayId) { 20215 const dsc = getCurrentScope().getPropagationContext().dsc; 20216 if (dsc) dsc.replay_id = replayId; 20217 const activeSpan = getActiveSpan(); 20218 if (activeSpan) { 20219 const dsc2 = getDynamicSamplingContextFromSpan(activeSpan); 20220 dsc2.replay_id = replayId; 20221 } 20222} 20223function addFeedbackBreadcrumb(replay, event) { 20224 replay.triggerUserActivity(); 20225 replay.addUpdate(() => { 20226 if (!event.timestamp) return true; 20227 replay.throttledAddEvent({ 20228 type: EventType.Custom, 20229 timestamp: event.timestamp * 1e3, 20230 data: { 20231 tag: "breadcrumb", 20232 payload: { 20233 timestamp: event.timestamp, 20234 type: "default", 20235 category: "sentry.feedback", 20236 data: { feedbackId: event.event_id } 20237 } 20238 } 20239 }); 20240 return false; 20241 }); 20242} 20243function shouldSampleForBufferEvent(replay, event) { 20244 if (replay.recordingMode !== "buffer") return false; 20245 if (event.message === UNABLE_TO_SEND_REPLAY) return false; 20246 if (!event.exception || event.type) return false; 20247 return isSampled(replay.getOptions().errorSampleRate); 20248} 20249function handleGlobalEventListener(replay) { 20250 return Object.assign((event, hint) => { 20251 if (replay.session && shouldRefreshSession(replay.session, { 20252 maxReplayDuration: replay.getOptions().maxReplayDuration, 20253 sessionIdleExpire: replay.timeouts.sessionIdleExpire 20254 })) resetReplayIdOnDynamicSamplingContext(); 20255 if (!replay.isEnabled() || replay.isPaused()) return event; 20256 if (isReplayEvent(event)) { 20257 delete event.breadcrumbs; 20258 return event; 20259 } 20260 if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) return event; 20261 if (!replay.checkAndHandleExpiredSession()) { 20262 resetReplayIdOnDynamicSamplingContext(); 20263 return event; 20264 } 20265 if (isFeedbackEvent(event)) { 20266 replay.flush(); 20267 event.contexts.feedback.replay_id = replay.getSessionId(); 20268 addFeedbackBreadcrumb(replay, event); 20269 return event; 20270 } 20271 if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) { 20272 DEBUG_BUILD$1 && debug.log("Ignoring error from rrweb internals", event); 20273 return null; 20274 } 20275 const isErrorEventSampled = shouldSampleForBufferEvent(replay, event); 20276 if (isErrorEventSampled || replay.recordingMode === "session") event.tags = { 20277 ...event.tags, 20278 replayId: replay.getSessionId() 20279 }; 20280 if (isErrorEventSampled && replay.recordingMode === "buffer" && replay.session?.sampled === "buffer") { 20281 const session = replay.session; 20282 session.dirty = true; 20283 if (replay.getOptions().stickySession) saveSession(session); 20284 } 20285 return event; 20286 }, { id: "Replay" }); 20287} 20288function createPerformanceSpans(replay, entries) { 20289 return entries.map(({ type, start, end, name, data }) => { 20290 const response = replay.throttledAddEvent({ 20291 type: EventType.Custom, 20292 timestamp: start, 20293 data: { 20294 tag: "performanceSpan", 20295 payload: { 20296 op: type, 20297 description: name, 20298 startTimestamp: start, 20299 endTimestamp: end, 20300 data 20301 } 20302 } 20303 }); 20304 return typeof response === "string" ? Promise.resolve(null) : response; 20305 }); 20306} 20307function handleHistory(handlerData) { 20308 const { from, to } = handlerData; 20309 const now = Date.now() / 1e3; 20310 return { 20311 type: "navigation.push", 20312 start: now, 20313 end: now, 20314 name: to, 20315 data: { previous: from } 20316 }; 20317} 20318function handleHistorySpanListener(replay) { 20319 return (handlerData) => { 20320 if (!replay.isEnabled()) return; 20321 const result = handleHistory(handlerData); 20322 if (result === null) return; 20323 replay.getContext().urls.push(result.name); 20324 replay.triggerUserActivity(); 20325 replay.addUpdate(() => { 20326 createPerformanceSpans(replay, [result]); 20327 return false;
20328 }); 20329 }; 20330} 20331function shouldFilterRequest(replay, url) { 20332 if (DEBUG_BUILD$1 && replay.getOptions()._experiments.traceInternals) return false; 20333 return isSentryRequestUrl(url, getClient()); 20334} 20335function addNetworkBreadcrumb(replay, result) { 20336 if (!replay.isEnabled()) return; 20337 if (result === null) return; 20338 if (shouldFilterRequest(replay, result.name)) return; 20339 replay.addUpdate(() => { 20340 createPerformanceSpans(replay, [result]); 20341 return true; 20342 }); 20343} 20344function getBodySize(body) { 20345 if (!body) return; 20346 const textEncoder = new TextEncoder(); 20347 try { 20348 if (typeof body === "string") return textEncoder.encode(body).length; 20349 if (body instanceof URLSearchParams) return textEncoder.encode(body.toString()).length; 20350 if (body instanceof FormData) { 20351 const formDataStr = serializeFormData(body); 20352 return textEncoder.encode(formDataStr).length; 20353 } 20354 if (body instanceof Blob) return body.size; 20355 if (body instanceof ArrayBuffer) return body.byteLength; 20356 } catch {} 20357} 20358function parseContentLengthHeader(header) { 20359 if (!header) return; 20360 const size = parseInt(header, 10); 20361 return isNaN(size) ? void 0 : size; 20362} 20363function mergeWarning(info, warning) { 20364 if (!info) return { 20365 headers: {}, 20366 size: void 0, 20367 _meta: { warnings: [warning] } 20368 }; 20369 const newMeta = { ...info._meta }; 20370 newMeta.warnings = [...newMeta.warnings || [], warning]; 20371 info._meta = newMeta; 20372 return info; 20373} 20374function makeNetworkReplayBreadcrumb(type, data) { 20375 if (!data) return null; 20376 const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data; 20377 return { 20378 type, 20379 start: startTimestamp / 1e3, 20380 end: endTimestamp / 1e3, 20381 name: url, 20382 data: { 20383 method, 20384 statusCode, 20385 request, 20386 response 20387 } 20388 }; 20389} 20390function buildSkippedNetworkRequestOrResponse(bodySize) { 20391 return { 20392 headers: {}, 20393 size: bodySize, 20394 _meta: { warnings: ["URL_SKIPPED"] } 20395 }; 20396} 20397function buildNetworkRequestOrResponse(headers, bodySize, body) { 20398 if (!bodySize && Object.keys(headers).length === 0) return; 20399 if (!bodySize) return { headers }; 20400 if (!body) return { 20401 headers, 20402 size: bodySize 20403 }; 20404 const info = { 20405 headers, 20406 size: bodySize 20407 }; 20408 const { body: normalizedBody, warnings } = normalizeNetworkBody(body); 20409 info.body = normalizedBody; 20410 if (warnings?.length) info._meta = { warnings }; 20411 return info; 20412} 20413function getAllowedHeaders(headers, allowedHeaders) { 20414 return Object.entries(headers).reduce((filteredHeaders, [key, value]) => { 20415 const normalizedKey = key.toLowerCase(); 20416 if (allowedHeaders.includes(normalizedKey) && headers[key]) filteredHeaders[normalizedKey] = value; 20417 return filteredHeaders; 20418 }, {}); 20419} 20420function normalizeNetworkBody(body) { 20421 if (!body || typeof body !== "string") return { body }; 20422 const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE; 20423 const isProbablyJson = _strIsProbablyJson(body); 20424 if (exceedsSizeLimit) { 20425 const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE); 20426 if (isProbablyJson) return { 20427 body: truncatedBody, 20428 warnings: ["MAYBE_JSON_TRUNCATED"] 20429 }; 20430 return { 20431 body: `${truncatedBody}\u2026`, 20432 warnings: ["TEXT_TRUNCATED"] 20433 }; 20434 } 20435 if (isProbablyJson) try { 20436 return { body: JSON.parse(body) }; 20437 } catch {} 20438 return { body }; 20439} 20440function _strIsProbablyJson(str) { 20441 const first = str[0]; 20442 const last = str[str.length - 1]; 20443 return first === "[" && last === "]" || first === "{" && last === "}"; 20444} 20445function urlMatches(url, urls) { 20446 return stringMatchesSomePattern(getFullUrl(url), urls); 20447} 20448function getFullUrl(url, baseURI = WINDOW.document.baseURI) { 20449 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith(WINDOW.location.origin)) return url; 20450 const fixedUrl = new URL(url, baseURI); 20451 if (fixedUrl.origin !== new URL(baseURI).origin) return url; 20452 const fullUrl = fixedUrl.href; 20453 if (!url.endsWith("/") && fullUrl.endsWith("/")) return fullUrl.slice(0, -1); 20454 return fullUrl; 20455} 20456async function captureFetchBreadcrumbToReplay(breadcrumb, hint, options) { 20457 try { 20458 const result = makeNetworkReplayBreadcrumb("resource.fetch", await _prepareFetchData(breadcrumb, hint, options)); 20459 addNetworkBreadcrumb(options.replay, result); 20460 } catch (error) { 20461 DEBUG_BUILD$1 && debug.exception(error, "Failed to capture fetch breadcrumb"); 20462 } 20463} 20464function enrichFetchBreadcrumb(breadcrumb, hint) { 20465 const { input, response } = hint; 20466 const reqSize = getBodySize(input ? getFetchRequestArgBody(input) : void 0); 20467 const resSize = response ? parseContentLengthHeader(response.headers.get("content-length")) : void 0; 20468 if (reqSize !== void 0) breadcrumb.data.request_body_size = reqSize; 20469 if (resSize !== void 0) breadcrumb.data.response_body_size = resSize; 20470} 20471async function _prepareFetchData(breadcrumb, hint, options) { 20472 const now = Date.now(); 20473 const { startTimestamp = now, endTimestamp = now } = hint; 20474 const { url, method, status_code: statusCode = 0, request_body_size: requestBodySize, response_body_size: responseBodySize } = breadcrumb.data; 20475 const captureDetails = urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls); 20476 return { 20477 startTimestamp, 20478 endTimestamp, 20479 url, 20480 method, 20481 statusCode, 20482 request: captureDetails ? _getRequestInfo(options, hint.input, requestBodySize) : buildSkippedNetwork
20482RequestOrResponse(requestBodySize), 20483 response: await _getResponseInfo(captureDetails, options, hint.response, responseBodySize) 20484 }; 20485} 20486function _getRequestInfo({ networkCaptureBodies, networkRequestHeaders }, input, requestBodySize) { 20487 const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {}; 20488 if (!networkCaptureBodies) return buildNetworkRequestOrResponse(headers, requestBodySize, void 0); 20489 const [bodyStr, warning] = getBodyString(getFetchRequestArgBody(input), debug); 20490 const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr); 20491 if (warning) return mergeWarning(data, warning); 20492 return data; 20493} 20494async function _getResponseInfo(captureDetails, { networkCaptureBodies, networkResponseHeaders }, response, responseBodySize) { 20495 if (!captureDetails && responseBodySize !== void 0) return buildSkippedNetworkRequestOrResponse(responseBodySize); 20496 const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {}; 20497 if (!response || !networkCaptureBodies && responseBodySize !== void 0) return buildNetworkRequestOrResponse(headers, responseBodySize, void 0); 20498 const [bodyText, warning] = await _parseFetchResponseBody(response); 20499 const result = getResponseData(bodyText, { 20500 networkCaptureBodies, 20501 responseBodySize, 20502 captureDetails, 20503 headers 20504 }); 20505 if (warning) return mergeWarning(result, warning); 20506 return result; 20507} 20508function getResponseData(bodyText, { networkCaptureBodies, responseBodySize, captureDetails, headers }) { 20509 try { 20510 const size = bodyText?.length && responseBodySize === void 0 ? getBodySize(bodyText) : responseBodySize; 20511 if (!captureDetails) return buildSkippedNetworkRequestOrResponse(size); 20512 if (networkCaptureBodies) return buildNetworkRequestOrResponse(headers, size, bodyText); 20513 return buildNetworkRequestOrResponse(headers, size, void 0); 20514 } catch (error) { 20515 DEBUG_BUILD$1 && debug.exception(error, "Failed to serialize response body"); 20516 return buildNetworkRequestOrResponse(headers, responseBodySize, void 0); 20517 } 20518} 20519async function _parseFetchResponseBody(response) { 20520 const res = _tryCloneResponse(response); 20521 if (!res) return [void 0, "BODY_PARSE_ERROR"]; 20522 try { 20523 return [await _tryGetResponseText(res)]; 20524 } catch (error) { 20525 if (error instanceof Error && error.message.indexOf("Timeout") > -1) { 20526 DEBUG_BUILD$1 && debug.warn("Parsing text body from response timed out"); 20527 return [void 0, "BODY_PARSE_TIMEOUT"]; 20528 } 20529 DEBUG_BUILD$1 && debug.exception(error, "Failed to get text body from response"); 20530 return [void 0, "BODY_PARSE_ERROR"]; 20531 } 20532} 20533function getAllHeaders(headers, allowedHeaders) { 20534 const allHeaders = {}; 20535 allowedHeaders.forEach((header) => { 20536 if (headers.get(header)) allHeaders[header] = headers.get(header); 20537 }); 20538 return allHeaders; 20539} 20540function getRequestHeaders(fetchArgs, allowedHeaders) { 20541 if (fetchArgs.length === 1 && typeof fetchArgs[0] !== "string") return getHeadersFromOptions(fetchArgs[0], allowedHeaders); 20542 if (fetchArgs.length === 2) return getHeadersFromOptions(fetchArgs[1], allowedHeaders); 20543 return {}; 20544} 20545function getHeadersFromOptions(input, allowedHeaders) { 20546 if (!input) return {}; 20547 const headers = input.headers; 20548 if (!headers) return {}; 20549 if (headers instanceof Headers) return getAllHeaders(headers, allowedHeaders); 20550 if (Array.isArray(headers)) return {}; 20551 return getAllowedHeaders(headers, allowedHeaders); 20552} 20553function _tryCloneResponse(response) { 20554 try { 20555 return response.clone(); 20556 } catch (error) { 20557 DEBUG_BUILD$1 && debug.exception(error, "Failed to clone response body"); 20558 } 20559} 20560function _tryGetResponseText(response) { 20561 return new Promise((resolve, reject) => { 20562 const timeout = setTimeout$3(() => reject(/* @__PURE__ */ new Error("Timeout while trying to read response body")), 500); 20563 _getResponseText(response).then((txt) => resolve(txt), (reason) => reject(reason)).finally(() => clearTimeout(timeout)); 20564 }); 20565} 20566async function _getResponseText(response) { 20567 return await response.text(); 20568} 20569async function captureXhrBreadcrumbToReplay(breadcrumb, hint, options) { 20570 try { 20571 const result = makeNetworkReplayBreadcrumb("resource.xhr", _prepareXhrData(breadcrumb, hint, options)); 20572 addNetworkBreadcrumb(options.replay, result); 20573 } catch (error) { 20574 DEBUG_BUILD$1 && debug.exception(error, "Failed to capture xhr breadcrumb"); 20575 } 20576} 20577function enrichXhrBreadcrumb(breadcrumb, hint) { 20578 const { xhr, input } = hint; 20579 if (!xhr) return; 20580 const reqSize = getBodySize(input); 20581 const resSize = xhr.getResponseHeader("content-length") ? parseContentLengthHeader(xhr.getResponseHeader("content-length")) : _getBodySize(xhr.response, xhr.responseType); 20582 if (reqSize !== void 0) breadcrumb.data.request_body_size = reqSize; 20583 if (resSize !== void 0) breadcrumb.data.response_body_size = resSize; 20584} 20585function _prepareXhrData(breadcrumb, hint, options) { 20586 const now = Date.now(); 20587 const { startTimestamp = now, endTimestamp = now, input, xhr } = hint; 20588 const { url, method, status_code: statusCode = 0, request_body_size: requestBodySize, response_body_size: responseBodySize } = breadcrumb.data; 20589 if (!url) return null; 20590 if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) return { 20591 startTimestamp, 20592 endTimestamp, 20593 url, 20594 method, 20595 statusCode,
20596 request: buildSkippedNetworkRequestOrResponse(requestBodySize), 20597 response: buildSkippedNetworkRequestOrResponse(responseBodySize) 20598 }; 20599 const xhrInfo = xhr[SENTRY_XHR_DATA_KEY]; 20600 const networkRequestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders) : {}; 20601 const networkResponseHeaders = getAllowedHeaders(parseXhrResponseHeaders(xhr), options.networkResponseHeaders); 20602 const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input, debug) : [void 0]; 20603 const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [void 0]; 20604 const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody); 20605 const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody); 20606 return { 20607 startTimestamp, 20608 endTimestamp, 20609 url, 20610 method, 20611 statusCode, 20612 request: requestWarning ? mergeWarning(request, requestWarning) : request, 20613 response: responseWarning ? mergeWarning(response, responseWarning) : response 20614 }; 20615} 20616function _getXhrResponseBody(xhr) { 20617 const errors = []; 20618 try { 20619 return [xhr.responseText]; 20620 } catch (e) { 20621 errors.push(e); 20622 } 20623 try { 20624 return _parseXhrResponse(xhr.response, xhr.responseType); 20625 } catch (e) { 20626 errors.push(e); 20627 } 20628 DEBUG_BUILD$1 && debug.warn("Failed to get xhr response body", ...errors); 20629 return [void 0]; 20630} 20631function _parseXhrResponse(body, responseType) { 20632 try { 20633 if (typeof body === "string") return [body]; 20634 if (body instanceof Document) return [body.body.outerHTML]; 20635 if (responseType === "json" && isObjectLike(body)) return [JSON.stringify(body)]; 20636 if (!body) return [void 0]; 20637 } catch (error) { 20638 DEBUG_BUILD$1 && debug.exception(error, "Failed to serialize body", body); 20639 return [void 0, "BODY_PARSE_ERROR"]; 20640 } 20641 DEBUG_BUILD$1 && debug.log("Skipping network body because of body type", body); 20642 return [void 0, "UNPARSEABLE_BODY_TYPE"]; 20643} 20644function _getBodySize(body, responseType) { 20645 try { 20646 return getBodySize(responseType === "json" && isObjectLike(body) ? JSON.stringify(body) : body); 20647 } catch { 20648 return; 20649 } 20650} 20651function handleNetworkBreadcrumbs(replay) { 20652 const client = getClient(); 20653 try { 20654 const { networkDetailAllowUrls, networkDetailDenyUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } = replay.getOptions(); 20655 const options = { 20656 replay, 20657 networkDetailAllowUrls, 20658 networkDetailDenyUrls, 20659 networkCaptureBodies, 20660 networkRequestHeaders, 20661 networkResponseHeaders 20662 }; 20663 if (client) client.on("beforeAddBreadcrumb", (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint)); 20664 } catch {} 20665} 20666function beforeAddNetworkBreadcrumb(options, breadcrumb, hint) { 20667 if (!breadcrumb.data) return; 20668 try { 20669 if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) { 20670 enrichXhrBreadcrumb(breadcrumb, hint); 20671 captureXhrBreadcrumbToReplay(breadcrumb, hint, options); 20672 } 20673 if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) { 20674 enrichFetchBreadcrumb(breadcrumb, hint); 20675 captureFetchBreadcrumbToReplay(breadcrumb, hint, options); 20676 } 20677 } catch (e) { 20678 DEBUG_BUILD$1 && debug.exception(e, "Error when enriching network breadcrumb"); 20679 } 20680} 20681function _isXhrBreadcrumb(breadcrumb) { 20682 return breadcrumb.category === "xhr"; 20683} 20684function _isFetchBreadcrumb(breadcrumb) { 20685 return breadcrumb.category === "fetch"; 20686} 20687function _isXhrHint(hint) { 20688 return hint?.xhr; 20689} 20690function _isFetchHint(hint) { 20691 return hint?.input !== void 0; 20692} 20693function addGlobalListeners(replay) { 20694 const client = getClient(); 20695 addClickKeypressInstrumentationHandler(handleDomListener(replay)); 20696 addHistoryInstrumentationHandler(handleHistorySpanListener(replay)); 20697 handleBreadcrumbs(replay); 20698 handleNetworkBreadcrumbs(replay); 20699 addEventProcessor(handleGlobalEventListener(replay)); 20700 if (client) { 20701 client.on("beforeSendEvent", handleBeforeSendEvent(replay)); 20702 client.on("afterSendEvent", handleAfterSendEvent(replay)); 20703 client.on("createDsc", (dsc) => { 20704 const replayId = replay.getSessionId(); 20705 if (replayId && replay.isEnabled() && replay.recordingMode === "session") { 20706 if (replay.checkAndHandleExpiredSession()) dsc.replay_id = replayId; 20707 } 20708 }); 20709 client.on("processSegmentSpan", handleProcessSegmentSpan(replay)); 20710 client.on("spanStart", (span) => { 20711 replay.lastActiveSpan = span; 20712 }); 20713 client.on("spanEnd", (span) => { 20714 replay.lastActiveSpan = span; 20715 }); 20716 client.on("beforeSendFeedback", async (feedbackEvent, options) => { 20717 const replayId = replay.getSessionId(); 20718 if (options?.includeReplay && replay.isEnabled() && replayId && feedbackEvent.contexts?.feedback) { 20719 if (feedbackEvent.contexts.feedback.source === "api") await replay.sendBufferedReplayOrFlush(); 20720 feedbackEvent.contexts.feedback.replay_id = replayId; 20721 } 20722 }); 20723 client.on("openFeedbackWidget", async () => { 20724 await replay.sendBufferedReplayOrFlush(); 20725 }); 20726 } 20727} 20728async function addMemoryEntry(replay) { 20729 try { 20730 return Promise.all(createPerformanceSpans(replay, [createMemoryEntry(WINDOW.performance.memory)])); 20731 } catch { 20732 return []; 20733 } 20734} 20735function createMemoryEntry(memoryEntry) { 20736 const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry; 20737 const time = Date.now() / 1e3; 20738 return { 20739 type: "memory", 20740 name: "memory", 20741 start: time, 20742 end: time, 20743 data: { memory: { 20744 jsHeapSizeLimit, 20745 totalJSHeapSize, 20746 usedJSHeapSize 20747 } } 20748 }; 20749} 20750function debounce(func, wait, options) { 20751 return debounce$1(func, wait, { 20752 ...options, 20753 setTimeoutImpl: setTimeout$3 20754 }); 20755} 20756function getRecordingSamplingOptions() { 20757 if (/iPhone|iPad|iPod/i.test(NAVIGATOR?.userAgent ?? "") || /Macintosh/i.test(NAVIGATOR?.userAgent ?? "") && NAVIGATOR?.maxTouchPoints && NAVIGATOR?.maxTouchPoints > 1) return { sampling: { mousemove: false } }; 20758 return {}; 20759} 20760function getHandleRecordingEmit(replay) { 20761 let hadFirstEvent = false;
20762 return (event, _isCheckout) => { 20763 try { 20764 if (!replay.checkAndHandleExpiredSession()) { 20765 DEBUG_BUILD$1 && debug.warn("Received replay event after session expired."); 20766 return; 20767 } 20768 const isCheckout = _isCheckout || !hadFirstEvent; 20769 hadFirstEvent = true; 20770 syncMirrorAttributesFromMutationEvent(event); 20771 if (replay.clickDetector) updateClickDetectorForRecordingEvent(replay.clickDetector, event); 20772 replay.addUpdate(() => { 20773 if (replay.recordingMode === "buffer" && isCheckout) replay.setInitialState(); 20774 if (!addEventSync(replay, event, isCheckout)) return true; 20775 if (!isCheckout) return false; 20776 const session = replay.session; 20777 addSettingsEvent(replay, isCheckout); 20778 if (replay.recordingMode === "buffer" && session && replay.eventBuffer && !session.dirty) { 20779 const earliestEvent = replay.eventBuffer.getEarliestTimestamp(); 20780 if (earliestEvent) { 20781 DEBUG_BUILD$1 && debug.log(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`); 20782 session.started = earliestEvent; 20783 if (replay.getOptions().stickySession) saveSession(session); 20784 } 20785 } 20786 if (session?.previousSessionId) return true; 20787 if (replay.recordingMode === "session") replay.flush(); 20788 return true; 20789 }); 20790 } catch (error) { 20791 replay.handleException(error); 20792 } 20793 }; 20794} 20795function syncMirrorAttributesFromMutationEvent(event) { 20796 const data = event.data; 20797 if (event.type !== EventType.IncrementalSnapshot || !data || typeof data !== "object" || !("source" in data) || data.source !== IncrementalSource.Mutation || !("attributes" in data) || !Array.isArray(data.attributes)) return; 20798 for (const mutation of data.attributes) { 20799 const node = record.mirror.getNode(mutation.id); 20800 const meta = node && record.mirror.getMeta(node); 20801 if (meta?.type !== NodeType.Element) continue; 20802 for (const [attributeName, value] of Object.entries(mutation.attributes)) if (value === null) delete meta.attributes[attributeName]; 20803 else meta.attributes[attributeName] = value; 20804 } 20805} 20806function createOptionsEvent(replay) { 20807 const options = replay.getOptions(); 20808 return { 20809 type: EventType.Custom, 20810 timestamp: Date.now(), 20811 data: { 20812 tag: "options", 20813 payload: { 20814 shouldRecordCanvas: replay.isRecordingCanvas(), 20815 sessionSampleRate: options.sessionSampleRate, 20816 errorSampleRate: options.errorSampleRate, 20817 useCompressionOption: options.useCompression, 20818 blockAllMedia: options.blockAllMedia, 20819 maskAllText: options.maskAllText, 20820 maskAllInputs: options.maskAllInputs, 20821 useCompression: replay.eventBuffer ? replay.eventBuffer.type === "worker" : false, 20822 networkDetailHasUrls: options.networkDetailAllowUrls.length > 0, 20823 networkCaptureBodies: options.networkCaptureBodies, 20824 networkRequestHasHeaders: options.networkRequestHeaders.length > 0, 20825 networkResponseHasHeaders: options.networkResponseHeaders.length > 0 20826 } 20827 } 20828 }; 20829} 20830function addSettingsEvent(replay, isCheckout) { 20831 if (!isCheckout || replay.session?.segmentId !== 0) return; 20832 addEventSync(replay, createOptionsEvent(replay), false); 20833} 20834function closestElementOfNode$2(node) { 20835 if (!node) return null; 20836 try { 20837 return node.nodeType === node.ELEMENT_NODE ? node : node.parentElement; 20838 } catch { 20839 return null; 20840 } 20841} 20842function createReplayEnvelope(replayEvent, recordingData, dsn, tunnel) { 20843 return createEnvelope(createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn), [[{ type: "replay_event" }, replayEvent], [{ 20844 type: "replay_recording", 20845 length: typeof recordingData === "string" ? new TextEncoder().encode(recordingData).length : recordingData.length 20846 }, recordingData]]); 20847} 20848function prepareRecordingData({ recordingData, headers }) { 20849 let payloadWithSequence; 20850 const replayHeaders = `${JSON.stringify(headers)} 20851`; 20852 if (typeof recordingData === "string") payloadWithSequence = `${replayHeaders}${recordingData}`; 20853 else { 20854 const sequence = new TextEncoder().encode(replayHeaders); 20855 payloadWithSequence = new Uint8Array(sequence.length + recordingData.length); 20856 payloadWithSequence.set(sequence); 20857 payloadWithSequence.set(recordingData, sequence.length); 20858 } 20859 return payloadWithSequence; 20860} 20861async function prepareReplayEvent({ client, scope, replayId: event_id, event }) { 20862 const eventHint = { 20863 event_id,
20864 integrations: typeof client["_integrations"] === "object" && client["_integrations"] !== null && !Array.isArray(client["_integrations"]) ? Object.keys(client["_integrations"]) : void 0 20865 }; 20866 client.emit("preprocessEvent", event, eventHint); 20867 const preparedEvent = await prepareEvent(client.getOptions(), event, eventHint, scope, client, getIsolationScope()); 20868 if (!preparedEvent) return null; 20869 client.emit("postprocessEvent", preparedEvent, eventHint); 20870 preparedEvent.platform = preparedEvent.platform || "javascript"; 20871 const { name, version, settings } = client.getSdkMetadata()?.sdk || {}; 20872 preparedEvent.sdk = { 20873 ...preparedEvent.sdk, 20874 name: name || "sentry.javascript.unknown", 20875 version: version || "0.0.0", 20876 settings 20877 }; 20878 return preparedEvent; 20879} 20880async function sendReplayRequest({ recordingData, replayId, segmentId: segment_id, eventContext, timestamp, session }) { 20881 const preparedRecordingData = prepareRecordingData({ 20882 recordingData, 20883 headers: { segment_id } 20884 }); 20885 const { urls, errorIds, traceIds, segmentNames, initialTimestamp } = eventContext; 20886 const client = getClient(); 20887 const scope = getCurrentScope(); 20888 const transport = client?.getTransport(); 20889 const dsn = client?.getDsn(); 20890 if (!client || !transport || !dsn || !session.sampled) return Promise.resolve({}); 20891 const replayEvent = await prepareReplayEvent({ 20892 scope, 20893 client, 20894 replayId, 20895 event: { 20896 type: REPLAY_EVENT_NAME, 20897 replay_start_timestamp: initialTimestamp / 1e3, 20898 timestamp: timestamp / 1e3, 20899 error_ids: errorIds, 20900 trace_ids: traceIds, 20901 segment_names: segmentNames, 20902 urls, 20903 replay_id: replayId, 20904 segment_id, 20905 replay_type: session.sampled 20906 } 20907 }); 20908 if (!replayEvent) { 20909 client.recordDroppedEvent("event_processor", "replay"); 20910 DEBUG_BUILD$1 && debug.log("An event processor returned `null`, will not send event."); 20911 return Promise.resolve({}); 20912 } 20913 delete replayEvent.sdkProcessingMetadata; 20914 const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel); 20915 let response; 20916 try { 20917 response = await transport.send(envelope); 20918 } catch (err) { 20919 const error = /* @__PURE__ */ new Error(UNABLE_TO_SEND_REPLAY); 20920 try { 20921 error.cause = err; 20922 } catch {} 20923 throw error; 20924 } 20925 const rateLimits = updateRateLimits({}, response); 20926 if (isRateLimited(rateLimits, "replay")) throw new RateLimitError(rateLimits); 20927 if (typeof response.statusCode === "number" && (response.statusCode < 200 || response.statusCode >= 300)) throw new TransportStatusCodeError(response.statusCode); 20928 return response; 20929} 20930async function sendReplay(replayData, retryConfig = { 20931 count: 0, 20932 interval: RETRY_BASE_INTERVAL 20933}) { 20934 const { recordingData, onError } = replayData; 20935 if (!recordingData.length) return; 20936 try { 20937 await sendReplayRequest(replayData); 20938 return true; 20939 } catch (err) { 20940 if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) throw err; 20941 setContext("Replays", { _retryCount: retryConfig.count }); 20942 if (onError) onError(err); 20943 if (retryConfig.count >= RETRY_MAX_COUNT) { 20944 const error = /* @__PURE__ */ new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`); 20945 try { 20946 error.cause = err; 20947 } catch {} 20948 throw error; 20949 } 20950 retryConfig.interval *= ++retryConfig.count; 20951 return new Promise((resolve, reject) => { 20952 setTimeout$3(async () => { 20953 try { 20954 await sendReplay(replayData, retryConfig); 20955 resolve(true); 20956 } catch (err2) { 20957 reject(err2); 20958 } 20959 }, retryConfig.interval); 20960 }); 20961 } 20962} 20963function throttle(fn, maxCount, durationSeconds) { 20964 const counter = /* @__PURE__ */ new Map(); 20965 const _cleanup = (now) => { 20966 const threshold = now - durationSeconds; 20967 counter.forEach((_value, key) => { 20968 if (key < threshold) counter.delete(key); 20969 }); 20970 }; 20971 const _getTotalCount = () => { 20972 return [...counter.values()].reduce((a, b) => a + b, 0); 20973 }; 20974 let isThrottled = false; 20975 return (...rest) => { 20976 const now = Math.floor(Date.now() / 1e3); 20977 _cleanup(now); 20978 if (_getTotalCount() >= maxCount) { 20979 const wasThrottled = isThrottled; 20980 isThrottled = true; 20981 return wasThrottled ? SKIPPED : THROTTLED; 20982 } 20983 isThrottled = false;
20984 const count = counter.get(now) || 0; 20985 counter.set(now, count + 1); 20986 return fn(...rest); 20987 }; 20988} 20989function getOption(selectors, defaultSelectors) { 20990 return [...selectors, ...defaultSelectors].join(","); 20991} 20992function getPrivacyOptions({ mask, unmask, block, unblock, ignore }) { 20993 return { 20994 maskTextSelector: getOption(mask, [".sentry-mask", "[data-sentry-mask]"]), 20995 unmaskTextSelector: getOption(unmask, []), 20996 blockSelector: getOption(block, [ 20997 ".sentry-block", 20998 "[data-sentry-block]", 20999 ...["base", "iframe[srcdoc]:not([src])"] 21000 ]), 21001 unblockSelector: getOption(unblock, []), 21002 ignoreSelector: getOption(ignore, [ 21003 ".sentry-ignore", 21004 "[data-sentry-ignore]", 21005 "input[type=\"file\"]" 21006 ]) 21007 }; 21008} 21009function maskAttribute({ el, key, maskAttributes, maskAllText, privacyOptions, value }) { 21010 if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) return value; 21011 const masksNamedAttribute = maskAttributes.includes(key); 21012 const masksSubmitButtonValue = maskAllText && key === "value" && el.tagName === "INPUT" && ["submit", "button"].includes(el.getAttribute("type") || ""); 21013 if (masksNamedAttribute || masksSubmitButtonValue) return value.replace(/[\S]/g, "*"); 21014 return value; 21015} 21016function _INTERNAL_instrumentRequestInterface() { 21017 if (typeof Request === "undefined" || _isRequestInstrumented) return; 21018 const OriginalRequest = Request; 21019 try { 21020 const SentryRequest = function(input, init) { 21021 const request = new OriginalRequest(input, init); 21022 if (init?.body != null) request[ORIGINAL_BODY] = init.body; 21023 return request; 21024 }; 21025 SentryRequest.prototype = OriginalRequest.prototype; 21026 GLOBAL_OBJ.Request = SentryRequest; 21027 _isRequestInstrumented = true; 21028 } catch {} 21029} 21030function loadReplayOptionsFromClient(initialOptions, client) { 21031 const opt = client.getOptions(); 21032 const finalOptions = { 21033 sessionSampleRate: 0, 21034 errorSampleRate: 0, 21035 ...initialOptions 21036 }; 21037 const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate); 21038 const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate); 21039 if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) consoleSandbox(() => { 21040 console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set."); 21041 }); 21042 if (replaysSessionSampleRate != null) finalOptions.sessionSampleRate = replaysSessionSampleRate; 21043 if (replaysOnErrorSampleRate != null) finalOptions.errorSampleRate = replaysOnErrorSampleRate; 21044 return finalOptions; 21045} 21046function _getMergedNetworkHeaders(headers) { 21047 return [...DEFAULT_NETWORK_HEADERS, ...headers.map((header) => header.toLowerCase())]; 21048} 21049function getReplay() { 21050 return getClient()?.getIntegrationByName("Replay"); 21051} 21052var WINDOW, REPLAY_SESSION_KEY, REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY, SESSION_IDLE_PAUSE_DURATION, SESSION_IDLE_EXPIRE_DURATION, DEFAULT_FLUSH_MIN_DELAY, DEFAULT_FLUSH_MAX_DELAY, BUFFER_CHECKOUT_TIME, RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, NETWORK_BODY_MAX_SIZE, CONSOLE_ARG_MAX_SIZE, SLOW_CLICK_THRESHOLD, SLOW_CLICK_SCROLL_TIMEOUT, REPLAY_MAX_EVENT_BUFFER_SIZE, MIN_REPLAY_DURATION, MIN_REPLAY_DURATION_LIMIT, MAX_REPLAY_DURATION, __defProp$1, __defNormalProp$1, __publicField$1, NodeType$1, Mirror$1, ORIGINAL_ATTRIBUTE_NAME, cachedImplementations$1, _id, tagNameRegex, IGNORED_NODE, canvasService, canvasCtx, URL_IN_CSS_REF, URL_PROTOCOL_MATCH, URL_WWW_MATCH, DATA_URI, SRCSET_NOT_SPACES, SRCSET_COMMAS_OR_SPACES, cachedDocument, DEPARTED_MIRROR_ACCESS_WARNING$1, _mirror$1, nowTimestamp, StyleSheetMirror, cachedImplementations$2, EventType, IncrementalSource, MouseInteractions, PointerTypes, MediaInteractions, errorHandler$1, callbackWrapper$1, chars$1, lookup$1, i$1, CanvasManagerNoop, StyleDeclarationParser, DoubleLinkedList, moveKey, MutationBuffer, mutationBuffers, INPUT_TAGS, lastInputValueMap, CrossOriginIframeMirror, IframeManagerNoop, IframeManager, ShadowDomManagerNoop, ShadowDomManager, StylesheetManager, ProcessedNodeManager, wrappedEmit, _takeFullSnapshot, mirror, n$1, ReplayEventTypeIncrementalSnapshot, ReplayEventTypeCustom, INTERACTIVE_SELECTOR, handlers, IncrementalMutationSources, ClickDetector, SLOW_CLICK_TAGS, NodeType, ATTRIBUTES_TO_RECORD, handleDomListener, ENTRY_TYPES, DEBUG_BUILD$1, t$1, CONSOLE_LEVELS, PREFIX, debug, EventBufferSizeExceededError, WorkerDestroyedError, EventBufferArray, WorkerHandler, EventBufferCompressionWorker, EventBufferProxy, MAX_CONTEXT_VALUES, NAVIGATOR, TransportStatusCodeError, RateLimitError, ReplayDurationLimitError, THROTTLED, SKIPPED, ReplayContainer, MEDIA_SELECTORS, DEFAULT_NETWORK_HEADERS, ORIGINAL_BODY, _initialized, _isRequestInstrumented, replayIntegration, Replay; 21053function init_esm$1() { 21054 return (init_esm$1 = __esmMin((() => { 21055 init_worldwide(), init_normalize(), init_is(), init_object(), init_time(), init_debug_logger(), init_exports(), init_breadcrumbs(), init_misc(), init_currentScopes(), init_browser(), init_spanUtils(), init_dynamicSamplingContext(), init_isSentryRequestUrl(), init_string(), init_envelope(), init_prepareEvent(), init_ratelimit(), init_semanticAttributes(), init_isBrowser(), init_captureSpan(); 21056 init_getNativeImplementation(), init_htmlTreeAsString(), init_instrument(), init_networkUtils(), init_xhr(), init_dom(), init_history(); 21057 WINDOW = GLOBAL_OBJ; 21058 REPLAY_SESSION_KEY = "sentryReplaySession"; 21059 REPLAY_EVENT_NAME = "replay_event";
21060 UNABLE_TO_SEND_REPLAY = "Unable to send Replay"; 21061 SESSION_IDLE_PAUSE_DURATION = 3e5; 21062 SESSION_IDLE_EXPIRE_DURATION = 9e5; 21063 DEFAULT_FLUSH_MIN_DELAY = 5e3; 21064 DEFAULT_FLUSH_MAX_DELAY = 5500; 21065 BUFFER_CHECKOUT_TIME = 6e4; 21066 RETRY_BASE_INTERVAL = 5e3; 21067 RETRY_MAX_COUNT = 3; 21068 NETWORK_BODY_MAX_SIZE = 15e4; 21069 CONSOLE_ARG_MAX_SIZE = 5e3; 21070 SLOW_CLICK_THRESHOLD = 3e3; 21071 SLOW_CLICK_SCROLL_TIMEOUT = 300; 21072 REPLAY_MAX_EVENT_BUFFER_SIZE = 2e7; 21073 MIN_REPLAY_DURATION = 4999; 21074 MIN_REPLAY_DURATION_LIMIT = 5e4; 21075 MAX_REPLAY_DURATION = 36e5; 21076 __defProp$1 = Object.defineProperty; 21077 __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { 21078 enumerable: true, 21079 configurable: true, 21080 writable: true, 21081 value 21082 }) : obj[key] = value; 21083 __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); 21084 NodeType$1 = /* @__PURE__ */ ((NodeType2) => { 21085 NodeType2[NodeType2["Document"] = 0] = "Document"; 21086 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType"; 21087 NodeType2[NodeType2["Element"] = 2] = "Element"; 21088 NodeType2[NodeType2["Text"] = 3] = "Text"; 21089 NodeType2[NodeType2["CDATA"] = 4] = "CDATA"; 21090 NodeType2[NodeType2["Comment"] = 5] = "Comment"; 21091 return NodeType2; 21092 })(NodeType$1 || {}); 21093 Mirror$1 = class { 21094 constructor() { 21095 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map()); 21096 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap()); 21097 } 21098 getId(n) { 21099 if (!n) return -1; 21100 return this.getMeta(n)?.id ?? -1; 21101 } 21102 getNode(id) { 21103 return this.idNodeMap.get(id) || null; 21104 } 21105 getIds() { 21106 return Array.from(this.idNodeMap.keys()); 21107 } 21108 getMeta(n) { 21109 return this.nodeMetaMap.get(n) || null; 21110 } 21111 removeNodeFromMap(n) { 21112 const id = this.getId(n); 21113 this.idNodeMap.delete(id); 21114 if (n.childNodes) n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode)); 21115 } 21116 has(id) { 21117 return this.idNodeMap.has(id); 21118 } 21119 hasNode(node) { 21120 return this.nodeMetaMap.has(node); 21121 } 21122 add(n, meta) { 21123 const id = meta.id; 21124 this.idNodeMap.set(id, n); 21125 this.nodeMetaMap.set(n, meta); 21126 } 21127 replace(id, n) { 21128 const oldNode = this.getNode(id); 21129 if (oldNode) { 21130 const meta = this.nodeMetaMap.get(oldNode); 21131 if (meta) this.nodeMetaMap.set(n, meta); 21132 } 21133 this.idNodeMap.set(id, n); 21134 } 21135 reset() { 21136 this.idNodeMap = /* @__PURE__ */ new Map(); 21137 this.nodeMetaMap = /* @__PURE__ */ new WeakMap(); 21138 } 21139 }; 21140 ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__"; 21141 cachedImplementations$1 = {}; 21142 _id = 1; 21143 tagNameRegex = /* @__PURE__ */ new RegExp("[^a-z0-9-_:]"); 21144 IGNORED_NODE = -2; 21145 URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm; 21146 URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i; 21147 URL_WWW_MATCH = /^www\..*/i; 21148 DATA_URI = /^(data:)([^,]*),(.*)/i; 21149 SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/; 21150 SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/; 21151 cachedDocument = /* @__PURE__ */ new WeakMap(); 21152 DEPARTED_MIRROR_ACCESS_WARNING$1 = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording."; 21153 _mirror$1 = { 21154 map: {}, 21155 getId() { 21156 console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21157 return -1; 21158 }, 21159 getNode() { 21160 console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21161 return null; 21162 }, 21163 removeNodeFromMap() { 21164 console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21165 }, 21166 has() { 21167 console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21168 return false; 21169 }, 21170 reset() { 21171 console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21172 } 21173 }; 21174 if (typeof window !== "undefined" && window.Proxy && window.Reflect) _mirror$1 = new Proxy(_mirror$1, { get(target, prop, receiver) { 21175 if (prop === "map") console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); 21176 return Reflect.get(target, prop, receiver); 21177 } }); 21178 nowTimestamp = Date.now; 21179 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime(); 21180 StyleSheetMirror = class { 21181 constructor() { 21182 this.id = 1; 21183 this.styleIDMap = /* @__PURE__ */ new WeakMap(); 21184 this.idStyleMap = /* @__PURE__ */ new Map(); 21185 } 21186 getId(stylesheet) { 21187 return this.styleIDMap.get(stylesheet) ?? -1; 21188 } 21189 has(stylesheet) { 21190 return this.styleIDMap.has(stylesheet); 21191 } 21192 /**
21193 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id. 21194 */ 21195 add(stylesheet, id) { 21196 if (this.has(stylesheet)) return this.getId(stylesheet); 21197 let newId; 21198 if (id === void 0) newId = this.id++; 21199 else newId = id; 21200 this.styleIDMap.set(stylesheet, newId); 21201 this.idStyleMap.set(newId, stylesheet); 21202 return newId; 21203 } 21204 getStyle(id) { 21205 return this.idStyleMap.get(id) || null; 21206 } 21207 reset() { 21208 this.styleIDMap = /* @__PURE__ */ new WeakMap(); 21209 this.idStyleMap = /* @__PURE__ */ new Map(); 21210 this.id = 1; 21211 } 21212 generateId() { 21213 return this.id++; 21214 } 21215 }; 21216 cachedImplementations$2 = {}; 21217 EventType = /* @__PURE__ */ ((EventType2) => { 21218 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded"; 21219 EventType2[EventType2["Load"] = 1] = "Load"; 21220 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot"; 21221 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot"; 21222 EventType2[EventType2["Meta"] = 4] = "Meta"; 21223 EventType2[EventType2["Custom"] = 5] = "Custom"; 21224 EventType2[EventType2["Plugin"] = 6] = "Plugin"; 21225 return EventType2; 21226 })(EventType || {}); 21227 IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => { 21228 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation"; 21229 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove"; 21230 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction"; 21231 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll"; 21232 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize"; 21233 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input"; 21234 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove"; 21235 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction"; 21236 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule"; 21237 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation"; 21238 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font"; 21239 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log"; 21240 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag"; 21241 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration"; 21242 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection"; 21243 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet"; 21244 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement"; 21245 return IncrementalSource2; 21246 })(IncrementalSource || {}); 21247 MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => { 21248 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp"; 21249 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown"; 21250 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click"; 21251 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu"; 21252 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick"; 21253 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus"; 21254 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur"; 21255 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart"; 21256 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed"; 21257 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd"; 21258 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel"; 21259 return MouseInteractions2; 21260 })(MouseInteractions || {}); 21261 PointerTypes = /* @__PURE__ */ ((PointerTypes2) => { 21262 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse"; 21263 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen"; 21264 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch"; 21265 return PointerTypes2; 21266 })(PointerTypes || {}); 21267 MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => { 21268 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play"; 21269 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause"; 21270 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked"; 21271 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange"; 21272 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange"; 21273 return MediaInteractions2; 21274 })(MediaInteractions || {}); 21275 callbackWrapper$1 = (cb) => { 21276 if (!errorHandler$1) return cb; 21277 const rrwebWrapped = ((...rest) => { 21278 try { 21279 return cb(...rest); 21280 } catch (error) { 21281 if (errorHandler$1 && errorHandler$1(error) === true) return () => {}; 21282 throw error; 21283 } 21284 }); 21285 return rrwebWrapped; 21286 }; 21287 chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
21287+/"; 21288 lookup$1 = typeof Uint8Array === "undefined" ? [] : /* @__PURE__ */ new Uint8Array(256); 21289 for (i$1 = 0; i$1 < chars$1.length; i$1++) lookup$1[chars$1.charCodeAt(i$1)] = i$1; 21290 CanvasManagerNoop = class { 21291 reset() {} 21292 freeze() {} 21293 unfreeze() {} 21294 lock() {} 21295 unlock() {} 21296 snapshot() {} 21297 addWindow() {} 21298 addShadowRoot() {} 21299 resetShadowRoots() {} 21300 }; 21301 StyleDeclarationParser = class { 21302 constructor(doc) { 21303 this.doc = doc; 21304 this.unattachedDoc = null; 21305 } 21306 parse(styleText) { 21307 return this.parseWithConstructableStylesheet(styleText) || this.parseWithDetachedElement(styleText); 21308 } 21309 parseWithConstructableStylesheet(styleText) { 21310 if (typeof CSSStyleSheet === "undefined" || typeof CSSStyleSheet.prototype.replaceSync !== "function") return null; 21311 try { 21312 const sheet = new CSSStyleSheet(); 21313 sheet.replaceSync(`x { ${styleText} }`); 21314 const rule = sheet.cssRules[0]; 21315 if (!rule || rule.type !== CSSRule.STYLE_RULE) return null; 21316 return rule.style; 21317 } catch { 21318 return null; 21319 } 21320 } 21321 parseWithDetachedElement(styleText) { 21322 const old = this.getUnattachedDoc().createElement("span"); 21323 old.setAttribute("style", styleText); 21324 return old.style; 21325 } 21326 getUnattachedDoc() { 21327 if (!this.unattachedDoc) try { 21328 this.unattachedDoc = document.implementation.createHTMLDocument(); 21329 } catch { 21330 this.unattachedDoc = this.doc; 21331 } 21332 return this.unattachedDoc; 21333 } 21334 }; 21335 DoubleLinkedList = class { 21336 constructor() { 21337 this.length = 0; 21338 this.head = null; 21339 this.tail = null; 21340 } 21341 get(position) { 21342 if (position >= this.length) throw new Error("Position outside of list range"); 21343 let current = this.head; 21344 for (let index = 0; index < position; index++) current = current?.next || null; 21345 return current; 21346 } 21347 addNode(n2) { 21348 const node = { 21349 value: n2, 21350 previous: null, 21351 next: null 21352 }; 21353 n2.__ln = node; 21354 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) { 21355 const current = n2.previousSibling.__ln.next; 21356 node.next = current; 21357 node.previous = n2.previousSibling.__ln; 21358 n2.previousSibling.__ln.next = node; 21359 if (current) current.previous = node; 21360 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) { 21361 const current = n2.nextSibling.__ln.previous; 21362 node.previous = current; 21363 node.next = n2.nextSibling.__ln; 21364 n2.nextSibling.__ln.previous = node; 21365 if (current) current.next = node; 21366 } else { 21367 if (this.head) this.head.previous = node; 21368 node.next = this.head; 21369 this.head = node; 21370 } 21371 if (node.next === null) this.tail = node; 21372 this.length++; 21373 } 21374 removeNode(n2) { 21375 const current = n2.__ln; 21376 if (!this.head) return; 21377 if (!current.previous) { 21378 this.head = current.next; 21379 if (this.head) this.head.previous = null; 21380 else this.tail = null; 21381 } else { 21382 current.previous.next = current.next; 21383 if (current.next) current.next.previous = current.previous; 21384 else this.tail = current.previous; 21385 } 21386 if (n2.__ln) delete n2.__ln; 21387 this.length--; 21388 } 21389 }; 21390 moveKey = (id, parentId) => `${id}@${parentId}`; 21391 MutationBuffer = class { 21392 constructor() { 21393 this.frozen = false; 21394 this.locked = false; 21395 this.texts = []; 21396 this.attributes = []; 21397 this.attributeMap = /* @__PURE__ */ new WeakMap(); 21398 this.removes = []; 21399 this.mapRemoves = []; 21400 this.movedMap = {}; 21401 this.addedSet = /* @__PURE__ */ new Set(); 21402 this.movedSet = /* @__PURE__ */ new Set(); 21403 this.droppedSet = /* @__PURE__ */ new Set(); 21404 this.processMutations = (mutations) => { 21405 mutations.forEach(this.processMutation); 21406 this.emit(); 21407 }; 21408 this.emit = () => { 21409 if (this.frozen || this.locked) return; 21410 const adds = []; 21411 const addedIds = /* @__PURE__ */ new Set(); 21412 const addList = new DoubleLinkedList(); 21413 const getNextId = (n2) => { 21414 let ns = n2; 21415 let nextId = IGNORED_NODE; 21416 while (nextId === IGNORED_NODE) { 21417 ns = ns && ns.nextSibling; 21418 nextId = ns && this.mirror.getId(ns); 21419 } 21420 return nextId; 21421 }; 21422 const pushAdd = (n2) => { 21423 if (!n2.parentNode || !inDom(n2)) return; 21424 const parentId = isShadowRoot(n2.parentNode) ? this.mirror.getId(getShadowHost(n2)) : this.mirror.getId(n2.parentNode); 21425 const nextId = getNextId(n2); 21426 if (parentId === -1 || nextId === -1) return addList.addNode(n2); 21427 const sn = serializeNodeWithId(n2, { 21428 doc: this.doc, 21429 mirror: this.mirror, 21430 blockClass: this.blockClass, 21431 blockSelector: this.blockSelector, 21432 maskAllText: this.maskAllText, 21433 unblockSelector: this.unblockSelector, 21434 maskTextClass: this.maskTextClass, 21435 unmaskTextClass: this.unmaskTextClass, 21436 maskTextSelector: this.maskTextSelector, 21437 unmaskTextSelector: this.unmaskTextSelector, 21438 skipChild: true, 21439 newlyAddedElement: true, 21440 inlineStylesheet: this.inlineStylesheet, 21441 maskInputOptions: this.maskInputOptions, 21442 maskAttributeFn: this.maskAttributeFn, 21443 maskTextFn: this.maskTextFn, 21444 maskInputFn: this.maskInputFn, 21445 slimDOMOptions: this.slimDOMOptions, 21446 dataURLOptions: this.dataURLOptions, 21447 recordCanvas: this.recordCanvas, 21448 inlineImages: this.inlineImages, 21449 onSerialize: (currentN) => { 21450 if (isSerializedIframe(currentN, this.mirror) && !isBlocked$1(currentN, this.blockClass, this.blockSelector, this.unblockSelector, false)) this.iframeManager.addIframe(currentN); 21451 if (isSerializedStylesheet(currentN, this.mirror)) this.stylesheetManager.trackLinkElement(currentN); 21452 if (hasShadowRoot(n2)) this.shadowDomManager.addShadowRoot(n2.shadowRoot, this.doc); 21453 }, 21454 onIframeLoad: (iframe, childSn) => { 21455 if (isBlocked$1(iframe, this.blockClass, this.blockSelector, this.unblockSelector, false)) return; 21456 this.iframeManager.attachIframe(iframe, childSn); 21457 const contentWindow = getIFrameContentWindow(iframe); 21458 if (contentWindow) this.canvasManager.addWindow(contentWindow); 21459 this.shadowDomManager.observeAttachShadow(iframe); 21460 }, 21461 onStylesheetLoad: (link, childSn) => { 21462 this.stylesheetManager.attachLinkElement(link, childSn); 21463 }, 21464 onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => { 21465 this.mutationCb({ 21466 adds: [], 21467 removes: [], 21468 texts: [], 21469 attributes: [{ 21470 id: serializedNode.id, 21471 attributes: { style: { 21472 width: `${width}px`, 21473 height: `${height}px` 21474 } } 21475 }] 21476 }); 21477 }, 21478 ignoreCSSAttributes: this.ignoreCSSAttributes 21479 }); 21480 if (sn) { 21481 adds.push({ 21482 parentId, 21483 nextId, 21484 node: sn 21485 });
21486 addedIds.add(sn.id); 21487 } 21488 }; 21489 while (this.mapRemoves.length) this.mirror.removeNodeFromMap(this.mapRemoves.shift()); 21490 for (const n2 of this.movedSet) { 21491 if (isParentRemoved(this.removes, n2, this.mirror) && !this.movedSet.has(n2.parentNode)) continue; 21492 pushAdd(n2); 21493 } 21494 for (const n2 of this.addedSet) if (!isAncestorInSet(this.droppedSet, n2) && !isParentRemoved(this.removes, n2, this.mirror)) pushAdd(n2); 21495 else if (isAncestorInSet(this.movedSet, n2)) pushAdd(n2); 21496 else this.droppedSet.add(n2); 21497 let candidate = null; 21498 while (addList.length) { 21499 let node = null; 21500 if (candidate) { 21501 const parentId = this.mirror.getId(candidate.value.parentNode); 21502 const nextId = getNextId(candidate.value); 21503 if (parentId !== -1 && nextId !== -1) node = candidate; 21504 } 21505 if (!node) { 21506 let tailNode = addList.tail; 21507 while (tailNode) { 21508 const _node = tailNode; 21509 tailNode = tailNode.previous; 21510 if (_node) { 21511 const parentId = this.mirror.getId(_node.value.parentNode); 21512 if (getNextId(_node.value) === -1) continue; 21513 else if (parentId !== -1) { 21514 node = _node; 21515 break; 21516 } else { 21517 const unhandledNode = _node.value; 21518 if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { 21519 const shadowHost = unhandledNode.parentNode.host; 21520 if (this.mirror.getId(shadowHost) !== -1) { 21521 node = _node; 21522 break; 21523 } 21524 } 21525 } 21526 } 21527 } 21528 } 21529 if (!node) { 21530 while (addList.head) addList.removeNode(addList.head.value); 21531 break; 21532 } 21533 candidate = node.previous; 21534 addList.removeNode(node.value); 21535 pushAdd(node.value); 21536 } 21537 const payload = { 21538 texts: this.texts.map((text) => ({ 21539 id: this.mirror.getId(text.node), 21540 value: text.value 21541 })).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)), 21542 attributes: this.attributes.map((attribute) => { 21543 const { attributes } = attribute; 21544 if (typeof attributes.style === "string") { 21545 const diffAsStr = JSON.stringify(attribute.styleDiff); 21546 const unchangedAsStr = JSON.stringify(attribute._unchangedStyles); 21547 if (diffAsStr.length < attributes.style.length) { 21548 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) attributes.style = attribute.styleDiff; 21549 } 21550 } 21551 return { 21552 id: this.mirror.getId(attribute.node), 21553 attributes 21554 }; 21555 }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)), 21556 removes: this.removes, 21557 adds 21558 }; 21559 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) return; 21560 this.texts = []; 21561 this.attributes = []; 21562 this.attributeMap = /* @__PURE__ */ new WeakMap(); 21563 this.removes = []; 21564 this.addedSet = /* @__PURE__ */ new Set(); 21565 this.movedSet = /* @__PURE__ */ new Set(); 21566 this.droppedSet = /* @__PURE__ */ new Set(); 21567 this.movedMap = {}; 21568 this.mutationCb(payload); 21569 }; 21570 this.processMutation = (m) => { 21571 if (isIgnored(m.target, this.mirror)) return; 21572 switch (m.type) { 21573 case "characterData": { 21574 const value = m.target.textContent; 21575 if (!isBlocked$1(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) && value !== m.oldValue) this.texts.push({ 21576 value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode$1(m.target)) : value.replace(/[\S]/g, "*") : value, 21577 node: m.target 21578 }); 21579 break; 21580 } 21581 case "attributes": { 21582 const target = m.target; 21583 let attributeName = m.attributeName; 21584 let value = m.target.getAttribute(attributeName); 21585 if (attributeName === "value") { 21586 const type = getInputType(target); 21587 const tagName = target.tagName; 21588 value = getInputValue(target, tagName, type); 21589 const isInputMasked = shouldMaskInput({ 21590 maskInputOptions: this.maskInputOptions, 21591 tagName, 21592 type 21593 }); 21594 value = maskInputValue({ 21595 isMasked: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked), 21596 element: target, 21597 value, 21598 maskInputFn: this.maskInputFn 21599 }); 21600 } 21601 if (isBlocked$1(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || value === m.oldValue) return; 21602 let item = this.attributeMap.get(m.target); 21603 if (target.tagName === "IFRAME" && attributeName === "src" && !this.keepIframeSrcFn(value)) { 21604 if (!getIFrameContentDocument(target)) attributeName = "rr_src"; 21605 else return; 21606 } 21607 if (!item) { 21608 item = { 21609 node: m.target, 21610 attributes: {}, 21611 styleDiff: {}, 21612 _unchangedStyles: {} 21613 }; 21614 this.attributes.push(item); 21615 this.attributeMap.set(m.target, item); 21616 } 21617 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") target.setAttribute("data-rr-is-password", "true"); 21618 if (!ignoreAttribute(target.tagName, attributeName)) { 21619 item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn); 21620 if (attributeName === "style") { 21621 const oldStyle = m.oldValue ? this.styleDeclarationParser.parse(m.oldValue) : null; 21622 for (const pname of Array.from(target.style)) { 21623 const newValue = target.style.getPropertyValue(pname); 21624 const newPriority = target.style.getPropertyPriority(pname); 21625 if (newValue !== (oldStyle?.getPropertyValue(pname) || "") || newPriority !== (oldStyle?.getPropertyPriority(pname) || "")) { 21626 if (newPriority === "") item.styleDiff[pname] = newValue; 21627 else item.styleDiff[pname] = [newValue, newPriority]; 21628 } else item._unchangedStyles[pname] = [newValue, newPriority]; 21629 } 21630 if (oldStyle) { 21631 for (const pname of Array.from(oldStyle)) if (target.style.getPropertyValue(pname) === "") item.styleDiff[pname] = false;
21632 } 21633 } 21634 } 21635 break; 21636 } 21637 case "childList": 21638 if (isBlocked$1(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) return; 21639 m.addedNodes.forEach((n2) => this.genAdds(n2, m.target)); 21640 m.removedNodes.forEach((n2) => { 21641 const nodeId = this.mirror.getId(n2); 21642 const parentId = isShadowRoot(m.target) ? this.mirror.getId(m.target.host) : this.mirror.getId(m.target); 21643 if (isBlocked$1(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || isIgnored(n2, this.mirror) || !isSerialized(n2, this.mirror)) return; 21644 if (this.addedSet.has(n2)) { 21645 deepDelete(this.addedSet, n2); 21646 this.droppedSet.add(n2); 21647 } else if (this.addedSet.has(m.target) && nodeId === -1); 21648 else if (isAncestorRemoved(m.target, this.mirror)); 21649 else if (this.movedSet.has(n2) && this.movedMap[moveKey(nodeId, parentId)]) deepDelete(this.movedSet, n2); 21650 else this.removes.push({ 21651 parentId, 21652 id: nodeId, 21653 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0 21654 }); 21655 this.mapRemoves.push(n2); 21656 }); 21657 } 21658 }; 21659 this.genAdds = (n2, target) => { 21660 if (this.processedNodeManager.inOtherBuffer(n2, this)) return; 21661 if (this.addedSet.has(n2) || this.movedSet.has(n2)) return; 21662 if (this.mirror.hasNode(n2)) { 21663 if (isIgnored(n2, this.mirror)) return; 21664 this.movedSet.add(n2); 21665 let targetId = null; 21666 if (target && this.mirror.hasNode(target)) targetId = this.mirror.getId(target); 21667 if (targetId && targetId !== -1) this.movedMap[moveKey(this.mirror.getId(n2), targetId)] = true; 21668 } else { 21669 this.addedSet.add(n2); 21670 this.droppedSet.delete(n2); 21671 } 21672 if (!isBlocked$1(n2, this.blockClass, this.blockSelector, this.unblockSelector, false)) { 21673 if (n2.childNodes) n2.childNodes.forEach((childN) => this.genAdds(childN)); 21674 if (hasShadowRoot(n2)) n2.shadowRoot.childNodes.forEach((childN) => { 21675 this.processedNodeManager.add(childN, this); 21676 this.genAdds(childN, n2); 21677 }); 21678 } 21679 }; 21680 } 21681 init(options) { 21682 [ 21683 "mutationCb", 21684 "blockClass", 21685 "blockSelector", 21686 "unblockSelector", 21687 "maskAllText", 21688 "maskTextClass", 21689 "unmaskTextClass", 21690 "maskTextSelector", 21691 "unmaskTextSelector", 21692 "inlineStylesheet", 21693 "maskInputOptions", 21694 "maskAttributeFn", 21695 "maskTextFn", 21696 "maskInputFn", 21697 "keepIframeSrcFn", 21698 "recordCanvas", 21699 "inlineImages", 21700 "slimDOMOptions", 21701 "dataURLOptions", 21702 "doc", 21703 "mirror", 21704 "iframeManager", 21705 "stylesheetManager", 21706 "shadowDomManager", 21707 "canvasManager", 21708 "processedNodeManager", 21709 "ignoreCSSAttributes" 21710 ].forEach((key) => { 21711 this[key] = options[key]; 21712 }); 21713 this.styleDeclarationParser = new StyleDeclarationParser(this.doc); 21714 } 21715 freeze() { 21716 this.frozen = true; 21717 this.canvasManager.freeze(); 21718 } 21719 unfreeze() { 21720 this.frozen = false; 21721 this.canvasManager.unfreeze(); 21722 this.emit(); 21723 } 21724 isFrozen() { 21725 return this.frozen; 21726 } 21727 lock() { 21728 this.locked = true; 21729 this.canvasManager.lock(); 21730 } 21731 unlock() { 21732 this.locked = false; 21733 this.canvasManager.unlock(); 21734 this.emit(); 21735 } 21736 reset() { 21737 this.shadowDomManager.reset(); 21738 this.canvasManager.reset(); 21739 } 21740 }; 21741 mutationBuffers = []; 21742 INPUT_TAGS = [ 21743 "INPUT", 21744 "TEXTAREA", 21745 "SELECT" 21746 ]; 21747 lastInputValueMap = /* @__PURE__ */ new WeakMap(); 21748 CrossOriginIframeMirror = class { 21749 constructor(generateIdFn) { 21750 this.generateIdFn = generateIdFn; 21751 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap(); 21752 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap(); 21753 } 21754 getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) { 21755 const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe); 21756 const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe); 21757 let id = idToRemoteIdMap.get(remoteId); 21758 if (!id) { 21759 id = this.generateIdFn(); 21760 idToRemoteIdMap.set(remoteId, id); 21761 remoteIdToIdMap.set(id, remoteId); 21762 } 21763 return id; 21764 } 21765 getIds(iframe, remoteId) { 21766 const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe); 21767 const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe); 21768 return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)); 21769 } 21770 getRemoteId(iframe, id, map) { 21771 const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe); 21772 if (typeof id !== "number") return id; 21773 const remoteId = remoteIdToIdMap.get(id); 21774 if (!remoteId) return -1; 21775 return remoteId; 21776 } 21777 getRemoteIds(iframe, ids) { 21778 const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe); 21779 return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap)); 21780 } 21781 reset(iframe) { 21782 if (!iframe) { 21783 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap(); 21784 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap(); 21785 return; 21786 } 21787 this.iframeIdToRemoteIdMap.delete(iframe); 21788 this.iframeRemoteIdToIdMap.delete(iframe); 21789 } 21790 getIdToRemoteIdMap(iframe) { 21791 let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe); 21792 if (!idToRemoteIdMap) { 21793 idToRemoteIdMap = /* @__PURE__ */ new Map(); 21794 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap); 21795 } 21796 return idToRemoteIdMap; 21797 } 21798 getRemoteIdToIdMap(iframe) { 21799 let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe); 21800 if (!remoteIdToIdMap) { 21801 remoteIdToIdMap = /* @__PURE__ */ new Map(); 21802 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap); 21803 } 21804 return remoteIdToIdMap; 21805 } 21806 }; 21807 IframeManagerNoop = class { 21808 constructor() { 21809 this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId); 21810 this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap(); 21811 } 21812 addIframe() {} 21813 addLoadListener() {} 21814 attachIframe() {} 21815 }; 21816 IframeManager = class { 21817 constructor(options) { 21818 this.iframes = /* @__PURE__ */ new WeakMap(); 21819 this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap(); 21820 this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId); 21821 this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap(); 21822 this.mutationCb = options.mutationCb; 21823 this.wrappedEmit = options.wrappedEmit; 21824 this.stylesheetManager = options.stylesheetManager; 21825 this.recordCrossOriginIframes = options.recordCrossOriginIframes; 21826 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)); 21827 this.mirror = options.mirror; 21828 if (this.recordCrossOriginIframes) window.addEventListener("message", this.handleMessage.bind(this)); 21829 } 21830 addIframe(iframeEl) { 21831 this.iframes.set(iframeEl, true); 21832 const contentWindow = getIFrameContentWindow(iframeEl); 21833 if (contentWindow) this.crossOriginIframeMap.set(contentWindow, iframeEl); 21834 } 21835 addLoadListener(cb) { 21836 this.loadListener = cb; 21837 } 21838 attachIframe(iframeEl, childSn) { 21839 this.mutationCb({ 21840 adds: [{ 21841 parentId: this.mirror.getId(iframeEl), 21842 nextId: null, 21843 node: childSn 21844 }], 21845 removes: [], 21846 texts: [], 21847 attributes: [], 21848 isAttachIframe: true 21849 }); 21850 if (this.recordCrossOriginIframes) getIFrameContentWindow(iframeEl)?.addEventListener("message", this.handleMessage.bind(this)); 21851 this.loadListener?.(iframeEl); 21852 const iframeDoc = getIFrameContentDocument(iframeEl); 21853 if (iframeDoc && iframeDoc.adoptedStyleSheets && iframeDoc.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets, this.mirror.getId(iframeDoc)); 21854 } 21855 handleMessage(message) { 21856 const crossOriginMessageEvent = message; 21857 if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return; 21858 if (!message.source) return; 21859 const iframeEl = this.crossOriginIframeMap.get(message.source); 21860 if (!iframeEl) return; 21861 const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event); 21862 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout); 21863 } 21864 transformCrossOriginEvent(iframeEl, e2) { 21865 switch (e2.type) { 21866 case EventType.FullSnapshot: { 21867 this.crossOriginIframeMirror.reset(iframeEl); 21868 this.crossOriginIframeStyleMirror.reset(iframeEl); 21869 this.replaceIdOnNode(e2.data.node, iframeEl); 21870 const rootId = e2.data.node.id; 21871 this.crossOriginIframeRootIdMap.set(iframeEl, rootId); 21872 this.patchRootIdOnNode(e2.data.node, rootId); 21873 return { 21874 timestamp: e2.timestamp, 21875 type: EventType.IncrementalSnapshot, 21876 data: { 21877 source: IncrementalSource.Mutation, 21878 adds: [{ 21879 parentId: this.mirror.getId(iframeEl), 21880 nextId: null, 21881 node: e2.data.node 21882 }], 21883 removes: [], 21884 texts: [], 21885 attributes: [], 21886 isAttachIframe: true 21887 } 21888 }; 21889 } 21890 case EventType.Meta: 21891 case EventType.Load: 21892 case EventType.DomContentLoaded: return false;
21893 case EventType.Plugin: return e2; 21894 case EventType.Custom: 21895 this.replaceIds(e2.data.payload, iframeEl, [ 21896 "id", 21897 "parentId", 21898 "previousId", 21899 "nextId" 21900 ]); 21901 return e2; 21902 case EventType.IncrementalSnapshot: switch (e2.data.source) { 21903 case IncrementalSource.Mutation: 21904 e2.data.adds.forEach((n2) => { 21905 this.replaceIds(n2, iframeEl, [ 21906 "parentId", 21907 "nextId", 21908 "previousId" 21909 ]); 21910 this.replaceIdOnNode(n2.node, iframeEl); 21911 const rootId = this.crossOriginIframeRootIdMap.get(iframeEl); 21912 rootId && this.patchRootIdOnNode(n2.node, rootId); 21913 }); 21914 e2.data.removes.forEach((n2) => { 21915 this.replaceIds(n2, iframeEl, ["parentId", "id"]); 21916 }); 21917 e2.data.attributes.forEach((n2) => { 21918 this.replaceIds(n2, iframeEl, ["id"]); 21919 }); 21920 e2.data.texts.forEach((n2) => { 21921 this.replaceIds(n2, iframeEl, ["id"]); 21922 }); 21923 return e2; 21924 case IncrementalSource.Drag: 21925 case IncrementalSource.TouchMove: 21926 case IncrementalSource.MouseMove: 21927 e2.data.positions.forEach((p) => { 21928 this.replaceIds(p, iframeEl, ["id"]); 21929 }); 21930 return e2; 21931 case IncrementalSource.ViewportResize: return false; 21932 case IncrementalSource.MediaInteraction: 21933 case IncrementalSource.MouseInteraction: 21934 case IncrementalSource.Scroll: 21935 case IncrementalSource.CanvasMutation: 21936 case IncrementalSource.Input: 21937 this.replaceIds(e2.data, iframeEl, ["id"]); 21938 return e2; 21939 case IncrementalSource.StyleSheetRule: 21940 case IncrementalSource.StyleDeclaration: 21941 this.replaceIds(e2.data, iframeEl, ["id"]); 21942 this.replaceStyleIds(e2.data, iframeEl, ["styleId"]); 21943 return e2; 21944 case IncrementalSource.Font: return e2; 21945 case IncrementalSource.Selection: 21946 e2.data.ranges.forEach((range) => { 21947 this.replaceIds(range, iframeEl, ["start", "end"]); 21948 }); 21949 return e2; 21950 case IncrementalSource.AdoptedStyleSheet: 21951 this.replaceIds(e2.data, iframeEl, ["id"]); 21952 this.replaceStyleIds(e2.data, iframeEl, ["styleIds"]); 21953 e2.data.styles?.forEach((style) => { 21954 this.replaceStyleIds(style, iframeEl, ["styleId"]); 21955 }); 21956 return e2; 21957 } 21958 } 21959 return false; 21960 } 21961 replace(iframeMirror, obj, iframeEl, keys) { 21962 for (const key of keys) { 21963 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue; 21964 if (Array.isArray(obj[key])) obj[key] = iframeMirror.getIds(iframeEl, obj[key]); 21965 else obj[key] = iframeMirror.getId(iframeEl, obj[key]); 21966 } 21967 return obj; 21968 } 21969 replaceIds(obj, iframeEl, keys) { 21970 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys); 21971 } 21972 replaceStyleIds(obj, iframeEl, keys) { 21973 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys); 21974 } 21975 replaceIdOnNode(node, iframeEl) { 21976 this.replaceIds(node, iframeEl, ["id", "rootId"]); 21977 if ("childNodes" in node) node.childNodes.forEach((child) => { 21978 this.replaceIdOnNode(child, iframeEl); 21979 }); 21980 } 21981 patchRootIdOnNode(node, rootId) { 21982 if (node.type !== NodeType$1.Document && !node.rootId) node.rootId = rootId; 21983 if ("childNodes" in node) node.childNodes.forEach((child) => { 21984 this.patchRootIdOnNode(child, rootId); 21985 }); 21986 } 21987 }; 21988 ShadowDomManagerNoop = class { 21989 init() {} 21990 addShadowRoot() {} 21991 observeAttachShadow() {} 21992 reset() {} 21993 }; 21994 ShadowDomManager = class { 21995 constructor(options) { 21996 this.shadowDoms = /* @__PURE__ */ new WeakSet(); 21997 this.restoreHandlers = []; 21998 this.mutationCb = options.mutationCb; 21999 this.scrollCb = options.scrollCb; 22000 this.bypassOptions = options.bypassOptions; 22001 this.mirror = options.mirror; 22002 this.init(); 22003 } 22004 init() { 22005 this.reset(); 22006 this.patchAttachShadow(Element, document); 22007 } 22008 addShadowRoot(shadowRoot, doc) { 22009 if (!isNativeShadowDom(shadowRoot)) return; 22010 if (this.shadowDoms.has(shadowRoot)) return; 22011 this.shadowDoms.add(shadowRoot); 22012 this.bypassOptions.canvasManager.addShadowRoot(shadowRoot); 22013 const observer = initMutationObserver({ 22014 ...this.bypassOptions, 22015 doc, 22016 mutationCb: this.mutationCb, 22017 mirror: this.mirror, 22018 shadowDomManager: this 22019 }, shadowRoot); 22020 this.restoreHandlers.push(() => observer.disconnect()); 22021 this.restoreHandlers.push(initScrollObserver({ 22022 ...this.bypassOptions, 22023 scrollCb: this.scrollCb, 22024 doc: shadowRoot, 22025 mirror: this.mirror 22026 })); 22027 setTimeout$2(() => { 22028 if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0) this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host)); 22029 this.restoreHandlers.push(initAdoptedStyleSheetObserver({ 22030 mirror: this.mirror, 22031 stylesheetManager: this.bypassOptions.stylesheetManager 22032 }, shadowRoot)); 22033 }, 0); 22034 } 22035 /** 22036 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms. 22037 */ 22038 observeAttachShadow(iframeElement) { 22039 const iframeDoc = getIFrameContentDocument(iframeElement); 22040 const iframeWindow = getIFrameContentWindow(iframeElement); 22041 if (!iframeDoc || !iframeWindow) return; 22042 this.patchAttachShadow(iframeWindow.Element, iframeDoc); 22043 } 22044 /** 22045 * Patch 'attachShadow' to observe newly added shadow doms. 22046 */ 22047 patchAttachShadow(element, doc) { 22048 const manager = this; 22049 this.restoreHandlers.push(patch$1(element.prototype, "attachShadow", function(original) { 22050 return function(option) { 22051 const shadowRoot = original.call(this, option); 22052 if (this.shadowRoot && inDom(this)) manager.addShadowRoot(this.shadowRoot, doc); 22053 return shadowRoot; 22054 }; 22055 })); 22056 } 22057 reset() {
vendor: 2,374 bytes, lines 22058-22138
22058 this.restoreHandlers.forEach((handler) => { 22059 try { 22060 handler(); 22061 } catch (e2) {} 22062 }); 22063 this.restoreHandlers = []; 22064 this.shadowDoms = /* @__PURE__ */ new WeakSet(); 22065 this.bypassOptions.canvasManager.resetShadowRoots(); 22066 } 22067 }; 22068 StylesheetManager = class { 22069 constructor(options) { 22070 this.trackedLinkElements = /* @__PURE__ */ new WeakSet(); 22071 this.styleMirror = new StyleSheetMirror(); 22072 this.mutationCb = options.mutationCb; 22073 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb; 22074 } 22075 attachLinkElement(linkEl, childSn) { 22076 if ("_cssText" in childSn.attributes) this.mutationCb({ 22077 adds: [], 22078 removes: [], 22079 texts: [], 22080 attributes: [{ 22081 id: childSn.id, 22082 attributes: childSn.attributes 22083 }] 22084 }); 22085 this.trackLinkElement(linkEl); 22086 } 22087 trackLinkElement(linkEl) { 22088 if (this.trackedLinkElements.has(linkEl)) return; 22089 this.trackedLinkElements.add(linkEl); 22090 this.trackStylesheetInLinkElement(linkEl); 22091 } 22092 adoptStyleSheets(sheets, hostId) { 22093 if (sheets.length === 0) return; 22094 const adoptedStyleSheetData = { 22095 id: hostId, 22096 styleIds: [] 22097 }; 22098 const styles = []; 22099 for (const sheet of sheets) { 22100 let styleId; 22101 if (!this.styleMirror.has(sheet)) { 22102 styleId = this.styleMirror.add(sheet); 22103 styles.push({ 22104 styleId, 22105 rules: Array.from(sheet.rules || CSSRule, (r2, index) => ({ 22106 rule: stringifyRule(r2), 22107 index 22108 })) 22109 }); 22110 } else styleId = this.styleMirror.getId(sheet); 22111 adoptedStyleSheetData.styleIds.push(styleId); 22112 } 22113 if (styles.length > 0) adoptedStyleSheetData.styles = styles; 22114 this.adoptedStyleSheetCb(adoptedStyleSheetData); 22115 } 22116 reset() { 22117 this.styleMirror.reset(); 22118 this.trackedLinkElements = /* @__PURE__ */ new WeakSet(); 22119 } 22120 trackStylesheetInLinkElement(_linkEl) {} 22121 }; 22122 ProcessedNodeManager = class { 22123 constructor() { 22124 this.nodeMap = /* @__PURE__ */ new WeakMap(); 22125 this.active = false; 22126 } 22127 inOtherBuffer(node, thisBuffer) { 22128 const buffers = this.nodeMap.get(node); 22129 return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer); 22130 } 22131 add(node, buffer) { 22132 if (!this.active) { 22133 this.active = true; 22134 onRequestAnimationFrame$1(() => { 22135 this.nodeMap = /* @__PURE__ */ new WeakMap(); 22136 this.active = false; 22137 }); 22138 }
22139 this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer)); 22140 } 22141 destroy() {} 22142 }; 22143 try { 22144 if (Array.from([1], (x) => x * 2)[0] !== 2) { 22145 const cleanFrame = document.createElement("iframe"); 22146 document.body.appendChild(cleanFrame); 22147 Array.from = cleanFrame.contentWindow?.Array.from || Array.from; 22148 document.body.removeChild(cleanFrame); 22149 } 22150 } catch (err) { 22151 console.debug("Unable to override Array.from", err); 22152 } 22153 mirror = createMirror$1(); 22154 record.mirror = mirror; 22155 record.takeFullSnapshot = takeFullSnapshot; 22156 (function(t2) { 22157 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped"; 22158 })(n$1 || (n$1 = {})); 22159 ReplayEventTypeIncrementalSnapshot = 3; 22160 ReplayEventTypeCustom = 5; 22161 INTERACTIVE_SELECTOR = "button,a"; 22162 IncrementalMutationSources = /* @__PURE__ */ new Set([ 22163 IncrementalSource.Mutation, 22164 IncrementalSource.StyleSheetRule, 22165 IncrementalSource.StyleDeclaration, 22166 IncrementalSource.AdoptedStyleSheet, 22167 IncrementalSource.CanvasMutation, 22168 IncrementalSource.Selection, 22169 IncrementalSource.MediaInteraction 22170 ]); 22171 ClickDetector = class { 22172 constructor(replay, slowClickConfig, _addBreadcrumbEvent = addBreadcrumbEvent) { 22173 this._lastMutation = 0; 22174 this._lastScroll = 0; 22175 this._clicks = []; 22176 this._timeout = slowClickConfig.timeout / 1e3; 22177 this._threshold = slowClickConfig.threshold / 1e3; 22178 this._scrollTimeout = slowClickConfig.scrollTimeout / 1e3; 22179 this._replay = replay; 22180 this._ignoreSelector = slowClickConfig.ignoreSelector; 22181 this._addBreadcrumbEvent = _addBreadcrumbEvent; 22182 } 22183 /** Register click detection handlers on mutation or scroll. */ 22184 addListeners() { 22185 const cleanupWindowOpen = onWindowOpen(() => { 22186 this._lastMutation = nowInSeconds(); 22187 }); 22188 this._teardown = () => { 22189 cleanupWindowOpen(); 22190 this._clicks = []; 22191 this._lastMutation = 0; 22192 this._lastScroll = 0; 22193 }; 22194 } 22195 /** Clean up listeners. */ 22196 removeListeners() { 22197 if (this._teardown) this._teardown(); 22198 if (this._checkClickTimeout) clearTimeout(this._checkClickTimeout); 22199 } 22200 /** @inheritDoc */ 22201 handleClick(breadcrumb, node) { 22202 if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) return; 22203 const newClick = { 22204 timestamp: timestampToS(breadcrumb.timestamp), 22205 clickBreadcrumb: breadcrumb, 22206 clickCount: 0, 22207 node 22208 }; 22209 if (this._clicks.some((click) => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)) return; 22210 this._clicks.push(newClick); 22211 if (this._clicks.length === 1) this._scheduleCheckClicks(); 22212 } 22213 /** @inheritDoc */ 22214 registerMutation(timestamp = Date.now()) { 22215 this._lastMutation = timestampToS(timestamp); 22216 } 22217 /** @inheritDoc */ 22218 registerScroll(timestamp = Date.now()) { 22219 this._lastScroll = timestampToS(timestamp); 22220 } 22221 /** @inheritDoc */ 22222 registerClick(element) { 22223 const node = getClosestInteractive(element); 22224 this._handleMultiClick(node); 22225 } 22226 /** Count multiple clicks on elements. */ 22227 _handleMultiClick(node) { 22228 this._getClicks(node).forEach((click) => { 22229 click.clickCount++; 22230 }); 22231 } 22232 /** Get all pending clicks for a given node. */ 22233 _getClicks(node) { 22234 return this._clicks.filter((click) => click.node === node); 22235 } 22236 /** Check the clicks that happened. */ 22237 _checkClicks() { 22238 const timedOutClicks = []; 22239 const now = nowInSeconds(); 22240 this._clicks.forEach((click) => { 22241 if (!click.mutationAfter && this._lastMutation) click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : void 0; 22242 if (!click.scrollAfter && this._lastScroll) click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : void 0; 22243 if (click.timestamp + this._timeout <= now) timedOutClicks.push(click); 22244 }); 22245 for (const click of timedOutClicks) { 22246 const pos = this._clicks.indexOf(click); 22247 if (pos > -1) { 22248 this._generateBreadcrumbs(click); 22249 this._clicks.splice(pos, 1); 22250 } 22251 } 22252 if (this._clicks.length) this._scheduleCheckClicks(); 22253 } 22254 /** Generate matching breadcrumb(s) for the click. */ 22255 _generateBreadcrumbs(click) { 22256 const replay = this._replay; 22257 const hadScroll = click.scrollAfter && click.scrollAfter <= this._scrollTimeout; 22258 const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold; 22259 const isSlowClick = !hadScroll && !hadMutation; 22260 const { clickCount, clickBreadcrumb }
22260 = click; 22261 if (isSlowClick) { 22262 const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1e3; 22263 const endReason = timeAfterClickMs < this._timeout * 1e3 ? "mutation" : "timeout"; 22264 const breadcrumb = { 22265 type: "default", 22266 message: clickBreadcrumb.message, 22267 timestamp: clickBreadcrumb.timestamp, 22268 category: "ui.slowClickDetected", 22269 data: { 22270 ...clickBreadcrumb.data, 22271 url: WINDOW.location.href, 22272 route: replay.getCurrentRoute(), 22273 timeAfterClickMs, 22274 endReason, 22275 clickCount: clickCount || 1 22276 } 22277 }; 22278 this._addBreadcrumbEvent(replay, breadcrumb); 22279 return; 22280 } 22281 if (clickCount > 1) { 22282 const breadcrumb = { 22283 type: "default", 22284 message: clickBreadcrumb.message, 22285 timestamp: clickBreadcrumb.timestamp, 22286 category: "ui.multiClick", 22287 data: { 22288 ...clickBreadcrumb.data, 22289 url: WINDOW.location.href, 22290 route: replay.getCurrentRoute(), 22291 clickCount, 22292 metric: true 22293 } 22294 }; 22295 this._addBreadcrumbEvent(replay, breadcrumb); 22296 } 22297 } 22298 /** Schedule to check current clicks. */ 22299 _scheduleCheckClicks() { 22300 if (this._checkClickTimeout) clearTimeout(this._checkClickTimeout); 22301 this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1e3); 22302 } 22303 }; 22304 SLOW_CLICK_TAGS = [ 22305 "A", 22306 "BUTTON", 22307 "INPUT" 22308 ]; 22309 NodeType = /* @__PURE__ */ ((NodeType2) => { 22310 NodeType2[NodeType2["Document"] = 0] = "Document"; 22311 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType"; 22312 NodeType2[NodeType2["Element"] = 2] = "Element"; 22313 NodeType2[NodeType2["Text"] = 3] = "Text"; 22314 NodeType2[NodeType2["CDATA"] = 4] = "CDATA"; 22315 NodeType2[NodeType2["Comment"] = 5] = "Comment"; 22316 return NodeType2; 22317 })(NodeType || {}); 22318 ATTRIBUTES_TO_RECORD = /* @__PURE__ */ new Set([ 22319 "id", 22320 "class", 22321 "aria-label", 22322 "role", 22323 "name", 22324 "alt", 22325 "title", 22326 "data-test-id", 22327 "data-testid", 22328 "disabled", 22329 "aria-disabled", 22330 "data-sentry-component" 22331 ]); 22332 handleDomListener = (replay) => { 22333 return (handlerData) => { 22334 if (!replay.isEnabled()) return; 22335 const result = handleDom(handlerData); 22336 if (!result) return; 22337 const isClick = handlerData.name === "click"; 22338 const event = isClick ? handlerData.event : void 0; 22339 if (isClick && replay.clickDetector && event?.target && !event.altKey && !event.metaKey && !event.ctrlKey && !event.shiftKey) handleClick(replay.clickDetector, result, getClickTargetNode(handlerData.event)); 22340 addBreadcrumbEvent(replay, result); 22341 }; 22342 }; 22343 ENTRY_TYPES = { 22344 resource: createResourceEntry, 22345 paint: createPaintEntry, 22346 navigation: createNavigationEntry 22347 }; 22348 DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 22349 t$1
vendor: 10,336 bytes, line 22349
22349 = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=e+=1<<t[s-1];var a=new r(i[30]);for(s=1;s<30;++s)for(var o=i[s];o<i[s+1];++o)a[o]=o-i[s]<<5|s;return{b:i,r:a}},o=a(e,2),h=o.b,f=o.r;h[28]=258,f[258]=28;for(var l=a(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,s=0,a=new n(r);s<i;++s)t[s]&&++a[t[s]-1];var o,h=new n(r);for(s=1;s<r;++s)h[s]=h[s-1]+a[s-1]<<1;if(e){o=new n(1<<r);var f=15-r;for(s=0;s<i;++s)if(t[s])for(var l=s<<4|t[s],c=r-t[s],v=h[t[s]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>f]=l}else for(o=new n(i),s=0;s<i;++s)t[s]&&(o[s]=u[h[t[s]-1]++]>>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],s=0;s<r.length;++s)r[s]&&i.push({s:s,f:r[s]});var a=i.length,o=i.slice();if(!a)return{t:F,l:0};if(1==a){var h=new t(i[0].s+1);return h[i[0].s]=1,{t:h,l:1}}i.sort(function(t,n){return t.f-n.f}),i.push({s:-1,f:25001});var f=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:f.f+l.f,l:f,r:l};c!=a-1;)f=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:f.f+l.f,l:f,r:l};var d=o[0].s;for(s=1;s<a;++s)o[s].s>d&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<<y;for(o.sort(function(t,n){return p[n.s]-p[t.s]||t.f-n.f});s<a;++s){var b=o[s].s;if(!(p[b]>e))break;w+=m-(1<<g-p[b]),p[b]=e}for(w>>=y;w>0;){var M=o[s].s;p[M]<e?w-=1<<e-p[M]++-1:++s}for(;s>=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;s<e;++s)t[i+s+4]=r[s];return 8*(i+4+e)},U=function(t,r,a,o,h,f,l,u,c,v,m){z(r,m++,a),++h[256];for(var b=x(h,15),M=b.t,E=b.l,A=x(f,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[s[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=w,P=p,Q=y,R=g;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)i+=e+=r[a];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(s[t]^s[t+1]<<A^s[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(s[j+Q]==s[j+Q-W]){for(var $=0;$<Z&&s[j+$]==s[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=s[j],++I[s[j]];w=U(s,p,g,F,I,S,O,q,G,j-G,w),g||(c.r=7&w|p[w/8|0]<<3,w-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+g;j+=65535){var at=j+65535;at>=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(s),32768),this.s.z=n.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,s=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),a=s.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(s,n),O(s,a-8,r.d()),O(s,a-4,e),s}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){j.prototype.flush.call(this)},t}(),G="undefined"!=typeof TextEncoder&&new TextEncoder,H="undefined"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(G)return G.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;o<e;++o){if(s+5>i.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new B,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new J((t,n)=>{this.deflate.push(t,n)}),this.stream.push("[")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener("message",function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&"function"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}}),postMessage({id:void 0,method:"init",success:!0,response:void 0});`;
22350 CONSOLE_LEVELS = [ 22351 "log", 22352 "warn", 22353 "error" 22354 ]; 22355 PREFIX = "[Replay] "; 22356 debug = makeReplayDebugLogger();
22357 EventBufferSizeExceededError = class extends Error { 22358 constructor() { 22359 super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`); 22360 } 22361 }; 22362 WorkerDestroyedError = class extends Error { 22363 constructor() { 22364 super("Worker destroyed"); 22365 } 22366 }; 22367 EventBufferArray = class { 22368 constructor() { 22369 this.events = []; 22370 this._totalSize = 0; 22371 this.hasCheckout = false; 22372 this.waitForCheckout = false; 22373 } 22374 /** @inheritdoc */ 22375 get hasEvents() { 22376 return this.events.length > 0; 22377 } 22378 /** @inheritdoc */ 22379 get type() { 22380 return "sync"; 22381 } 22382 /** @inheritdoc */ 22383 destroy() { 22384 this.events = []; 22385 } 22386 /** @inheritdoc */ 22387 async addEvent(event) { 22388 const eventSize = JSON.stringify(event).length; 22389 this._totalSize += eventSize; 22390 if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) throw new EventBufferSizeExceededError(); 22391 this.events.push(event); 22392 } 22393 /** @inheritdoc */ 22394 finish() { 22395 return new Promise((resolve) => { 22396 const eventsRet = this.events; 22397 this.clear(); 22398 resolve(JSON.stringify(eventsRet)); 22399 }); 22400 } 22401 /** @inheritdoc */ 22402 clear() { 22403 this.events = []; 22404 this._totalSize = 0; 22405 this.hasCheckout = false; 22406 } 22407 /** @inheritdoc */ 22408 getEarliestTimestamp() { 22409 let ts = null; 22410 for (const { timestamp } of this.events) if (ts === null || timestamp < ts) ts = timestamp; 22411 return ts === null ? ts : timestampToMs(ts); 22412 } 22413 }; 22414 WorkerHandler = class { 22415 constructor(worker) { 22416 this._onMessage = ({ data }) => { 22417 const response = data; 22418 if (typeof response.id !== "number") return; 22419 const pending = this._pending.get(response.id); 22420 if (!pending || pending.method !== response.method) return; 22421 this._pending.delete(response.id); 22422 if (!response.success) { 22423 DEBUG_BUILD$1 && debug.error("Error in compression worker: ", response.response); 22424 pending.reject(/* @__PURE__ */ new Error("Error in compression worker")); 22425 return; 22426 } 22427 pending.resolve(response.response); 22428 }; 22429 this._worker = worker; 22430 this._id = 0; 22431 this._pending = /* @__PURE__ */ new Map(); 22432 this._worker.addEventListener("message", this._onMessage); 22433 } 22434 /** 22435 * Ensure the worker is ready (or not). 22436 * This will either resolve when the worker is ready, or reject if an error occurred. 22437 */ 22438 ensureReady() { 22439 if (this._ensureReadyPromise) return this._ensureReadyPromise; 22440 this._ensureReadyPromise = new Promise((resolve, reject) => { 22441 this._worker.addEventListener("message", ({ data }) => { 22442 if (data.success) resolve(); 22443 else { 22444 DEBUG_BUILD$1 && debug.warn("Received worker message with unsuccessful status", data); 22445 reject(/* @__PURE__ */ new Error("Received worker message with unsuccessful status")); 22446 } 22447 }, { once: true }); 22448 this._worker.addEventListener("error", (error) => { 22449 DEBUG_BUILD$1 && debug.warn("Failed to load Replay compression worker", error); 22450 reject(/* @__PURE__ */ new Error(`Failed to load Replay compression worker: ${error instanceof ErrorEvent && error.message ? error.message : "Unknown error. This can happen due to CSP policy restrictions, network issues, or the worker script failing to load."}`)); 22451 }, { once: true }); 22452 }); 22453 return this._ensureReadyPromise; 22454 } 22455 /** 22456 * Destroy the worker. 22457 */ 22458 destroy() { 22459 DEBUG_BUILD$1 && debug.log("Destroying compression worker"); 22460 this._worker.removeEventListener("message", this._onMessage); 22461 this._pending.forEach((pending) => pending.reject(new WorkerDestroyedError())); 22462 this._pending.clear(); 22463 this._worker.terminate(); 22464 } 22465 /** 22466 * Post message to worker and wait for response before resolving promise. 22467 */ 22468 postMessage(method, arg) { 22469 const id = this._getAndIncrementId(); 22470 return new Promise((resolve, reject) => { 22471 this._pending.set(id, { 22472 method, 22473 resolve, 22474 reject 22475 }); 22476 try { 22477 this._worker.postMessage({ 22478 id, 22479 method, 22480 arg 22481 }); 22482 } catch (error) { 22483 this._pending.delete(id); 22484 reject(error); 22485 } 22486 }); 22487 } 22488 /** Get the current ID and increment it for the next call. */ 22489 _getAndIncrementId() { 22490 return this._id++; 22491 } 22492 }; 22493 EventBufferCompressionWorker = class { 22494 constructor(worker) { 22495 this._worker = new WorkerHandler(worker); 22496 this._earliestTimestamp = null; 22497 this._totalSize = 0; 22498 this.hasCheckout = false;
22499 this.waitForCheckout = false; 22500 } 22501 /** @inheritdoc */ 22502 get hasEvents() { 22503 return !!this._earliestTimestamp; 22504 } 22505 /** @inheritdoc */ 22506 get type() { 22507 return "worker"; 22508 } 22509 /** 22510 * Ensure the worker is ready (or not). 22511 * This will either resolve when the worker is ready, or reject if an error occurred. 22512 */ 22513 ensureReady() { 22514 return this._worker.ensureReady(); 22515 } 22516 /** 22517 * Destroy the event buffer. 22518 */ 22519 destroy() { 22520 this._worker.destroy(); 22521 } 22522 /** 22523 * Add an event to the event buffer. 22524 * 22525 * Returns true if event was successfully received and processed by worker. 22526 */ 22527 addEvent(event) { 22528 const timestamp = timestampToMs(event.timestamp); 22529 if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) this._earliestTimestamp = timestamp; 22530 const data = JSON.stringify(event); 22531 this._totalSize += data.length; 22532 if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) return Promise.reject(new EventBufferSizeExceededError()); 22533 return this._sendEventToWorker(data); 22534 } 22535 /** 22536 * Finish the event buffer and return the compressed data. 22537 */ 22538 finish() { 22539 return this._finishRequest(); 22540 } 22541 /** @inheritdoc */ 22542 clear() { 22543 this._earliestTimestamp = null; 22544 this._totalSize = 0; 22545 this.hasCheckout = false; 22546 this._worker.postMessage("clear").then(null, (e) => { 22547 DEBUG_BUILD$1 && debug.exception(e, "Sending \"clear\" message to worker failed", e); 22548 }); 22549 } 22550 /** @inheritdoc */ 22551 getEarliestTimestamp() { 22552 return this._earliestTimestamp; 22553 } 22554 /** 22555 * Send the event to the worker. 22556 */ 22557 _sendEventToWorker(data) { 22558 return this._worker.postMessage("addEvent", data); 22559 } 22560 /** 22561 * Finish the request and return the compressed data from the worker. 22562 */ 22563 async _finishRequest() { 22564 const response = await this._worker.postMessage("finish"); 22565 this._earliestTimestamp = null; 22566 this._totalSize = 0; 22567 return response; 22568 } 22569 }; 22570 EventBufferProxy = class { 22571 constructor(worker) { 22572 this._fallback = new EventBufferArray(); 22573 this._compression = new EventBufferCompressionWorker(worker); 22574 this._used = this._fallback; 22575 this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded(); 22576 } 22577 /** @inheritdoc */ 22578 get waitForCheckout() { 22579 return this._used.waitForCheckout; 22580 } 22581 /** @inheritdoc */ 22582 get type() { 22583 return this._used.type; 22584 } 22585 /** @inheritDoc */ 22586 get hasEvents() { 22587 return this._used.hasEvents; 22588 } 22589 /** @inheritdoc */ 22590 get hasCheckout() { 22591 return this._used.hasCheckout; 22592 } 22593 /** @inheritdoc */ 22594 set hasCheckout(value) { 22595 this._used.hasCheckout = value; 22596 } 22597 /** @inheritdoc */ 22598 set waitForCheckout(value) { 22599 this._used.waitForCheckout = value; 22600 } 22601 /** @inheritDoc */ 22602 destroy() { 22603 this._fallback.destroy(); 22604 this._compression.destroy(); 22605 } 22606 /** @inheritdoc */ 22607 clear() { 22608 return this._used.clear(); 22609 } 22610 /** @inheritdoc */ 22611 getEarliestTimestamp() { 22612 return this._used.getEarliestTimestamp(); 22613 } 22614 /** 22615 * Add an event to the event buffer. 22616 * 22617 * Returns true if event was successfully added.
22618 */ 22619 addEvent(event) { 22620 return this._used.addEvent(event); 22621 } 22622 /** @inheritDoc */ 22623 async finish() { 22624 await this.ensureWorkerIsLoaded(); 22625 return this._used.finish(); 22626 } 22627 /** Ensure the worker has loaded. */ 22628 ensureWorkerIsLoaded() { 22629 return this._ensureWorkerIsLoadedPromise; 22630 } 22631 /** Actually check if the worker has been loaded. */ 22632 async _ensureWorkerIsLoaded() { 22633 try { 22634 await this._compression.ensureReady(); 22635 } catch (error) { 22636 DEBUG_BUILD$1 && debug.exception(error, "Failed to load the compression worker, falling back to simple buffer"); 22637 return; 22638 } 22639 await this._switchToCompressionWorker(); 22640 } 22641 /** Switch the used buffer to the compression worker. */ 22642 async _switchToCompressionWorker() { 22643 const { events, hasCheckout, waitForCheckout } = this._fallback; 22644 const addEventPromises = []; 22645 for (const event of events) addEventPromises.push(this._compression.addEvent(event)); 22646 this._compression.hasCheckout = hasCheckout; 22647 this._compression.waitForCheckout = waitForCheckout; 22648 this._used = this._compression; 22649 try { 22650 await Promise.all(addEventPromises); 22651 this._fallback.clear(); 22652 } catch (error) { 22653 if (error instanceof WorkerDestroyedError) return; 22654 DEBUG_BUILD$1 && debug.exception(error, "Failed to add events when switching buffers."); 22655 } 22656 } 22657 }; 22658 MAX_CONTEXT_VALUES = 100; 22659 NAVIGATOR = GLOBAL_OBJ.navigator; 22660 TransportStatusCodeError = class extends Error { 22661 constructor(statusCode) { 22662 super(`Transport returned status code ${statusCode}`); 22663 } 22664 }; 22665 RateLimitError = class extends Error { 22666 constructor(rateLimits) { 22667 super("Rate limit hit"); 22668 this.rateLimits = rateLimits; 22669 } 22670 }; 22671 ReplayDurationLimitError = class extends Error { 22672 constructor() { 22673 super("Session is too long, not sending replay"); 22674 } 22675 }; 22676 THROTTLED = "__THROTTLED"; 22677 SKIPPED = "__SKIPPED"; 22678 ReplayContainer = class { 22679 constructor({ options, recordingOptions }) { 22680 this.eventBuffer = null; 22681 this.performanceEntries = []; 22682 this.replayPerformanceEntries = []; 22683 this.recordingMode = "session"; 22684 this.timeouts = { 22685 sessionIdlePause: SESSION_IDLE_PAUSE_DURATION, 22686 sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION 22687 }; 22688 this._lastActivity = Date.now(); 22689 this._isEnabled = false; 22690 this._isPaused = false; 22691 this._requiresManualStart = false;
22692 this._hasInitializedCoreListeners = false; 22693 this._context = { 22694 errorIds: /* @__PURE__ */ new Set(), 22695 traceIds: /* @__PURE__ */ new Set(), 22696 segmentNames: /* @__PURE__ */ new Set(), 22697 urls: [], 22698 initialTimestamp: Date.now(), 22699 initialUrl: "" 22700 }; 22701 this._recordingOptions = recordingOptions; 22702 this._options = options; 22703 this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, { maxWait: this._options.flushMaxDelay }); 22704 this._throttledAddEvent = throttle((event, isCheckout) => addEvent(this, event, isCheckout), 300, 5); 22705 const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions(); 22706 const slowClickConfig = slowClickTimeout ? { 22707 threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout), 22708 timeout: slowClickTimeout, 22709 scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT, 22710 ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(",") : "" 22711 } : void 0; 22712 if (slowClickConfig) this.clickDetector = new ClickDetector(this, slowClickConfig); 22713 if (DEBUG_BUILD$1) { 22714 const experiments = options._experiments; 22715 debug.setConfig({ 22716 captureExceptions: !!experiments.captureExceptions, 22717 traceInternals: !!experiments.traceInternals 22718 }); 22719 } 22720 this._handleVisibilityChange = () => { 22721 if (WINDOW.document.visibilityState === "visible") this._doChangeToForegroundTasks(); 22722 else this._doChangeToBackgroundTasks(); 22723 }; 22724 this._handleWindowBlur = () => { 22725 const breadcrumb = createBreadcrumb({ category: "ui.blur" }); 22726 this._doChangeToBackgroundTasks(breadcrumb); 22727 }; 22728 this._handleWindowFocus = () => { 22729 const breadcrumb = createBreadcrumb({ category: "ui.focus" }); 22730 this._doChangeToForegroundTasks(breadcrumb); 22731 }; 22732 this._handleKeyboardEvent = (event) => { 22733 handleKeyboardEvent(this, event); 22734 }; 22735 } 22736 /** Get the event context. */ 22737 getContext() { 22738 return this._context; 22739 } 22740 /** If recording is currently enabled. */ 22741 isEnabled() { 22742 return this._isEnabled; 22743 } 22744 /** If recording is currently paused. */ 22745 isPaused() { 22746 return this._isPaused; 22747 } 22748 /** 22749 * Determine if canvas recording is enabled 22750 */ 22751 isRecordingCanvas() { 22752 return Boolean(this._canvas); 22753 } 22754 /** Get the replay integration options. */ 22755 getOptions() { 22756 return this._options; 22757 } 22758 /** A wrapper to conditionally capture exceptions. */ 22759 handleException(error) { 22760 DEBUG_BUILD$1 && debug.exception(error); 22761 if (this._options.onError) this._options.onError(error); 22762 } 22763 /** 22764 * Initializes the plugin based on sampling configuration. Should not be 22765 * called outside of constructor. 22766 */ 22767 initializeSampling(previousSessionId) { 22768 const { errorSampleRate, sessionSampleRate } = this._options; 22769 const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0; 22770 this._requiresManualStart = requiresManualStart; 22771 if (requiresManualStart) return; 22772 this._initializeSessionForSampling(previousSessionId); 22773 if (!this.session) { 22774 DEBUG_BUILD$1 && debug.exception(/* @__PURE__ */ new Error("Unable to initialize and create session")); 22775 return; 22776 } 22777 if (this.session.sampled === false) return; 22778 this.recordingMode = this.session.sampled === "buffer" && this.session.segmentId === 0 ? "buffer" : "session"; 22779 DEBUG_BUILD$1 && debug.infoTick(`Starting replay in ${this.recordingMode} mode`); 22780 this._initializeRecording(); 22781 } 22782 /** 22783 * Start a replay regardless of sampling rate. Calling this will always 22784 * create a new session. Will log a message if replay is already in progress. 22785 * 22786 * Creates or loads a session, attaches listeners to varying events (DOM, 22787 * _performanceObserver, Recording, Sentry SDK, etc) 22788 */ 22789 start() { 22790 if (this._isEnabled && this.recordingMode === "session") { 22791 DEBUG_BUILD$1 && debug.log("Recording is already in progress"); 22792 return; 22793 } 22794 if (this._isEnabled && this.recordingMode === "buffer") { 22795 DEBUG_BUILD$1 && debug.log("Buffering is in progress, call `flush()` to save the replay"); 22796 return; 22797 } 22798 DEBUG_BUILD$1 && debug.infoTick("Starting replay in session mode"); 22799 this._updateUserActivity(); 22800 const session = loadOrCreateSession({ 22801 maxReplayDuration: this._options.maxReplayDuration, 22802 sessionIdleExpire: this.timeouts.sessionIdleExpire 22803 }, { 22804 stickySession: this._options.stickySession, 22805 sessionSampleRate: 1, 22806 allowBuffering: false 22807 }); 22808 this.session = session; 22809 this.recordingMode = "session"; 22810 this._initializeRecording(); 22811 } 22812 /** 22813 * Start replay buffering. Buffers until `flush()` is called or, if 22814 * `replaysOnErrorSampleRate` > 0, an error occurs. 22815 */
22816 startBuffering() { 22817 if (this._isEnabled) { 22818 DEBUG_BUILD$1 && debug.log("Buffering is in progress, call `flush()` to save the replay"); 22819 return; 22820 } 22821 DEBUG_BUILD$1 && debug.infoTick("Starting replay in buffer mode"); 22822 const session = loadOrCreateSession({ 22823 sessionIdleExpire: this.timeouts.sessionIdleExpire, 22824 maxReplayDuration: this._options.maxReplayDuration 22825 }, { 22826 stickySession: this._options.stickySession, 22827 sessionSampleRate: 0, 22828 allowBuffering: true 22829 }); 22830 this.session = session; 22831 this.recordingMode = "buffer"; 22832 this._initializeRecording(); 22833 } 22834 /** 22835 * Start recording. 22836 * 22837 * Note that this will cause a new DOM checkout 22838 */ 22839 startRecording() { 22840 try { 22841 const canvasOptions = this._canvas; 22842 this._stopRecording = record({ 22843 ...this._recordingOptions, 22844 ...this.recordingMode === "buffer" ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME } : this._options._experiments.continuousCheckout && { checkoutEveryNms: Math.max(36e4, this._options._experiments.continuousCheckout) }, 22845 emit: getHandleRecordingEmit(this), 22846 ...getRecordingSamplingOptions(), 22847 onMutation: this._onMutationHandler.bind(this), 22848 ...canvasOptions ? { 22849 recordCanvas: canvasOptions.recordCanvas, 22850 getCanvasManager: canvasOptions.getCanvasManager, 22851 sampling: canvasOptions.sampling, 22852 dataURLOptions: canvasOptions.dataURLOptions 22853 } : {} 22854 }); 22855 } catch (err) { 22856 this.handleException(err); 22857 } 22858 } 22859 /** 22860 * Stops the recording, if it was running. 22861 * 22862 * Returns true if it was previously stopped, or is now stopped, 22863 * otherwise false. 22864 */ 22865 stopRecording() { 22866 try { 22867 if (this._stopRecording) { 22868 this._stopRecording(); 22869 this._stopRecording = void 0; 22870 } 22871 return true; 22872 } catch (err) { 22873 this.handleException(err); 22874 return false; 22875 } 22876 } 22877 /** 22878 * Currently, this needs to be manually called (e.g. for tests). Sentry SDK 22879 * does not support a teardown 22880 */ 22881 async stop({ forceFlush = false, reason } = {}) { 22882 if (!this._isEnabled) return; 22883 this._isEnabled = false; 22884 this.recordingMode = "buffer"; 22885 const stopReason = reason ?? "manual"; 22886 getClient()?.emit("replayEnd", { 22887 sessionId: this.session?.id, 22888 reason: stopReason 22889 }); 22890 try { 22891 DEBUG_BUILD$1 && debug.log(`Stopping Replay triggered by ${stopReason}`); 22892 resetReplayIdOnDynamicSamplingContext(); 22893 this._removeListeners(); 22894 this.stopRecording(); 22895 this._debouncedFlush.cancel(); 22896 if (forceFlush) await this._flush({ force: true }); 22897 this.eventBuffer?.destroy(); 22898 this.eventBuffer = null; 22899 clearSession(this); 22900 } catch (err) { 22901 this.handleException(err); 22902 } 22903 } 22904 /** 22905 * Pause some replay functionality. See comments for `_isPaused`. 22906 * This differs from stop as this only stops DOM recording, it is 22907 * not as thorough of a shutdown as `stop()`. 22908 */ 22909 pause() { 22910 if (this._isPaused) return; 22911 this._isPaused = true; 22912 this.stopRecording(); 22913 DEBUG_BUILD$1 && debug.log("Pausing replay"); 22914 } 22915 /** 22916 * Resumes recording, see notes for `pause(). 22917 * 22918 * Note that calling `startRecording()` here will cause a 22919 * new DOM checkout.` 22920 */ 22921 resume() { 22922 if (!this._isPaused || !this._checkSession()) return; 22923 this._isPaused = false; 22924 this.startRecording(); 22925 DEBUG_BUILD$1 && debug.log("Resuming replay"); 22926 } 22927 /** 22928 * If not in "session" recording mode, flush event buffer which will create a new replay. 22929 * Unless `continueRecording` is false, the replay will continue to record and 22930 * behave as a "session"-based replay. 22931 * 22932 * Otherwise, queue up a flush. 22933 */ 22934 async sendBufferedReplayOrFlush({ continueRecording = true } = {}) { 22935 if (this.recordingMode === "session") return this.flushImmediate(); 22936 const activityTime = Date.now(); 22937 DEBUG_BUILD$1 && debug.log("Converting buffer to session"); 22938 await this.flushImmediate(); 22939 const hasStoppedRecording = this.stopRecording(); 22940 if (!continueRecording || !hasStoppedRecording) return; 22941 if (this.recordingMode === "session") return; 22942 this.recordingMode = "session"; 22943 if (this.session) { 22944 this.session.dirty = false;
22945 this._updateUserActivity(activityTime); 22946 this._updateSessionActivity(activityTime); 22947 this._maybeSaveSession(); 22948 setReplayIdOnDynamicSamplingContext(this.session.id); 22949 } 22950 this.startRecording(); 22951 } 22952 /** 22953 * We want to batch uploads of replay events. Save events only if 22954 * `<flushMinDelay>` milliseconds have elapsed since the last event 22955 * *OR* if `<flushMaxDelay>` milliseconds have elapsed. 22956 * 22957 * Accepts a callback to perform side-effects and returns true to stop batch 22958 * processing and hand back control to caller. 22959 */ 22960 addUpdate(cb) { 22961 const cbResult = cb(); 22962 if (this.recordingMode === "buffer" || !this._isEnabled) return; 22963 if (cbResult === true) return; 22964 this._debouncedFlush(); 22965 } 22966 /** 22967 * Updates the user activity timestamp and resumes recording. This should be 22968 * called in an event handler for a user action that we consider as the user 22969 * being "active" (e.g. a mouse click). 22970 */ 22971 triggerUserActivity() { 22972 this._updateUserActivity(); 22973 if (!this._stopRecording) { 22974 if (!this._checkSession()) return; 22975 this.resume(); 22976 return; 22977 } 22978 this.checkAndHandleExpiredSession(); 22979 this._updateSessionActivity(); 22980 } 22981 /** 22982 * Updates the user activity timestamp *without* resuming 22983 * recording. Some user events (e.g. keydown) can be create 22984 * low-value replays that only contain the keypress as a 22985 * breadcrumb. Instead this would require other events to 22986 * create a new replay after a session has expired. 22987 */ 22988 updateUserActivity() { 22989 this._updateUserActivity(); 22990 this._updateSessionActivity(); 22991 } 22992 /** 22993 * Only flush if `this.recordingMode === 'session'` 22994 */ 22995 conditionalFlush() { 22996 if (this.recordingMode === "buffer") return Promise.resolve(); 22997 return this.flushImmediate(); 22998 } 22999 /** 23000 * Flush using debounce flush 23001 */ 23002 flush() { 23003 return this._debouncedFlush(); 23004 } 23005 /** 23006 * Always flush via `_debouncedFlush` so that we do not have flushes triggered 23007 * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be 23008 * cases of multiple flushes happening closely together. 23009 */ 23010 flushImmediate() { 23011 this._debouncedFlush(); 23012 return this._debouncedFlush.flush(); 23013 } 23014 /** 23015 * Cancels queued up flushes. 23016 */ 23017 cancelFlush() { 23018 this._debouncedFlush.cancel(); 23019 } 23020 /** Get the current session (=replay) ID 23021 * 23022 * @param onlyIfSampled - If true, will only return the session ID if the session is sampled. 23023 */ 23024 getSessionId(onlyIfSampled) { 23025 if (onlyIfSampled && this.session?.sampled === false) return; 23026 return this.session?.id; 23027 } 23028 /** 23029 * Checks if recording should be stopped due to user inactivity. Otherwise 23030 * check if session is expired and create a new session if so. Triggers a new 23031 * full snapshot on new session. 23032 * 23033 * Returns true if session is not expired, false otherwise. 23034 * @hidden 23035 */ 23036 checkAndHandleExpiredSession() { 23037 if (this._lastActivity && isExpired(this._lastActivity, this.timeouts.sessionIdlePause) && this.session?.sampled === "session") { 23038 this.pause(); 23039 return; 23040 } 23041 if (!this._checkSession()) return false; 23042 return true; 23043 } 23044 /** 23045 * Capture some initial state that can change throughout the lifespan of the 23046 * replay. This is required because otherwise they would be captured at the 23047 * first flush. 23048 */ 23049 setInitialState() { 23050 const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`; 23051 const url = `${WINDOW.location.origin}${urlPath}`; 23052 this.performanceEntries = []; 23053 this.replayPerformanceEntries = []; 23054 this._clearContext(); 23055 this._context.initialUrl = url; 23056 this._context.initialTimestamp = Date.now(); 23057 this._context.urls.push(url); 23058 } 23059 /** 23060 * Add a breadcrumb event, that may be throttled. 23061 * If it was throttled, we add a custom breadcrumb to indicate that. 23062 */ 23063 throttledAddEvent(event, isCheckout) { 23064 const res = this._throttledAddEvent(event, isCheckout); 23065 if (res === THROTTLED) { 23066 const breadcrumb = createBreadcrumb({ category: "replay.throttled" }); 23067 this.addUpdate(() => { 23068 return !addEventSync(this, { 23069 type: ReplayEventTypeCustom, 23070 timestamp: breadcrumb.timestamp || 0, 23071 data: { 23072 tag: "breadcrumb", 23073 payload: breadcrumb, 23074 metric: true 23075 } 23076 }); 23077 }); 23078 } 23079 return res; 23080 } 23081 /** 23082 * This will get the parametrized route name of the current page. 23083 * This is only available if performance is enabled, and if an instrumented router is used. 23084 */ 23085 getCurrentRoute() { 23086 const lastActiveSpan = this.lastActiveSpan || getActiveSpan(); 23087 const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan); 23088 const source = (lastRootSpan && spanToJSON(lastRootSpan).data || {})[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 23089 if (!lastRootSpan || !source || !["route", "custom"].includes(source)) return; 23090 return spanToJSON(lastRootSpan).description; 23091 } 23092 /** 23093 * Initialize and start all listeners to varying events (DOM, 23094 * Performance Observer, Recording, Sentry SDK, etc) 23095 */ 23096 _initializeRecording() { 23097 this.setInitialState(); 23098 this._updateSessionActivity(); 23099 this.eventBuffer = createEventBuffer({ 23100 useCompression: this._options.useCompression, 23101 workerUrl: this._options.workerUrl 23102 }); 23103 this._removeListeners(); 23104 this._addListeners(); 23105 this._isEnabled = true; 23106 this._isPaused = false;
23107 if (this.session) getClient()?.emit("replayStart", { 23108 sessionId: this.session.id, 23109 recordingMode: this.recordingMode 23110 }); 23111 this.startRecording(); 23112 if (this.recordingMode === "session" && this.session) setReplayIdOnDynamicSamplingContext(this.session.id); 23113 } 23114 /** 23115 * Loads (or refreshes) the current session. 23116 */ 23117 _initializeSessionForSampling(previousSessionId) { 23118 const allowBuffering = this._options.errorSampleRate > 0; 23119 const session = loadOrCreateSession({ 23120 sessionIdleExpire: this.timeouts.sessionIdleExpire, 23121 maxReplayDuration: this._options.maxReplayDuration, 23122 previousSessionId 23123 }, { 23124 stickySession: this._options.stickySession, 23125 sessionSampleRate: this._options.sessionSampleRate, 23126 allowBuffering 23127 }); 23128 this.session = session; 23129 } 23130 /** 23131 * Checks and potentially refreshes the current session. 23132 * Returns false if session is not recorded. 23133 */ 23134 _checkSession() { 23135 if (!this.session) return false; 23136 const currentSession = this.session; 23137 if (shouldRefreshSession(currentSession, { 23138 sessionIdleExpire: this.timeouts.sessionIdleExpire, 23139 maxReplayDuration: this._options.maxReplayDuration 23140 })) { 23141 this._refreshSession(currentSession); 23142 return false; 23143 } 23144 return true; 23145 } 23146 /** 23147 * Refresh a session with a new one. 23148 * This stops the current session (without forcing a flush, as that would never work since we are expired), 23149 * and then does a new sampling based on the refreshed session. 23150 */ 23151 async _refreshSession(session) { 23152 if (!this._isEnabled) return; 23153 await this.stop({ reason: "sessionExpired" }); 23154 this.initializeSampling(session.id); 23155 } 23156 /** 23157 * Adds listeners to record events for the replay 23158 */ 23159 _addListeners() { 23160 try { 23161 WINDOW.document.addEventListener("visibilitychange", this._handleVisibilityChange); 23162 WINDOW.addEventListener("blur", this._handleWindowBlur); 23163 WINDOW.addEventListener("focus", this._handleWindowFocus); 23164 WINDOW.addEventListener("keydown", this._handleKeyboardEvent); 23165 if (this.clickDetector) this.clickDetector.addListeners(); 23166 if (!this._hasInitializedCoreListeners) { 23167 addGlobalListeners(this); 23168 this._hasInitializedCoreListeners = true; 23169 } 23170 } catch (err) { 23171 this.handleException(err); 23172 } 23173 this._performanceCleanupCallback = setupPerformanceObserver(this); 23174 } 23175 /** 23176 * Cleans up listeners that were created in `_addListeners` 23177 */ 23178 _removeListeners() { 23179 try { 23180 WINDOW.document.removeEventListener("visibilitychange", this._handleVisibilityChange); 23181 WINDOW.removeEventListener("blur", this._handleWindowBlur); 23182 WINDOW.removeEventListener("focus", this._handleWindowFocus); 23183 WINDOW.removeEventListener("keydown", this._handleKeyboardEvent); 23184 if (this.clickDetector) this.clickDetector.removeListeners(); 23185 if (this._performanceCleanupCallback) this._performanceCleanupCallback(); 23186 } catch (err) { 23187 this.handleException(err); 23188 } 23189 } 23190 /** 23191 * Tasks to run when we consider a page to be hidden (via blurring and/or visibility) 23192 */ 23193 _doChangeToBackgroundTasks(breadcrumb) { 23194 if (!this.session) return; 23195 if (shouldRefreshSession(this.session, { 23196 maxReplayDuration: this._options.maxReplayDuration, 23197 sessionIdleExpire: this.timeouts.sessionIdleExpire 23198 })) { 23199 resetReplayIdOnDynamicSamplingContext(); 23200 return; 23201 } 23202 if (breadcrumb) this._createCustomBreadcrumb(breadcrumb); 23203 this.conditionalFlush(); 23204 } 23205 /** 23206 * Tasks to run when we consider a page to be visible (via focus and/or visibility) 23207 */ 23208 _doChangeToForegroundTasks(breadcrumb) { 23209 if (!this.session) return; 23210 if (!this.checkAndHandleExpiredSession()) { 23211 DEBUG_BUILD$1 && debug.log("Document has become active, but session has expired"); 23212 return; 23213 } 23214 if (breadcrumb) this._createCustomBreadcrumb(breadcrumb); 23215 } 23216 /** 23217 * Update user activity (across session lifespans) 23218 */ 23219 _updateUserActivity(_lastActivity = Date.now()) { 23220 this._lastActivity = _lastActivity; 23221 } 23222 /** 23223 * Updates the session's last activity timestamp 23224 */ 23225 _updateSessionActivity(_lastActivity = Date.now()) { 23226 if (this.session) { 23227 this.session.lastActivity = _lastActivity; 23228 this._maybeSaveSession(); 23229 } 23230 } 23231 /** 23232 * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb 23233 */ 23234 _createCustomBreadcrumb(breadcrumb) { 23235 this.addUpdate(() => { 23236 this.throttledAddEvent({ 23237 type: EventType.Custom, 23238 timestamp: breadcrumb.timestamp || 0, 23239 data: { 23240 tag: "breadcrumb", 23241 payload: breadcrumb 23242 } 23243 }); 23244 }); 23245 } 23246 /** 23247 * Observed performance events are added to `this.performanceEntries`. These 23248 * are included in the replay event before it is finished and sent to Sentry. 23249 */ 23250 _addPerformanceEntries() { 23251 let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries); 23252 this.performanceEntries = []; 23253 this.replayPerformanceEntries = []; 23254 if (this._requiresManualStart) {
23255 const initialTimestampInSeconds = this._context.initialTimestamp / 1e3; 23256 performanceEntries = performanceEntries.filter((entry) => entry.start >= initialTimestampInSeconds); 23257 } 23258 return Promise.all(createPerformanceSpans(this, performanceEntries)); 23259 } 23260 /** 23261 * Clear _context 23262 */ 23263 _clearContext() { 23264 this._context.errorIds.clear(); 23265 this._context.traceIds.clear(); 23266 this._context.segmentNames.clear(); 23267 this._context.urls = []; 23268 } 23269 /** Update the initial timestamp based on the buffer content. */ 23270 _updateInitialTimestampFromEventBuffer() { 23271 const { session, eventBuffer } = this; 23272 if (!session || !eventBuffer || this._requiresManualStart) return; 23273 if (session.segmentId) return; 23274 const earliestEvent = eventBuffer.getEarliestTimestamp(); 23275 if (earliestEvent && earliestEvent < this._context.initialTimestamp) this._context.initialTimestamp = earliestEvent; 23276 } 23277 /** 23278 * Return and clear _context 23279 */ 23280 _popEventContext() { 23281 const _context = { 23282 initialTimestamp: this._context.initialTimestamp, 23283 initialUrl: this._context.initialUrl, 23284 errorIds: Array.from(this._context.errorIds), 23285 traceIds: Array.from(this._context.traceIds), 23286 segmentNames: Array.from(this._context.segmentNames), 23287 urls: this._context.urls 23288 }; 23289 this._clearContext(); 23290 return _context; 23291 } 23292 /** 23293 * Flushes replay event buffer to Sentry. 23294 * 23295 * Performance events are only added right before flushing - this is 23296 * due to the buffered performance observer events. 23297 * 23298 * Should never be called directly, only by `flush` 23299 */ 23300 async _runFlush() { 23301 const replayId = this.getSessionId(); 23302 if (!this.session || !this.eventBuffer || !replayId) { 23303 DEBUG_BUILD$1 && debug.error("No session or eventBuffer found to flush."); 23304 return; 23305 } 23306 await this._addPerformanceEntries(); 23307 if (!this.eventBuffer?.hasEvents) return; 23308 await addMemoryEntry(this); 23309 if (!this.eventBuffer) return; 23310 if (replayId !== this.getSessionId()) return; 23311 try { 23312 this._updateInitialTimestampFromEventBuffer(); 23313 const timestamp = Date.now(); 23314 if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 3e4) throw new ReplayDurationLimitError(); 23315 const eventContext = this._popEventContext(); 23316 const segmentId = this.session.segmentId++; 23317 this._maybeSaveSession(); 23318 await sendReplay({ 23319 replayId, 23320 recordingData: await this.eventBuffer.finish(), 23321 segmentId, 23322 eventContext, 23323 session: this.session, 23324 timestamp, 23325 onError: (err) => this.handleException(err) 23326 }); 23327 } catch (err) { 23328 this.handleException(err); 23329 this.stop({ reason: "sendError" }); 23330 const client = getClient(); 23331 if (client) { 23332 let dropReason; 23333 if (err instanceof RateLimitError) dropReason = "ratelimit_backoff"; 23334 else if (err instanceof ReplayDurationLimitError) dropReason = "invalid"; 23335 else dropReason = "send_error"; 23336 client.recordDroppedEvent(dropReason, "replay"); 23337 } 23338 } 23339 } 23340 /** 23341 * Flush recording data to Sentry. Creates a lock so that only a single flush 23342 * can be active at a time. Do not call this directly. 23343 */ 23344 async _flush({ force = false } = {}) { 23345 if (!this._isEnabled && !force) return; 23346 if (!this.checkAndHandleExpiredSession()) { 23347 DEBUG_BUILD$1 && debug.error("Attempting to finish replay event after session expired."); 23348 return; 23349 } 23350 if (!this.session) return; 23351 const start = this.session.started; 23352 const duration = Date.now() - start; 23353 this._debouncedFlush.cancel(); 23354 const tooShort = duration < this._options.minReplayDuration; 23355 const tooLong = duration > this._options.maxReplayDuration + 5e3; 23356 if (tooShort || tooLong) { 23357 DEBUG_BUILD$1 && debug.log(`Session duration (${Math.floor(duration / 1e3)}s) is too ${tooShort ? "short" : "long"}, not sending replay.`); 23358 if (tooShort) this._debouncedFlush(); 23359 return; 23360 } 23361 const eventBuffer = this.eventBuffer; 23362 if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) DEBUG_BUILD$1 && debug.log("Flushing initial segment without checkout."); 23363 const _flushInProgress = !!this._flushLock; 23364 if (!this._flushLock) this._flushLock = this._runFlush();
23365 try { 23366 await this._flushLock; 23367 } catch (err) { 23368 this.handleException(err); 23369 } finally { 23370 this._flushLock = void 0; 23371 if (_flushInProgress) this._debouncedFlush(); 23372 } 23373 } 23374 /** Save the session, if it is sticky */ 23375 _maybeSaveSession() { 23376 if (this.session && this._options.stickySession) saveSession(this.session); 23377 } 23378 /** Handler for rrweb.record.onMutation */ 23379 _onMutationHandler(mutations) { 23380 const { ignoreMutations } = this._options._experiments; 23381 if (ignoreMutations?.length) { 23382 if (mutations.some((mutation) => { 23383 const el = closestElementOfNode$2(mutation.target); 23384 const selector = ignoreMutations.join(","); 23385 return el?.matches(selector); 23386 })) return false; 23387 } 23388 const count = mutations.length; 23389 const mutationLimit = this._options.mutationLimit; 23390 const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit; 23391 const overMutationLimit = mutationLimit && count > mutationLimit; 23392 if (count > mutationBreadcrumbLimit || overMutationLimit) { 23393 const breadcrumb = createBreadcrumb({ 23394 category: "replay.mutations", 23395 data: { 23396 count, 23397 limit: overMutationLimit 23398 } 23399 }); 23400 this._createCustomBreadcrumb(breadcrumb); 23401 } 23402 if (overMutationLimit) { 23403 this.stop({ 23404 reason: "mutationLimit", 23405 forceFlush: this.recordingMode === "session" 23406 }); 23407 return false; 23408 } 23409 return true; 23410 } 23411 }; 23412 MEDIA_SELECTORS = "img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]"; 23413 DEFAULT_NETWORK_HEADERS = [ 23414 "content-length", 23415 "content-type", 23416 "accept" 23417 ]; 23418 ORIGINAL_BODY = /* @__PURE__ */ Symbol.for("sentry__originalRequestBody"); 23419 _initialized = false; 23420 _isRequestInstrumented = false; 23421 replayIntegration = ((options) => { 23422 return new Replay(options); 23423 }); 23424 Replay = class { 23425 constructor({ flushMinDelay = DEFAULT_FLUSH_MIN_DELAY, flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY, minReplayDuration = MIN_REPLAY_DURATION, maxReplayDuration = MAX_REPLAY_DURATION, stickySession = true, useCompression = true, workerUrl, _experiments = {}, maskAllText = true, maskAllInputs = true, blockAllMedia = true, mutationBreadcrumbLimit = 750, mutationLimit = 1e4, slowClickTimeout = 7e3, slowClickIgnoreSelectors = [], networkDetailAllowUrls = [], networkDetailDenyUrls = [], networkCaptureBodies = true, networkRequestHeaders = [], networkResponseHeaders = [], mask = [], maskAttributes = [ 23426 "title", 23427 "placeholder", 23428 "aria-label" 23429 ], unmask = [], block = [], unblock = [], ignore = [], maskFn, beforeAddRecordingEvent, beforeErrorSampling, onError, attachRawBodyFromRequest = false } = {}) { 23430 this.name = "Replay"; 23431 const privacyOptions = getPrivacyOptions({ 23432 mask, 23433 unmask, 23434 block, 23435 unblock, 23436 ignore 23437 }); 23438 this._recordingOptions = { 23439 maskAllInputs, 23440 maskAllText, 23441 maskInputOptions: { password: true }, 23442 maskTextFn: maskFn, 23443 maskInputFn: maskFn, 23444 maskAttributeFn: (key, value, el) => maskAttribute({ 23445 maskAttributes, 23446 maskAllText, 23447 privacyOptions, 23448 key, 23449 value, 23450 el 23451 }), 23452 ...privacyOptions, 23453 slimDOMOptions: "all", 23454 inlineStylesheet: true, 23455 inlineImages: false, 23456 collectFonts: true, 23457 errorHandler: (err) => { 23458 try { 23459 err.__rrweb__ = true; 23460 } catch {} 23461 }, 23462 recordCrossOriginIframes: Boolean(_experiments.recordCrossOriginIframes) 23463 }; 23464 this._initialOptions = { 23465 flushMinDelay, 23466 flushMaxDelay, 23467 minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT), 23468 maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION), 23469 stickySession, 23470 useCompression, 23471 workerUrl, 23472 blockAllMedia, 23473 maskAllInputs, 23474 maskAllText, 23475 mutationBreadcrumbLimit, 23476 mutationLimit, 23477 slowClickTimeout, 23478 slowClickIgnoreSelectors, 23479 networkDetailAllowUrls, 23480 networkDetailDenyUrls, 23481 networkCaptureBodies, 23482 networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
23483 networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders), 23484 beforeAddRecordingEvent, 23485 beforeErrorSampling, 23486 onError, 23487 attachRawBodyFromRequest, 23488 _experiments 23489 }; 23490 if (this._initialOptions.blockAllMedia) { 23491 this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector ? MEDIA_SELECTORS : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`; 23492 this._recordingOptions.ignoreCSSAttributes = /* @__PURE__ */ new Set(["background-image"]); 23493 } 23494 if (this._isInitialized && isBrowser()) throw new Error("Multiple Sentry Session Replay instances are not supported"); 23495 this._isInitialized = true; 23496 } 23497 /** If replay has already been initialized */ 23498 get _isInitialized() { 23499 return _initialized; 23500 } 23501 /** Update _isInitialized */ 23502 set _isInitialized(value) { 23503 _initialized = value; 23504 } 23505 /** 23506 * Setup and initialize replay container 23507 */ 23508 afterAllSetup(client) { 23509 if (!isBrowser() || this._replay) return; 23510 if (this._initialOptions.attachRawBodyFromRequest) _INTERNAL_instrumentRequestInterface(); 23511 this._setup(client); 23512 this._initialize(client); 23513 } 23514 /** 23515 * Start a replay regardless of sampling rate. Calling this will always 23516 * create a new session. Will log a message if replay is already in progress. 23517 * 23518 * Creates or loads a session, attaches listeners to varying events (DOM, 23519 * PerformanceObserver, Recording, Sentry SDK, etc) 23520 */ 23521 start() { 23522 if (!this._replay) return; 23523 this._replay.start(); 23524 } 23525 /** 23526 * Start replay buffering. Buffers until `flush()` is called or, if 23527 * `replaysOnErrorSampleRate` > 0, until an error occurs. 23528 */ 23529 startBuffering() { 23530 if (!this._replay) return; 23531 this._replay.startBuffering(); 23532 } 23533 /** 23534 * Currently, this needs to be manually called (e.g. for tests). Sentry SDK 23535 * does not support a teardown 23536 * 23537 * @param options.flush - Whether to flush the pending replay segment when stopping. 23538 * When recording in `session` mode, `stop()` flushes the buffered-but-unsent segment by 23539 * default (`flush: true`), matching the previous behavior. Pass `flush: false` to stop 23540 * recording without sending that pending segment — useful when a user withdraws consent 23541 * and no further data should leave the browser. 23542 * 23543 * Note: `flush: false` only prevents the *pending* (final) segment from being sent. It does 23544 * **not** retract segments that were already sent earlier during `session` recording. 23545 */ 23546 stop(options) { 23547 if (!this._replay) return Promise.resolve(); 23548 return this._replay.stop({ 23549 forceFlush: options?.flush ?? this._replay.recordingMode === "session", 23550 reason: "manual" 23551 }); 23552 } 23553 /** 23554 * If not in "session" recording mode, flush event buffer which will create a new replay. 23555 * If replay is not enabled, a new session replay is started. 23556 * Unless `continueRecording` is false, the replay will continue to record and 23557 * behave as a "session"-based replay. 23558 * 23559 * Otherwise, queue up a flush. 23560 */ 23561 flush(options) { 23562 if (!this._replay) return Promise.resolve(); 23563 if (!this._replay.isEnabled()) { 23564 this._replay.start(); 23565 return Promise.resolve(); 23566 } 23567 return this._replay.sendBufferedReplayOrFlush(options); 23568 } 23569 /** 23570 * Get the current session ID. 23571 * 23572 * @param onlyIfSampled - If true, will only return the session ID if the session is sampled. 23573 * 23574 */ 23575 getReplayId(onlyIfSampled) { 23576 if (!this._replay?.isEnabled()) return; 23577 return this._replay.getSessionId(onlyIfSampled); 23578 } 23579 /** 23580 * Get the current recording mode. This can be either `session` or `buffer`. 23581 * 23582 * `session`: Recording the whole session, sending it continuously 23583 * `buffer`: Always keeping the last 60s of recording, requires: 23584 * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs 23585 * - or calling `flush()` to send the replay 23586 */ 23587 getRecordingMode() { 23588 if (!this._replay?.isEnabled()) return; 23589 return this._replay.recordingMode; 23590 } 23591 processSpan(span) { 23592 const replayId = this.getReplayId(true); 23593 if (replayId) { 23594 safeSetSpanJSONAttributes(span, { "sentry.replay_id": replayId }); 23595 if (this.getRecordingMode() === "buffer") safeSetSpanJSONAttributes(span, { "sentry._internal.replay_is_buffering": true }); 23596 } 23597 } 23598 /** 23599 * Initializes replay. 23600 */ 23601 _initialize(client) { 23602 if (!this._replay) return; 23603 this._maybeLoadFromReplayCanvasIntegration(client); 23604 this._replay.initializeSampling(); 23605 } 23606 /** Setup the integration. */ 23607 _setup(client) { 23608 const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client); 23609 this._replay = new ReplayContainer({ 23610 options: finalOptions, 23611 recordingOptions: this._recordingOptions 23612 }); 23613 } 23614 /** Get canvas options from ReplayCanvas integration, if it is also added. */ 23615 _maybeLoadFromReplayCanvasIntegration(client) { 23616 try { 23617 const canvasIntegration = client.getIntegrationByName("ReplayCanvas"); 23618 if (!canvasIntegration) return; 23619 this._replay["_canvas"] = canvasIntegration.getOptions(); 23620 } catch {} 23621 } 23622 }; 23623 })))(); 23624} 23625//#endregion 23626//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/replay-canvas/build/npm/esm/index.js 23627function createMirror() { 23628 return new Mirror(); 23629} 23630function elementClassMatchesRegex(el, regex) { 23631 for (let eIndex = el.classList.length; eIndex--;) { 23632 const className = el.classList[eIndex]; 23633 if (regex.test(className)) return true; 23634 } 23635 return false;
23636} 23637function distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) { 23638 if (!node) return -1; 23639 if (node.nodeType !== node.ELEMENT_NODE) return -1; 23640 if (distance > limit) return -1; 23641 if (matchPredicate(node)) return distance; 23642 return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1); 23643} 23644function createMatchPredicate(className, selector) { 23645 return (node) => { 23646 const el = node; 23647 if (el === null) return false; 23648 try { 23649 if (className) { 23650 if (typeof className === "string") { 23651 if (el.matches(`.${className}`)) return true; 23652 } else if (elementClassMatchesRegex(el, className)) return true; 23653 } 23654 if (selector && el.matches(selector)) return true; 23655 return false; 23656 } catch { 23657 return false; 23658 } 23659 }; 23660} 23661function hookSetter(target, key, d, isRevoked, win = window) { 23662 const original = win.Object.getOwnPropertyDescriptor(target, key); 23663 win.Object.defineProperty(target, key, isRevoked ? d : { set(value) { 23664 setTimeout$1(() => { 23665 d.set.call(this, value); 23666 }, 0); 23667 if (original && original.set) original.set.call(this, value); 23668 } }); 23669 return () => hookSetter(target, key, original || {}, true); 23670} 23671function patch(source, name, replacement) { 23672 try { 23673 if (!(name in source)) return () => {}; 23674 const original = source[name]; 23675 const wrapped = replacement(original); 23676 if (typeof wrapped === "function") { 23677 wrapped.prototype = wrapped.prototype || {}; 23678 Object.defineProperties(wrapped, { __rrweb_original__: { 23679 enumerable: false, 23680 value: original 23681 } }); 23682 } 23683 source[name] = wrapped; 23684 return () => { 23685 source[name] = original; 23686 }; 23687 } catch { 23688 return () => {}; 23689 } 23690} 23691function closestElementOfNode(node) { 23692 if (!node) return null; 23693 try { 23694 return node.nodeType === node.ELEMENT_NODE ? node : node.parentElement; 23695 } catch (error) { 23696 return null; 23697 } 23698} 23699function isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) { 23700 if (!node) return false; 23701 const el = closestElementOfNode(node); 23702 if (!el) return false; 23703 const blockedPredicate = createMatchPredicate(blockClass, blockSelector); 23704 if (!checkAncestors) { 23705 const isUnblocked = unblockSelector && el.matches(unblockSelector); 23706 return blockedPredicate(el) && !isUnblocked; 23707 } 23708 const blockDistance = distanceToMatch(el, blockedPredicate); 23709 let unblockDistance = -1; 23710 if (blockDistance < 0) return false; 23711 if (unblockSelector) unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector)); 23712 if (blockDistance > -1 && unblockDistance < 0) return true; 23713 return blockDistance < unblockDistance; 23714} 23715function getImplementation(name) { 23716 const cached = cachedImplementations[name]; 23717 if (cached) return cached; 23718 const document2 = window.document; 23719 let impl = window[name]; 23720 if (document2 && typeof document2.createElement === "function") try { 23721 const sandbox = document2.createElement("iframe"); 23722 sandbox.hidden = true; 23723 document2.head.appendChild(sandbox); 23724 const contentWindow = sandbox.contentWindow; 23725 if (contentWindow && contentWindow[name]) impl = contentWindow[name]; 23726 document2.head.removeChild(sandbox); 23727 } catch (e) {} 23728 return cachedImplementations[name] = impl.bind(window); 23729} 23730function onRequestAnimationFrame(...rest) { 23731 return getImplementation("requestAnimationFrame")(...rest); 23732} 23733function setTimeout$1(...rest) { 23734 return getImplementation("setTimeout")(...rest); 23735} 23736function registerErrorHandler(handler) { 23737 errorHandler = handler; 23738} 23739function variableListFor(ctx, ctor) { 23740 let contextMap = canvasVarMap.get(ctx); 23741 if (!contextMap) { 23742 contextMap = /* @__PURE__ */ new Map(); 23743 canvasVarMap.set(ctx, contextMap); 23744 } 23745 if (!contextMap.has(ctor)) contextMap.set(ctor, []); 23746 return contextMap.get(ctor); 23747} 23748function serializeArg(value, win, ctx) { 23749 if (value instanceof Array) return value.map((arg) => serializeArg(arg, win, ctx)); 23750 else if (value === null) return value; 23751 else if (value instanceof Float32Array || value instanceof Float64Array || value instanceof Int32Array || value instanceof Uint32Array || value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray) return { 23752 rr_type: value.constructor.name, 23753 args: [Object.values(value)] 23754 }; 23755 else if (value instanceof ArrayBuffer) return { 23756 rr_type: value.constructor.name, 23757 base64: encode(value) 23758 }; 23759 else if (value instanceof DataView) return { 23760 rr_type: value.constructor.name, 23761 args: [ 23762 serializeArg(value.buffer, win, ctx), 23763 value.byteOffset, 23764 value.byteLength 23765 ] 23766 }; 23767 else if (value instanceof HTMLImageElement) { 23768 const name = value.constructor.name; 23769 const { src } = value; 23770 return { 23771 rr_type: name, 23772 src 23773 }; 23774 } else if (value instanceof HTMLCanvasElement) return { 23775 rr_type: "HTMLImageElement", 23776 src: value.toDataURL() 23777 }; 23778 else if (value instanceof ImageData) return { 23779 rr_type: value.constructor.name, 23780 args: [ 23781 serializeArg(value.data, win, ctx), 23782 value.width, 23783 value.height 23784 ] 23785 }; 23786 else if (isInstanceOfWebGLObject(value, win) || typeof value === "object") return { 23787 rr_type: value.constructor.name, 23788 index: saveWebGLVar(value, win, ctx) 23789 }; 23790 return value; 23791} 23792function initCanvas2DMutationObserver(cb, win, blockClass2, blockSelector, unblockSelector) { 23793 const handlers = []; 23794 const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype); 23795 for (const prop of props2D) try { 23796 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") continue; 23797 const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) { 23798 return function(...args) { 23799 if (!isBlocked(this.canvas, blockClass2, blockSelector, unblockSelector, true)) setTimeout$1(() => {
23800 const recordArgs = serializeArgs(args, win, this); 23801 cb(this.canvas, { 23802 type: CanvasContext["2D"], 23803 property: prop, 23804 args: recordArgs 23805 }); 23806 }, 0); 23807 return original.apply(this, args); 23808 }; 23809 }); 23810 handlers.push(restoreHandler); 23811 } catch { 23812 const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, { set(v) { 23813 cb(this.canvas, { 23814 type: CanvasContext["2D"], 23815 property: prop, 23816 args: [v], 23817 setter: true 23818 }); 23819 } }); 23820 handlers.push(hookHandler); 23821 } 23822 return () => { 23823 handlers.forEach((h) => h()); 23824 }; 23825} 23826function getNormalizedContextName(contextType) { 23827 return contextType === "experimental-webgl" ? "webgl" : contextType; 23828} 23829function initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, setPreserveDrawingBufferToTrue) { 23830 const handlers = []; 23831 try { 23832 const restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) { 23833 return function(contextType, ...args) { 23834 if (!isBlocked(this, blockClass, blockSelector, unblockSelector, true)) { 23835 const ctxName = getNormalizedContextName(contextType); 23836 if (!("__context" in this)) this.__context = ctxName; 23837 if (setPreserveDrawingBufferToTrue && ["webgl", "webgl2"].includes(ctxName)) { 23838 if (args[0] && typeof args[0] === "object") { 23839 const contextAttributes = args[0]; 23840 if (!contextAttributes.preserveDrawingBuffer) contextAttributes.preserveDrawingBuffer = true; 23841 } else args.splice(0, 1, { preserveDrawingBuffer: true }); 23842 } 23843 } 23844 return original.apply(this, [contextType, ...args]); 23845 }; 23846 }); 23847 handlers.push(restoreHandler); 23848 } catch { 23849 console.error("failed to patch HTMLCanvasElement.prototype.getContext"); 23850 } 23851 return () => { 23852 handlers.forEach((h) => h()); 23853 }; 23854} 23855function patchGLPrototype(prototype, type, cb, blockClass2, blockSelector, unblockSelector, _mirror2, win) { 23856 const handlers = []; 23857 const props = Object.getOwnPropertyNames(prototype); 23858 for (const prop of props) { 23859 if ([ 23860 "isContextLost", 23861 "canvas", 23862 "drawingBufferWidth", 23863 "drawingBufferHeight" 23864 ].includes(prop)) continue; 23865 try { 23866 if (typeof prototype[prop] !== "function") continue; 23867 const restoreHandler = patch(prototype, prop, function(original) { 23868 return function(...args) { 23869 const result = original.apply(this, args); 23870 saveWebGLVar(result, win, this); 23871 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass2, blockSelector, unblockSelector, true)) { 23872 const recordArgs = serializeArgs(args, win, this); 23873 const mutation = { 23874 type, 23875 property: prop, 23876 args: recordArgs 23877 }; 23878 cb(this.canvas, mutation); 23879 } 23880 return result; 23881 }; 23882 }); 23883 handlers.push(restoreHandler); 23884 } catch { 23885 const hookHandler = hookSetter(prototype, prop, { set(v) { 23886 cb(this.canvas, { 23887 type, 23888 property: prop, 23889 args: [v], 23890 setter: true 23891 }); 23892 } }); 23893 handlers.push(hookHandler); 23894 } 23895 } 23896 return handlers; 23897} 23898function initCanvasWebGLMutationObserver(cb, win, blockClass2, blockSelector, unblockSelector, mirror) { 23899 const handlers = []; 23900 handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass2, blockSelector, unblockSelector, mirror, win)); 23901 if (typeof win.WebGL2RenderingContext !== "undefined") handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass2, blockSelector, unblockSelector, mirror, win)); 23902 return () => { 23903 handlers.forEach((h) => h()); 23904 }; 23905} 23906function t() { 23907 const t2 = new Blob([r]); 23908 return URL.createObjectURL(t2); 23909} 23910var __defProp, __defNormalProp, __publicField, Mirror, DEPARTED_MIRROR_ACCESS_WARNING, _mirror, cachedImplementations, CanvasContext, errorHandler, callbackWrapper, chars, lookup, i, encode, canvasVarMap, saveWebGLVar, serializeArgs, isInstanceOfWebGLObject, r, CanvasManager, n, CANVAS_QUALITY, INTEGRATION_NAME$3, DEFAULT_MAX_CANVAS_SIZE, _replayCanvasIntegration, replayCanvasIntegration; 23911function init_esm$2() { 23912 return (init_esm$2 = __esmMin((() => { 23913 init_integration(); 23914 __defProp = Object.defineProperty; 23915 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { 23916 enumerable: true, 23917 configurable: true, 23918 writable: true, 23919 value 23920 }) : obj[key] = value; 23921 __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); 23922 Mirror = class { 23923 constructor() {
23924 __publicField(this, "idNodeMap", /* @__PURE__ */ new Map()); 23925 __publicField(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap()); 23926 } 23927 getId(n) { 23928 if (!n) return -1; 23929 return this.getMeta(n)?.id ?? -1; 23930 } 23931 getNode(id) { 23932 return this.idNodeMap.get(id) || null; 23933 } 23934 getIds() { 23935 return Array.from(this.idNodeMap.keys()); 23936 } 23937 getMeta(n) { 23938 return this.nodeMetaMap.get(n) || null; 23939 } 23940 removeNodeFromMap(n) { 23941 const id = this.getId(n); 23942 this.idNodeMap.delete(id); 23943 if (n.childNodes) n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode)); 23944 } 23945 has(id) { 23946 return this.idNodeMap.has(id); 23947 } 23948 hasNode(node) { 23949 return this.nodeMetaMap.has(node); 23950 } 23951 add(n, meta) { 23952 const id = meta.id; 23953 this.idNodeMap.set(id, n); 23954 this.nodeMetaMap.set(n, meta); 23955 } 23956 replace(id, n) { 23957 const oldNode = this.getNode(id); 23958 if (oldNode) { 23959 const meta = this.nodeMetaMap.get(oldNode); 23960 if (meta) this.nodeMetaMap.set(n, meta); 23961 } 23962 this.idNodeMap.set(id, n); 23963 } 23964 reset() { 23965 this.idNodeMap = /* @__PURE__ */ new Map(); 23966 this.nodeMetaMap = /* @__PURE__ */ new WeakMap(); 23967 } 23968 }; 23969 DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording."; 23970 _mirror = { 23971 map: {}, 23972 getId() { 23973 console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23974 return -1; 23975 }, 23976 getNode() { 23977 console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23978 return null; 23979 }, 23980 removeNodeFromMap() { 23981 console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23982 }, 23983 has() { 23984 console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23985 return false; 23986 }, 23987 reset() { 23988 console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23989 } 23990 }; 23991 if (typeof window !== "undefined" && window.Proxy && window.Reflect) _mirror = new Proxy(_mirror, { get(target, prop, receiver) { 23992 if (prop === "map") console.error(DEPARTED_MIRROR_ACCESS_WARNING); 23993 return Reflect.get(target, prop, receiver); 23994 } }); 23995 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())); 23996 cachedImplementations = {}; 23997 CanvasContext = /* @__PURE__ */ ((CanvasContext2) => { 23998 CanvasContext2[CanvasContext2["2D"] = 0] = "2D"; 23999 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL"; 24000 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2"; 24001 return CanvasContext2; 24002 })(CanvasContext || {}); 24003 callbackWrapper = (cb) => { 24004 if (!errorHandler) return cb; 24005 const rrwebWrapped = ((...rest) => { 24006 try { 24007 return cb(...rest); 24008 } catch (error) { 24009 if (errorHandler && errorHandler(error) === true) return () => {}; 24010 throw error; 24011 } 24012 }); 24013 return rrwebWrapped; 24014 }; 24015 chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 24016 lookup = typeof Uint8Array === "undefined" ? [] : /* @__PURE__ */ new Uint8Array(256); 24017 for (i = 0; i < chars.length; i++) lookup[chars.charCodeAt(i)] = i; 24018 encode = function(arraybuffer) { 24019 var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = ""; 24020 for (i2 = 0; i2 < len; i2 += 3) { 24021 base64 += chars[bytes[i2] >> 2]; 24022 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4]; 24023 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6]; 24024 base64 += chars[bytes[i2 + 2] & 63]; 24025 } 24026 if (len % 3 === 2) base64 = base64.substring(0, base64.length - 1) + "="; 24027 else if (len % 3 === 1) base64 = base64.substring(0, base64.length - 2) + "=="; 24028 return base64; 24029 }; 24030 canvasVarMap = /* @__PURE__ */ new Map(); 24031 saveWebGLVar = (value, win, ctx) => { 24032 if (!value || !(isInstanceOfWebGLObject(value, win) || typeof value === "object")) return; 24033 const name = value.constructor.name; 24034 const list = variableListFor(ctx, name); 24035 let index = list.indexOf(value); 24036 if (index === -1) { 24037 index = list.length; 24038 list.push(value); 24039 } 24040 return index; 24041 }; 24042 serializeArgs = (args, win, ctx) => { 24043 return args.map((arg) => serializeArg(arg, win, ctx)); 24044 }; 24045 isInstanceOfWebGLObject = (value, win) => { 24046 const supportedWebGLConstructorNames = [ 24047 "WebGLActiveInfo", 24048 "WebGLBuffer", 24049 "WebGLFramebuffer", 24050 "WebGLProgram", 24051 "WebGLRenderbuffer", 24052 "WebGLShader", 24053 "WebGLShaderPrecisionFormat", 24054 "WebGLTexture", 24055 "WebGLUniformLocation", 24056 "WebGLVertexArrayObject", 24057 "WebGLVertexArrayObjectOES" 24058 ].filter((name) => typeof win[name] === "function"); 24059 return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name])); 24060 }; 24061 r = `for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
24061+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s="";for(a=0;a<r;a+=3)s+=e[n[a]>>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+"=":r%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+"-"+t;if("OffscreenCanvas"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext("2d");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return""}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext("bitmaprenderer"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:"low"});w?.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`; 24062 CanvasManager = class { 24063 constructor(options) { 24064 this.pendingCanvasMutations = /* @__PURE__ */ new Map(); 24065 this.rafStamps = { 24066 latestId: 0, 24067 invokeId: null 24068 }; 24069 this.shadowDoms = /* @__PURE__ */ new Set(); 24070 this.windowsSet = /* @__PURE__ */ new WeakSet(); 24071 this.windows = []; 24072 this.restoreHandlers = []; 24073 this.frozen = false; 24074 this.locked = false; 24075 this.snapshotInProgressMap = /* @__PURE__ */ new Map(); 24076 this.worker = null; 24077 this.lastSnapshotTime = 0; 24078 this.processMutation = (target, mutation) => { 24079 if (this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId || !this.rafStamps.invokeId) this.rafStamps.invokeId = this.rafStamps.latestId; 24080 if (!this.pendingCanvasMutations.has(target)) this.pendingCanvasMutations.set(target, []); 24081 this.pendingCanvasMutations.get(target).push(mutation); 24082 }; 24083 const { enableManualSnapshot, sampling = "all", win, recordCanvas, errorHandler: errorHandler2 } = options; 24084 options.sampling = sampling; 24085 this.mutationCb = options.mutationCb; 24086 this.mirror = options.mirror; 24087 this.options = options; 24088 if (errorHandler2) registerErrorHandler(errorHandler2); 24089 if (recordCanvas && typeof sampling === "number" || enableManualSnapshot) this.worker = this.initFPSWorker(); 24090 this.addWindow(win); 24091 if (enableManualSnapshot) return; 24092 callbackWrapper(() => { 24093 if (recordCanvas && sampling === "all") { 24094 this.startRAFTimestamping(); 24095 this.startPendingCanvasMutationFlusher(); 24096 } 24097 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(); 24098 })(); 24099 } 24100 reset() { 24101 this.pendingCanvasMutations.clear(); 24102 this.restoreHandlers.forEach((handler) => { 24103 try { 24104 handler(); 24105 } catch (e) {} 24106 }); 24107 this.restoreHandlers = []; 24108 this.windowsSet = /* @__PURE__ */ new WeakSet(); 24109 this.windows = []; 24110 this.shadowDoms = /* @__PURE__ */ new Set(); 24111 this.worker?.terminate(); 24112 this.worker = null; 24113 this.snapshotInProgressMap = /* @__PURE__ */ new Map(); 24114 } 24115 freeze() { 24116 this.frozen = true; 24117 } 24118 unfreeze() { 24119 this.frozen = false; 24120 } 24121 lock() { 24122 this.locked = true; 24123 } 24124 unlock() { 24125 this.locked = false; 24126 } 24127 addWindow(win) { 24128 const { sampling = "all", blockClass, blockSelector, unblockSelector, recordCanvas, enableManualSnapshot } = this.options; 24129 if (this.windowsSet.has(win)) return; 24130 if (enableManualSnapshot) { 24131 this.windowsSet.add(win); 24132 this.windows.push(new WeakRef(win)); 24133 return; 24134 } 24135 callbackWrapper(() => { 24136 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector); 24137 if (recordCanvas && typeof sampling === "number") { 24138 const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true); 24139 this.restoreHandlers.push(() => { 24140 canvasContextReset(); 24141 }); 24142 } 24143 })(); 24144 this.windowsSet.add(win); 24145 this.windows.push(new WeakRef(win)); 24146 } 24147 addShadowRoot(shadowRoot) { 24148 this.shadowDoms.add(new WeakRef(shadowRoot)); 24149 } 24150 resetShadowRoots() { 24151 this.shadowDoms = /* @__PURE__ */ new Set(); 24152 } 24153 snapshot(canvasElement, options) { 24154 if (options?.skipRequestAnimationFrame) { 24155 this.takeSnapshot(performance.now(), true, canvasElement); 24156 return; 24157 } 24158 onRequestAnimationFrame((timestamp) => this.takeSnapshot(timestamp, true, canvasElement)); 24159 } 24160 initFPSWorker() { 24161 const worker = new Worker(t()); 24162 worker.onmessage = (e) => { 24163 const data = e.data; 24164 const { id } = data; 24165 this.snapshotInProgressMap.set(id, false); 24166 if (!("base64" in data)) return; 24167 const { base64, type, width, height } = data; 24168 this.mutationCb({ 24169 id, 24170 type: CanvasContext["2D"], 24171 commands: [{ 24172 property: "clearRect", 24173 args: [ 24174 0, 24175 0, 24176 width, 24177 height 24178 ] 24179 }, {
24180 property: "drawImage", 24181 args: [ 24182 { 24183 rr_type: "ImageBitmap", 24184 args: [{ 24185 rr_type: "Blob", 24186 data: [{ 24187 rr_type: "ArrayBuffer", 24188 base64 24189 }], 24190 type 24191 }] 24192 }, 24193 0, 24194 0, 24195 width, 24196 height 24197 ] 24198 }] 24199 }); 24200 }; 24201 return worker; 24202 } 24203 initCanvasFPSObserver() { 24204 let rafId; 24205 if (!this.windows.length && !this.shadowDoms.size) return; 24206 const rafCallback = (timestamp) => { 24207 this.takeSnapshot(timestamp, false); 24208 rafId = onRequestAnimationFrame(rafCallback); 24209 }; 24210 rafId = onRequestAnimationFrame(rafCallback); 24211 this.restoreHandlers.push(() => { 24212 if (rafId) cancelAnimationFrame(rafId); 24213 }); 24214 } 24215 initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) { 24216 const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false); 24217 const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector); 24218 const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror); 24219 this.restoreHandlers.push(() => { 24220 canvasContextReset(); 24221 canvas2DReset(); 24222 canvasWebGL1and2Reset(); 24223 }); 24224 } 24225 /** 24226 * Returns all `canvas` elements that are not blocked by the given selectors. Searches all windows and shadow roots. 24227 */ 24228 getCanvasElements(blockClass, blockSelector, unblockSelector) { 24229 const matchedCanvas = []; 24230 const searchCanvas = (root) => { 24231 root.querySelectorAll("canvas").forEach((canvas) => { 24232 if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) matchedCanvas.push(canvas); 24233 }); 24234 }; 24235 for (const item of this.windows) { 24236 const window2 = item.deref(); 24237 let _document; 24238 try { 24239 _document = window2 && window2.document; 24240 } catch {} 24241 if (_document) searchCanvas(_document); 24242 } 24243 for (const item of this.shadowDoms) { 24244 const shadowRoot = item.deref(); 24245 if (shadowRoot) searchCanvas(shadowRoot); 24246 } 24247 return matchedCanvas; 24248 } 24249 /** 24250 * Takes a snapshot of the provided canvas element, or will search all windows/shadow roots for canvases. Will self-throttle based on `options.sampling`. 24251 * 24252 * @returns `true` if the snapshot was taken, `false` if it was throttled. 24253 */ 24254 takeSnapshot(timestamp, isManualSnapshot, canvasElement) { 24255 const { sampling, blockClass, blockSelector, unblockSelector, dataURLOptions, maxCanvasSize } = this.options; 24256 const timeBetweenSnapshots = 1e3 / (sampling === "all" ? 2 : sampling || 2); 24257 if (this.lastSnapshotTime && timestamp - this.lastSnapshotTime < timeBetweenSnapshots) return false; 24258 this.lastSnapshotTime = timestamp; 24259 (canvasElement ? [canvasElement] : this.getCanvasElements(blockClass, blockSelector, unblockSelector)).forEach((canvas) => { 24260 const id = this.mirror.getId(canvas); 24261 if (!this.mirror.hasNode(canvas) || !canvas.width || !canvas.height || this.snapshotInProgressMap.get(id)) return; 24262 this.snapshotInProgressMap.set(id, true); 24263 if (!isManualSnapshot && ["webgl", "webgl2"].includes(canvas.__context)) { 24264 const context = canvas.getContext(canvas.__context); 24265 if (context?.getContextAttributes()?.preserveDrawingBuffer === false) context.clear(context.COLOR_BUFFER_BIT); 24266 } 24267 createImageBitmap(canvas).then((bitmap) => { 24268 this.worker?.postMessage({ 24269 id, 24270 bitmap, 24271 width: canvas.width, 24272 height: canvas.height, 24273 dataURLOptions, 24274 maxCanvasSize 24275 }, [bitmap]); 24276 }).catch((error) => { 24277 callbackWrapper(() => { 24278 this.snapshotInProgressMap.delete(id); 24279 throw error; 24280 })(); 24281 }); 24282 }); 24283 return true; 24284 } 24285 startPendingCanvasMutationFlusher() { 24286 onRequestAnimationFrame(() => this.flushPendingCanvasMutations()); 24287 } 24288 startRAFTimestamping() { 24289 const setLatestRAFTimestamp = (timestamp) => { 24290 this.rafStamps.latestId = timestamp; 24291 onRequestAnimationFrame(setLatestRAFTimestamp); 24292 }; 24293 onRequestAnimationFrame(setLatestRAFTimestamp); 24294 } 24295 flushPendingCanvasMutations() { 24296 this.pendingCanvasMutations.forEach((_values, canvas) => { 24297 const id = this.mirror.getId(canvas); 24298 this.flushPendingCanvasMutationFor(canvas, id); 24299 }); 24300 onRequestAnimationFrame(() => this.flushPendingCanvasMutations()); 24301 } 24302 flushPendingCanvasMutationFor(canvas, id) { 24303 if (this.frozen || this.locked) return; 24304 const valuesWithType = this.pendingCanvasMutations.get(canvas); 24305 if (!valuesWithType || id === -1) return; 24306 const values = valuesWithType.map((value) => { 24307 const { type: type2, ...rest } = value; 24308 return rest; 24309 }); 24310 const { type }
24310 = valuesWithType[0]; 24311 this.mutationCb({ 24312 id, 24313 type, 24314 commands: values 24315 }); 24316 this.pendingCanvasMutations.delete(canvas); 24317 } 24318 }; 24319 try { 24320 if (Array.from([1], (x) => x * 2)[0] !== 2) { 24321 const cleanFrame = document.createElement("iframe"); 24322 document.body.appendChild(cleanFrame); 24323 Array.from = cleanFrame.contentWindow?.Array.from || Array.from; 24324 document.body.removeChild(cleanFrame); 24325 } 24326 } catch (err) { 24327 console.debug("Unable to override Array.from", err); 24328 } 24329 createMirror(); 24330 (function(t2) { 24331 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped"; 24332 })(n || (n = {})); 24333 CANVAS_QUALITY = { 24334 low: { 24335 sampling: { canvas: 1 }, 24336 dataURLOptions: { 24337 type: "image/webp", 24338 quality: .25 24339 } 24340 }, 24341 medium: { 24342 sampling: { canvas: 2 }, 24343 dataURLOptions: { 24344 type: "image/webp", 24345 quality: .4 24346 } 24347 }, 24348 high: { 24349 sampling: { canvas: 4 }, 24350 dataURLOptions: { 24351 type: "image/webp", 24352 quality: .5 24353 } 24354 } 24355 }; 24356 INTEGRATION_NAME$3 = "ReplayCanvas"; 24357 DEFAULT_MAX_CANVAS_SIZE = 1280; 24358 _replayCanvasIntegration = ((options = {}) => { 24359 const [maxCanvasWidth, maxCanvasHeight] = options.maxCanvasSize || []; 24360 const _canvasOptions = { 24361 quality: options.quality || "medium", 24362 enableManualSnapshot: options.enableManualSnapshot, 24363 maxCanvasSize: [maxCanvasWidth ? Math.min(maxCanvasWidth, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE, maxCanvasHeight ? Math.min(maxCanvasHeight, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE] 24364 }; 24365 let currentCanvasManager; 24366 let canvasManagerResolve; 24367 const _canvasManager = new Promise((resolve) => canvasManagerResolve = resolve); 24368 return { 24369 name: INTEGRATION_NAME$3, 24370 getOptions() { 24371 const { quality, enableManualSnapshot, maxCanvasSize } = _canvasOptions; 24372 return { 24373 enableManualSnapshot, 24374 recordCanvas: true, 24375 getCanvasManager: (getCanvasManagerOptions) => { 24376 const manager = new CanvasManager({ 24377 ...getCanvasManagerOptions, 24378 enableManualSnapshot, 24379 maxCanvasSize, 24380 errorHandler: (err) => { 24381 try { 24382 if (typeof err === "object") err.__rrweb__ = true; 24383 } catch {} 24384 } 24385 }); 24386 currentCanvasManager = manager; 24387 canvasManagerResolve(manager); 24388 return manager; 24389 }, 24390 ...CANVAS_QUALITY[quality] || CANVAS_QUALITY.medium 24391 }; 24392 }, 24393 async snapshot(canvasElement, options2) { 24394 (currentCanvasManager || await _canvasManager).snapshot(canvasElement, options2); 24395 } 24396 }; 24397 }); 24398 replayCanvasIntegration = defineIntegration(_replayCanvasIntegration); 24399 })))(); 24400} 24401//#endregion 24402//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/utils.js 24403function baggageHeaderHasSentryValues(baggageHeader) { 24404 return baggageHeader.split(",").some((value) => value.trim().startsWith("sentry-")); 24405} 24406function getFullURL(url) { 24407 try { 24408 return new URL(url, WINDOW$4.location.origin).href; 24409 } catch { 24410 return; 24411 } 24412} 24413function isPerformanceResourceTiming(entry) { 24414 return entry.entryType === "resource" && "initiatorType" in entry && typeof entry.nextHopProtocol === "string" && (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest"); 24415} 24416function createHeadersSafely(headers) { 24417 try { 24418 return new Headers(headers); 24419 } catch { 24420 return; 24421 } 24422} 24423function init_utils$9() { 24424 return (init_utils$9 = __esmMin((() => { 24425 init_helpers(); 24426 })))(); 24427} 24428//#endregion 24429//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/request.js 24430function instrumentOutgoingRequests(client, _options) { 24431 const { traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, tracePropagationTargets, onRequestSpanStart, onRequestSpanEnd } = { 24432 ...defaultRequestInstrumentationOptions, 24433 ..._options 24434 }; 24435 const shouldCreateSpan = typeof shouldCreateSpanForRequest === "function" ? shouldCreateSpanForRequest : (_) => true; 24436 const shouldAttachHeadersWithTargets = (url) => shouldAttachHeaders(url, tracePropagationTargets); 24437 const spans = {}; 24438 const propagateTraceparent = client.getOptions().propagateTraceparent; 24439 if (traceFetch) addFetchInstrumentationHandler((handlerData) => { 24440 const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, { 24441 propagateTraceparent, 24442 onRequestSpanEnd 24443 }); 24444 if (createdSpan) { 24445 const fullUrl = getFullURL(handlerData.fetchData.url); 24446 const host = fullUrl ? parseUrl(fullUrl).host : void 0;
24447 const sanitizedFullUrl = fullUrl ? stripDataUrlContent(fullUrl) : void 0; 24448 createdSpan.setAttributes({ 24449 [ws]: sanitizedFullUrl, 24450 [Yu]: sanitizedFullUrl, 24451 "server.address": host 24452 }); 24453 if (enableHTTPTimings) addHTTPTimings(createdSpan, client); 24454 onRequestSpanStart?.(createdSpan, { headers: handlerData.headers }); 24455 } 24456 }); 24457 if (traceXHR) addXhrInstrumentationHandler((handlerData) => { 24458 const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent, onRequestSpanEnd); 24459 if (createdSpan) { 24460 if (enableHTTPTimings) addHTTPTimings(createdSpan, client); 24461 onRequestSpanStart?.(createdSpan, { headers: createHeadersSafely(handlerData.xhr.__sentry_xhr_v3__?.request_headers) }); 24462 } 24463 }); 24464} 24465function addHTTPTimings(span, client) { 24466 const { url } = spanToJSON(span).data; 24467 if (!url || typeof url !== "string") return; 24468 let onEntryFound = () => void setTimeout(unsubscribePerformanceObsever); 24469 if (hasSpanStreamingEnabled(client)) { 24470 const originalEnd = span.end.bind(span); 24471 span.end = (endTimestamp) => { 24472 const capturedEndTimestamp = endTimestamp ?? timestampInSeconds(); 24473 let isEnded = false; 24474 const endSpanAndCleanup = () => { 24475 if (isEnded) return; 24476 isEnded = true; 24477 setTimeout(unsubscribePerformanceObsever); 24478 originalEnd(capturedEndTimestamp); 24479 clearTimeout(fallbackTimeout); 24480 }; 24481 onEntryFound = endSpanAndCleanup; 24482 const fallbackTimeout = setTimeout(endSpanAndCleanup, HTTP_TIMING_WAIT_MS); 24483 }; 24484 } 24485 const unsubscribePerformanceObsever = addPerformanceInstrumentationHandler("resource", ({ entries }) => { 24486 entries.forEach((entry) => { 24487 if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) { 24488 span.setAttributes(resourceTimingToSpanAttributes(entry)); 24489 onEntryFound(); 24490 } 24491 }); 24492 }); 24493} 24494function shouldAttachHeaders(targetUrl, tracePropagationTargets) { 24495 const href = getLocationHref(); 24496 if (!href) { 24497 const isRelativeSameOriginRequest = !!targetUrl.match(/^\/(?!\/)/); 24498 if (!tracePropagationTargets) return isRelativeSameOriginRequest; 24499 else return stringMatchesSomePattern(targetUrl, tracePropagationTargets); 24500 } else { 24501 let resolvedUrl; 24502 let currentOrigin; 24503 try { 24504 resolvedUrl = new URL(targetUrl, href); 24505 currentOrigin = new URL(href).origin; 24506 } catch { 24507 return false; 24508 } 24509 const isSameOriginRequest = resolvedUrl.origin === currentOrigin; 24510 if (!tracePropagationTargets) return isSameOriginRequest; 24511 else return stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) || isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets); 24512 } 24513} 24514function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans, propagateTraceparent, onRequestSpanEnd) { 24515 const xhr = handlerData.xhr; 24516 const sentryXhrData = xhr?.[SENTRY_XHR_DATA_KEY]; 24517 if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) return; 24518 const { url, method } = sentryXhrData; 24519 const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(url); 24520 if (handlerData.endTimestamp) { 24521 const spanId = xhr.__sentry_xhr_span_id__; 24522 if (!spanId) return; 24523 const span2 = spans[spanId]; 24524 if (span2) { 24525 if (shouldCreateSpanResult && sentryXhrData.status_code !== void 0) { 24526 setHttpStatus(span2, sentryXhrData.status_code); 24527 span2.end(); 24528 onRequestSpanEnd?.(span2, { 24529 headers: createHeadersSafely(parseXhrResponseHeaders(xhr)), 24530 error: handlerData.error 24531 }); 24532 } 24533 delete spans[spanId]; 24534 } 24535 return; 24536 } 24537 const fullUrl = getFullURL(url); 24538 const parsedUrl = fullUrl ? parseUrl(fullUrl) : parseUrl(url); 24539 const sanitizedFullUrl = fullUrl ? stripDataUrlContent(fullUrl) : void 0; 24540 const urlForSpanName = stripDataUrlContent(stripUrlQueryAndFragment(url)); 24541 const client = getClient(); 24542 const hasParent = !!getActiveSpan(); 24543 const shouldEmitSpan = hasParent || !!client && hasSpanStreamingEnabled(client); 24544 const span = shouldCreateSpanResult && shouldEmitSpan ? startInactiveSpan({ 24545 name: `${method} ${urlForSpanName}`, 24546 attributes: { 24547 url: stripDataUrlContent(url), 24548 type: "xhr", 24549 "http.method": method, 24550 "http.url": sanitizedFullUrl, 24551 [Yu]: sanitizedFullUrl, 24552 "server.address": parsedUrl?.host, 24553 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser", 24554 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client", 24555 ...parsedUrl?.search && { "http.query": parsedUrl?.search }, 24556 ...parsedUrl?.hash && { "http.fragment": parsedUrl?.hash } 24557 } 24558 }) : new SentryNonRecordingSpan(); 24559 const spanForTraceHeaders = spanIsIgnored(span) && hasParent ? void 0 : span; 24560 if (shouldCreateSpanResult && !shouldEmitSpan) client?.recordDroppedEvent("no_parent_span", "span"); 24561 xhr.__sentry_xhr_span_id__ = span.spanContext().spanId; 24562 spans[xhr.__sentry_xhr_span_id__] = span; 24563 if (shouldAttachHeaders2(url)) addTracingHeadersToXhrRequest(xhr, hasSpansEnabled() && shouldEmitSpan ? spanForTraceHeaders : void 0, propagateTraceparent); 24564 if (client) client.emit("beforeOutgoingRequestSpan", span, handlerData); 24565 return span; 24566} 24567function addTracingHeadersToXhrRequest(xhr, span, propagateTraceparent) { 24568 const { "sentry-trace": sentryTrace, baggage, traceparent } = getTraceData({ 24569 span,
24570 propagateTraceparent 24571 }); 24572 if (sentryTrace) setHeaderOnXhr(xhr, sentryTrace, baggage, traceparent); 24573} 24574function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader, traceparentHeader) { 24575 const originalHeaders = xhr.__sentry_xhr_v3__?.request_headers; 24576 if (originalHeaders?.["sentry-trace"] || !xhr.setRequestHeader) return; 24577 try { 24578 xhr.setRequestHeader("sentry-trace", sentryTraceHeader); 24579 if (traceparentHeader && !originalHeaders?.["traceparent"]) xhr.setRequestHeader("traceparent", traceparentHeader); 24580 if (sentryBaggageHeader) { 24581 const originalBaggageHeader = originalHeaders?.["baggage"]; 24582 if (!originalBaggageHeader || !baggageHeaderHasSentryValues(originalBaggageHeader)) xhr.setRequestHeader("baggage", sentryBaggageHeader); 24583 } 24584 } catch {} 24585} 24586var defaultRequestInstrumentationOptions, HTTP_TIMING_WAIT_MS; 24587function init_request() { 24588 return (init_request = __esmMin((() => { 24589 init_fetch$1(), init_fetch(), init_url(), init_spanUtils(), init_time(), init_hasSpansEnabled(), init_spanstatus(), init_currentScopes(), init_trace(), init_semanticAttributes(), init_sentryNonRecordingSpan(), init_browser(), init_string(), init_traceData(); 24590 init_xhr(), init_instrument(), init_resourceTiming(), init_networkUtils(); 24591 init_utils$9(); 24592 init_attributes$1(); 24593 defaultRequestInstrumentationOptions = { 24594 traceFetch: true, 24595 traceXHR: true, 24596 enableHTTPTimings: true, 24597 trackFetchStreamPerformance: false 24598 }; 24599 HTTP_TIMING_WAIT_MS = 300; 24600 })))(); 24601} 24602//#endregion 24603//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/fetchStreamPerformance.js 24604var responseToStreamSpan, responseToFallbackTimeout, STREAM_RESOLVE_FALLBACK_MS, STREAMING_CONTENT_TYPES, fetchStreamPerformanceIntegration; 24605function init_fetchStreamPerformance() { 24606 return (init_fetchStreamPerformance = __esmMin((() => { 24607 init_integration(), init_fetch$1(), init_url(), init_trace(), init_semanticAttributes(); 24608 responseToStreamSpan = /* @__PURE__ */ new WeakMap(); 24609 responseToFallbackTimeout = /* @__PURE__ */ new WeakMap(); 24610 STREAM_RESOLVE_FALLBACK_MS = 9e4; 24611 STREAMING_CONTENT_TYPES = [ 24612 "text/event-stream", 24613 "application/x-ndjson", 24614 "application/stream+json" 24615 ]; 24616 fetchStreamPerformanceIntegration = defineIntegration(() => { 24617 return { 24618 name: "FetchStreamPerformance", 24619 setup() { 24620 addFetchEndInstrumentationHandler((handlerData) => { 24621 if (handlerData.response) { 24622 const streamSpan = responseToStreamSpan.get(handlerData.response); 24623 if (streamSpan && handlerData.endTimestamp) { 24624 streamSpan.end(handlerData.endTimestamp); 24625 const fallbackTimeout = responseToFallbackTimeout.get(handlerData.response); 24626 if (fallbackTimeout) clearTimeout(fallbackTimeout); 24627 } 24628 } 24629 }); 24630 addFetchInstrumentationHandler((handlerData) => { 24631 if (handlerData.endTimestamp && handlerData.response) { 24632 const contentType = handlerData.response.headers?.get("content-type") || ""; 24633 if (handlerData.response.headers?.get("content-length") || !STREAMING_CONTENT_TYPES.some((t) => contentType.startsWith(t))) return; 24634 const url = handlerData.fetchData?.url || ""; 24635 const method = handlerData.fetchData?.method || "GET"; 24636 const parsedUrl = parseStringToURLObject(url); 24637 const streamSpan = startInactiveSpan({ 24638 name: `${method} ${url.startsWith("data:") ? stripDataUrlContent(url) : parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url}`, 24639 startTime: handlerData.endTimestamp, 24640 attributes: { 24641 url: stripDataUrlContent(url), 24642 "http.method": method, 24643 type: "fetch", 24644 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client.stream", 24645 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.stream" 24646 } 24647 }); 24648 responseToStreamSpan.set(handlerData.response, streamSpan); 24649 const fallbackTimeout = setTimeout(() => { 24650 if (streamSpan.isRecording()) streamSpan.end(); 24651 }, STREAM_RESOLVE_FALLBACK_MS); 24652 responseToFallbackTimeout.set(handlerData.response, fallbackTimeout); 24653 } 24654 }); 24655 } 24656 }; 24657 }); 24658 })))(); 24659} 24660//#endregion 24661//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/webVitals.js 24662var WEB_VITALS_INTEGRATION_NAME, webVitalsIntegration; 24663function init_webVitals() { 24664 return (init_webVitals = __esmMin((() => { 24665 init_integration(); 24666 init_inp(), init_browserMetrics(), init_webVitalSpans(); 24667 WEB_VITALS_INTEGRATION_NAME = "WebVitals"; 24668 webVitalsIntegration = defineIntegration((options = {}) => { 24669 const ignored = new Set(options.ignore ?? []); 24670 return { 24671 name: WEB_VITALS_INTEGRATION_NAME, 24672 setup(client) { 24673 const spanStreamingEnabled = hasSpanStreamingEnabled(client); 24674 const { enableStandaloneClsSpans, enableStandaloneLcpSpans } = options._experiments ?? {}; 24675 const recordClsStandaloneSpans = spanStreamingEnabled || ignored.has("cls") ? void 0 : enableStandaloneClsSpans || false; 24676 const recordLcpStandaloneSpans = spanStreamingEnabled || ignored.has("lcp") ? void 0 : enableStandaloneLcpSpans || false; 24677 const finalizeWebVitals = startTrackingWebVitals({ 24678 recordClsStandaloneSpans, 24679 recordLcpStandaloneSpans, 24680 client 24681 }); 24682 const pageloadSpans = /* @__PURE__ */ new WeakSet(); 24683 client.on("afterStartPageLoadSpan", (span) => { 24684 pageloadSpans.add(span); 24685 }); 24686 client.on("spanEnd", (span) => { 24687 if (!pageloadSpans.delete(span)) return; 24688 finalizeWebVitals(); 24689 addWebVitalsToSpan(span, { 24690 recordClsOnPageloadSpan: recordClsStandaloneSpans === false, 24691 recordLcpOnPageloadSpan: recordLcpStandaloneSpans === false, 24692 spanStreamingEnabled 24693 }); 24694 }); 24695 if (spanStreamingEnabled) { 24696 if (!ignored.has("lcp")) trackLcpAsSpan(client); 24697 if (!ignored.has("cls")) trackClsAsSpan(client); 24698 if (!ignored.has("inp")) trackInpAsSpan(); 24699 } else if (!ignored.has("inp")) startTrackingINP(); 24700 }, 24701 afterAllSetup() { 24702 if (!ignored.has("inp")) registerInpInteractionListener(); 24703 } 24704 }; 24705 }); 24706 })))(); 24707} 24708//#endregion 24709//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/backgroundtab.js
24710function registerBackgroundTabDetection() { 24711 if (WINDOW$4.document) WINDOW$4.document.addEventListener("visibilitychange", () => { 24712 const activeSpan = getActiveSpan(); 24713 if (!activeSpan) return; 24714 const rootSpan = getRootSpan(activeSpan); 24715 if (WINDOW$4.document.hidden && rootSpan) { 24716 const cancelledStatus = "cancelled"; 24717 const { op, status } = spanToJSON(rootSpan); 24718 if (DEBUG_BUILD$2) debug$2.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`); 24719 if (!status) rootSpan.setStatus({ 24720 code: 2, 24721 message: cancelledStatus 24722 }); 24723 rootSpan.setAttribute("sentry.cancellation_reason", "document.hidden"); 24724 rootSpan.end(); 24725 } 24726 }); 24727 else DEBUG_BUILD$2 && debug$2.warn("[Tracing] Could not set up background tab detection due to lack of global document"); 24728} 24729function init_backgroundtab() { 24730 return (init_backgroundtab = __esmMin((() => { 24731 init_spanUtils(), init_debug_logger(), init_spanstatus(); 24732 init_debug_build$2(); 24733 init_helpers(); 24734 })))(); 24735} 24736//#endregion 24737//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/linkedTraces.js 24738function linkTraces(client, { linkPreviousTrace, consistentTraceSampling }) { 24739 const useSessionStorage = linkPreviousTrace === "session-storage"; 24740 let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : void 0; 24741 client.on("spanStart", (span) => { 24742 if (getRootSpan(span) !== span) return; 24743 const oldPropagationContext = getCurrentScope().getPropagationContext(); 24744 inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext); 24745 if (useSessionStorage) storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo); 24746 }); 24747 let isFirstTraceOnPageload = true; 24748 if (consistentTraceSampling) client.on("beforeSampling", (mutableSamplingContextData) => { 24749 if (!inMemoryPreviousTraceInfo) return; 24750 const scope = getCurrentScope(); 24751 const currentPropagationContext = scope.getPropagationContext(); 24752 if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) { 24753 isFirstTraceOnPageload = false; 24754 return; 24755 } 24756 scope.setPropagationContext({ 24757 ...currentPropagationContext, 24758 dsc: { 24759 ...currentPropagationContext.dsc,
24760 sample_rate: String(inMemoryPreviousTraceInfo.sampleRate), 24761 sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)) 24762 }, 24763 sampleRand: inMemoryPreviousTraceInfo.sampleRand 24764 }); 24765 mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext); 24766 mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate; 24767 mutableSamplingContextData.spanAttributes = { 24768 ...mutableSamplingContextData.spanAttributes, 24769 [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate 24770 }; 24771 }); 24772} 24773function addPreviousTraceSpanLink(previousTraceInfo, span, oldPropagationContext) { 24774 const spanJson = spanToJSON(span); 24775 function getSampleRate() { 24776 try { 24777 const oldSampleRate = Number(spanJson.data?.["sentry.sample_rate"] ?? oldPropagationContext.dsc?.sample_rate); 24778 return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate; 24779 } catch { 24780 return 0; 24781 } 24782 } 24783 const updatedPreviousTraceInfo = { 24784 spanContext: span.spanContext(), 24785 startTimestamp: spanJson.start_timestamp, 24786 sampleRate: getSampleRate(), 24787 sampleRand: oldPropagationContext.sampleRand 24788 }; 24789 if (!previousTraceInfo) return updatedPreviousTraceInfo; 24790 const previousTraceSpanCtx = previousTraceInfo.spanContext; 24791 if (previousTraceSpanCtx.traceId === spanJson.trace_id) return previousTraceInfo; 24792 if (Date.now() / 1e3 - previousTraceInfo.startTimestamp <= 3600) { 24793 if (DEBUG_BUILD$2) debug$2.log(`Adding previous_trace \`${JSON.stringify(previousTraceSpanCtx)}\` link to span \`${JSON.stringify({ 24794 op: spanJson.op, 24795 ...span.spanContext() 24796 })}\``); 24797 span.addLink({ 24798 context: previousTraceSpanCtx, 24799 attributes: { [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: "previous_trace" } 24800 }); 24801 span.setAttribute(PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE, `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${spanContextSampled(previousTraceSpanCtx) ? 1 : 0}`); 24802 } 24803 return updatedPreviousTraceInfo; 24804} 24805function storePreviousTraceInSessionStorage(previousTraceInfo) { 24806 try { 24807 WINDOW$4.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo)); 24808 } catch (e) { 24809 DEBUG_BUILD$2 && debug$2.warn("Could not store previous trace in sessionStorage", e); 24810 } 24811} 24812function getPreviousTraceFromSessionStorage() { 24813 try { 24814 const previousTraceInfo = WINDOW$4.sessionStorage?.getItem(PREVIOUS_TRACE_KEY); 24815 return JSON.parse(previousTraceInfo); 24816 } catch { 24817 return; 24818 } 24819} 24820function spanContextSampled(ctx) { 24821 return ctx.traceFlags === 1; 24822} 24823var PREVIOUS_TRACE_KEY, PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE; 24824function init_linkedTraces() { 24825 return (init_linkedTraces = __esmMin((() => { 24826 init_spanUtils(), init_currentScopes(), init_semanticAttributes(), init_debug_logger(); 24827 init_debug_build$2(); 24828 init_helpers(); 24829 PREVIOUS_TRACE_KEY = "sentry_previous_trace"; 24830 PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = "sentry.previous_trace"; 24831 })))(); 24832} 24833//#endregion 24834//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/browserTracingIntegration.js 24835function isBotUserAgent() { 24836 const nav = WINDOW$4.navigator; 24837 if (!nav?.userAgent) return false; 24838 return BOT_USER_AGENT_RE.test(nav.userAgent); 24839} 24840function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) { 24841 client.emit("startPageLoadSpan", spanOptions, traceOptions); 24842 getCurrentScope().setTransactionName(spanOptions.name); 24843 const pageloadSpan = getActiveIdleSpan(client); 24844 if (pageloadSpan) client.emit("afterStartPageLoadSpan", pageloadSpan); 24845 return pageloadSpan; 24846} 24847function startBrowserTracingNavigationSpan(client, spanOptions, options) { 24848 const { url, isRedirect: isRedirect2 } = options || {}; 24849 client.emit("beforeStartNavigationSpan", spanOptions, { 24850 isRedirect: isRedirect2, 24851 url 24852 }); 24853 client.emit("startNavigationSpan", spanOptions, { 24854 isRedirect: isRedirect2, 24855 url 24856 }); 24857 const scope = getCurrentScope(); 24858 scope.setTransactionName(spanOptions.name); 24859 if (url && !isRedirect2) scope.setSDKProcessingMetadata({ normalizedRequest: { 24860 ...getHttpRequestData(), 24861 url 24862 } }); 24863 return getActiveIdleSpan(client); 24864} 24865function getMetaContent(metaName) { 24866 return (WINDOW$4.document?.querySelector(`meta[name=${metaName}]`))?.getAttribute("content") || void 0; 24867} 24868function getServerTiming(name) { 24869 return ((WINDOW$4.performance?.getEntriesByType?.("navigation")[0])?.serverTiming?.find((entry2) => entry2.name === name))?.description; 24870} 24871function registerInteractionListener(client, idleTimeout, finalTimeout, childSpanTimeout, latestRoute) { 24872 const optionalWindowDocument = WINDOW$4.document; 24873 let inflightInteractionSpan; 24874 const registerInteractionTransaction = () => { 24875 const op = "ui.action.click"; 24876 const activeIdleSpan = getActiveIdleSpan(client); 24877 if (activeIdleSpan) { 24878 const currentRootSpanOp = spanToJSON(activeIdleSpan).op; 24879 if (["navigation", "pageload"].includes(currentRootSpanOp)) { 24880 DEBUG_BUILD$2 && debug$2.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`); 24881 return; 24882 } 24883 } 24884 if (inflightInteractionSpan) { 24885 inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "interactionInterrupted"); 24886 inflightInteractionSpan.end(); 24887 inflightInteractionSpan = void 0; 24888 } 24889 if (!latestRoute.name) { 24890 DEBUG_BUILD$2 && debug$2.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`); 24891 return; 24892 } 24893 inflightInteractionSpan = startIdleSpan({ 24894 name: latestRoute.name, 24895 op, 24896 attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || "url" } 24897 }, { 24898 idleTimeout, 24899 finalTimeout, 24900 childSpanTimeout 24901 }); 24902 }; 24903 if (optionalWindowDocument) addEventListener("click", registerInteractionTransaction, { capture: true }); 24904} 24905function getActiveIdleSpan(client) { 24906 return client[ACTIVE_IDLE_SPAN_PROPERTY]; 24907} 24908function setActiveIdleSpan(client, span) {
24909 addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span); 24910} 24911function isRedirect(activeSpan, lastInteractionTimestamp) { 24912 const spanData = spanToJSON(activeSpan); 24913 const now = dateTimestampInSeconds(); 24914 if (now - spanData.start_timestamp > REDIRECT_THRESHOLD) return false; 24915 if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) return false; 24916 return true; 24917} 24918var BROWSER_TRACING_INTEGRATION_ID, BOT_USER_AGENT_RE, DEFAULT_BROWSER_TRACING_OPTIONS, browserTracingIntegration, ACTIVE_IDLE_SPAN_PROPERTY, REDIRECT_THRESHOLD; 24919function init_browserTracingIntegration() { 24920 return (init_browserTracingIntegration = __esmMin((() => { 24921 init_idleSpan(), init_debug_logger(), init_browser(), init_time(), init_url(), init_errors(), init_worldwide(), init_currentScopes(), init_hasSpansEnabled(), init_propagationContext(), init_tracing(), init_spanUtils(), init_trace(), init_semanticAttributes(), init_dynamicSamplingContext(), init_object(); 24922 init_history(), init_browserMetrics(); 24923 init_debug_build$2(); 24924 init_helpers(); 24925 init_fetchStreamPerformance(); 24926 init_webVitals(); 24927 init_backgroundtab(); 24928 init_linkedTraces(); 24929 init_request(); 24930 init_attributes$1(); 24931 BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing"; 24932 BOT_USER_AGENT_RE = /Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i; 24933 DEFAULT_BROWSER_TRACING_OPTIONS = { 24934 ...TRACING_DEFAULTS, 24935 instrumentNavigation: true, 24936 instrumentPageLoad: true, 24937 markBackgroundSpan: true, 24938 enableLongTask: true, 24939 enableLongAnimationFrame: true, 24940 enableInp: true, 24941 ignoreResourceSpans: [], 24942 ignorePerformanceApiSpans: [], 24943 detectRedirects: true, 24944 linkPreviousTrace: "in-memory", 24945 consistentTraceSampling: false, 24946 enableReportPageLoaded: false, 24947 _experiments: {}, 24948 ...defaultRequestInstrumentationOptions 24949 }; 24950 browserTracingIntegration = ((options = {}) => { 24951 if ("enableElementTiming" in options) consoleSandbox(() => { 24952 console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead."); 24953 }); 24954 const latestRoute = { 24955 name: void 0, 24956 source: void 0 24957 }; 24958 const optionalWindowDocument = WINDOW$4.document; 24959 const { enableInp, enableLongTask, enableLongAnimationFrame, _experiments: { enableInteractions, enableStandaloneClsSpans, enableStandaloneLcpSpans }, beforeStartSpan, idleTimeout, finalTimeout, childSpanTimeout, markBackgroundSpan, traceFetch, traceXHR, trackFetchStreamPerformance, shouldCreateSpanForRequest, enableHTTPTimings, ignoreResourceSpans, ignorePerformanceApiSpans, instrumentPageLoad, instrumentNavigation, detectRedirects, linkPreviousTrace, consistentTraceSampling, enableReportPageLoaded, onRequestSpanStart, onRequestSpanEnd } = { 24960 ...DEFAULT_BROWSER_TRACING_OPTIONS, 24961 ...options 24962 }; 24963 const _isBot = isBotUserAgent(); 24964 let lastInteractionTimestamp; 24965 let _pageloadSpan; 24966 function _createRouteSpan(client, startSpanOptions, makeActive = true, url) { 24967 const isPageloadSpan = startSpanOptions.op === "pageload"; 24968 const initialSpanName = startSpanOptions.name; 24969 const finalStartSpanOptions = beforeStartSpan ? beforeStartSpan(startSpanOptions) : startSpanOptions; 24970 const urlObject = parseStringToURLObject(url || getLocationHref()); 24971 const attributes = { 24972 ...urlObject?.pathname && { ["url.path"]: urlObject.pathname }, 24973 ...urlObject && !isURLObjectRelative(urlObject) && { ["url.full"]: urlObject.href }, 24974 ...finalStartSpanOptions.attributes 24975 }; 24976 if (initialSpanName !== finalStartSpanOptions.name) attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = "custom"; 24977 finalStartSpanOptions.attributes = attributes; 24978 if (!makeActive) { 24979 const now = dateTimestampInSeconds(); 24980 startInactiveSpan({ 24981 ...finalStartSpanOptions, 24982 startTime: now 24983 }).end(now); 24984 return; 24985 } 24986 latestRoute.name = finalStartSpanOptions.name; 24987 latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 24988 const idleSpan = startIdleSpan(finalStartSpanOptions, { 24989 idleTimeout, 24990 finalTimeout, 24991 childSpanTimeout, 24992 disableAutoFinish: isPageloadSpan, 24993 beforeSpanEnd: (span) => { 24994 addPerformanceEntries(span, { 24995 ignoreResourceSpans, 24996 ignorePerformanceApiSpans, 24997 spanStreamingEnabled: hasSpanStreamingEnabled(client) 24998 }); 24999 setActiveIdleSpan(client, void 0); 25000 const scope = getCurrentScope(); 25001 const oldPropagationContext = scope.getPropagationContext(); 25002 scope.setPropagationContext({ 25003 ...oldPropagationContext, 25004 traceId: idleSpan.spanContext().traceId, 25005 sampled: spanIsSampled(idleSpan), 25006 dsc: getDynamicSamplingContextFromSpan(span) 25007 }); 25008 if (isPageloadSpan) _pageloadSpan = void 0; 25009 }, 25010 trimIdleSpanEndTimestamp: !enableReportPageLoaded 25011 }); 25012 if (isPageloadSpan && enableReportPageLoaded) _pageloadSpan = idleSpan;
25013 setActiveIdleSpan(client, idleSpan); 25014 function emitFinish() { 25015 if (optionalWindowDocument && ["interactive", "complete"].includes(optionalWindowDocument.readyState)) { 25016 client.emit("idleSpanEnableAutoFinish", idleSpan); 25017 optionalWindowDocument.removeEventListener("readystatechange", emitFinish); 25018 } 25019 } 25020 if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) { 25021 optionalWindowDocument.addEventListener("readystatechange", emitFinish); 25022 emitFinish(); 25023 } 25024 } 25025 return { 25026 name: BROWSER_TRACING_INTEGRATION_ID, 25027 setup(client) { 25028 if (_isBot) { 25029 DEBUG_BUILD$2 && debug$2.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent."); 25030 return; 25031 } 25032 registerSpanErrorInstrumentation(); 25033 if (enableLongAnimationFrame && GLOBAL_OBJ.PerformanceObserver && PerformanceObserver.supportedEntryTypes?.includes("long-animation-frame")) startTrackingLongAnimationFrames(); 25034 else if (enableLongTask) startTrackingLongTasks(); 25035 if (enableInteractions) startTrackingInteractions(); 25036 if (detectRedirects && optionalWindowDocument) { 25037 const interactionHandler = () => { 25038 lastInteractionTimestamp = timestampInSeconds(); 25039 }; 25040 addEventListener("click", interactionHandler, { capture: true }); 25041 addEventListener("keydown", interactionHandler, { 25042 capture: true, 25043 passive: true 25044 }); 25045 } 25046 function maybeEndActiveSpan() { 25047 const activeSpan = getActiveIdleSpan(client); 25048 if (activeSpan && !spanToJSON(activeSpan).timestamp) { 25049 DEBUG_BUILD$2 && debug$2.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`); 25050 activeSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "cancelled"); 25051 activeSpan.end(); 25052 } 25053 } 25054 client.on("startNavigationSpan", (startSpanOptions, navigationOptions) => { 25055 if (getClient() !== client) return; 25056 if (navigationOptions?.isRedirect) { 25057 DEBUG_BUILD$2 && debug$2.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span."); 25058 _createRouteSpan(client, { 25059 op: "navigation.redirect", 25060 ...startSpanOptions 25061 }, false, navigationOptions.url); 25062 return; 25063 } 25064 lastInteractionTimestamp = void 0; 25065 maybeEndActiveSpan(); 25066 const scope = getCurrentScope(); 25067 scope.setPropagationContext({ 25068 traceId: generateTraceId(), 25069 sampleRand: Math.random(), 25070 propagationSpanId: hasSpansEnabled() ? void 0 : generateSpanId() 25071 }); 25072 scope.setSDKProcessingMetadata({ normalizedRequest: void 0 }); 25073 _createRouteSpan(client, { 25074 op: "navigation", 25075 ...startSpanOptions, 25076 parentSpan: null, 25077 forceTransaction: true 25078 }, true, navigationOptions?.url); 25079 }); 25080 client.on("startPageLoadSpan", (startSpanOptions, traceOptions = {}) => { 25081 if (getClient() !== client) return; 25082 maybeEndActiveSpan(); 25083 const propagationContext = propagationContextFromHeaders(traceOptions.sentryTrace || getMetaContent("sentry-trace") || getServerTiming("sentry-trace"), traceOptions.baggage || getMetaContent("baggage") || getServerTiming("baggage")); 25084 const scope = getCurrentScope(); 25085 scope.setPropagationContext(propagationContext); 25086 if (!hasSpansEnabled()) scope.getPropagationContext().propagationSpanId = generateSpanId(); 25087 scope.setSDKProcessingMetadata({ normalizedRequest: getHttpRequestData() }); 25088 _createRouteSpan(client, { 25089 op: "pageload", 25090 ...startSpanOptions 25091 }); 25092 }); 25093 client.on("endPageloadSpan", () => { 25094 if (enableReportPageLoaded && _pageloadSpan) { 25095 _pageloadSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "reportPageLoaded"); 25096 _pageloadSpan.end(); 25097 } 25098 }); 25099 }, 25100 afterAllSetup(client) { 25101 if (_isBot) return; 25102 if (client.addIntegration && !client.getIntegrationByName?.("WebVitals")) client.addIntegration(webVitalsIntegration({ 25103 ignore: enableInp ? [] : ["inp"], 25104 _experiments: { 25105 enableStandaloneClsSpans, 25106 enableStandaloneLcpSpans 25107 } 25108 })); 25109 let startingUrl = getLocationHref(); 25110 if (linkPreviousTrace !== "off") linkTraces(client, { 25111 linkPreviousTrace, 25112 consistentTraceSampling 25113 }); 25114 if (WINDOW$4.location) { 25115 if (instrumentPageLoad) { 25116 const origin = browserPerformanceTimeOrigin(); 25117 startBrowserTracingPageLoadSpan(client, { 25118 name: WINDOW$4.location.pathname, 25119 startTime: origin ? origin / 1e3 : void 0, 25120 attributes: { 25121 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", 25122 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.browser" 25123 } 25124 }); 25125 } 25126 if (instrumentNavigation) addHistoryInstrumentationHandler(({ to, from }) => { 25127 if (from === void 0 && startingUrl?.indexOf(to) !== -1) { 25128 startingUrl = void 0; 25129 return; 25130 } 25131 startingUrl = void 0; 25132 const parsed = parseStringToURLObject(to); 25133 const activeSpan = getActiveIdleSpan(client); 25134 const navigationIsRedirect = activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp); 25135 startBrowserTracingNavigationSpan(client, { 25136 name: parsed?.pathname || WINDOW$4.location.pathname, 25137 attributes: { 25138 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", 25139 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.browser" 25140 } 25141 }, {
25142 url: to, 25143 isRedirect: navigationIsRedirect 25144 }); 25145 }); 25146 } 25147 if (markBackgroundSpan) registerBackgroundTabDetection(); 25148 if (enableInteractions) registerInteractionListener(client, idleTimeout, finalTimeout, childSpanTimeout, latestRoute); 25149 instrumentOutgoingRequests(client, { 25150 traceFetch, 25151 traceXHR, 25152 tracePropagationTargets: client.getOptions().tracePropagationTargets, 25153 shouldCreateSpanForRequest, 25154 enableHTTPTimings, 25155 onRequestSpanStart, 25156 onRequestSpanEnd 25157 }); 25158 if (trackFetchStreamPerformance) client.addIntegration(fetchStreamPerformanceIntegration()); 25159 } 25160 }; 25161 }); 25162 ACTIVE_IDLE_SPAN_PROPERTY = "_sentry_idleSpan"; 25163 REDIRECT_THRESHOLD = 1.5; 25164 })))(); 25165} 25166//#endregion 25167//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/reportPageLoaded.js 25168function reportPageLoaded(client = getClient()) { 25169 client?.emit("endPageloadSpan"); 25170} 25171function init_reportPageLoaded() { 25172 return (init_reportPageLoaded = __esmMin((() => { 25173 init_currentScopes(); 25174 })))(); 25175} 25176//#endregion 25177//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/tracing/setActiveSpan.js 25178function setActiveSpanInBrowser(span) { 25179 const maybePreviousActiveSpan = getActiveSpan(); 25180 if (maybePreviousActiveSpan === span) return; 25181 const scope = getCurrentScope(); 25182 span.end = new Proxy(span.end, { apply(target, thisArg, args) { 25183 _setSpanForScope(scope, maybePreviousActiveSpan); 25184 return Reflect.apply(target, thisArg, args); 25185 } }); 25186 _setSpanForScope(scope, span); 25187} 25188function init_setActiveSpan() { 25189 return (init_setActiveSpan = __esmMin((() => { 25190 init_spanUtils(), init_currentScopes(), init_spanOnScope(); 25191 })))(); 25192} 25193//#endregion 25194//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/spanstreaming.js 25195var spanStreamingIntegration; 25196function init_spanstreaming() { 25197 return (init_spanstreaming = __esmMin((() => { 25198 init_integration(), init_debug_logger(), init_beforeSendSpan(), init_spanBuffer(), init_spanUtils(), init_captureSpan(); 25199 init_debug_build$2(); 25200 spanStreamingIntegration = defineIntegration(() => { 25201 return { 25202 name: "SpanStreaming", 25203 beforeSetup(client) { 25204 const clientOptions = client.getOptions(); 25205 if (!clientOptions.traceLifecycle) { 25206 DEBUG_BUILD$2 && debug$2.log("[SpanStreaming] setting `traceLifecycle` to \"stream\""); 25207 clientOptions.traceLifecycle = "stream"; 25208 } 25209 }, 25210 setup(client) { 25211 const initialMessage = "SpanStreaming integration requires"; 25212 const fallbackMsg = "Falling back to static trace lifecycle."; 25213 const clientOptions = client.getOptions(); 25214 if (!hasSpanStreamingEnabled(client)) { 25215 clientOptions.traceLifecycle = "static"; 25216 DEBUG_BUILD$2 && debug$2.warn(`${initialMessage} \`traceLifecycle\` to be set to "stream"! ${fallbackMsg}`); 25217 return; 25218 } 25219 const beforeSendSpan = clientOptions.beforeSendSpan; 25220 if (beforeSendSpan && !isStreamedBeforeSendSpanCallback(beforeSendSpan)) { 25221 clientOptions.traceLifecycle = "static"; 25222 DEBUG_BUILD$2 && debug$2.warn(`${initialMessage} a beforeSendSpan callback using \`withStreamedSpan\`! ${fallbackMsg}`); 25223 return; 25224 } 25225 const buffer = new SpanBuffer(client); 25226 client.on("afterSpanEnd", (span) => { 25227 if (!spanIsSampled(span)) return; 25228 buffer.add(captureSpan(span, client)); 25229 }); 25230 client.on("afterSegmentSpanEnd", (segmentSpan) => { 25231 const traceId = segmentSpan.spanContext().traceId; 25232 setTimeout(() => { 25233 buffer.flush(traceId); 25234 }, 500); 25235 }); 25236 } 25237 }; 25238 }); 25239 })))(); 25240} 25241//#endregion 25242//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/transports/offline.js 25243function promisifyRequest(request) { 25244 return new Promise((resolve, reject) => { 25245 request.oncomplete = request.onsuccess = () => resolve(request.result); 25246 request.onabort = request.onerror = () => reject(request.error); 25247 }); 25248} 25249function createStore(dbName, storeName) { 25250 const request = indexedDB.open(dbName);
25251 request.onupgradeneeded = () => request.result.createObjectStore(storeName); 25252 const dbp = promisifyRequest(request); 25253 return (callback) => dbp.then((db) => callback(db.transaction(storeName, "readwrite").objectStore(storeName))); 25254} 25255function keys(store) { 25256 return promisifyRequest(store.getAllKeys()); 25257} 25258function push(store, value, maxQueueSize) { 25259 return store((store2) => { 25260 return keys(store2).then((keys2) => { 25261 if (keys2.length >= maxQueueSize) return; 25262 store2.put(value, Math.max(...keys2, 0) + 1); 25263 return promisifyRequest(store2.transaction); 25264 }); 25265 }); 25266} 25267function unshift(store, value, maxQueueSize) { 25268 return store((store2) => { 25269 return keys(store2).then((keys2) => { 25270 if (keys2.length >= maxQueueSize) return; 25271 store2.put(value, Math.min(...keys2, 0) - 1); 25272 return promisifyRequest(store2.transaction); 25273 }); 25274 }); 25275} 25276function shift(store) { 25277 return store((store2) => { 25278 return keys(store2).then((keys2) => { 25279 const firstKey = keys2[0]; 25280 if (firstKey == null) return; 25281 return promisifyRequest(store2.get(firstKey)).then((value) => { 25282 store2.delete(firstKey); 25283 return promisifyRequest(store2.transaction).then(() => value); 25284 }); 25285 }); 25286 }); 25287} 25288function createIndexedDbStore(options) { 25289 let store; 25290 function getStore() { 25291 if (store == void 0) store = createStore(options.dbName || "sentry-offline", options.storeName || "queue"); 25292 return store; 25293 } 25294 return { 25295 push: async (env) => { 25296 try { 25297 const serialized = serializeEnvelope(env); 25298 await push(getStore(), serialized, options.maxQueueSize || 30); 25299 } catch {} 25300 }, 25301 unshift: async (env) => { 25302 try { 25303 const serialized = serializeEnvelope(env); 25304 await unshift(getStore(), serialized, options.maxQueueSize || 30); 25305 } catch {} 25306 }, 25307 shift: async () => { 25308 try { 25309 const deserialized = await shift(getStore()); 25310 if (deserialized) return parseEnvelope(deserialized); 25311 } catch {} 25312 } 25313 }; 25314} 25315function makeIndexedDbOfflineTransport(createTransport) { 25316 return (options) => { 25317 const transport = createTransport({ 25318 ...options, 25319 createStore: createIndexedDbStore 25320 }); 25321 WINDOW$4.addEventListener("online", async (_) => { 25322 await transport.flush(); 25323 }); 25324 return transport; 25325 }; 25326} 25327function makeBrowserOfflineTransport(createTransport = makeFetchTransport) { 25328 return makeIndexedDbOfflineTransport(makeOfflineTransport(createTransport)); 25329} 25330function init_offline$1() { 25331 return (init_offline$1 = __esmMin((() => { 25332 init_offline(), init_envelope(); 25333 init_helpers(); 25334 init_fetch$2(); 25335 })))(); 25336} 25337//#endregion 25338//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/profiling/utils.js 25339function isUserAgentData(data) { 25340 return typeof data === "object" && data !== null && "getHighEntropyValues" in data; 25341} 25342function isProcessedJSSelfProfile(profile) { 25343 return !("thread_metadata" in profile); 25344} 25345function enrichWithThreadInformation(profile) { 25346 if (!isProcessedJSSelfProfile(profile)) return profile; 25347 return convertJSSelfProfileToSampledFormat(profile); 25348} 25349function getTraceId(event) { 25350 const traceId = event.contexts?.trace?.trace_id; 25351 if (typeof traceId === "string" && traceId.length !== 32) { 25352 if (DEBUG_BUILD$2) debug$2.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`); 25353 } 25354 if (typeof traceId !== "string") return ""; 25355 return traceId; 25356} 25357function createProfilePayload(profile_id, start_timestamp, processed_profile, event) { 25358 if (event.type !== "transaction") throw new TypeError("Profiling events may only be attached to transactions, this should never occur."); 25359 if (processed_profile === void 0 || processed_profile === null) throw new TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${processed_profile} instead.`); 25360 const traceId = getTraceId(event); 25361 const enrichedThreadProfile = enrichWithThreadInformation(processed_profile); 25362 const transactionStartMs = start_timestamp ? start_timestamp : typeof event.start_timestamp === "number" ? event.start_timestamp * 1e3 : timestampInSeconds() * 1e3; 25363 const transactionEndMs = typeof event.timestamp === "number" ? event.timestamp * 1e3 : timestampInSeconds() * 1e3; 25364 return { 25365 event_id: profile_id, 25366 timestamp: new Date(transactionStartMs).toISOString(), 25367 platform: "javascript", 25368 version: "1", 25369 release: event.release || "", 25370 environment: event.environment || "production", 25371 runtime: { 25372 name: "javascript",
25373 version: WINDOW$4.navigator.userAgent 25374 }, 25375 os: { 25376 name: OS_PLATFORM, 25377 version: OS_PLATFORM_VERSION, 25378 build_number: OS_BROWSER 25379 }, 25380 device: { 25381 locale: OS_LOCALE, 25382 model: OS_MODEL, 25383 manufacturer: OS_BROWSER, 25384 architecture: OS_ARCH, 25385 is_emulator: false 25386 }, 25387 debug_meta: { images: applyDebugMetadata(processed_profile.resources) }, 25388 profile: enrichedThreadProfile, 25389 transactions: [{ 25390 name: event.transaction || "", 25391 id: event.event_id || uuid4(), 25392 trace_id: traceId, 25393 active_thread_id: PROFILER_THREAD_ID_STRING, 25394 relative_start_ns: "0", 25395 relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0) 25396 }] 25397 }; 25398} 25399function createProfileChunkPayload(jsSelfProfile, client, profilerId) { 25400 if (jsSelfProfile == null) throw new TypeError(`Cannot construct profiling event envelope without a valid profile. Got ${jsSelfProfile} instead.`); 25401 const continuousProfile = convertToContinuousProfile(jsSelfProfile); 25402 const options = client.getOptions(); 25403 const sdk = client.getSdkMetadata?.()?.sdk; 25404 return { 25405 chunk_id: uuid4(), 25406 client_sdk: { 25407 name: sdk?.name ?? "sentry.javascript.browser", 25408 version: sdk?.version ?? "0.0.0" 25409 }, 25410 profiler_id: profilerId || uuid4(), 25411 platform: "javascript", 25412 version: "2", 25413 release: options.release ?? "", 25414 environment: options.environment ?? "production", 25415 debug_meta: { images: applyDebugMetadata(jsSelfProfile.resources) }, 25416 profile: continuousProfile 25417 }; 25418} 25419function validateProfileChunk(chunk) { 25420 try { 25421 if (!chunk || typeof chunk !== "object") return { reason: "chunk is not an object" }; 25422 const isHex32 = (val) => typeof val === "string" && /^[a-f0-9]{32}$/.test(val); 25423 if (!isHex32(chunk.profiler_id)) return { reason: "missing or invalid profiler_id" }; 25424 if (!isHex32(chunk.chunk_id)) return { reason: "missing or invalid chunk_id" }; 25425 if (!chunk.client_sdk) return { reason: "missing client_sdk metadata" }; 25426 const profile = chunk.profile; 25427 if (!profile) return { reason: "missing profile data" }; 25428 if (!Array.isArray(profile.frames) || !profile.frames.length) return { reason: "profile has no frames" }; 25429 if (!Array.isArray(profile.stacks) || !profile.stacks.length) return { reason: "profile has no stacks" }; 25430 if (!Array.isArray(profile.samples) || !profile.samples.length) return { reason: "profile has no samples" }; 25431 return { valid: true }; 25432 } catch (e) { 25433 return { reason: `unknown validation error: ${e}` }; 25434 } 25435} 25436function convertToContinuousProfile(input) { 25437 const frames = []; 25438 for (let i = 0; i < input.frames.length; i++) { 25439 const frame = input.frames[i]; 25440 if (!frame) continue; 25441 frames[i] = { 25442 function: frame.name, 25443 abs_path: typeof frame.resourceId === "number" ? input.resources[frame.resourceId] : void 0, 25444 lineno: frame.line, 25445 colno: frame.column 25446 }; 25447 } 25448 const stacks = []; 25449 for (let i = 0; i < input.stacks.length; i++) { 25450 const stackHead = input.stacks[i]; 25451 if (!stackHead) continue; 25452 const list = []; 25453 let current = stackHead; 25454 while (current) { 25455 list.push(current.frameId); 25456 current = current.parentId === void 0 ? void 0 : input.stacks[current.parentId]; 25457 } 25458 stacks[i] = list; 25459 } 25460 const perfOrigin = browserPerformanceTimeOrigin(); 25461 const origin = typeof performance.timeOrigin === "number" ? performance.timeOrigin : perfOrigin || 0; 25462 const adjustForOriginChange = origin - (perfOrigin || origin); 25463 const samples = []; 25464 for (let i = 0; i < input.samples.length; i++) { 25465 const sample = input.samples[i]; 25466 if (!sample) continue; 25467 const timestampSeconds = (origin + (sample.timestamp - adjustForOriginChange)) / 1e3; 25468 samples[i] = { 25469 stack_id: sample.stackId ?? 0, 25470 thread_id: PROFILER_THREAD_ID_STRING, 25471 timestamp: timestampSeconds 25472 }; 25473 } 25474 return { 25475 frames, 25476 stacks, 25477 samples, 25478 thread_metadata: { [PROFILER_THREAD_ID_STRING]: { name: PROFILER_THREAD_NAME } } 25479 }; 25480} 25481function isAutomatedPageLoadSpan(span) { 25482 return spanToJSON(span).op === "pageload"; 25483} 25484function convertJSSelfProfileToSampledFormat(input) { 25485 let EMPTY_STACK_ID = void 0; 25486 let STACK_ID = 0; 25487 const profile = { 25488 samples: [], 25489 stacks: [], 25490 frames: [], 25491 thread_metadata: { [PROFILER_THREAD_ID_STRING]: { name: PROFILER_THREAD_NAME } } 25492 }; 25493 const firstSample = input.samples[0]; 25494 if (!firstSample) return profile; 25495 const start = firstSample.timestamp; 25496 const perfOrigin = browserPerformanceTimeOrigin(); 25497 const origin = typeof performance.timeOrigin === "number" ? performance.timeOrigin : perfOrigin || 0; 25498 const adjustForOriginChange = origin - (perfOrigin || origin);
25499 input.samples.forEach((jsSample, i) => { 25500 if (jsSample.stackId === void 0) { 25501 if (EMPTY_STACK_ID === void 0) { 25502 EMPTY_STACK_ID = STACK_ID; 25503 profile.stacks[EMPTY_STACK_ID] = []; 25504 STACK_ID++; 25505 } 25506 profile["samples"][i] = { 25507 elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0), 25508 stack_id: EMPTY_STACK_ID, 25509 thread_id: PROFILER_THREAD_ID_STRING 25510 }; 25511 return; 25512 } 25513 let stackTop = input.stacks[jsSample.stackId]; 25514 const stack = []; 25515 while (stackTop) { 25516 stack.push(stackTop.frameId); 25517 const frame = input.frames[stackTop.frameId]; 25518 if (frame && profile.frames[stackTop.frameId] === void 0) profile.frames[stackTop.frameId] = { 25519 function: frame.name, 25520 abs_path: typeof frame.resourceId === "number" ? input.resources[frame.resourceId] : void 0, 25521 lineno: frame.line, 25522 colno: frame.column 25523 }; 25524 stackTop = stackTop.parentId === void 0 ? void 0 : input.stacks[stackTop.parentId]; 25525 } 25526 const sample = { 25527 elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0), 25528 stack_id: STACK_ID, 25529 thread_id: PROFILER_THREAD_ID_STRING 25530 }; 25531 profile["stacks"][STACK_ID] = stack; 25532 profile["samples"][i] = sample; 25533 STACK_ID++; 25534 }); 25535 return profile; 25536} 25537function addProfilesToEnvelope(envelope, profiles) { 25538 if (!profiles.length) return envelope; 25539 for (const profile of profiles) envelope[1].push([{ type: "profile" }, profile]); 25540 return envelope; 25541} 25542function findProfiledTransactionsFromEnvelope(envelope) { 25543 const events = []; 25544 forEachEnvelopeItem(envelope, (item, type) => { 25545 if (type !== "transaction") return; 25546 for (let j = 1; j < item.length; j++) if (item[j]?.contexts?.profile?.profile_id) events.push(item[j]); 25547 }); 25548 return events; 25549} 25550function applyDebugMetadata(resource_paths) { 25551 const stackParser = (getClient()?.getOptions())?.stackParser; 25552 if (!stackParser) return []; 25553 return getDebugImagesForResources(stackParser, resource_paths); 25554} 25555function isValidSampleRate(rate) { 25556 if (typeof rate !== "number" && typeof rate !== "boolean" || typeof rate === "number" && isNaN(rate)) { 25557 DEBUG_BUILD$2 && debug$2.warn(`[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(rate)} of type ${JSON.stringify(typeof rate)}.`); 25558 return false; 25559 } 25560 if (rate === true || rate === false) return true; 25561 if (rate < 0 || rate > 1) { 25562 DEBUG_BUILD$2 && debug$2.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`); 25563 return false; 25564 } 25565 return true; 25566} 25567function isValidProfile(profile) { 25568 if (profile.samples.length < 2) { 25569 if (DEBUG_BUILD$2) debug$2.log("[Profiling] Discarding profile because it contains less than 2 samples"); 25570 return false; 25571 } 25572 if (!profile.frames.length) { 25573 if (DEBUG_BUILD$2) debug$2.log("[Profiling] Discarding profile because it contains no frames"); 25574 return false; 25575 } 25576 return true; 25577} 25578function isJSProfilerSupported(maybeProfiler) { 25579 return typeof maybeProfiler === "function"; 25580} 25581function startJSSelfProfile() { 25582 const JSProfilerConstructor = WINDOW$4.Profiler; 25583 if (!isJSProfilerSupported(JSProfilerConstructor)) { 25584 if (DEBUG_BUILD$2) debug$2.log("[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object."); 25585 return; 25586 } 25587 const samplingIntervalMS = 10; 25588 const maxSamples = Math.floor(MAX_PROFILE_DURATION_MS / samplingIntervalMS); 25589 try { 25590 return new JSProfilerConstructor({ 25591 sampleInterval: samplingIntervalMS, 25592 maxBufferSize: maxSamples 25593 }); 25594 } catch (_e) { 25595 if (DEBUG_BUILD$2) { 25596 debug$2.log("[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header."); 25597 debug$2.log("[Profiling] Disabling profiling for current user session."); 25598 } 25599 PROFILING_CONSTRUCTOR_FAILED = true; 25600 } 25601} 25602function shouldProfileSpanLegacy(span) { 25603 if (PROFILING_CONSTRUCTOR_FAILED) { 25604 if (DEBUG_BUILD$2) debug$2.log("[Profiling] Profiling has been disabled for the duration of the current user session."); 25605 return false; 25606 } 25607 if (!span.isRecording()) { 25608 DEBUG_BUILD$2 && debug$2.log("[Profiling] Discarding profile because root span was not sampled."); 25609 return false;
25610 } 25611 const options = getClient()?.getOptions(); 25612 if (!options) { 25613 DEBUG_BUILD$2 && debug$2.log("[Profiling] Profiling disabled, no options found."); 25614 return false; 25615 } 25616 const profilesSampleRate = options.profilesSampleRate; 25617 if (!isValidSampleRate(profilesSampleRate)) { 25618 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Discarding profile because of invalid sample rate."); 25619 return false; 25620 } 25621 if (!profilesSampleRate) { 25622 DEBUG_BUILD$2 && debug$2.log("[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0"); 25623 return false; 25624 } 25625 if (!(profilesSampleRate === true ? true : Math.random() < profilesSampleRate)) { 25626 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(profilesSampleRate)})`); 25627 return false; 25628 } 25629 return true; 25630} 25631function shouldProfileSession(options) { 25632 if (PROFILING_CONSTRUCTOR_FAILED) { 25633 if (DEBUG_BUILD$2) debug$2.log("[Profiling] Profiling has been disabled for the duration of the current user session as the JS Profiler could not be started."); 25634 return false; 25635 } 25636 if (options.profileLifecycle !== "trace" && options.profileLifecycle !== "manual") { 25637 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Session not sampled. Invalid `profileLifecycle` option."); 25638 return false; 25639 } 25640 const profileSessionSampleRate = options.profileSessionSampleRate; 25641 if (!isValidSampleRate(profileSessionSampleRate)) { 25642 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Discarding profile because of invalid profileSessionSampleRate."); 25643 return false; 25644 } 25645 if (!profileSessionSampleRate) { 25646 DEBUG_BUILD$2 && debug$2.log("[Profiling] Discarding profile because profileSessionSampleRate is not defined or set to 0"); 25647 return false; 25648 } 25649 return Math.random() <= profileSessionSampleRate; 25650} 25651function hasLegacyProfiling(options) { 25652 return typeof options.profilesSampleRate !== "undefined"; 25653} 25654function createProfilingEvent(profile_id, start_timestamp, profile, event) { 25655 if (!isValidProfile(profile)) return null; 25656 return createProfilePayload(profile_id, start_timestamp, profile, event); 25657} 25658function getActiveProfilesCount() { 25659 return PROFILE_MAP.size; 25660} 25661function takeProfileFromGlobalCache(profile_id) { 25662 const profile = PROFILE_MAP.get(profile_id); 25663 if (profile) PROFILE_MAP.delete(profile_id); 25664 return profile; 25665} 25666function addProfileToGlobalCache(profile_id, profile) { 25667 PROFILE_MAP.set(profile_id, profile); 25668 if (PROFILE_MAP.size > 30) { 25669 const last = PROFILE_MAP.keys().next().value; 25670 if (last !== void 0) PROFILE_MAP.delete(last); 25671 } 25672} 25673function setThreadAttributes(span) { 25674 span.setAttribute("thread.id", PROFILER_THREAD_ID_STRING); 25675 span.setAttribute("thread.name", PROFILER_THREAD_NAME); 25676} 25677var MS_TO_NS, isMainThread, PROFILER_THREAD_ID_STRING, PROFILER_THREAD_NAME, navigator$1, OS_PLATFORM, OS_PLATFORM_VERSION, OS_ARCH, OS_BROWSER, OS_MODEL, OS_LOCALE, userAgentData, PROFILING_CONSTRUCTOR_FAILED, MAX_PROFILE_DURATION_MS, PROFILE_MAP, PROFILED_ROOT_SPANS; 25678function init_utils$10() { 25679 return (init_utils$10 = __esmMin((() => { 25680 init_worldwide(), init_spanUtils(), init_debug_logger(), init_currentScopes(), init_envelope(), init_misc(), init_time(), init_constants(), init_debug_ids(); 25681 init_debug_build$2(); 25682 init_helpers(); 25683 MS_TO_NS = 1e6; 25684 isMainThread = "window" in GLOBAL_OBJ && GLOBAL_OBJ.window === GLOBAL_OBJ && typeof importScripts === "undefined"; 25685 PROFILER_THREAD_ID_STRING = String(0); 25686 PROFILER_THREAD_NAME = isMainThread ? "main" : "worker"; 25687 navigator$1 = WINDOW$4.navigator; 25688 OS_PLATFORM = ""; 25689 OS_PLATFORM_VERSION = ""; 25690 OS_ARCH = ""; 25691 OS_BROWSER = navigator$1?.userAgent || ""; 25692 OS_MODEL = ""; 25693 OS_LOCALE = navigator$1?.language || navigator$1?.languages?.[0] || ""; 25694 userAgentData = navigator$1?.userAgentData; 25695 if (isUserAgentData(userAgentData)) userAgentData.getHighEntropyValues([ 25696 "architecture", 25697 "model", 25698 "platform", 25699 "platformVersion", 25700 "fullVersionList" 25701 ]).then((ua) => { 25702 OS_PLATFORM = ua.platform || ""; 25703 OS_ARCH = ua.architecture || ""; 25704 OS_MODEL = ua.model || ""; 25705 OS_PLATFORM_VERSION = ua.platformVersion || ""; 25706 if (ua.fullVersionList?.length) { 25707 const firstUa = ua.fullVersionList[ua.fullVersionList.length - 1]; 25708 OS_BROWSER = `${firstUa.brand} ${firstUa.version}`; 25709 } 25710 }).catch((e) => void 0); 25711 PROFILING_CONSTRUCTOR_FAILED = false;
25712 MAX_PROFILE_DURATION_MS = 3e4; 25713 PROFILE_MAP = /* @__PURE__ */ new Map(); 25714 PROFILED_ROOT_SPANS = /* @__PURE__ */ new WeakSet(); 25715 })))(); 25716} 25717//#endregion 25718//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/profiling/startProfileForSpan.js 25719function startProfileForSpan(span) { 25720 let startTimestamp; 25721 if (isAutomatedPageLoadSpan(span)) startTimestamp = timestampInSeconds() * 1e3; 25722 const profiler = startJSSelfProfile(); 25723 if (!profiler) return; 25724 if (DEBUG_BUILD$2) debug$2.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`); 25725 const profileId = uuid4(); 25726 let processedProfile = null; 25727 getCurrentScope().setContext("profile", { 25728 profile_id: profileId, 25729 start_timestamp: startTimestamp 25730 }); 25731 PROFILED_ROOT_SPANS.add(span); 25732 setThreadAttributes(span); 25733 async function onProfileHandler() { 25734 if (!span) return; 25735 if (!profiler) return; 25736 if (processedProfile) { 25737 if (DEBUG_BUILD$2) debug$2.log("[Profiling] profile for:", spanToJSON(span).description, "already exists, returning early"); 25738 return; 25739 } 25740 return profiler.stop().then((profile) => { 25741 if (maxDurationTimeoutID) { 25742 WINDOW$4.clearTimeout(maxDurationTimeoutID); 25743 maxDurationTimeoutID = void 0; 25744 } 25745 if (DEBUG_BUILD$2) debug$2.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`); 25746 if (!profile) { 25747 if (DEBUG_BUILD$2) debug$2.log(`[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`, "this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started"); 25748 return; 25749 } 25750 processedProfile = profile; 25751 addProfileToGlobalCache(profileId, profile); 25752 }).catch((error) => { 25753 if (DEBUG_BUILD$2) debug$2.log("[Profiling] error while stopping profiler:", error); 25754 }); 25755 } 25756 let maxDurationTimeoutID = WINDOW$4.setTimeout(() => { 25757 if (DEBUG_BUILD$2) debug$2.log("[Profiling] max profile duration elapsed, stopping profiling for:", spanToJSON(span).description); 25758 onProfileHandler(); 25759 }, MAX_PROFILE_DURATION_MS); 25760 const originalEnd = span.end.bind(span); 25761 function profilingWrappedSpanEnd() { 25762 if (!span) return originalEnd(); 25763 onProfileHandler().then(() => { 25764 originalEnd(); 25765 }, () => { 25766 originalEnd(); 25767 }); 25768 return span; 25769 } 25770 span.end = profilingWrappedSpanEnd; 25771} 25772function init_startProfileForSpan() { 25773 return (init_startProfileForSpan = __esmMin((() => { 25774 init_time(), init_debug_logger(), init_spanUtils(), init_misc(), init_currentScopes(); 25775 init_debug_build$2(); 25776 init_helpers(); 25777 init_utils$10(); 25778 })))(); 25779} 25780//#endregion 25781//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/profiling/UIProfiler.js 25782var CHUNK_INTERVAL_MS, MAX_ROOT_SPAN_PROFILE_MS, UIProfiler; 25783function init_UIProfiler() { 25784 return (init_UIProfiler = __esmMin((() => { 25785 init_debug_logger(), init_misc(), init_currentScopes(), init_spanUtils(), init_envelope(), init_dsn(); 25786 init_debug_build$2(); 25787 init_utils$10(); 25788 CHUNK_INTERVAL_MS = 6e4; 25789 MAX_ROOT_SPAN_PROFILE_MS = 3e5; 25790 UIProfiler = class { 25791 constructor() { 25792 this._client = void 0; 25793 this._profiler = void 0; 25794 this._chunkTimer = void 0; 25795 this._profilerId = void 0; 25796 this._isRunning = false; 25797 this._sessionSampled = false; 25798 this._lifecycleMode = void 0; 25799 this._activeRootSpanIds = /* @__PURE__ */ new Set(); 25800 this._rootSpanTimeouts = /* @__PURE__ */ new Map(); 25801 } 25802 /** 25803 * Initialize the profiler with client, session sampling and lifecycle mode. 25804 */ 25805 initialize(client) { 25806 const lifecycleMode = client.getOptions().profileLifecycle; 25807 const sessionSampled = shouldProfileSession(client.getOptions()); 25808 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Initializing profiler (lifecycle='${lifecycleMode}').`); 25809 if (!sessionSampled) DEBUG_BUILD$2 && debug$2.log("[Profiling] Session not sampled. Skipping lifecycle profiler initialization."); 25810 this._profilerId = uuid4(); 25811 this._client = client; 25812 this._sessionSampled = sessionSampled; 25813 this._lifecycleMode = lifecycleMode; 25814 if (lifecycleMode === "trace") this._setupTraceLifecycleListeners(client); 25815 client.on("spanStart", (span) => { 25816 if (this._isRunning) setThreadAttributes(span); 25817 }); 25818 } 25819 /** Starts UI profiling (only effective in 'manual' mode and when sampled). */ 25820 start() { 25821 if (this._lifecycleMode === "trace") { 25822 DEBUG_BUILD$2 && debug$2.warn("[Profiling] `profileLifecycle` is set to \"trace\". Calls to `uiProfiler.start()` are ignored in trace mode."); 25823 return; 25824 } 25825 if (this._isRunning) { 25826 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Profile session is already running, `uiProfiler.start()` is a
25826no-op."); 25827 return; 25828 } 25829 if (!this._sessionSampled) { 25830 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Session is not sampled, `uiProfiler.start()` is a no-op."); 25831 return; 25832 } 25833 this._beginProfiling(); 25834 } 25835 /** Stops UI profiling (only effective in 'manual' mode). */ 25836 stop() { 25837 if (this._lifecycleMode === "trace") { 25838 DEBUG_BUILD$2 && debug$2.warn("[Profiling] `profileLifecycle` is set to \"trace\". Calls to `uiProfiler.stop()` are ignored in trace mode."); 25839 return; 25840 } 25841 if (!this._isRunning) { 25842 DEBUG_BUILD$2 && debug$2.warn("[Profiling] Profiler is not running, `uiProfiler.stop()` is a no-op."); 25843 return; 25844 } 25845 this._endProfiling(); 25846 } 25847 /** Handle an already-active root span at integration setup time (used only in trace mode). */ 25848 notifyRootSpanActive(rootSpan) { 25849 if (this._lifecycleMode !== "trace" || !this._sessionSampled) return; 25850 const spanId = rootSpan.spanContext().spanId; 25851 if (!spanId || this._activeRootSpanIds.has(spanId)) return; 25852 this._registerTraceRootSpan(spanId); 25853 const rootSpanCount = this._activeRootSpanIds.size; 25854 if (rootSpanCount === 1) { 25855 DEBUG_BUILD$2 && debug$2.log("[Profiling] Detected already active root span during setup. Active root spans now:", rootSpanCount); 25856 this._beginProfiling(); 25857 } 25858 if (this._isRunning) setThreadAttributes(rootSpan); 25859 } 25860 /** 25861 * Begin profiling if not already running. 25862 */ 25863 _beginProfiling() { 25864 if (this._isRunning) return; 25865 this._isRunning = true; 25866 DEBUG_BUILD$2 && debug$2.log("[Profiling] Started profiling with profiler ID:", this._profilerId); 25867 getGlobalScope().setContext("profile", { profiler_id: this._profilerId }); 25868 this._startProfilerInstance(); 25869 if (!this._profiler) { 25870 DEBUG_BUILD$2 && debug$2.log("[Profiling] Failed to start JS Profiler; stopping."); 25871 this._resetProfilerInfo(); 25872 return; 25873 } 25874 this._startPeriodicChunking(); 25875 } 25876 /** End profiling session; final chunk will be collected and sent. */ 25877 _endProfiling() { 25878 if (!this._isRunning) return; 25879 this._isRunning = false; 25880 if (this._chunkTimer) { 25881 clearTimeout(this._chunkTimer); 25882 this._chunkTimer = void 0; 25883 } 25884 this._clearAllRootSpanTimeouts(); 25885 this._collectCurrentChunk().catch((e) => { 25886 DEBUG_BUILD$2 && debug$2.error("[Profiling] Failed to collect current profile chunk on `stop()`:", e); 25887 }); 25888 if (this._lifecycleMode === "manual") getGlobalScope().setContext("profile", {}); 25889 } 25890 /** Trace-mode: attach spanStart/spanEnd listeners. */ 25891 _setupTraceLifecycleListeners(client) { 25892 client.on("spanStart", (span) => { 25893 if (!this._sessionSampled) { 25894 DEBUG_BUILD$2 && debug$2.log("[Profiling] Span not profiled because of negative sampling decision for user session."); 25895 return; 25896 } 25897 if (span !== getRootSpan(span)) return; 25898 if (!span.isRecording()) { 25899 DEBUG_BUILD$2 && debug$2.log("[Profiling] Discarding profile because root span was not sampled."); 25900 return; 25901 } 25902 const spanId = span.spanContext().spanId; 25903 if (!spanId || this._activeRootSpanIds.has(spanId)) return; 25904 this._registerTraceRootSpan(spanId); 25905 const rootSpanCount = this._activeRootSpanIds.size; 25906 if (rootSpanCount === 1) { 25907 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Root span ${spanId} started. Profiling active while there are active root spans (count=${rootSpanCount}).`); 25908 this._beginProfiling(); 25909 } 25910 }); 25911 client.on("spanEnd", (span) => { 25912 if (!this._sessionSampled) return; 25913 const spanId = span.spanContext().spanId; 25914 if (!spanId || !this._activeRootSpanIds.has(spanId)) return; 25915 this._activeRootSpanIds.delete(spanId); 25916 const rootSpanCount = this._activeRootSpanIds.size; 25917 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Root span with ID ${spanId} ended. Will continue profiling for as long as there are active root spans (currently: ${rootSpanCount}).`); 25918 if (rootSpanCount === 0) { 25919 this._collectCurrentChunk().catch((e) => { 25920 DEBUG_BUILD$2 && debug$2.error("[Profiling] Failed to collect current profile chunk on last `spanEnd`:", e); 25921 }); 25922 this._endProfiling(); 25923 } 25924 }); 25925 } 25926 /** 25927 * Resets profiling information from scope and resets running state (used on failure) 25928 */ 25929 _resetProfilerInfo() { 25930 this._isRunning = false;
25931 getGlobalScope().setContext("profile", {}); 25932 } 25933 /** 25934 * Clear and reset all per-root-span timeouts. 25935 */ 25936 _clearAllRootSpanTimeouts() { 25937 this._rootSpanTimeouts.forEach((timeout) => clearTimeout(timeout)); 25938 this._rootSpanTimeouts.clear(); 25939 } 25940 /** Keep track of root spans and schedule safeguard timeout (trace mode). */ 25941 _registerTraceRootSpan(spanId) { 25942 this._activeRootSpanIds.add(spanId); 25943 const timeout = setTimeout(() => this._onRootSpanTimeout(spanId), MAX_ROOT_SPAN_PROFILE_MS); 25944 this._rootSpanTimeouts.set(spanId, timeout); 25945 } 25946 /** 25947 * Start a profiler instance if needed. 25948 */ 25949 _startProfilerInstance() { 25950 if (this._profiler?.stopped === false) return; 25951 const profiler = startJSSelfProfile(); 25952 if (!profiler) { 25953 DEBUG_BUILD$2 && debug$2.log("[Profiling] Failed to start JS Profiler."); 25954 return; 25955 } 25956 this._profiler = profiler; 25957 } 25958 /** 25959 * Schedule the next 60s chunk while running. 25960 * Each tick collects a chunk and restarts the profiler. 25961 * A chunk should be closed when there are no active root spans anymore OR when the maximum chunk interval is reached. 25962 */ 25963 _startPeriodicChunking() { 25964 if (!this._isRunning) return; 25965 this._chunkTimer = setTimeout(() => { 25966 this._collectCurrentChunk().catch((e) => { 25967 DEBUG_BUILD$2 && debug$2.error("[Profiling] Failed to collect current profile chunk during periodic chunking:", e); 25968 }); 25969 if (this._isRunning) { 25970 this._startProfilerInstance(); 25971 if (!this._profiler) { 25972 this._resetProfilerInfo(); 25973 return; 25974 } 25975 this._startPeriodicChunking(); 25976 } 25977 }, CHUNK_INTERVAL_MS); 25978 } 25979 /** 25980 * Handle timeout for a specific root span ID to avoid indefinitely running profiler if `spanEnd` never fires. 25981 * If this was the last active root span, collect the current chunk and stop profiling. 25982 */ 25983 _onRootSpanTimeout(rootSpanId) { 25984 if (!this._rootSpanTimeouts.has(rootSpanId)) return; 25985 this._rootSpanTimeouts.delete(rootSpanId); 25986 if (!this._activeRootSpanIds.has(rootSpanId)) return; 25987 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Reached 5-minute timeout for root span ${rootSpanId}. You likely started a manual root span that never called \`.end()\`.`); 25988 this._activeRootSpanIds.delete(rootSpanId); 25989 if (this._activeRootSpanIds.size === 0) this._endProfiling(); 25990 } 25991 /** 25992 * Stop current profiler instance, convert profile to chunk & send. 25993 */ 25994 async _collectCurrentChunk() { 25995 const prevProfiler = this._profiler; 25996 this._profiler = void 0; 25997 if (!prevProfiler) return; 25998 try { 25999 const chunk = createProfileChunkPayload(await prevProfiler.stop(), this._client, this._profilerId); 26000 const validationReturn = validateProfileChunk(chunk); 26001 if ("reason" in validationReturn) { 26002 DEBUG_BUILD$2 && debug$2.log("[Profiling] Discarding invalid profile chunk (this is probably a bug in the SDK):", validationReturn.reason); 26003 return; 26004 } 26005 this._sendProfileChunk(chunk); 26006 DEBUG_BUILD$2 && debug$2.log("[Profiling] Collected browser profile chunk."); 26007 } catch (e) { 26008 DEBUG_BUILD$2 && debug$2.log("[Profiling] Error while stopping JS Profiler for chunk:", e); 26009 } 26010 } 26011 /** 26012 * Send a profile chunk as a standalone envelope. 26013 */ 26014 _sendProfileChunk(chunk) { 26015 const client = this._client; 26016 const sdkInfo = getSdkMetadataForEnvelopeHeader(client.getSdkMetadata?.()); 26017 const dsn = client.getDsn(); 26018 const tunnel = client.getOptions().tunnel; 26019 const envelope = createEnvelope({ 26020 event_id: uuid4(), 26021 sent_at: (/* @__PURE__ */ new Date()).toISOString(), 26022 ...sdkInfo && { sdk: sdkInfo }, 26023 ...!!tunnel && dsn && { dsn: dsnToString(dsn) } 26024 }, [[{ 26025 type: "profile_chunk", 26026 platform: "javascript" 26027 }, chunk]]); 26028 client.sendEnvelope(envelope).then(null, (reason) => { 26029 DEBUG_BUILD$2 && debug$2.error("Error while sending profile chunk envelope:", reason); 26030 }); 26031 } 26032 }; 26033 })))(); 26034} 26035//#endregion 26036//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/profiling/integration.js 26037var INTEGRATION_NAME$2, _browserProfilingIntegration, browserProfilingIntegration; 26038function init_integration$1() { 26039 return (init_integration$1 = __esmMin((() => { 26040 init_integration(), init_debug_logger(), init_spanUtils(), init_hasSpansEnabled(); 26041 init_debug_build$2(); 26042 init_helpers(); 26043 init_startProfileForSpan(); 26044 init_UIProfiler(); 26045 init_utils$10(); 26046 INTEGRATION_NAME$2 = "BrowserProfiling"; 26047 _browserProfilingIntegration = (() => { 26048 return { 26049 name: INTEGRATION_NAME$2, 26050 setup(client) { 26051 const options = client.getOptions(); 26052 const profiler = new UIProfiler(); 26053 if (!hasLegacyProfiling(options) && !options.profileLifecycle) options.profileLifecycle = "manual"; 26054 if (hasLegacyProfiling(options) && !options.profilesSampleRate) { 26055 DEBUG_BUILD$2 && debug$2.log("[Profiling] Profiling disabled, no profiling options foun
26055d."); 26056 return; 26057 } 26058 const activeSpan = getActiveSpan(); 26059 const rootSpan = activeSpan && getRootSpan(activeSpan); 26060 if (hasLegacyProfiling(options) && options.profileSessionSampleRate !== void 0) DEBUG_BUILD$2 && debug$2.warn("[Profiling] Both legacy profiling (`profilesSampleRate`) and UI profiling settings are defined. `profileSessionSampleRate` has no effect when legacy profiling is enabled."); 26061 if (!hasLegacyProfiling(options)) { 26062 const lifecycleMode = options.profileLifecycle; 26063 client.on("startUIProfiler", () => profiler.start()); 26064 client.on("stopUIProfiler", () => profiler.stop()); 26065 if (lifecycleMode === "manual") profiler.initialize(client); 26066 else if (lifecycleMode === "trace") { 26067 if (!hasSpansEnabled(options)) { 26068 DEBUG_BUILD$2 && debug$2.warn("[Profiling] `profileLifecycle` is 'trace' but tracing is disabled. Set a `tracesSampleRate` or `tracesSampler` to enable span tracing."); 26069 return; 26070 } 26071 profiler.initialize(client); 26072 if (rootSpan) profiler.notifyRootSpanActive(rootSpan); 26073 WINDOW$4.setTimeout(() => { 26074 const laterActiveSpan = getActiveSpan(); 26075 const laterRootSpan = laterActiveSpan && getRootSpan(laterActiveSpan); 26076 if (laterRootSpan) profiler.notifyRootSpanActive(laterRootSpan); 26077 }, 0); 26078 } 26079 } else { 26080 if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) { 26081 if (shouldProfileSpanLegacy(rootSpan)) startProfileForSpan(rootSpan); 26082 } 26083 client.on("spanStart", (span) => { 26084 const rootSpan2 = getRootSpan(span); 26085 if (span === rootSpan2) { 26086 if (shouldProfileSpanLegacy(span)) startProfileForSpan(span); 26087 } else if (PROFILED_ROOT_SPANS.has(rootSpan2)) setThreadAttributes(span); 26088 }); 26089 client.on("beforeEnvelope", (envelope) => { 26090 if (!getActiveProfilesCount()) return; 26091 const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope); 26092 if (!profiledTransactionEvents.length) return; 26093 const profilesToAddToEnvelope = []; 26094 for (const profiledTransaction of profiledTransactionEvents) { 26095 const context = profiledTransaction?.contexts; 26096 const profile_id = context?.profile?.["profile_id"]; 26097 const start_timestamp = context?.profile?.["start_timestamp"]; 26098 if (typeof profile_id !== "string") { 26099 DEBUG_BUILD$2 && debug$2.log("[Profiling] cannot find profile for a span without a profile context"); 26100 continue; 26101 } 26102 if (!profile_id) { 26103 DEBUG_BUILD$2 && debug$2.log("[Profiling] cannot find profile for a span without a profile context"); 26104 continue; 26105 } 26106 if (context?.profile) delete context.profile; 26107 const profile = takeProfileFromGlobalCache(profile_id); 26108 if (!profile) { 26109 DEBUG_BUILD$2 && debug$2.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`); 26110 continue; 26111 } 26112 const profileEvent = createProfilingEvent(profile_id, start_timestamp, profile, profiledTransaction); 26113 if (profileEvent) profilesToAddToEnvelope.push(profileEvent); 26114 } 26115 addProfilesToEnvelope(envelope, profilesToAddToEnvelope); 26116 }); 26117 } 26118 } 26119 }; 26120 }); 26121 browserProfilingIntegration = defineIntegration(_browserProfilingIntegration); 26122 })))(); 26123} 26124//#endregion 26125//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/spotlight.js 26126function setupSidecarForwarding(client, sidecarUrl) { 26127 const makeFetch = getNativeImplementation("fetch"); 26128 let failCount = 0; 26129 client.on("beforeEnvelope", (envelope) => { 26130 if (failCount > 3) { 26131 debug$2.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:", failCount); 26132 return; 26133 } 26134 makeFetch(sidecarUrl, { 26135 method: "POST", 26136 body: serializeEnvelope(envelope), 26137 headers: { "Content-Type": "application/x-sentry-envelope" }, 26138 mode: "cors" 26139 }).then((res) => { 26140 if (res.status >= 200 && res.status < 400) failCount = 0; 26141 }, (err) => { 26142 failCount++;
26143 debug$2.error("Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/", err); 26144 }); 26145 }); 26146} 26147var INTEGRATION_NAME$1, SPOTLIGHT_IGNORE_SPANS, _spotlightIntegration, spotlightBrowserIntegration; 26148function init_spotlight() { 26149 return (init_spotlight = __esmMin((() => { 26150 init_integration(), init_debug_logger(), init_envelope(); 26151 init_getNativeImplementation(); 26152 init_debug_build$2(); 26153 INTEGRATION_NAME$1 = "SpotlightBrowser"; 26154 SPOTLIGHT_IGNORE_SPANS = [{ 26155 op: "ui.interaction.click", 26156 name: "#sentry-spotlight" 26157 }]; 26158 _spotlightIntegration = ((options = {}) => { 26159 const sidecarUrl = options.sidecarUrl || "http://localhost:8969/stream"; 26160 return { 26161 name: INTEGRATION_NAME$1, 26162 setup: () => { 26163 DEBUG_BUILD$2 && debug$2.log("Using Sidecar URL", sidecarUrl); 26164 }, 26165 beforeSetup(client) { 26166 const opts = client.getOptions(); 26167 opts.ignoreSpans = [...opts.ignoreSpans || [], ...SPOTLIGHT_IGNORE_SPANS]; 26168 }, 26169 afterAllSetup: (client) => { 26170 setupSidecarForwarding(client, sidecarUrl); 26171 } 26172 }; 26173 }); 26174 spotlightBrowserIntegration = defineIntegration(_spotlightIntegration); 26175 })))(); 26176} 26177//#endregion 26178//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/featureFlags/launchdarkly/integration.js 26179function buildLaunchDarklyFlagUsedHandler() { 26180 return { 26181 name: "sentry-flag-auditor", 26182 type: "flag-used", 26183 synchronous: true, 26184 /** 26185 * Handle a flag evaluation by storing its name and value on the current scope. 26186 */ 26187 method: (flagKey, flagDetail, _context) => { 26188 _INTERNAL_insertFlagToScope(flagKey, flagDetail.value); 26189 _INTERNAL_addFeatureFlagToActiveSpan(flagKey, flagDetail.value); 26190 } 26191 }; 26192} 26193var launchDarklyIntegration; 26194function init_integration$2() { 26195 return (init_integration$2 = __esmMin((() => { 26196 init_integration(), init_featureFlags(); 26197 launchDarklyIntegration = defineIntegration(() => { 26198 return { 26199 name: "LaunchDarkly", 26200 processEvent(event, _hint, _client) { 26201 return _INTERNAL_copyFlagsFromScopeToEvent(event); 26202 } 26203 }; 26204 }); 26205 })))(); 26206} 26207//#endregion 26208//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/featureFlags/openfeature/integration.js 26209var openFeatureIntegration, OpenFeatureIntegrationHook; 26210function init_integration$3() { 26211 return (init_integration$3 = __esmMin((() => { 26212 init_integration(), init_featureFlags(); 26213 openFeatureIntegration = defineIntegration(() => { 26214 return { 26215 name: "OpenFeature", 26216 processEvent(event, _hint, _client) { 26217 return _INTERNAL_copyFlagsFromScopeToEvent(event); 26218 } 26219 }; 26220 }); 26221 OpenFeatureIntegrationHook = class { 26222 /** 26223 * Successful evaluation result. 26224 */ 26225 after(_hookContext, evaluationDetails) { 26226 _INTERNAL_insertFlagToScope(evaluationDetails.flagKey, evaluationDetails.value); 26227 _INTERNAL_addFeatureFlagToActiveSpan(evaluationDetails.flagKey, evaluationDetails.value); 26228 } 26229 /** 26230 * On error evaluation result. 26231 */ 26232 error(hookContext, _error, _hookHints) { 26233 _INTERNAL_insertFlagToScope(hookContext.flagKey, hookContext.defaultValue); 26234 _INTERNAL_addFeatureFlagToActiveSpan(hookContext.flagKey, hookContext.defaultValue); 26235 } 26236 }; 26237 })))(); 26238} 26239//#endregion 26240//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/featureFlags/unleash/integration.js 26241function _wrappedIsEnabled(original) { 26242 return function(...args) { 26243 const toggleName = args[0]; 26244 const result = original.apply(this, args); 26245 if (typeof toggleName === "string" && typeof result === "boolean") { 26246 _INTERNAL_insertFlagToScope(toggleName, result); 26247 _INTERNAL_addFeatureFlagToActiveSpan(toggleName, result); 26248 } else if (DEBUG_BUILD$2) debug$2.error(`[Feature Flags] UnleashClient.isEnabled does not match expected signature. arg0: ${toggleName} (${typeof toggleName}), result: ${result} (${typeof result})`); 26249 return result; 26250 }; 26251} 26252var unleashIntegration; 26253function init_integration$4() { 26254 return (init_integration$4 = __esmMin((() => { 26255 init_integration(), init_featureFlags(), init_object(), init_debug_logger(); 26256 init_debug_build$2(); 26257 unleashIntegration = defineIntegration(({ featureFlagClientClass: unleashClientClass }) => { 26258 return { 26259 name: "Unleash", 26260 setupOnce() { 26261 const unleashClientPrototype = unleashClientClass.prototype; 26262 fill(unleashClientPrototype, "isEnabled", _wrappedIsEnabled); 26263 }, 26264 processEvent(event, _hint, _client) { 26265 return _INTERNAL_copyFlagsFromScopeToEvent(event); 26266 } 26267 }; 26268 }); 26269 })))(); 26270} 26271//#endregion 26272//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/featureFlags/growthbook/integration.js 26273var growthbookIntegration; 26274function init_integration$5() { 26275 return (init_integration$5 = __esmMin((() => { 26276 init_growthbook(); 26277 growthbookIntegration = (({ growthbookClass }) => growthbookIntegration$1({ growthbookClass })); 26278 })))(); 26279} 26280//#endregion 26281//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/featureFlags/statsig/integration.js 26282var statsigIntegration; 26283function init_integration$6() { 26284 return (init_integration$6 = __esmMin((() => { 26285 init_integration(), init_featureFlags(); 26286 statsigIntegration = defineIntegration(({ featureFlagClient: statsigClient }) => { 26287 return { 26288 name: "Statsig", 26289 setup(_client) { 26290 statsigClient.on("gate_evaluation", (event) => { 26291 _INTERNAL_insertFlagToScope(event.gate.name, event.gate.value); 26292 _INTERNAL_addFeatureFlagToActiveSpan(event.gate.name, event.gate.value); 26293 }); 26294 }, 26295 processEvent(event, _hint, _client) { 26296 return _INTERNAL_copyFlagsFromScopeToEvent(event); 26297 } 26298 }; 26299 }); 26300 })))(); 26301} 26302//#endregion 26303//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/diagnose-sdk.js 26304async function diagnoseSdkConnectivity() { 26305 const client = getClient(); 26306 if (!client) return "no-client-active"; 26307 if (!client.getDsn()) return "no-dsn-configured"; 26308 const url = client.getOptions().tunnel || "https://o447951.ingest.sentry.io/api/4509632503087104/envelope/?sentry_version=7&sentry_key=c1dfb07d783ad5325c245c1fd3725390&sentry_client=sentry.javascript.browser%2F1.33.7"; 26309 try { 26310 await suppressTracing(() => fetch(url, { 26311 body: "{}", 26312 method: "POST", 26313 mode: "cors", 26314 credentials: "omit" 26315 })); 26316 } catch { 26317 return "sentry-unreachable"; 26318 } 26319} 26320function init_diagnose_sdk() { 26321 return (init_diagnose_sdk = __esmMin((() => { 26322 init_currentScopes(), init_trace(); 26323 })))(); 26324} 26325//#endregion 26326//#region node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/build/npm/esm/prod/integrations/webWorker.js 26327function listenForSentryMessages(worker) { 26328 worker.addEventListener("message", (event) => { 26329 if (isSentryMessage(event.data)) { 26330 event.stopImmediatePropagation(); 26331 if (event.data._sentryDebugIds) { 26332 DEBUG_BUILD$2 && debug$2.log("Sentry debugId web worker message received", event.data); 26333 WINDOW$4._sentryDebugIds = { 26334 ...event.data._sentryDebugIds, 26335 ...WINDOW$4._sentryDebugIds 26336 }; 26337 } 26338 if (event.data._sentryModuleMetadata) { 26339 DEBUG_BUILD$2 && debug$2.log("Sentry module metadata web worker message received", event.data); 26340 WINDOW$4._sentryModuleMetadata = { 26341 ...event.data._sentryModuleMetadata, 26342 ...WINDOW$4._sentryModuleMetadata 26343 }; 26344 } 26345 if (event.data._sentryWasmImages) { 26346 DEBUG_BUILD$2 && debug$2.log("Sentry WASM images web worker message received", event.data); 26347 const existingImages = WINDOW$4._sentryWasmImages || []; 26348 const newImages = event.data._sentryWasmImages.filter((newImg) => isPlainObject(newImg) && typeof newImg.code_file === "string" && !existingImages.some((existing) => existing.code_file === newImg.code_file)); 26349 WINDOW$4._sentryWasmImages = [...existingImages, ...newImages]; 26350 } 26351 if (event.data._sentryWorkerError) { 26352 DEBUG_BUILD$2 && debug$2.log("Sentry worker rejection message received", event.data._sentryWorkerError); 26353 handleForwardedWorkerRejection(event.data._sentryWorkerError); 26354 } 26355 } 26356 }); 26357} 26358function handleForwardedWorkerRejection(workerError) { 26359 const client = getClient(); 26360 if (!client) return; 26361 const stackParser = client.getOptions().stackParser; 26362 const attachStacktrace = client.getOptions().attachStacktrace; 26363 const error = workerError.reason; 26364 const event = isPrimitive(error) ? _eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(stackParser, error, void 0, attachStacktrace, true); 26365 event.level = "error"; 26366 if (workerError.filename) event.contexts = { 26367 ...event.contexts, 26368 worker: { filename: workerError.filename } 26369 }; 26370 captureEvent(event, { 26371 originalException: error, 26372 mechanism: { 26373 handled: false, 26374 type: "auto.browser.web_worker.onunhandledrejection" 26375 } 26376 }); 26377 DEBUG_BUILD$2 && debug$2.log("Captured worker unhandled rejection", error); 26378} 26379function registerWebWorker({ self }) { 26380 self.postMessage({ 26381 _sentryMessage: true, 26382 _sentryDebugIds: self._sentryDebugIds ?? void 0, 26383 _sentryModuleMetadata: self._sentryModuleMetadata ?? void 0 26384 }); 26385 self.addEventListener("unhandledrejection", (event) => { 26386 const serializedError = { 26387 reason: _getUnhandledRejectionError(event), 26388 filename: self.location?.href 26389 }; 26390 self.postMessage({ 26391 _sentryMessage: true, 26392 _sentryWorkerError: serializedError 26393 }); 26394 DEBUG_BUILD$2 && debug$2.log("[Sentry Worker] Forwarding unhandled rejection to parent", serializedError); 26395 }); 26396 DEBUG_BUILD$2 && debug$2.log("[Sentry Worker] Registered worker with unhandled rejection handling"); 26397} 26398function isSentryMessage(eventData) { 26399 if (!isPlainObject(eventData) || eventData._sentryMessage !== true) return false;
26400 const hasDebugIds = "_sentryDebugIds" in eventData; 26401 const hasModuleMetadata = "_sentryModuleMetadata" in eventData; 26402 const hasWorkerError = "_sentryWorkerError" in eventData; 26403 const hasWasmImages = "_sentryWasmImages" in eventData; 26404 if (!hasDebugIds && !hasModuleMetadata && !hasWorkerError && !hasWasmImages) return false; 26405 if (hasDebugIds && !(isPlainObject(eventData._sentryDebugIds) || eventData._sentryDebugIds === void 0)) return false; 26406 if (hasModuleMetadata && !(isPlainObject(eventData._sentryModuleMetadata) || eventData._sentryModuleMetadata === void 0)) return false; 26407 if (hasWorkerError && !isPlainObject(eventData._sentryWorkerError)) return false; 26408 if (hasWasmImages && (!Array.isArray(eventData._sentryWasmImages) || !eventData._sentryWasmImages.every((img) => isPlainObject(img) && typeof img.code_file === "string"))) return false; 26409 return true; 26410} 26411var INTEGRATION_NAME, webWorkerIntegration; 26412function init_webWorker() { 26413 return (init_webWorker = __esmMin((() => { 26414 init_integration(), init_debug_logger(), init_is(), init_currentScopes(), init_exports(); 26415 init_debug_build$2(); 26416 init_eventbuilder$1(); 26417 init_helpers(); 26418 init_globalhandlers(); 26419 INTEGRATION_NAME = "WebWorker"; 26420 webWorkerIntegration = defineIntegration(({ worker }) => ({ 26421 name: INTEGRATION_NAME, 26422 setupOnce: () => { 26423 (Array.isArray(worker) ? worker : [worker]).forEach((w) => listenForSentryMessages(w)); 26424 }, 26425 addWorker: (worker2) => listenForSentryMessages(worker2) 26426 })); 26427 })))(); 26428} 26429//#endregion 26430//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/isSyntheticEvent.js 26431function isSyntheticEvent(wat) { 26432 return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat; 26433} 26434function init_isSyntheticEvent() { 26435 return (init_isSyntheticEvent = __esmMin((() => { 26436 init_is(); 26437 })))(); 26438} 26439//#endregion 26440//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/sdk.js 26441function init(options) { 26442 const opts = { ...options }; 26443 applySdkMetadata(opts, "react"); 26444 setContext("react", { version: import_react$6.version }); 26445 const client = init$1(opts); 26446 setNormalizeStringifier(normalizeStringifyValue); 26447 return client; 26448} 26449function normalizeStringifyValue(value) { 26450 if (isSyntheticEvent(value)) return "[SyntheticEvent]"; 26451 return normalizeStringifyValue$1(value); 26452} 26453var import_react$6; 26454function init_sdk$2() { 26455 return (init_sdk$2 = __esmMin((() => { 26456 init_exports(), init_sdk$1(), init_normalizeStringifyValue(); 26457 init_sdkMetadata(), init_normalize(); 26458 import_react$6 = require_react(); 26459 init_isSyntheticEvent(); 26460 })))(); 26461} 26462//#endregion 26463//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/error.js 26464function isAtLeastReact17(reactVersion) { 26465 const reactMajor = reactVersion.match(/^([^.]+)/); 26466 return reactMajor !== null && parseInt(reactMajor[0]) >= 17; 26467} 26468function setCause(error, cause) { 26469 const seenErrors = /* @__PURE__ */ new WeakSet(); 26470 function recurse(error2, cause2) { 26471 if (seenErrors.has(error2)) return; 26472 if (error2.cause) { 26473 seenErrors.add(error2); 26474 return recurse(error2.cause, cause2); 26475 } 26476 error2.cause = cause2; 26477 } 26478 recurse(error, cause); 26479} 26480function captureReactException$1(error, { componentStack }, hint) { 26481 if (isAtLeastReact17(import_react$5.version) && isError(error) && componentStack) { 26482 const errorBoundaryError = new Error(error.message); 26483 errorBoundaryError.name = `React ErrorBoundary ${error.name}`; 26484 errorBoundaryError.stack = componentStack; 26485 setCause(error, errorBoundaryError); 26486 } 26487 return captureException(error, hint); 26488} 26489function reactErrorHandler(callback) { 26490 return (error, errorInfo) => { 26491 const hasCallback = !!callback; 26492 const eventId = captureReactException$1(error, errorInfo, { mechanism: { 26493 handled: hasCallback, 26494 type: "auto.function.react.error_handler" 26495 } }); 26496 if (hasCallback) callback(error, errorInfo, eventId); 26497 }; 26498} 26499var import_react$5; 26500function init_error() { 26501 return (init_error = __esmMin((() => { 26502 init_exports(); 26503 init_is(); 26504 import_react$5 = require_react(); 26505 })))(); 26506} 26507//#endregion 26508//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/constants.js 26509var REACT_RENDER_OP, REACT_UPDATE_OP, REACT_MOUNT_OP; 26510function init_constants$7() { 26511 return (init_constants$7 = __esmMin((() => { 26512 REACT_RENDER_OP = "ui.react.render"; 26513 REACT_UPDATE_OP = "ui.react.update"; 26514 REACT_MOUNT_OP = "ui.react.mount"; 26515 })))(); 26516} 26517//#endregion 26518//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/hoist-non-react-statics.js 26519function isMemo(component) { 26520 return typeof component === "object" && component !== null && component.$$typeof === MemoType; 26521} 26522function getStatics(component) { 26523 if (isMemo(component)) return MEMO_STATICS; 26524 const componentType = component.$$typeof; 26525 return componentType && TYPE_STATICS[componentType] || REACT_STATICS; 26526} 26527function hoistNonReactStatics(targetComponent, sourceComponent, excludelist) { 26528 if (typeof sourceComponent !== "string") { 26529 if (objectPrototype) { 26530 const inheritedComponent = getPrototypeOf(sourceComponent); 26531 if (inheritedComponent && inheritedComponent !== objectPrototype) hoistNonReactStatics(targetComponent, inheritedComponent); 26532 } 26533 let keys = getOwnPropertyNames(sourceComponent); 26534 if (getOwnPropertySymbols) keys = keys.concat(getOwnPropertySymbols(sourceComponent)); 26535 const targetStatics = getStatics(targetComponent); 26536 const sourceStatics = getStatics(sourceComponent); 26537 for (const key of keys) if (!KNOWN_STATICS[key] && !sourceStatics?.[key] && !target
26537Statics?.[key] && !getOwnPropertyDescriptor(targetComponent, key)) { 26538 const descriptor = getOwnPropertyDescriptor(sourceComponent, key); 26539 if (descriptor) try { 26540 defineProperty(targetComponent, key, descriptor); 26541 } catch (_e) {} 26542 } 26543 } 26544 return targetComponent; 26545} 26546var REACT_STATICS, KNOWN_STATICS, FORWARD_REF_STATICS, MEMO_STATICS, ForwardRefType, MemoType, TYPE_STATICS, defineProperty, getOwnPropertyNames, getOwnPropertySymbols, getOwnPropertyDescriptor, getPrototypeOf, objectPrototype; 26547function init_hoist_non_react_statics() { 26548 return (init_hoist_non_react_statics = __esmMin((() => { 26549 REACT_STATICS = { 26550 childContextTypes: true, 26551 contextType: true, 26552 contextTypes: true, 26553 defaultProps: true, 26554 displayName: true, 26555 getDefaultProps: true, 26556 getDerivedStateFromError: true, 26557 getDerivedStateFromProps: true, 26558 mixins: true, 26559 propTypes: true, 26560 type: true 26561 }; 26562 KNOWN_STATICS = { 26563 name: true, 26564 length: true, 26565 prototype: true, 26566 caller: true, 26567 callee: true, 26568 arguments: true, 26569 arity: true 26570 }; 26571 FORWARD_REF_STATICS = { 26572 $$typeof: true, 26573 render: true, 26574 defaultProps: true, 26575 displayName: true, 26576 propTypes: true 26577 }; 26578 MEMO_STATICS = { 26579 $$typeof: true, 26580 compare: true, 26581 defaultProps: true, 26582 displayName: true, 26583 propTypes: true, 26584 type: true 26585 }; 26586 ForwardRefType = /* @__PURE__ */ Symbol.for("react.forward_ref"); 26587 MemoType = /* @__PURE__ */ Symbol.for("react.memo"); 26588 TYPE_STATICS = {}; 26589 TYPE_STATICS[ForwardRefType] = FORWARD_REF_STATICS; 26590 TYPE_STATICS[MemoType] = MEMO_STATICS; 26591 defineProperty = Object.defineProperty.bind(Object); 26592 getOwnPropertyNames = Object.getOwnPropertyNames.bind(Object); 26593 getOwnPropertySymbols = Object.getOwnPropertySymbols?.bind(Object); 26594 getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor.bind(Object); 26595 getPrototypeOf = Object.getPrototypeOf.bind(Object); 26596 objectPrototype = Object.prototype; 26597 })))(); 26598} 26599//#endregion 26600//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/profiler.js 26601function withProfiler(WrappedComponent, options) { 26602 const componentDisplayName = options?.name || WrappedComponent.displayName || WrappedComponent.name || "unknown"; 26603 const Wrapped = (props) => /* @__PURE__ */ import_react$4.createElement(Profiler, { 26604 ...options, 26605 name: componentDisplayName, 26606 updateProps: props 26607 }, /* @__PURE__ */ import_react$4.createElement(WrappedComponent, { ...props })); 26608 Wrapped.displayName = `profiler(${componentDisplayName})`; 26609 hoistNonReactStatics(Wrapped, WrappedComponent); 26610 return Wrapped; 26611} 26612function useProfiler(name, options = { 26613 disabled: false, 26614 hasRenderSpan: true 26615}) { 26616 const [mountSpan] = import_react$4.useState(() => { 26617 if (options?.disabled) return; 26618 return startInactiveSpan({ 26619 name: `<${name}>`, 26620 onlyIfParent: true, 26621 op: REACT_MOUNT_OP, 26622 attributes: { 26623 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.react.profiler", 26624 "ui.component_name": name 26625 } 26626 }); 26627 }); 26628 import_react$4.useEffect(() => { 26629 if (mountSpan) mountSpan.end(); 26630 return () => { 26631 if (mountSpan && options.hasRenderSpan) { 26632 const startTime = spanToJSON(mountSpan).timestamp; 26633 const endTimestamp = timestampInSeconds(); 26634 const renderSpan = startInactiveSpan({ 26635 name: `<${name}>`, 26636 onlyIfParent: true, 26637 op: REACT_RENDER_OP, 26638 startTime, 26639 attributes: { 26640 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.react.profiler", 26641 "ui.component_name": name 26642 } 26643 }); 26644 if (renderSpan) renderSpan.end(endTimestamp); 26645 } 26646 }; 26647 }, []); 26648} 26649var import_react$4, Profiler; 26650function init_profiler() { 26651 return (init_profiler = __esmMin((() => { 26652 init_trace(); 26653 init_semanticAttributes(), init_time(), init_spanUtils(); 26654 import_react$4 = /* @__PURE__ */ __toESM(require_react()); 26655 init_constants$7(); 26656 init_hoist_non_react_statics(); 26657 Profiler = class extends import_react$4.Component { 26658 constructor(props) { 26659 super(props); 26660 const { name, disabled = false } = this.props; 26661 if (disabled) return; 26662 this._mountSpan = startInactiveSpan({ 26663 name: `<${name}>`, 26664 onlyIfParent: true, 26665 op: REACT_MOUNT_OP, 26666 attributes: { 26667 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.react.profiler",
26668 "ui.component_name": name 26669 } 26670 }); 26671 } 26672 componentDidMount() { 26673 if (this._mountSpan) this._mountSpan.end(); 26674 } 26675 shouldComponentUpdate({ updateProps, includeUpdates = true }) { 26676 if (includeUpdates && this._mountSpan && updateProps !== this.props.updateProps) { 26677 const changedProps = Object.keys(updateProps).filter((k) => updateProps[k] !== this.props.updateProps[k]); 26678 if (changedProps.length > 0) { 26679 const now = timestampInSeconds(); 26680 this._updateSpan = withActiveSpan(this._mountSpan, () => { 26681 return startInactiveSpan({ 26682 name: `<${this.props.name}>`, 26683 onlyIfParent: true, 26684 op: REACT_UPDATE_OP, 26685 startTime: now, 26686 attributes: { 26687 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.react.profiler", 26688 "ui.component_name": this.props.name, 26689 "ui.react.changed_props": changedProps 26690 } 26691 }); 26692 }); 26693 } 26694 } 26695 return true; 26696 } 26697 componentDidUpdate() { 26698 if (this._updateSpan) { 26699 this._updateSpan.end(); 26700 this._updateSpan = void 0; 26701 } 26702 } 26703 componentWillUnmount() { 26704 const endTimestamp = timestampInSeconds(); 26705 const { name, includeRender = true } = this.props; 26706 if (this._mountSpan && includeRender) { 26707 const startTime = spanToJSON(this._mountSpan).timestamp; 26708 withActiveSpan(this._mountSpan, () => { 26709 const renderSpan = startInactiveSpan({ 26710 onlyIfParent: true, 26711 name: `<${name}>`, 26712 op: REACT_RENDER_OP, 26713 startTime, 26714 attributes: { 26715 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.react.profiler", 26716 "ui.component_name": name 26717 } 26718 }); 26719 if (renderSpan) renderSpan.end(endTimestamp); 26720 }); 26721 } 26722 } 26723 render() { 26724 return this.props.children; 26725 } 26726 }; 26727 Object.assign(Profiler, { defaultProps: { 26728 disabled: false, 26729 includeRender: true, 26730 includeUpdates: true 26731 } }); 26732 })))(); 26733} 26734//#endregion 26735//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/debug-build.js 26736var DEBUG_BUILD; 26737function init_debug_build$3() { 26738 return (init_debug_build$3 = __esmMin((() => { 26739 DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; 26740 })))(); 26741} 26742//#endregion 26743//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/errorboundary.js 26744function withErrorBoundary(WrappedComponent, errorBoundaryOptions) { 26745 const componentDisplayName = WrappedComponent.displayName || WrappedComponent.name || "unknown"; 26746 const Wrapped = import_react$3.memo((props) => /* @__PURE__ */ import_react$3.createElement(ErrorBoundary, { ...errorBoundaryOptions }, /* @__PURE__ */ import_react$3.createElement(WrappedComponent, { ...props }))); 26747 Wrapped.displayName = `errorBoundary(${componentDisplayName})`; 26748 hoistNonReactStatics(Wrapped, WrappedComponent); 26749 return Wrapped; 26750} 26751var import_react$3, INITIAL_STATE, ErrorBoundary; 26752function init_errorboundary() { 26753 return (init_errorboundary = __esmMin((() => { 26754 init_currentScopes(), init_report_dialog(); 26755 init_debug_logger(); 26756 import_react$3 = /* @__PURE__ */ __toESM(require_react()); 26757 init_debug_build$3(); 26758 init_error(); 26759 init_hoist_non_react_statics(); 26760 INITIAL_STATE = { 26761 componentStack: null, 26762 error: null, 26763 eventId: null 26764 }; 26765 ErrorBoundary = class extends import_react$3.Component { 26766 constructor(props) { 26767 super(props); 26768 this.state = INITIAL_STATE; 26769 this._openFallbackReportDialog = true; 26770 const client = getClient(); 26771 if (client && props.showDialog) { 26772 this._openFallbackReportDialog = false; 26773 this._cleanupHook = client.on("afterSendEvent", (event) => { 26774 if (!event.type && this._lastEventId && event.event_id === this._lastEventId) showReportDialog({ 26775 ...props.dialogOptions, 26776 eventId: this._lastEventId 26777 }); 26778 }); 26779 } 26780 } 26781 componentDidCatch(error, errorInfo) { 26782 const { componentStack } = errorInfo; 26783 const { beforeCapture, onError, showDialog, dialogOptions } = this.props; 26784 withScope((scope) => { 26785 if (beforeCapture) beforeCapture(scope, error, componentStack); 26786 const eventId = captureReactException$1(error, errorInfo, { mechanism: { 26787 handled: this.props.handled != null ? this.props.handled : !!this.props.fallback, 26788 type: "auto.function.react.error_boundary" 26789 } }); 26790 if (onError) onError(error, componentStack, eventId); 26791 if (showDialog) { 26792 this._lastEventId = eventId; 26793 if (this._openFallbackReportDialog) showReportDialog({ 26794 ...dialogOptions, 26795 eventId 26796 }); 26797 } 26798 this.setState({ 26799 error, 26800 componentStack, 26801 eventId 26802 }); 26803 }); 26804 } 26805 componentDidMount() { 26806 const { onMount } = this.props; 26807 if (onMount) onMount(); 26808 } 26809 componentWillUnmount() { 26810 const { error, componentStack, eventId } = this.state; 26811 const { onUnmount } = this.props; 26812 if (onUnmount) { 26813 if (this.state === INITIAL_STATE) onUnmount(null, null, null); 26814 else onUnmount(error, componentStack, eventId); 26815 } 26816 if (this._cleanupHook) { 26817 this._cleanupHook(); 26818 this._cleanupHook = void 0; 26819 } 26820 } 26821 resetErrorBoundary() { 26822 const { onReset } = this.props; 26823 const { error, componentStack, eventId } = this.state; 26824 if (onReset) onReset(error, componentStack, eventId); 26825 this.setState(INITIAL_STATE); 26826 } 26827 render() { 26828 const { fallback, children } = this.props; 26829 const state = this.state; 26830 if (state.componentStack === null) return typeof children === "function" ? children() : children; 26831 const element = typeof fallback === "function" ? import_react$3.createElement(fallback, { 26832 error: state.error, 26833 componentStack: state.componentStack, 26834 resetError: () => this.resetErrorBoundary(), 26835 eventId: state.eventId 26836 }) : fallback; 26837 if (import_react$3.isValidElement(element)) return element; 26838 if (fallback) DEBUG_BUILD && debug$2.warn("fallback did not produce a valid ReactElement"); 26839 return null; 26840 } 26841 }; 26842 })))(); 26843} 26844//#endregion 26845//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/redux.js 26846function createReduxEnhancer(enhancerOptions) { 26847 const options = { 26848 ...defaultOptions, 26849 ...enhancerOptions 26850 }; 26851 return (next) => (reducer, initialState) => { 26852 options.attachReduxState && getGlobalScope().addEventProcessor((event, hint) => { 26853 try { 26854 if (event.type === void 0 && event.contexts.state.state.type === "redux") hint.attachments = [...hint.attachments || [], { 26855 filename: "redux_state.json", 26856 data: JSON.stringify(event.contexts.state.state.value) 26857 }
26857]; 26858 } catch {} 26859 return event; 26860 }); 26861 function sentryWrapReducer(reducer2) { 26862 return (state, action) => { 26863 const newState = reducer2(state, action); 26864 const scope = getCurrentScope(); 26865 const transformedAction = options.actionTransformer(action); 26866 if (typeof transformedAction !== "undefined" && transformedAction !== null) addBreadcrumb({ 26867 category: ACTION_BREADCRUMB_CATEGORY, 26868 data: transformedAction, 26869 type: ACTION_BREADCRUMB_TYPE 26870 }); 26871 const transformedState = options.stateTransformer(newState); 26872 if (typeof transformedState !== "undefined" && transformedState !== null) { 26873 const normalizationDepth = (getClient()?.getOptions())?.normalizeDepth || 3; 26874 const newStateContext = { state: { 26875 type: "redux", 26876 value: transformedState 26877 } }; 26878 setNormalizationDepthOverrideHint(newStateContext, 3 + normalizationDepth); 26879 scope.setContext("state", newStateContext); 26880 } else scope.setContext("state", null); 26881 const { configureScopeWithState } = options; 26882 if (typeof configureScopeWithState === "function") configureScopeWithState(scope, newState); 26883 return newState; 26884 }; 26885 } 26886 const store = next(sentryWrapReducer(reducer), initialState); 26887 store.replaceReducer = new Proxy(store.replaceReducer, { apply: function(target, thisArg, args) { 26888 target.apply(thisArg, [sentryWrapReducer(args[0])]); 26889 } }); 26890 return store; 26891 }; 26892} 26893var ACTION_BREADCRUMB_CATEGORY, ACTION_BREADCRUMB_TYPE, defaultOptions; 26894function init_redux() { 26895 return (init_redux = __esmMin((() => { 26896 init_currentScopes(), init_breadcrumbs(), init_normalizationHints(); 26897 ACTION_BREADCRUMB_CATEGORY = "redux.action"; 26898 ACTION_BREADCRUMB_TYPE = "info"; 26899 defaultOptions = { 26900 attachReduxState: true, 26901 actionTransformer: (action) => action, 26902 stateTransformer: (state) => state || null 26903 }; 26904 })))(); 26905} 26906//#endregion 26907//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouterv3.js 26908function reactRouterV3BrowserTracingIntegration(options) { 26909 const integration = browserTracingIntegration({ 26910 ...options, 26911 instrumentPageLoad: false, 26912 instrumentNavigation: false 26913 }); 26914 const { history, routes, match, instrumentPageLoad = true, instrumentNavigation = true } = options; 26915 return { 26916 ...integration, 26917 afterAllSetup(client) { 26918 integration.afterAllSetup(client); 26919 if (instrumentPageLoad && WINDOW$4.location) normalizeTransactionName(routes, WINDOW$4.location, match, (localName, source = "url") => { 26920 startBrowserTracingPageLoadSpan(client, { 26921 name: localName, 26922 attributes: { 26923 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "pageload", 26924 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.react.reactrouter_v3", 26925 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, 26926 ...source === "route" && { ["url.template"]: localName } 26927 } 26928 }); 26929 }); 26930 if (instrumentNavigation && history.listen) history.listen((location) => { 26931 if (location.action === "PUSH" || location.action === "POP") normalizeTransactionName(routes, location, match, (localName, source = "url") => { 26932 startBrowserTracingNavigationSpan(client, { 26933 name: localName, 26934 attributes: { 26935 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "navigation", 26936 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.react.reactrouter_v3", 26937 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, 26938 ...source === "route" && { ["url.template"]: localName } 26939 } 26940 }); 26941 }); 26942 }); 26943 } 26944 }; 26945} 26946function normalizeTransactionName(appRoutes, location, match, callback) { 26947 let name = location.pathname; 26948 match({ 26949 location, 26950 routes: appRoutes 26951 }, (error, _redirectLocation, renderProps) => { 26952 if (error || !renderProps) return callback(name); 26953 const routePath = getRouteStringFromRoutes(renderProps.routes || []); 26954 if (routePath.length === 0 || routePath === "/*") return callback(name); 26955 name = routePath; 26956 return callback(name, "route"); 26957 }); 26958} 26959function getRouteStringFromRoutes(routes) { 26960 if (!Array.isArray(routes) || routes.length === 0) return ""; 26961 const routesWithPaths = routes.filter((route) => !!route.path); 26962 let index = -1; 26963 for (let x = routesWithPaths.length - 1; x >= 0; x--) if (routesWithPaths[x].path?.startsWith("/")) { 26964 index = x; 26965 break; 26966 } 26967 return routesWithPaths.slice(index).reduce((acc, { path }) => { 26968 return `${acc}${acc === "/" || acc === "" ? path : `/${path}`}`; 26969 }, ""); 26970} 26971function init_reactrouterv3() { 26972 return (init_reactrouterv3 = __esmMin((() => { 26973 init_browserTracingIntegration(), init_helpers(); 26974 init_semanticAttributes(); 26975 init_attributes$1(); 26976 })))(); 26977} 26978//#endregion 26979//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/tanstackrouter.js 26980function tanstackRouterBrowserTracingIntegration(router, options = {}) { 26981 const castRouterInstance = router; 26982 const browserTracingIntegrationInstance = browserTracingIntegration({ 26983 ...options, 26984 instrumentNavigation: false, 26985 instrumentPageLoad: false 26986 }); 26987 const { instrumentPageLoad = true, instrumentNavigation = true } = options; 26988 return { 26989 ...browserTracingIntegrationInstance, 26990 afterAllSetup(client) { 26991 browserTracingIntegrationInstance.afterAllSetup(client); 26992 const resolveRouteMatch = (pathname, search) => { 26993 const matchedRoutes = castRouterInstance.matchRoutes(pathname, search, { 26994 preload: false, 26995 throwOnError: false 26996 }); 26997 const lastMatch = matchedRoutes[matchedRoutes.length - 1]; 26998 return lastMatch?.routeId !== "__root__" ? lastMatch : void 0; 26999 }; 27000 const applyRouteMatch = (span, match, toLocation, fallbackName) => { 27001 span.updateName(match ? match.routeId : fallbackName); 27002 span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, match ? "route" : "url"); 27003 span.setAttributes({ 27004 ...match && { ["url.template"]: match.routeId }, 27005 ...locationToSpanUrlAttributes(castRouterInstance, toLocation), 27006 ...routeMatchToParamSpanAttributes(match) 27007 }); 27008 }; 27009 const initialWindowLocation = WINDOW$4.location; 27010 if (instrumentPageLoad && initialWindowLocation) { 27011 const initialRouterLocation = castRouterInstance.state?.location; 27012 const routeMatch = initialRouterLocation ? resolveRouteMatch(initialRouterLocation.pathname, initialRouterLocation.search) : resolveRouteMatch(initialWindowLocation.pathname, castRouterInstance.options.parseSearch(initialWindowLocation.search)); 27013 const pageloadSpan = startBrowserTracingPageLoadSpan(client, { 27014 name: routeMatch ? routeMatch.routeId : initialWindowLocation.pathname, 27015 attributes: { 27016 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "pageload", 27017 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.react.tanstack_router", 27018 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: routeMatch ? "route" : "url", 27019 ...routeMatch && { ["url.template"]: routeMatch.routeId }, 27020 ...routeMatchToParamSpanAttributes(routeMatch) 27021 } 27022 }); 27023 const unsubscribePageloadResolved = castRouterInstance.subscribe("onResolved", (onResolvedArgs) => { 27024 unsubscribePageloadResolved(); 27025 if (!pageloadSpan) return; 27026 const { toLocation } = onResolvedArgs; 27027 const resolvedMatch = resolveRouteMatch(toLocation.pathname, toLocation.search); 27028 applyRouteMatch(pageloadSpan, resolvedMatch, toLocation, toLocation.pathname); 27029 }); 27030 } 27031 if (instrumentNavigation) { 27032 let inFlightNavigationSpan; 27033 castRouterInstance.subscribe("onBeforeLoad", (onBeforeLoadArgs) => { 27034 const { toLocation, fromLocation } = onBeforeLoadArgs; 27035 if (!fromLocation || toLocation.state === fromLocation.state) return; 27036 const routeMatch = resolveRouteMatch(toLocation.pathname, toLocation.search); 27037 const fallbackName = WINDOW$4.location?.pathname || toLocation.pathname; 27038 if (inFlightNavigationSpan) { 27039 applyRouteMatch(inFlightNavigationSpan, routeMatch, toLocation, fallbackName); 27040 return; 27041 } 27042 inFlightNavigationSpan = startBrowserTracingNavigationSpan(client, { 27043 name: routeMatch ? routeMatch.routeId : fallbackName, 27044 attributes: { 27045 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "navigation", 27046 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.react.tanstack_router", 27047 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: routeMatch ? "route" : "url", 27048 ...routeMatch && { ["url.template"]: routeMatch.routeId }, 27049 ...routeMatchToParamSpanAttributes(routeMatch) 27050 } 27051 }, { url: locationToAbsoluteUrl(castRouterInstance, toLocation) }); 27052 }); 27053 castRouterInstance.subscribe("onResolved", (onResolvedArgs) => { 27054 const span = inFlightNavigationSpan; 27055 inFlightNavigationSpan = void 0; 27056 if (!span) return; 27057 const { toLocation } = onResolvedArgs; 27058 const resolvedMatch = resolveRouteMatch(toLocation.pathname, toLocation.search); 27059 if (resolvedMatch) applyRouteMatch(span, resolvedMatch, toLocation, WINDOW$4.location?.pathname || toLocation.pathname); 27060 }); 27061 } 27062 } 27063 }; 27064} 27065function locationToAbsoluteUrl(router, location) { 27066 const search = router.options.stringifySearch?.(location.search) ?? ""; 27067 return getAbsoluteUrl(`${location.pathname}${search && search !== "?" ? search : ""}`); 27068} 27069function locationToSpanUrlAttributes(router, location) { 27070 const absoluteUrl = locationToAbsoluteUrl(router, location); 27071 return { 27072 [Vu]: location.pathname, 27073 [Yu]: absoluteUrl 27074 }; 27075} 27076function routeMatchToParamSpanAttributes(match) { 27077 if (!match) return {}; 27078 const paramAttributes = {};
27079 Object.entries(match.params).forEach(([key, value]) => { 27080 paramAttributes[`url.path.params.${key}`] = value; 27081 paramAttributes[`${Fu}.${key}`] = value; 27082 paramAttributes[`${Jl}.${key}`] = value; 27083 }); 27084 return paramAttributes; 27085} 27086function init_tanstackrouter() { 27087 return (init_tanstackrouter = __esmMin((() => { 27088 init_browserTracingIntegration(), init_helpers(), init_location(); 27089 init_semanticAttributes(); 27090 init_attributes$1(); 27091 })))(); 27092} 27093//#endregion 27094//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter.js 27095function reactRouterV4BrowserTracingIntegration(options) { 27096 const integration = browserTracingIntegration({ 27097 ...options, 27098 instrumentPageLoad: false, 27099 instrumentNavigation: false 27100 }); 27101 const { history, routes, matchPath, instrumentPageLoad = true, instrumentNavigation = true } = options; 27102 return { 27103 ...integration, 27104 afterAllSetup(client) { 27105 integration.afterAllSetup(client); 27106 instrumentReactRouter(client, instrumentPageLoad, instrumentNavigation, history, "reactrouter_v4", routes, matchPath); 27107 } 27108 }; 27109} 27110function reactRouterV5BrowserTracingIntegration(options) { 27111 const integration = browserTracingIntegration({ 27112 ...options, 27113 instrumentPageLoad: false, 27114 instrumentNavigation: false 27115 }); 27116 const { history, routes, matchPath, instrumentPageLoad = true, instrumentNavigation = true } = options; 27117 return { 27118 ...integration, 27119 afterAllSetup(client) { 27120 integration.afterAllSetup(client); 27121 instrumentReactRouter(client, instrumentPageLoad, instrumentNavigation, history, "reactrouter_v5", routes, matchPath); 27122 } 27123 }; 27124} 27125function instrumentReactRouter(client, instrumentPageLoad, instrumentNavigation, history, instrumentationName, allRoutes = [], matchPath) { 27126 function getInitPathName() { 27127 if (history.location) return history.location.pathname; 27128 if (WINDOW$4.location) return WINDOW$4.location.pathname; 27129 } 27130 function normalizeTransactionName(pathname) { 27131 if (allRoutes.length === 0 || !matchPath) return [pathname, "url"]; 27132 const branches = matchRoutes(allRoutes, pathname, matchPath); 27133 for (const branch of branches) if (branch.match.isExact) return [branch.match.path, "route"]; 27134 return [pathname, "url"]; 27135 } 27136 if (instrumentPageLoad) { 27137 const initPathName = getInitPathName(); 27138 if (initPathName) { 27139 const [name, source] = normalizeTransactionName(initPathName); 27140 startBrowserTracingPageLoadSpan(client, { 27141 name, 27142 attributes: { 27143 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "pageload", 27144 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.pageload.react.${instrumentationName}`, 27145 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, 27146 ...source === "route" && { ["url.template"]: name } 27147 } 27148 }); 27149 } 27150 } 27151 if (instrumentNavigation && history.listen) history.listen((location, action) => { 27152 if (action && (action === "PUSH" || action === "POP")) { 27153 const [name, source] = normalizeTransactionName(location.pathname); 27154 startBrowserTracingNavigationSpan(client, { 27155 name, 27156 attributes: { 27157 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "navigation", 27158 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.navigation.react.${instrumentationName}`, 27159 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, 27160 ...source === "route" && { ["url.template"]: name } 27161 } 27162 }); 27163 } 27164 }); 27165} 27166function matchRoutes(routes, pathname, matchPath, branch = []) { 27167 routes.some((route) => { 27168 const match = route.path ? matchPath(pathname, route) : branch.length ? branch[branch.length - 1].match : computeRootMatch(pathname); 27169 if (match) { 27170 branch.push({ 27171 route, 27172 match 27173 }); 27174 if (route.routes) matchRoutes(route.routes, pathname, matchPath, branch); 27175 } 27176 return !!match; 27177 }); 27178 return branch; 27179} 27180function computeRootMatch(pathname) { 27181 return { 27182 path: "/", 27183 url: "/", 27184 params: {}, 27185 isExact: pathname === "/" 27186 }; 27187} 27188function withSentryRouting(Route) { 27189 const componentDisplayName = Route.displayName || Route.name; 27190 const WrappedRoute = (props) => { 27191 if (props?.computedMatch?.isExact) { 27192 const route = props.computedMatch.path; 27193 const activeRootSpan = getActiveRootSpan$1(); 27194 getCurrentScope().setTransactionName(route); 27195 if (activeRootSpan) { 27196 activeRootSpan.updateName(route); 27197 activeRootSpan.setAttributes({ 27198 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "route", 27199 [ju]: route 27200 }); 27201 } 27202 } 27203 return /* @__PURE__ */ import_react$2.createElement(Route, { ...props }); 27204 }; 27205 WrappedRoute.displayName = `sentryRoute(${componentDisplayName})`; 27206 hoistNonReactStatics(WrappedRoute, Route); 27207 return WrappedRoute; 27208} 27209function getActiveRootSpan$1() { 27210 const span = getActiveSpan(); 27211 const rootSpan = span && getRootSpan(span); 27212 if (!rootSpan) return; 27213 const op = spanToJSON(rootSpan).op; 27214 return op === "navigation" || op === "pageload" ? rootSpan : void 0; 27215} 27216var import_react$2; 27217function init_reactrouter() { 27218 return (init_reactrouter = __esmMin((() => { 27219 init_browserTracingIntegration(), init_helpers(); 27220 init_semanticAttributes(), init_currentScopes(), init_spanUtils(); 27221 import_react$2 = /* @__PURE__ */ __toESM(require_react()); 27222 init_hoist_non_react_statics(); 27223 init_attributes$1(); 27224 })))(); 27225} 27226//#endregion 27227//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter-compat-utils/route-manifest.js
27228function stripBasenameFromPathname(pathname, basename) { 27229 if (!basename || basename === "/") return pathname; 27230 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return pathname; 27231 const startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; 27232 const nextChar = pathname.charAt(startIndex); 27233 if (nextChar && nextChar !== "/") return pathname; 27234 return pathname.slice(startIndex) || "/"; 27235} 27236function matchRouteManifest(pathname, manifest, basename) { 27237 if (!pathname || !manifest?.length) return null; 27238 const normalizedPathname = basename ? stripBasenameFromPathname(pathname, basename) : pathname; 27239 let sorted = SORTED_MANIFEST_CACHE.get(manifest); 27240 if (!sorted) { 27241 sorted = sortBySpecificity(manifest); 27242 SORTED_MANIFEST_CACHE.set(manifest, sorted); 27243 DEBUG_BUILD && debug$2.log("[React Router] Sorted route manifest by specificity:", sorted.length, "patterns"); 27244 } 27245 for (const pattern of sorted) if (matchesPattern(normalizedPathname, pattern)) { 27246 DEBUG_BUILD && debug$2.log("[React Router] Matched pathname", normalizedPathname, "to pattern", pattern); 27247 return pattern; 27248 } 27249 DEBUG_BUILD && debug$2.log("[React Router] No manifest match found for pathname:", normalizedPathname); 27250 return null; 27251} 27252function matchesPattern(pathname, pattern) { 27253 if (pattern === "/") return pathname === "/" || pathname === ""; 27254 const pathSegments = splitPath(pathname); 27255 const patternSegments = splitPath(pattern); 27256 if (patternSegments.length > 0 && patternSegments[patternSegments.length - 1] === "*") { 27257 const patternSegmentsWithoutWildcard = patternSegments.slice(0, -1); 27258 if (pathSegments.length < patternSegmentsWithoutWildcard.length) return false; 27259 for (const [i, patternSegment] of patternSegmentsWithoutWildcard.entries()) if (!segmentMatches(pathSegments[i], patternSegment)) return false; 27260 return true; 27261 } 27262 if (pathSegments.length !== patternSegments.length) return false; 27263 for (const [i, patternSegment] of patternSegments.entries()) if (!segmentMatches(pathSegments[i], patternSegment)) return false; 27264 return true; 27265} 27266function segmentMatches(pathSegment, patternSegment) { 27267 if (pathSegment === void 0 || patternSegment === void 0) return false; 27268 if (PARAM_RE.test(patternSegment)) return true; 27269 return pathSegment === patternSegment; 27270} 27271function splitPath(path) { 27272 return path.split("/").filter(Boolean); 27273} 27274function computeScore(pattern) { 27275 const segments = pattern.split("/"); 27276 let score = segments.length; 27277 if (segments.includes("*")) score += SPLAT_PENALTY; 27278 for (const segment of segments) if (segment === "*") continue; 27279 else if (PARAM_RE.test(segment)) score += DYNAMIC_SEGMENT_SCORE; 27280 else if (segment === "") score += EMPTY_SEGMENT_SCORE; 27281 else score += STATIC_SEGMENT_SCORE; 27282 return score; 27283} 27284function sortBySpecificity(manifest) { 27285 return [...manifest].sort((a, b) => { 27286 const aScore = computeScore(a); 27287 return computeScore(b) - aScore; 27288 }); 27289} 27290var SORTED_MANIFEST_CACHE, PARAM_RE, STATIC_SEGMENT_SCORE, DYNAMIC_SEGMENT_SCORE, EMPTY_SEGMENT_SCORE, SPLAT_PENALTY; 27291function init_route_manifest() { 27292 return (init_route_manifest = __esmMin((() => { 27293 init_debug_logger(); 27294 init_debug_build$3(); 27295 SORTED_MANIFEST_CACHE = /* @__PURE__ */ new WeakMap(); 27296 PARAM_RE = /^:[\w-]+$/; 27297 STATIC_SEGMENT_SCORE = 10; 27298 DYNAMIC_SEGMENT_SCORE = 3; 27299 EMPTY_SEGMENT_SCORE = 1; 27300 SPLAT_PENALTY = -2; 27301 })))(); 27302} 27303//#endregion 27304//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter-compat-utils/utils.js 27305function setNavigationContext(targetPath, span) { 27306 const token = {}; 27307 if (_navigationContextStack.length >= MAX_CONTEXT_STACK_SIZE) { 27308 DEBUG_BUILD && debug$2.warn("[React Router] Navigation context stack overflow - removing oldest context"); 27309 _navigationContextStack.shift(); 27310 } 27311 _navigationContextStack.push({ 27312 token, 27313 targetPath, 27314 span 27315 }); 27316 return token; 27317} 27318function clearNavigationContext(token) { 27319 if (_navigationContextStack[_navigationContextStack.length - 1]?.token === token) _navigationContextStack.pop(); 27320} 27321function getNavigationContext() { 27322 const length = _navigationContextStack.length; 27323 return length > 0 ? _navigationContextStack[length - 1] ?? null : null; 27324}
27325function initializeRouterUtils(matchRoutes, stripBasename = false) { 27326 _matchRoutes$1 = matchRoutes; 27327 _stripBasename = stripBasename; 27328} 27329function pickPath(match) { 27330 return trimWildcard(match.route.path || ""); 27331} 27332function pickSplat(match) { 27333 return match.params["*"] || ""; 27334} 27335function trimWildcard(path) { 27336 return path[path.length - 1] === "*" ? path.slice(0, -1) : path; 27337} 27338function trimSlash(path) { 27339 return path[path.length - 1] === "/" ? path.slice(0, -1) : path; 27340} 27341function pathEndsWithWildcard(path) { 27342 return path.endsWith("*"); 27343} 27344function transactionNameHasWildcard(name) { 27345 return name.includes("/*") || name.endsWith("*"); 27346} 27347function pathIsWildcardAndHasChildren(path, branch) { 27348 return pathEndsWithWildcard(path) && !!branch.route.children?.length || false; 27349} 27350function routeIsDescendant(route) { 27351 return !!(!route.children && route.element && route.path?.endsWith("/*")); 27352} 27353function sendIndexPath(pathBuilder, pathname, basename) { 27354 const reconstructedPath = pathBuilder && pathBuilder.length > 0 ? pathBuilder : _stripBasename ? stripBasenameFromPathname(pathname, basename) : pathname; 27355 let formattedPath = reconstructedPath.slice(-2) === "/*" ? reconstructedPath.slice(0, -2) : reconstructedPath; 27356 if (formattedPath.length > 1 && formattedPath[formattedPath.length - 1] === "/") formattedPath = formattedPath.slice(0, -1); 27357 return [formattedPath, "route"]; 27358} 27359function getNumberOfUrlSegments(url) { 27360 return url.split(/\\?\//).filter((s) => s.length > 0 && s !== ",").length; 27361} 27362function prefixWithSlash(path) { 27363 return path[0] === "/" ? path : `/${path}`; 27364} 27365function rebuildRoutePathFromAllRoutes(allRoutes, location) { 27366 const matchedRoutes = _matchRoutes$1(allRoutes, location); 27367 if (!matchedRoutes || matchedRoutes.length === 0) return ""; 27368 for (const match of matchedRoutes) if (match.route.path && match.route.path !== "*") { 27369 const path = pickPath(match); 27370 const strippedPath = stripBasenameFromPathname(location.pathname, prefixWithSlash(match.pathnameBase)); 27371 if (location.pathname === strippedPath) return trimSlash(strippedPath); 27372 return trimSlash(trimSlash(path || "") + prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes.filter((route) => route !== match.route), { pathname: strippedPath }))); 27373 } 27374 return ""; 27375} 27376function reconstructNameFromDescendantParent(location, allRoutes, currentName) { 27377 const descendantParents = allRoutes.filter(routeIsDescendant); 27378 if (!descendantParents.length) return; 27379 const matchedParents = _matchRoutes$1(descendantParents, location); 27380 const parentMatch = matchedParents?.[matchedParents.length - 1]; 27381 if (!parentMatch || !pickSplat(parentMatch)) return; 27382 const parentTemplate = trimSlash(trimWildcard(parentMatch.route.path || "")); 27383 if (!parentTemplate) return; 27384 const expectedPrefix = prefixWithSlash(parentTemplate); 27385 const firstElement = parentTemplate.split("/")[0]; 27386 const hasDynamicLead = firstElement?.startsWith(":") && currentName?.split("/").includes(firstElement); 27387 if (currentName === expectedPrefix || currentName?.startsWith(`${expectedPrefix}/`) || hasDynamicLead) return; 27388 const remainingPathname = stripBasenameFromPathname(location.pathname, prefixWithSlash(parentMatch.pathnameBase)) || "/"; 27389 const remainingName = rebuildRoutePathFromAllRoutes(allRoutes.filter((route) => route !== parentMatch.route), { pathname: remainingPathname }); 27390 return remainingName ? prefixWithSlash(`${parentTemplate}${prefixWithSlash(remainingName)}`) : void 0; 27391} 27392function locationIsInsideDescendantRoute(location, routes) { 27393 const matchedRoutes = _matchRoutes$1(routes, location); 27394 if (matchedRoutes) { 27395 for (const match of matchedRoutes) if (routeIsDescendant(match.route) && pickSplat(match)) return true; 27396 } 27397 return false; 27398} 27399function getFallbackTransactionName(location, basename) { 27400 return _stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname || ""; 27401} 27402function getNormalizedName(routes, location, branches, basename = "") { 27403 if (!routes || routes.length === 0) return [_stripBasename ? stripBasenameFromPathname(location.pathname, basename) : location.pathname, "url"]; 27404 if (!branches) return [getFallbackTransactionName(location, basename), "url"]; 27405 let pathBuilder = ""; 27406 for (const branch of branches) { 27407 const route = branch.route; 27408 if (!route) continue; 27409 if (route.index) return sendIndexPath(pathBuilder, branch.pathname, base
27409name); 27410 const path = route.path; 27411 if (!path || pathIsWildcardAndHasChildren(path, branch)) continue; 27412 const newPath = path[0] === "/" || pathBuilder[pathBuilder.length - 1] === "/" ? path : `/${path}`; 27413 pathBuilder = trimSlash(pathBuilder) + prefixWithSlash(newPath); 27414 if (trimSlash(location.pathname) !== trimSlash(basename + branch.pathname)) continue; 27415 if (getNumberOfUrlSegments(pathBuilder) !== getNumberOfUrlSegments(branch.pathname) && !pathEndsWithWildcard(pathBuilder)) return [(_stripBasename ? "" : basename) + newPath, "route"]; 27416 if (pathIsWildcardAndHasChildren(pathBuilder, branch)) pathBuilder = pathBuilder.slice(0, -1); 27417 return [(_stripBasename ? "" : basename) + pathBuilder, "route"]; 27418 } 27419 return [getFallbackTransactionName(location, basename), "url"]; 27420} 27421function resolveRouteNameAndSource(location, routes, allRoutes, branches, basename = "", lazyRouteManifest, enableAsyncRouteHandlers) { 27422 if (enableAsyncRouteHandlers && lazyRouteManifest && lazyRouteManifest.length > 0) { 27423 const manifestMatch = matchRouteManifest(location.pathname, lazyRouteManifest, base
27423name); 27424 if (manifestMatch) return [(_stripBasename ? "" : basename) + manifestMatch, "route"]; 27425 } 27426 let name; 27427 let source = "url"; 27428 const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes); 27429 if (isInDescendantRoute) { 27430 name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes, location)); 27431 source = "route"; 27432 } 27433 if (!isInDescendantRoute || !name) [name, source] = getNormalizedName(routes, location, branches, basename); 27434 const anchoredName = reconstructNameFromDescendantParent(location, allRoutes, name); 27435 if (anchoredName) return [anchoredName, "route"]; 27436 return [name || location.pathname, source]; 27437} 27438function getActiveRootSpan() { 27439 const span = getActiveSpan(); 27440 const rootSpan = span ? getRootSpan(span) : void 0; 27441 if (!rootSpan) return; 27442 const op = spanToJSON(rootSpan).op; 27443 return op === "navigation" || op === "pageload" ? rootSpan : void 0; 27444} 27445var _matchRoutes$1, _stripBasename, _navigationContextStack, MAX_CONTEXT_STACK_SIZE; 27446function init_utils$11() { 27447 return (init_utils$11 = __esmMin((() => { 27448 init_spanUtils(), init_debug_logger(); 27449 init_debug_build$3(); 27450 init_route_manifest(); 27451 _stripBasename = false; 27452 _navigationContextStack = []; 27453 MAX_CONTEXT_STACK_SIZE = 10; 27454 })))(); 27455} 27456//#endregion 27457//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter-compat-utils/lazy-routes.js 27458function captureCurrentLocation() { 27459 const navContext = getNavigationContext(); 27460 if (navContext) { 27461 if (navContext.targetPath) return { 27462 pathname: navContext.targetPath, 27463 search: "", 27464 hash: "", 27465 state: null, 27466 key: "default" 27467 }; 27468 return null; 27469 } 27470 if (typeof WINDOW$4 !== "undefined") try { 27471 const windowLocation = WINDOW$4.location; 27472 if (windowLocation) return { 27473 pathname: windowLocation.pathname, 27474 search: windowLocation.search || "", 27475 hash: windowLocation.hash || "", 27476 state: null, 27477 key: "default" 27478 }; 27479 } catch { 27480 DEBUG_BUILD && debug$2.warn("[React Router] Could not access window.location"); 27481 } 27482 return null; 27483} 27484function captureActiveSpan() { 27485 const navContext = getNavigationContext(); 27486 if (navContext) return navContext.span; 27487 return getActiveRootSpan(); 27488} 27489function createAsyncHandlerProxy(originalFunction, route, handlerKey, processResolvedRoutes) { 27490 const proxy = new Proxy(originalFunction, { apply(target, thisArg, argArray) { 27491 const locationAtInvocation = captureCurrentLocation(); 27492 const spanAtInvocation = captureActiveSpan(); 27493 const result = target.apply(thisArg, argArray); 27494 handleAsyncHandlerResult(result, route, handlerKey, processResolvedRoutes, locationAtInvocation, spanAtInvocation); 27495 return result; 27496 } }); 27497 addNonEnumerableProperty(proxy, "__sentry_proxied__", true); 27498 return proxy; 27499} 27500function handleAsyncHandlerResult(result, route, handlerKey, processResolvedRoutes, currentLocation, capturedSpan) { 27501 if (isThenable(result)) result.then((resolvedRoutes) => { 27502 if (Array.isArray(resolvedRoutes)) processResolvedRoutes(resolvedRoutes, route, currentLocation ?? void 0, capturedSpan); 27503 }).catch((e) => { 27504 DEBUG_BUILD && debug$2.warn(`Error resolving async handler '${handlerKey}' for route`, route, e); 27505 }); 27506 else if (Array.isArray(result)) processResolvedRoutes(result, route, currentLocation ?? void 0, capturedSpan); 27507} 27508function checkRouteForAsyncHandler(route, processResolvedRoutes) { 27509 if (route.handle && typeof route.handle === "object") for (const key of Object.keys(route.handle)) { 27510 const maybeFn = route.handle[key]; 27511 if (typeof maybeFn === "function" && !maybeFn.__sentry_proxied__) route.handle[key] = createAsyncHandlerProxy(maybeFn, route, key, processResolvedRoutes); 27512 } 27513 if (Array.isArray(route.children)) for (const child of route.children) checkRouteForAsyncHandler(child, processResolvedRoutes); 27514} 27515function init_lazy_routes() { 27516 return (init_lazy_routes = __esmMin((() => { 27517 init_helpers(); 27518 init_object(), init_debug_logger(), init_is(); 27519 init_debug_build$3(); 27520 init_utils$11(); 27521 })))(); 27522} 27523//#endregion 27524//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter-compat-utils/instrumentation.js 27525function scheduleCallback(callback) { 27526 if (WINDOW$4?.requestAnimationFrame) return WINDOW$4.requestAnimationFrame(callback); 27527 return setTimeout(callback, 0); 27528} 27529function cancelScheduledCallback(id) { 27530 if (WINDOW$4?.cancelAnimationFrame) WINDOW$4.cancelAnimationFrame(id); 27531 else clearTimeout(id); 27532} 27533function computeLocationKey(location) { 27534 return `${location.pathname}${location.search || ""}${location.hash || ""}`; 27535} 27536function isParameterizedRoute(routeName) { 27537 return routeName.includes(":") || routeName.includes("*"); 27538} 27539function shouldSkipNavigation(trackedNav, locationKey, proposedName, spanHasEnded) { 27540 if (!trackedNav) return { 27541 skip: false, 27542 shouldUpdate: false 27543 }; 27544 if (trackedNav.locationKey === locationKey && (trackedNav.isPlaceholder || !spanHasEnded)) { 27545 const currentHasWildcard = !!trackedNav.routeName && transactionNameHasWildcard(trackedNav.routeName); 27546 const proposedHasWildcard = transactionNameHasWildcard(proposedName); 27547 const currentIsParameterized = !!trackedNav.routeName && isParameterizedRoute(trackedNav.routeName); 27548 const proposedIsParameterized = isParameterizedRoute(proposedName); 27549 const isWildcardUpgrade = currentHasWildcard && !proposedHasWildcard; 27550 const isRawToParameterized = !currentIsParameterized && proposedIsParameterized; 27551 const isMoreSpecific = proposedName !== trackedNav.routeName && proposedName.length > (trackedNav.routeName?.length || 0) && !proposedHasWildcard; 27552 return { 27553 skip: true, 27554 shouldUpdate: !!(trackedNav.routeName && (isWildcardUpgrade || isRawToParameterized || isMoreSpecific)) 27555 }; 27556 } 27557 return { 27558 skip: false, 27559 shouldUpdate: false 27560 }; 27561} 27562function addResolvedRoutesToParent(resolvedRoutes, parentRoute) { 27563 const existingChildren = parentRoute.children || []; 27564 const newRoutes = resolvedRoutes.filter((newRoute) => !existingChildren.some((existing) => existing === newRoute || newRoute.path && existing.path === newRoute.path || newRoute.i
27564d && existing.id === newRoute.id)); 27565 if (newRoutes.length > 0) parentRoute.children = [...existingChildren, ...newRoutes]; 27566} 27567function trackLazyRouteLoad(span, promise) { 27568 let promises = pendingLazyRouteLoads.get(span); 27569 if (!promises) { 27570 promises = /* @__PURE__ */ new Set(); 27571 pendingLazyRouteLoads.set(span, promises); 27572 } 27573 promises.add(promise); 27574 promise.finally(() => { 27575 const currentPromises = pendingLazyRouteLoads.get(span); 27576 if (currentPromises) currentPromises.delete(promise); 27577 }); 27578} 27579function createDeferredLazyRoutePromise(span) { 27580 trackLazyRouteLoad(span, new Promise((resolve) => { 27581 deferredLazyRouteResolvers.set(span, resolve); 27582 })); 27583} 27584function resolveDeferredLazyRoutePromise(span) { 27585 const resolver = deferredLazyRouteResolvers.get(span); 27586 if (resolver) { 27587 resolver(); 27588 deferredLazyRouteResolvers.delete(span); 27589 if (span.__sentry_may_have_lazy_routes__) span.__sentry_may_have_lazy_routes__ = false; 27590 } 27591} 27592function processResolvedRoutes(resolvedRoutes, parentRoute, currentLocation = null, capturedSpan) { 27593 resolvedRoutes.forEach((child) => { 27594 allRoutes.add(child); 27595 if (_enableAsyncRouteHandlers) checkRouteForAsyncHandler(child, processResolvedRoutes); 27596 }); 27597 if (parentRoute) addResolvedRoutesToParent(resolvedRoutes, parentRoute); 27598 const targetSpan = capturedSpan ?? getActiveRootSpan(); 27599 if (targetSpan) { 27600 const spanJson = spanToJSON(targetSpan); 27601 if (spanJson.timestamp) { 27602 DEBUG_BUILD && debug$2.warn("[React Router] Lazy handler resolved after span ended - skipping update"); 27603 return; 27604 } 27605 const spanOp = spanJson.op; 27606 let location = currentLocation; 27607 if (!location && !capturedSpan) { 27608 if (typeof WINDOW$4 !== "undefined") { 27609 const globalLocation = WINDOW$4.location; 27610 if (globalLocation?.pathname) location = { pathname: globalLocation.pathname }; 27611 } 27612 } 27613 if (location) { 27614 if (spanOp === "pageload") updatePageloadTransaction({ 27615 activeRootSpan: targetSpan, 27616 location: { pathname: location.pathname }, 27617 routes: Array.from(allRoutes), 27618 allRoutes: Array.from(allRoutes) 27619 }); 27620 else if (spanOp === "navigation") updateNavigationSpan(targetSpan, location, Array.from(allRoutes), false, _matchRoutes); 27621 } 27622 } 27623} 27624function updateNavigationSpan(activeRootSpan, location, allRoutes2, forceUpdate = false, matchRoutes) { 27625 const spanJson = spanToJSON(activeRootSpan); 27626 const currentName = spanJson.description; 27627 const hasBeenNamed = activeRootSpan?.__sentry_navigation_name_set__; 27628 const currentNameHasWildcard = currentName && transactionNameHasWildcard(currentName);
27629 if ((!hasBeenNamed || forceUpdate || currentNameHasWildcard) && !spanJson.timestamp) { 27630 const [name, source] = resolveRouteNameAndSource(location, allRoutes2, allRoutes2, matchRoutes(allRoutes2, location) || [], _basename, _lazyRouteManifest, _enableAsyncRouteHandlers); 27631 const currentSource = spanJson.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 27632 if (name && (!currentName || !hasBeenNamed && (currentSource !== "route" || source === "route") || currentSource !== "route" && source === "route" || currentSource === "route" && source === "route" && currentNameHasWildcard)) { 27633 activeRootSpan.updateName(name); 27634 activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); 27635 if (source === "route") activeRootSpan.setAttribute(ju, name); 27636 if (!transactionNameHasWildcard(name) && source === "route") addNonEnumerableProperty(activeRootSpan, "__sentry_navigation_name_set__", true); 27637 } 27638 } 27639} 27640function setupRouterSubscription(router, routes, version, basename, activeRootSpan) { 27641 let isInitialPageloadComplete = false; 27642 let hasSeenPageloadSpan = !!activeRootSpan && spanToJSON(activeRootSpan).op === "pageload"; 27643 let hasSeenPopAfterPageload = false; 27644 let scheduledNavigationHandler = null; 27645 let lastHandledPathname = null; 27646 router.subscribe((state) => { 27647 if (!isInitialPageloadComplete) { 27648 const currentRootSpan = getActiveRootSpan(); 27649 if (currentRootSpan && spanToJSON(currentRootSpan).op === "pageload") hasSeenPageloadSpan = true; 27650 else if (hasSeenPageloadSpan) { 27651 if (state.historyAction === "POP" && !hasSeenPopAfterPageload) hasSeenPopAfterPageload = true; 27652 else isInitialPageloadComplete = true; 27653 } 27654 } 27655 if (state.historyAction === "PUSH" || state.historyAction === "POP" && isInitialPageloadComplete) { 27656 const currentLocationKey = computeLocationKey(state.location); 27657 const navigationHandler = () => { 27658 if (lastHandledPathname === currentLocationKey) return; 27659 lastHandledPathname = currentLocationKey; 27660 scheduledNavigationHandler = null; 27661 handleNavigation({ 27662 location: state.location, 27663 routes, 27664 navigationType: state.historyAction, 27665 version, 27666 basename, 27667 allRoutes: Array.from(allRoutes) 27668 }); 27669 }; 27670 if (state.navigation.state !== "idle") { 27671 if (lastHandledPathname !== currentLocationKey) lastHandledPathname = null; 27672 if (scheduledNavigationHandler !== null) cancelScheduledCallback(scheduledNavigationHandler); 27673 scheduledNavigationHandler = scheduleCallback(navigationHandler); 27674 } else { 27675 if (scheduledNavigationHandler !== null) { 27676 cancelScheduledCallback(scheduledNavigationHandler); 27677 scheduledNavigationHandler = null; 27678 } 27679 navigationHandler(); 27680 } 27681 } 27682 }); 27683} 27684function createV6CompatibleWrapCreateBrowserRouter(createRouterFunction, version) { 27685 if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) { 27686 DEBUG_BUILD && debug$2.warn(`reactRouter${version ? `V${version}` : ""}Instrumentation was unable to wrap the \`createRouter\` function because of one or more missing parameters.`); 27687 return createRouterFunction; 27688 } 27689 return function(routes, opts) { 27690 addRoutesToAllRoutes(routes); 27691 if (_enableAsyncRouteHandlers) for (const route of routes) checkRouteForAsyncHandler(route, processResolvedRoutes); 27692 const activeRootSpan = getActiveRootSpan(); 27693 if (opts && "patchRoutesOnNavigation" in opts && typeof opts.patchRoutesOnNavigation === "function" && activeRootSpan) { 27694 addNonEnumerableProperty(activeRootSpan, "__sentry_may_have_lazy_routes__", true); 27695 createDeferredLazyRoutePromise(activeRootSpan); 27696 } 27697 const router = createRouterFunction(routes, wrapPatchRoutesOnNavigation(opts, false, activeRootSpan)); 27698 const basename = opts?.basename; 27699 if (router.state.historyAction === "POP" && activeRootSpan) updatePageloadTransaction({ 27700 activeRootSpan, 27701 location: router.state.location, 27702 routes, 27703 basename, 27704 allRoutes: Array.from(allRoutes) 27705 }); 27706 _basename = basename || ""; 27707 setupRouterSubscription(router, routes, version, basename, activeRootSpan); 27708 return router; 27709 }; 27710} 27711function createV6CompatibleWrapCreateMemoryRouter(createRouterFunction, version) { 27712 if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) { 27713 DEBUG_BUILD && debug$2.warn(`reactRouter${version ? `V${version}` : ""}Instrumentation was unable to wrap the \`createMemoryRouter\` function because of one or more missing parameters.`); 27714 return createRouterFunction; 27715 } 27716 return function(routes, opts) { 27717 addRoutesToAllRoutes(routes); 27718 if (_enableAsyncRouteHandlers) for (const route of routes) checkRouteForAsyncHandler(route, processResolvedRoutes); 27719 const memoryActiveRootSpanEarly = getActiveRootSpan(); 27720 if (opts && "patchRoutesOnNavigation" in opts && typeof opts.patchRoutesOnNavigation === "function" && memoryActiveRootSpanEarly) { 27721 addNonEnumerableProperty(memoryActiveRootSpanEarly, "__sentry_may_have_lazy_routes__", true); 27722 createDeferredLazyRoutePromise(memoryActiveRootSpanEarly); 27723 } 27724 const router = createRouterFunction(routes, wrapPatchRoutesOnNavigation(opts, true, memoryActiveRootSpanEarly)); 27725 const basename = opts?.basename; 27726 let initialEntry = void 0; 27727 const initialEntries = opts?.initialEntries; 27728 const initialIndex = opts?.initialIndex; 27729 const hasOnlyOneInitialEntry = initialEntries?.length === 1; 27730 const hasIndexedEntry = initialIndex !== void 0 && initialEntries?.[initialIndex]; 27731 initialEntry = hasOnlyOneInitialEntry ? initialEntries[0] : hasIndexedEntry ? initialEntries[initialIndex] : void 0; 27732 const location = initialEntry ? typeof initialEntry === "string" ? { pathname: initialEntry } : initialEntry : router.state.location; 27733 const memoryActiveRootSpan = getActiveRootSpan(); 27734 if (router.state.historyAction === "POP" && memoryActiveRootSpan) updatePageloadTransaction({ 27735 activeRootSpan: memoryActiveRootSpan, 27736 location, 27737 routes, 27738 basename, 27739 allRoutes: Array.from(allRoutes) 27740 }); 27741 _basename = basename || ""; 27742 setupRouterSubscription(router, routes, version, basename, memoryActiveRootSpan); 27743 return router; 27744 }; 27745} 27746function createReactRouterV6CompatibleTracingIntegration(options, version) { 27747 const integration = browserTracingIntegration({ 27748 ...options, 27749 instrumentPageLoad: false, 27750 instrumentNavigation: false 27751 }); 27752 const { useEffect, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes, str
27752ipBasename, enableAsyncRouteHandlers = false, instrumentPageLoad = true, instrumentNavigation = true, lazyRouteTimeout, lazyRouteManifest } = options; 27753 return { 27754 ...integration, 27755 setup(client) { 27756 integration.setup(client); 27757 const finalTimeout = options.finalTimeout ?? 3e4; 27758 const defaultMaxWait = (options.idleTimeout ?? 1e3) * 3; 27759 const configuredMaxWait = lazyRouteTimeout ?? defaultMaxWait; 27760 if (configuredMaxWait === Infinity) { 27761 _lazyRouteTimeout = finalTimeout; 27762 DEBUG_BUILD && debug$2.log("[React Router] lazyRouteTimeout set to Infinity, capping at finalTimeout:", finalTimeout, "ms to prevent indefinite hangs"); 27763 } else if (Number.isNaN(configuredMaxWait)) { 27764 DEBUG_BUILD && debug$2.warn("[React Router] lazyRouteTimeout must be a number, falling back to default:", defaultMaxWait); 27765 _lazyRouteTimeout = defaultMaxWait; 27766 } else if (configuredMaxWait < 0) { 27767 DEBUG_BUILD && debug$2.warn("[React Router] lazyRouteTimeout must be non-negative or Infinity, got:", configuredMaxWait, "falling back to:", defaultMaxWait); 27768 _lazyRouteTimeout = defaultMaxWait; 27769 } else _lazyRouteTimeout = configuredMaxWait; 27770 _useEffect = useEffect; 27771 _useLocation = useLocation; 27772 _useNavigationType = useNavigationType; 27773 _matchRoutes = matchRoutes; 27774 _createRoutesFromChildren = createRoutesFromChildren; 27775 _enableAsyncRouteHandlers = enableAsyncRouteHandlers; 27776 _lazyRouteManifest = lazyRouteManifest; 27777 initializeRouterUtils(matchRoutes, stripBasename || false); 27778 }, 27779 afterAllSetup(client) { 27780 integration.afterAllSetup(client); 27781 const initPathName = WINDOW$4.location?.pathname; 27782 if (instrumentPageLoad && initPathName) startBrowserTracingPageLoadSpan(client, { 27783 name: initPathName, 27784 attributes: { 27785 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", 27786 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "pageload", 27787 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.pageload.react.reactrouter${version ? `_v${version}` : ""}` 27788 } 27789 }); 27790 if (instrumentNavigation) CLIENTS_WITH_INSTRUMENT_NAVIGATION.add(client); 27791 } 27792 }; 27793} 27794function createV6CompatibleWrapUseRoutes(origUseRoutes, version) { 27795 if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) { 27796 DEBUG_BUILD && debug$2.warn("reactRouterV6Instrumentation was unable to wrap `useRoutes` because of one or more missing parameters."); 27797 return origUseRoutes; 27798 } 27799 const SentryRoutes = (props) => { 27800 const isMountRenderPass = import_react$1.useRef(true); 27801 const { routes, locationArg } = props; 27802 const Routes = origUseRoutes(routes, locationArg); 27803 const location = _useLocation(); 27804 const navigationType = _useNavigationType(); 27805 const stableLocationParam = typeof locationArg === "string" || locationArg?.pathname ? locationArg : location; 27806 useIsomorphicLayoutEffect(() => { 27807 const added = addRoutesToAllRoutes(routes); 27808 return () => removeRoutesFromAllRoutes(added); 27809 }); 27810 useIsomorphicLayoutEffect(() => { 27811 const normalizedLocation = typeof stableLocationParam === "string" ? { pathname: stableLocationParam } : stableLocationParam; 27812 if (isMountRenderPass.current) { 27813 updatePageloadTransaction({ 27814 activeRootSpan: getActiveRootSpan(), 27815 location: normalizedLocation, 27816 routes, 27817 allRoutes: Array.from(allRoutes) 27818 }); 27819 isMountRenderPass.current = false; 27820 } else handleNavigation({ 27821 location: normalizedLocation, 27822 routes, 27823 navigationType, 27824 version, 27825 allRoutes: Array.from(allRoutes) 27826 }); 27827 }, [navigationType, stableLocationParam]); 27828 return Routes; 27829 }; 27830 return (routes, locationArg) => { 27831 return /* @__PURE__ */ import_react$1.createElement(SentryRoutes, { 27832 routes, 27833 locationArg 27834 }); 27835 }; 27836} 27837function wrapPatchRoutesOnNavigation(opts, isMemoryRouter = false, capturedSpan) { 27838 if (!opts || !("patchRoutesOnNavigation" in opts) || typeof opts.patchRoutesOnNavigation !== "function") return opts || {}; 27839 const originalPatchRoutes = opts.patchRoutesOnNavigation; 27840 return { 27841 ...opts, 27842 patchRoutesOnNavigation: async (args) => { 27843 const targetPath = args?.path; 27844 const activeRootSpan = getActiveRootSpan() ?? capturedSpan; 27845 if (!isMemoryRouter) { 27846 const originalPatch = args?.patch; 27847 const matches = args?.matches; 27848 if (originalPatch) args.patch = (routeId, children) => { 27849 addRoutesToAllRoutes(children); 27850 if (matches && matches.length > 0) { 27851 const leafRoute = matches[matches.length - 1]?.route; 27852 if (leafRoute) { 27853 const matchingRoute = Array.from(allRoutes).find((route) => { 27854 const idMatches = route.id !== void 0 && route.id === routeId; 27855 const referenceMatches = route === leafRoute; 27856 const pathMatches = route.path !== void 0 && leafRoute.path !== void 0 && route.path === leafRoute.path; 27857 return idMatches || referenceMatches || pathMatches; 27858 }); 27859 if (matchingRoute) addResolvedRoutesToParent(children, matchingRoute); 27860 } 27861 } 27862 const spanJson = activeRootSpan ? spanToJSON(activeRootSpan) : void 0; 27863 if (targetPath && activeRootSpan && spanJson && !spanJson.timestamp && spanJson.op === "navigation") updateNavigationSpan(activeRootSpan, { 27864 pathname: targetPath, 27865 search: "", 27866 hash: "", 27867 state: null, 27868 key: "default" 27869 }, Array.from(allRoutes), true, _matchRoutes); 27870 return originalPatch(routeId, children); 27871 }; 27872 } 27873 const lazyLoadPromise = (async () => { 27874 const contextToken = setNavigationContext(targetPath, activeRootSpan); 27875 let result; 27876 try { 27877 result = await originalPatchRoutes(args); 27878 } finally { 27879 clearNavigationContext(contextToken); 27880 if (activeRootSpan) resolveDeferredLazyRoutePromise(activeRootSpan); 27881 } 27882 const spanJson = activeRootSpan ? spanToJSON(activeRootSpan) : void 0; 27883 if (activeRootSpan && spanJson && !spanJson.timestamp && spanJson.op === "navigation") { 27884 const pathname = targetPath; 27885 if (pathname) updateNavigationSpan(activeRootSpan, { 27886 pathname, 27887 search: "", 27888 hash: "", 27889 state: null, 27890 key: "default" 27891 }, Array.from(allRoutes), false, _matchRoutes); 27892 } 27893 return result; 27894 })(); 27895 if (activeRootSpan) trackLazyRouteLoad(activeRootSpan, lazyLoadPromise); 27896 return lazyLoadPromise; 27897 } 27898 }; 27899} 27900function handleNavigation(opts) { 27901 const { location, routes, navigationType, version, matches, basename, allRoutes: allRoutes2 } = opts; 27902 const branches = Array.isArray(matches) ? matches : _matchRoutes(allRoutes2 || routes, location, basename); 27903 const client = getClient(); 27904 if (!client || !CLIENTS_WITH_INSTRUMENT_NAVIGATION.has(client)) return; 27905 const activeRootSpan = getActiveRootSpan(); 27906 if (activeRootSpan && spanToJSON(activeRootSpan).op === "pageload" && navigationType === "POP") return; 27907 if ((navigationType === "PUSH" || navigationType === "POP") && branches) { 27908 const [name, source] = resolveRouteNameAndSource(location, allRoutes2 || routes, allRoutes2 || routes, branches, basename, _lazyRouteManifest, _enableAsyncRouteHandlers); 27909 const locationKey = computeLocationKey(location); 27910 const trackedNav = activeNavigationSpans.get(client); 27911 const { skip, shouldUpdate } = shouldSkipNavigation(trackedNav, locationKey, name, trackedNav && !trackedNav.isPlaceholder ? !!spanToJSON(trackedNav.span).timestamp : false); 27912 if (skip) { 27913 if (shouldUpdate && trackedNav) { 27914 const oldName = trackedNav.routeName; 27915 if (trackedNav.isPlaceholder) { 27916 trackedNav.routeName = name; 27917 DEBUG_BUILD && debug$2.log(`[Tracing] Updated placeholder navigation name from "${oldName}" to "${name}" (will apply to real span)`); 27918 } else { 27919 trackedNav.span.updateName(name); 27920 trackedNav.span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); 27921 if (source === "route") trackedNav.span.setAttribute(ju, name); 27922 addNonEnumerableProperty(trackedNav.span, "__sentry_navigation_name_set__", true); 27923 trackedNav.routeName = name; 27924 DEBUG_BUILD && debug$2.log(`[Tracing] Updated navigation span name from "${oldName}" to "${name}"`); 27925 } 27926 } else DEBUG_BUILD && debug$2.log(`[Tracing] Skipping duplicate navigation for location: ${locationKey}`); 27927 return; 27928 } 27929 const placeholderEntry = { 27930 span: { end: () => {} }, 27931 routeName: name, 27932 pathname: location.pathname, 27933 locationKey, 27934 isPlaceholder: true 27935 }; 27936 activeNavigationSpans.set(client, placeholderEntry); 27937 let navigationSpan; 27938 try { 27939 navigationSpan = startBrowserTracingNavigationSpan(client, { 27940 name: placeholderEntry.routeName, 27941 attributes: { 27942 [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, 27943 [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "navigation", 27944 [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.navigation.react.reactrouter${version ? `_v${version}` : ""}`, 27945 ...source === "route" && { ["url.template"]: placeholderEntry.routeName } 27946 } 27947 }); 27948 } catch (e) { 27949 activeNavigationSpans.delete(client); 27950 throw e; 27951 } 27952 if (navigationSpan) { 27953 activeNavigationSpans.set(client, { 27954 span: navigationSpan, 27955 routeName: placeholderEntry.routeName, 27956 pathname: location.pathname, 27957 locationKey 27958 }); 27959 patchSpanEnd(navigationSpan, location, routes, basename, "navigation"); 27960 } else activeNavigationSpans.delete(client); 27961 } 27962} 27963function addRoutesToAllRoutes(routes) { 27964 const added = [];
27965 routes.forEach((route) => { 27966 getChildRoutesRecursively(route).forEach((r) => { 27967 allRoutes.add(r); 27968 added.push(r); 27969 }); 27970 }); 27971 return added; 27972} 27973function removeRoutesFromAllRoutes(routes) { 27974 routes.forEach((route) => { 27975 allRoutes.delete(route); 27976 }); 27977} 27978function getChildRoutesRecursively(route, allRoutes2 = /* @__PURE__ */ new Set()) { 27979 if (!allRoutes2.has(route)) { 27980 allRoutes2.add(route); 27981 if (route.children && !route.index) route.children.forEach((child) => { 27982 getChildRoutesRecursively(child, allRoutes2).forEach((r) => { 27983 allRoutes2.add(r); 27984 }); 27985 }); 27986 } 27987 return allRoutes2; 27988} 27989function updatePageloadTransaction({ activeRootSpan, location, routes, matches, basename, allRoutes: allRoutes2 }) { 27990 const branches = Array.isArray(matches) ? matches : _matchRoutes(allRoutes2 || routes, location, basename); 27991 if (branches) { 27992 const [name, source] = resolveRouteNameAndSource(location, allRoutes2 || routes, allRoutes2 || routes, branches, basename, _lazyRouteManifest, _enableAsyncRouteHandlers); 27993 getCurrentScope().setTransactionName(name || "/"); 27994 if (activeRootSpan) { 27995 activeRootSpan.updateName(name); 27996 activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); 27997 if (source === "route") activeRootSpan.setAttribute(ju, name); 27998 patchSpanEnd(activeRootSpan, location, routes, basename, "pageload"); 27999 } 28000 } else if (activeRootSpan) patchSpanEnd(activeRootSpan, location, routes, basename, "pageload"); 28001} 28002function shouldUpdateWildcardSpanName(currentName, currentSource, newName, newSource, allowNoCurrentName = false) { 28003 if (!newName) return false; 28004 if (!currentName && allowNoCurrentName) return true; 28005 if (currentName && transactionNameHasWildcard(currentName) && newSource === "route" && !transactionNameHasWildcard(newName)) return true; 28006 if (currentSource !== "route" && newSource === "route") return true; 28007 return false; 28008} 28009function tryUpdateSpanNameBeforeEnd(span, spanJson, currentName, location, routes, basename, spanType, allRoutes2) { 28010 try { 28011 const currentSource = spanJson.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 28012 if (currentSource === "route" && currentName && !transactionNameHasWildcard(currentName)) return; 28013 const currentAllRoutes = Array.from(allRoutes2); 28014 const routesToUse = currentAllRoutes.length > 0 ? currentAllRoutes : routes; 28015 const branches = _matchRoutes(routesToUse, location, basename); 28016 if (!branches) return; 28017 const [name, source] = resolveRouteNameAndSource(location, routesToUse, routesToUse, branches, basename, _lazyRouteManifest, _enableAsyncRouteHandlers); 28018 const isImprovement = shouldUpdateWildcardSpanName(currentName, currentSource, name, source, true); 28019 const spanNotEnded = spanType === "pageload" || !spanJson.timestamp; 28020 if (isImprovement && spanNotEnded) { 28021 span.updateName(name); 28022 span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); 28023 if (source === "route") span.setAttribute(ju, name); 28024 } 28025 } catch (error) { 28026 DEBUG_BUILD && debug$2.warn(`Error updating span details before ending: ${error}`); 28027 } 28028} 28029function patchSpanEnd(span, location, routes, basename, spanType) { 28030 const patchedPropertyName = `__sentry_${spanType}_end_patched__`; 28031 if (span?.[patchedPropertyName] || !span.end) return; 28032 const originalEnd = span.end.bind(span); 28033 let endCalled = false; 28034 span.end = function patchedEnd(...args) { 28035 if (endCalled) return; 28036 endCalled = true; 28037 const endTimestamp = args.length > 0 ? args[0] : Date.now() / 1e3; 28038 const spanJson = spanToJSON(span); 28039 const currentName = spanJson.description; 28040 const currentSource = spanJson.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; 28041 const cleanupNavigationSpan = () => { 28042 const client = getClient(); 28043 if (client && spanType === "navigation") { 28044 const trackedNav = activeNavigationSpans.get(client); 28045 if (trackedNav && trackedNav.span === span) activeNavigationSpans.delete(client); 28046 } 28047 }; 28048 const pendingPromises = pendingLazyRouteLoads.get(span); 28049 const mayHaveLazyRoutes = span.__sentry_may_have_lazy_routes__; 28050 if ((pendingPromises && pendingPromises.size > 0 || mayHaveLazyRoutes) && currentName && (transactionNameHasWildcard(currentName) || currentSource !== "route")) { 28051 if (_lazyRouteTimeout === 0) { 28052 tryUpdateSpanNameBeforeEnd(span, spanJson, currentName, location, routes, basename, spanType, allRoutes); 28053 cleanupNavigationSpan(); 28054 originalEnd(endTimestamp); 28055 return; 28056 } 28057 const timeoutPromise = new Promise((r) => setTimeout(r, _lazyRouteTimeout)); 28058 let waitPromise; 28059 if (pendingPromises && pendingPromises.size > 0) { 28060 const allSettled = Promise.allSettled(pendingPromises).then(() => {}); 28061 waitPromise = _lazyRouteTimeout === Infinity ? allSettled : Promise.race([allSettled, timeoutPromise]); 28062 } else waitPromise = timeoutPromise; 28063 waitPromise.then(() => { 28064 const updatedSpanJson = spanToJSON(span);
28065 tryUpdateSpanNameBeforeEnd(span, updatedSpanJson, updatedSpanJson.description, location, routes, basename, spanType, allRoutes); 28066 cleanupNavigationSpan(); 28067 originalEnd(endTimestamp); 28068 }).catch(() => { 28069 cleanupNavigationSpan(); 28070 originalEnd(endTimestamp); 28071 }); 28072 return; 28073 } 28074 tryUpdateSpanNameBeforeEnd(span, spanJson, currentName, location, routes, basename, spanType, allRoutes); 28075 cleanupNavigationSpan(); 28076 originalEnd(endTimestamp); 28077 }; 28078 addNonEnumerableProperty(span, patchedPropertyName, true); 28079} 28080function createV6CompatibleWithSentryReactRouterRouting(Routes, version) { 28081 if (!_useEffect || !_useLocation || !_useNavigationType || !_createRoutesFromChildren || !_matchRoutes) { 28082 DEBUG_BUILD && debug$2.warn(`reactRouterV6Instrumentation was unable to wrap Routes because of one or more missing parameters. 28083 useEffect: ${_useEffect}. useLocation: ${_useLocation}. useNavigationType: ${_useNavigationType}. 28084 createRoutesFromChildren: ${_createRoutesFromChildren}. matchRoutes: ${_matchRoutes}.`); 28085 return Routes; 28086 } 28087 const SentryRoutes = (props) => { 28088 const isMountRenderPass = import_react$1.useRef(true); 28089 const location = _useLocation(); 28090 const navigationType = _useNavigationType(); 28091 const routes = _createRoutesFromChildren(props.children); 28092 useIsomorphicLayoutEffect(() => { 28093 const added = addRoutesToAllRoutes(routes); 28094 return () => removeRoutesFromAllRoutes(added); 28095 }); 28096 useIsomorphicLayoutEffect(() => { 28097 if (isMountRenderPass.current) { 28098 updatePageloadTransaction({ 28099 activeRootSpan: getActiveRootSpan(), 28100 location, 28101 routes, 28102 allRoutes: Array.from(allRoutes) 28103 }); 28104 isMountRenderPass.current = false; 28105 } else handleNavigation({ 28106 location, 28107 routes, 28108 navigationType, 28109 version, 28110 allRoutes: Array.from(allRoutes) 28111 }); 28112 }, [location, navigationType]); 28113 return /* @__PURE__ */ import_react$1.createElement(Routes, { ...props }); 28114 }; 28115 hoistNonReactStatics(SentryRoutes, Routes); 28116 return SentryRoutes; 28117} 28118var import_react$1, _useEffect, _useLocation, _useNavigationType, _createRoutesFromChildren, _matchRoutes, _enableAsyncRouteHandlers, _lazyRouteTimeout, _lazyRouteManifest, _basename, CLIENTS_WITH_INSTRUMENT_NAVIGATION, useIsomorphicLayoutEffect, activeNavigationSpans, allRoutes, pendingLazyRouteLoads, deferredLazyRouteResolvers; 28119function init_instrumentation() { 28120 return (init_instrumentation = __esmMin((() => { 28121 init_helpers(), init_browserTracingIntegration(); 28122 init_semanticAttributes(), init_debug_logger(), init_object(), init_spanUtils(), init_currentScopes(); 28123 import_react$1 = /* @__PURE__ */ __toESM(require_react()); 28124 init_debug_build$3(); 28125 init_hoist_non_react_statics(); 28126 init_lazy_routes(); 28127 init_utils$11(); 28128 init_attributes$1(); 28129 _enableAsyncRouteHandlers = false; 28130 _lazyRouteTimeout = 3e3; 28131 _basename = ""; 28132 CLIENTS_WITH_INSTRUMENT_NAVIGATION = /* @__PURE__ */ new WeakSet(); 28133 useIsomorphicLayoutEffect = WINDOW$4?.document ? import_react$1.useLayoutEffect : import_react$1.useEffect; 28134 activeNavigationSpans = /* @__PURE__ */ new WeakMap(); 28135 allRoutes = /* @__PURE__ */ new Set(); 28136 pendingLazyRouteLoads = /* @__PURE__ */ new WeakMap(); 28137 deferredLazyRouteResolvers = /* @__PURE__ */ new WeakMap(); 28138 })))(); 28139} 28140//#endregion 28141//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouterv6.js 28142function reactRouterV6BrowserTracingIntegration(options) { 28143 return createReactRouterV6CompatibleTracingIntegration(options, "6"); 28144} 28145function wrapUseRoutesV6(origUseRoutes) { 28146 return createV6CompatibleWrapUseRoutes(origUseRoutes, "6"); 28147} 28148function wrapCreateBrowserRouterV6(createRouterFunction) { 28149 return createV6CompatibleWrapCreateBrowserRouter(createRouterFunction, "6"); 28150} 28151function wrapCreateMemoryRouterV6(createMemoryRouterFunction) { 28152 return createV6CompatibleWrapCreateMemoryRouter(createMemoryRouterFunction, "6"); 28153} 28154function withSentryReactRouterV6Routing(routes) { 28155 return createV6CompatibleWithSentryReactRouterRouting(routes, "6"); 28156} 28157function init_reactrouterv6() { 28158 return (init_reactrouterv6 = __esmMin((() => { 28159 init_instrumentation(); 28160 })))(); 28161} 28162//#endregion 28163//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouterv7.js 28164function reactRouterV7BrowserTracingIntegration(options) { 28165 return createReactRouterV6CompatibleTracingIntegration(options, "7"); 28166} 28167function withSentryReactRouterV7Routing(routes) { 28168 return createV6CompatibleWithSentryReactRouterRouting(routes, "7"); 28169} 28170function wrapCreateBrowserRouterV7(createRouterFunction) { 28171 return createV6CompatibleWrapCreateBrowserRouter(createRouterFunction, "7"); 28172} 28173function wrapCreateMemoryRouterV7(createMemoryRouterFunction) { 28174 return createV6CompatibleWrapCreateMemoryRouter(createMemoryRouterFunction, "7"); 28175} 28176function wrapUseRoutesV7(origUseRoutes) { 28177 return createV6CompatibleWrapUseRoutes(origUseRoutes, "7"); 28178} 28179function init_reactrouterv7() { 28180 return (init_reactrouterv7 = __esmMin((() => { 28181 init_instrumentation(); 28182 })))(); 28183} 28184//#endregion 28185//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/reactrouter.compat.js 28186function reactRouterBrowserTracingIntegration(options) { 28187 return createReactRouterV6CompatibleTracingIntegration(options, ""); 28188} 28189function wrapReactRouterRouting(routes) { 28190 return createV6CompatibleWithSentryReactRouterRouting(routes, ""); 28191} 28192function wrapCreateBrowserRouter(createRouterFunction) { 28193 return createV6CompatibleWrapCreateBrowserRouter(createRouterFunction, ""); 28194} 28195function wrapCreateMemoryRouter(createMemoryRouterFunction) { 28196 return createV6CompatibleWrapCreateMemoryRouter(createMemoryRouterFunction, ""); 28197} 28198function wrapUseRoutes(origUseRoutes) { 28199 return createV6CompatibleWrapUseRoutes(origUseRoutes, ""); 28200} 28201function init_reactrouter_compat() { 28202 return (init_reactrouter_compat = __esmMin((() => { 28203 init_instrumentation(); 28204 })))(); 28205} 28206//#endregion 28207//#region node_modules/.pnpm/@[email protected][email protected]/node_modules/@sentry/react/build/esm/index.js 28208var esm_exports = /* @__PURE__ */ __exportAll({ 28209 BrowserClient: () => BrowserClient, 28210 ErrorBoundary: () => ErrorBoundary, 28211 MULTIPLEXED_TRANSPORT_EXTRA_KEY: () => MULTIPLEXED_TRANSPORT_EXTRA_KEY, 28212 OpenFeatureIntegrationHook: () => OpenFeatureIntegrationHook, 28213 Profiler: () => Profiler, 28214 SDK_VERSION: () => SDK_VERSION, 28215 SEMANTIC_ATTRIBUTE_SENTRY_OP: () => SEMANTIC_ATTRIBUTE_SENTRY_OP, 28216 SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN: () => SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 28217 SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE: () => SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, 28218 SEMANTIC_ATTRIBUTE_SENTRY_SOURCE: () => SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 28219 Scope: () => Scope, 28220 WINDOW: () => WINDOW$4, 28221 addBreadcrumb: () => addBreadcrumb, 28222 addEventProcessor: () => addEventProcessor, 28223 addIntegration: () => addIntegration, 28224 bindScopeToEmitter: () =>
28224 bindScopeToEmitter, 28225 breadcrumbsIntegration: () => breadcrumbsIntegration, 28226 browserApiErrorsIntegration: () => browserApiErrorsIntegration, 28227 browserProfilingIntegration: () => browserProfilingIntegration, 28228 browserSessionIntegration: () => browserSessionIntegration, 28229 browserTracingIntegration: () => browserTracingIntegration, 28230 buildLaunchDarklyFlagUsedHandler: () => buildLaunchDarklyFlagUsedHandler, 28231 captureConsoleIntegration: () => captureConsoleIntegration, 28232 captureEvent: () => captureEvent, 28233 captureException: () => captureException, 28234 captureFeedback: () => captureFeedback, 28235 captureMessage: () => captureMessage, 28236 captureReactException: () => captureReactException$1, 28237 captureSession: () => captureSession, 28238 chromeStackLineParser: () => chromeStackLineParser, 28239 close: () => close, 28240 consoleLoggingIntegration: () => consoleLoggingIntegration, 28241 contextLinesIntegration: () => contextLinesIntegration, 28242 continueTrace: () => continueTrace, 28243 createConsolaReporter: () => createConsolaReporter, 28244 createLangChainCallbackHandler: () => createLangChainCallbackHandler, 28245 createReduxEnhancer: () => createReduxEnhancer, 28246 createTransport: () => createTransport, 28247 createUserFeedbackEnvelope: () => createUserFeedbackEnvelope, 28248 cultureContextIntegration: () => cultureContextIntegration, 28249 dedupeIntegration: () => dedupeIntegration, 28250 defaultRequestInstrumentationOptions: () => defaultRequestInstrumentationOptions, 28251 defaultStackLineParsers: () => defaultStackLineParsers, 28252 defaultStackParser: () => defaultStackParser, 28253 diagnoseSdkConnectivity: () => diagnoseSdkConnectivity, 28254 elementTimingIntegration: () => elementTimingIntegration, 28255 endSession: () => endSession, 28256 eventFiltersIntegration: () => eventFiltersIntegration, 28257 eventFromException: () => eventFromException, 28258 eventFromMessage: () => eventFromMessage, 28259 exceptionFromError: () => exceptionFromError, 28260 extraErrorDataIntegration: () => extraErrorDataIntegration, 28261 featureFlagsIntegration: () => featureFlagsIntegration, 28262 feedbackAsyncIntegration: () => feedbackAsyncIntegration, 28263 feedbackIntegration: () => feedbackSyncIntegration, 28264 feedbackSyncIntegration: () => feedbackSyncIntegration, 28265 fetchStreamPerformanceIntegration: () => fetchStreamPerformanceIntegration, 28266 flush: () => flush, 28267 forceLoad: () => forceLoad, 28268 functionToStringIntegration: () => functionToStringIntegration, 28269 geckoStackLineParser: () => geckoStackLineParser, 28270 getAbsoluteUrl: () => getAbsoluteUrl, 28271 getActiveSpan: () => getActiveSpan, 28272 getClient: () => getClient, 28273 getCurrentScope: () => getCurrentScope, 28274 getDefaultIntegrations: () => getDefaultIntegrations, 28275 getFeedback: () => getFeedback, 28276 getGlobalScope: () => getGlobalScope, 28277 getIsolationScope: () => getIsolationScope, 28278 getReplay: () => getReplay, 28279 getRootSpan: () => getRootSpan, 28280 getSpanDescendants: () => getSpanDescendants, 28281 getSpanStatusFromHttpCode: () => getSpanStatusFromHttpCode, 28282 getTraceData: () => getTraceData, 28283 globalHandlersIntegration: () => globalHandlersIntegration, 28284 graphqlClientIntegration: () => graphqlClientIntegration, 28285 growthbookIntegration: () => growthbookIntegration, 28286 httpClientIntegration: () => httpClientIntegration, 28287 httpContextIntegration: () => httpContextIntegration, 28288 inboundFiltersIntegration: () => inboundFiltersIntegration, 28289 init: () => init, 28290 instrumentAnthropicAiClient: () => instrumentAnthropicAiClient, 28291 instrumentCreateReactAgent: () => instrumentCreateReactAgent, 28292 instrumentGoogleGenAIClient: () => instrumentGoogleGenAIClient, 28293 instrumentLangChainEmbeddings: () => instrumentLangChainEmbeddings, 28294 instrumentLangGraph: () => instrumentLangGraph, 28295 instrumentOpenAiClient: () => instrumentOpenAiClient, 28296 instrumentOutgoingRequests: () => instrumentOutgoingRequests, 28297 instrumentStateGraph: () => instrumentStateGraph, 28298 instrumentSupabaseClient: () => instrumentSupabaseClient, 28299 isBotUserAgent: () => isBotUserAgent, 28300 isEnabled: () => isEnabled, 28301 isInitialized: () => isInitialized$1, 28302 lastEventId: () => lastEventId, 28303 launchDarklyIntegration: () => launchDarklyIntegration, 28304 lazyLoadIntegration: () => lazyLoadIntegration, 28305 linkedErrorsIntegration: () => linkedErrorsIntegration, 28306 logger: () => public_api_exports$1, 28307 makeBrowserOfflineTransport: () => makeBrowserOfflineTransport, 28308 makeFetchTransport: () => makeFetchTransport, 28309 makeMultiplexedTransport: () => makeMultiplexedTransport, 28310 metrics: () => public_api_exports, 28311 moduleMetadataIntegration: () => moduleMetadataIntegration, 28312 normalizeStringifyValue: () => normalizeStringifyValue$1, 28313 onLoad: () => onLoad, 28314 openFeatureIntegration: () => openFeatureIntegration, 28315 opera10StackLineParser: () => opera10StackLineParser, 28316 opera11StackLineParser: () => opera11StackLineParser, 28317 parameterize: () => parameterize, 28318 reactErrorHandler: () => reactErrorHandler, 28319 reactRouterBrowserTracingIntegration: () => reactRouterBrowserTracingIntegration, 28320 reactRouterV3BrowserTracingIntegration: () => reactRouterV3BrowserTracingIntegration, 28321 reactRouterV4BrowserTracingIntegration: () => reactRouterV4BrowserTracingIntegration, 28322 reactRouterV5BrowserTracingIntegration: () => reactRouterV5BrowserTracingIntegration, 28323 reactRouterV6BrowserTracingIntegration: () => reactRouterV6BrowserTracingIntegration, 28324 reactRouterV7BrowserTracingIntegration: () => reactRouterV7BrowserTracingIntegration, 28325 registerSpanErrorInstrumentation: () => registerSpanErrorInstrumentation, 28326 registerWebWorker: () => registerWebWorker, 28327 replayCanvasIntegration: () => replayCanvasIntegration, 28328 replayIntegration: () => replayIntegration, 28329 reportPageLoaded: () => reportPageLoaded, 28330 reportingObserverIntegration: () => reportingObserverIntegration, 28331 rewriteFramesIntegration: () => rewriteFramesIntegration, 28332 sendFeedback: () => sendFeedback, 28333 setActiveSpanInBrowser: () => setActiveSpanInBrowser, 28334 setAttribute: () => setAttribute, 28335 setAttributes: () => setAttributes, 28336 setContext: () => setContext, 28337 setConversationId: () => setConversationId, 28338 setCurrentClient: () => setCurrentClient, 28339 setExtra: () => setExtra, 28340 setExtras: () => setExtras, 28341 setHttpStatus: () => setHttpStatus, 28342 setMeasurement: () => setMeasurement, 28343 setTag: () => setTag, 28344 setTags: () => setTags, 28345 setUser: () => setUser, 28346 showReportDialog: () => showReportDialog, 28347 spanStreamingIntegration: () => spanStreamingIntegration, 28348 spanToBaggageHeader: () => spanToBaggageHeader, 28349 spanToJSON: () => spanToJSON, 28350 spanToTraceHeader: () => spanToTraceHeader, 28351 spotlightBrowserIntegration: () => spotlightBrowserIntegration, 28352 startBrowserTracingNavigationSpan: () => startBrowserTracingNavigationSpan, 28353 startBrowserTracingPageLoadSpan: () => startBrowserTracingPageLoadSpan, 28354 startInactiveSpan: () => startInactiveSpan, 28355 startNewTrace: () => startNewTrace, 28356 startSession: () => startSession, 28357 startSpan: () => startSpan, 28358 startSpanManual: () => startSpanManual, 28359 statsigIntegration: () => statsigIntegration, 28360 supabaseIntegration: () => supabaseIntegration, 28361 suppressTracing: () => suppressTracing, 28362 tanstackRouterBrowserTracingIntegration: () => tanstackRouterBrowserTracingIntegration, 28363 thirdPartyErrorFilterIntegration: () => thirdPartyErrorFilterIntegration, 28364 uiProfiler: () => uiProfiler, 28365 unleashIntegration: () => unleashIntegration, 28366 updateSpanName: () => updateSpanName, 28367 useProfiler: () => useProfiler, 28368 viewHierarchyIntegration: () => viewHierarchyIntegration, 28369 webVitalsIntegration: () => webVitalsIntegration, 28370 webWorkerIntegration: () => webWorkerIntegration, 28371 winjsStackLineParser: () => winjsStackLineParser, 28372 withActiveSpan: () => withActiveSpan, 28373 withErrorBoundary: () => withErrorBoundary, 28374 withIsolationScope: () => withIsolationScope, 28375 withProfiler: () => withProfiler, 28376 withScope: () => withScope, 28377 withSentryReactRouterV6Routing: () => withSentryReactRouterV6Routing, 28378 withSentryReactRouterV7Routing: () => withSentryReactRouterV7Routing, 28379 withSentryRouting: () => withSentryRouting, 28380 withStreamedSpan: () => withStreamedSpan, 28381 wrapCreateBrowserRouter: () => wrapCreateBrowserRouter, 28382 wrapCreateBrowserRouterV6: () => wrapCreateBrowserRouterV6, 28383 wrapCreateBrowserRouterV7: () => wrapCreateBrowserRouterV7, 28384 wrapCreateMemoryRouter: () => wrapCreateMemoryRouter, 28385 wrapCreateMemoryRouterV6: () => wrapCreateMemoryRouterV6, 28386 wrapCreateMemoryRouterV7: () => wrapCreateMemoryRouterV7, 28387 wrapReactRouterRouting: () => wrapReactRouterRouting, 28388 wrapUseRoutes: () => wrapUseRoutes, 28389 wrapUseRoutesV6: () => wrapUseRoutesV6, 28390 wrapUseRoutesV7: () => wrapUseRoutesV7, 28391 zodErrorsIntegration: () => zodErrorsIntegration 28392}); 28393function init_esm$3() { 28394 return (init_esm$3 = __esmMin((() => { 28395 init_feedbackAsync(); 28396 init_feedbackSync(); 28397 init_errors(); 28398 init_utils(); 28399 init_idleSpan(); 28400 init_sentrySpan(); 28401 init_segmentSpanCaptureStrategy(); 28402 init_sentryNonRecordingSpan(); 28403 init_spanstatus(); 28404 init_trace(); 28405 init_bindScopeToEmitter(); 28406 init_dynamicSamplingContext(); 28407 init_measurement(); 28408 init_sampling(); 28409 init_logSpans(); 28410 init_captureSpan(); 28411 init_semanticAttributes(); 28412 init_envelope$1(); 28413 init_exports(); 28414 init_currentScopes(); 28415 init_debug_build(); 28416 init_debug_logger(); 28417 init_is(); 28418 init_misc(); 28419 init_time(); 28420 init_tracing(); 28421 init_defaultScopes(); 28422 init_asyncContext(); 28423 init_carrier(); 28424 init_spanOnScope(); 28425 init_session(); 28426 init_scope(); 28427 init_eventProcessors(); 28428 init_api(); 28429 init_client(); 28430 init_sdk(); 28431 init_base(); 28432 init_offline(); 28433 init_multiplexed(); 28434 init_integration(); 28435 init_filterKeyValueData(); 28436 init_filterCookies(); 28437 init_filtering_snippets(); 28438 init_scopeData(); 28439 init_prepareEvent(); 28440 init_dsn(); 28441 init_envelope(); 28442 init_randomSafeContext(); 28443 init_hasSpansEnabled(); 28444 init_beforeSendSpan(); 28445 init_isSentryRequestUrl(); 28446 init_handleCallbackErrors(); 28447 init_parameterize(); 28448 init_spanUtils(); 28449 init_sdkMetadata(); 28450 init_traceData(); 28451 init_string(); 28452 init_weakRef(); 28453 init_should_ignore_span(); 28454 init_defaultPiiToCollectionOptions(); 28455 init_constants(); 28456 init_breadcrumbs(); 28457 init_functiontostring(); 28458 init_eventFilters(); 28459 init_aggregate_errors(); 28460 init_eventbuilder(); 28461 init_moduleMetadata(); 28462 init_attributes$1(); 28463 init_captureconsole(); 28464 init_dedupe(); 28465 init_extraerrordata(); 28466 init_rewriteframes(); 28467 init_supabase(); 28468 init_zoderrors(); 28469 init_third_party_errors_filter(); 28470 init_console(); 28471 init_worldwide(); 28472 init_featureFlagsIntegration(); 28473 init_growthbook(); 28474 init_conversationId(); 28475 init_fetch(); 28476 init_feedback(); 28477 init_internal(); 28478 init_public_api(); 28479 init_console_integration(); 28480 init_internal$1(); 28481 init_public_api$1(); 28482 init_consola(); 28483 init_utils$2(); 28484 init_gen_ai_attributes(); 28485 init_openai();
28486 init_utils$3(); 28487 init_streaming(); 28488 init_constants$2(); 28489 init_anthropic_ai(); 28490 init_streaming$1(); 28491 init_constants$3(); 28492 init_google_genai(); 28493 init_streaming$2(); 28494 init_constants$4(); 28495 init_langchain(); 28496 init_embeddings(); 28497 init_utils$6(); 28498 init_constants$5(); 28499 init_langgraph(); 28500 init_utils$7(); 28501 init_constants$6(); 28502 init_spanBuffer(); 28503 init_featureFlags(); 28504 init_fetch$1(); 28505 init_globalError(); 28506 init_globalUnhandledRejection(); 28507 init_handlers(); 28508 init_isBrowser(); 28509 init_normalize(); 28510 init_normalizationHints(); 28511 init_object(); 28512 init_path(); 28513 init_promisebuffer(); 28514 init_stacktrace(); 28515 init_supports(); 28516 init_syncpromise(); 28517 init_clientreport(); 28518 init_ratelimit(); 28519 init_baggage(); 28520 init_url(); 28521 init_propagationContext(); 28522 init_version(); 28523 init_debug_ids(); 28524 init_metadata(); 28525 init_browser(); 28526 init_helpers(); 28527 init_client$1(); 28528 init_fetch$2(); 28529 init_profiling(); 28530 init_stack_parsers(); 28531 init_eventbuilder$1(); 28532 init_userfeedback(); 28533 init_sdk$1(); 28534 init_report_dialog(); 28535 init_breadcrumbs$1(); 28536 init_globalhandlers(); 28537 init_httpcontext(); 28538 init_linkederrors(); 28539 init_browserapierrors(); 28540 init_browsersession(); 28541 init_lazyLoadIntegration(); 28542 init_reportingobserver(); 28543 init_httpclient(); 28544 init_contextlines(); 28545 init_graphqlClient(); 28546 init_view_hierarchy(); 28547 init_esm$1(); 28548 init_esm$2(); 28549 init_esm(); 28550 init_request(); 28551 init_browserTracingIntegration(); 28552 init_instrument(); 28553 init_browserMetrics(); 28554 init_elementTiming(); 28555 init_utils$8(); 28556 init_webVitalSpans(); 28557 init_whenIdleOrHidden(); 28558 init_dom(); 28559 init_history(); 28560 init_getNativeImplementation(); 28561 init_xhr(); 28562 init_networkUtils(); 28563 init_resourceTiming(); 28564 init_htmlTreeAsString(); 28565 init_location(); 28566 init_inp(); 28567 init_normalizeStringifyValue(); 28568 init_reportPageLoaded(); 28569 init_setActiveSpan(); 28570 init_spanstreaming(); 28571 init_fetchStreamPerformance(); 28572 init_webVitals(); 28573 init_offline$1(); 28574 init_integration$1(); 28575 init_spotlight(); 28576 init_culturecontext(); 28577 init_integration$2(); 28578 init_integration$3(); 28579 init_integration$4(); 28580 init_integration$5(); 28581 init_integration$6(); 28582 init_diagnose_sdk(); 28583 init_webWorker(); 28584 init_sdk$2(); 28585 init_error(); 28586 init_profiler(); 28587 init_errorboundary(); 28588 init_redux(); 28589 init_reactrouterv3(); 28590 init_tanstackrouter(); 28591 init_reactrouter(); 28592 init_reactrouterv6(); 28593 init_reactrouterv7(); 28594 init_reactrouter_compat(); 28595 })))(); 28596} 28597//#endregion 28598//#region app/frontend/lib/sentry.ts 28599function isGoogleTranslateStackOverflow(event) { 28600 if (!/\bCriOS\//.test(navigator.userAgent) || event.exception?.values?.length !== 1) return false; 28601 const exception = event.exception.values[0]; 28602 if (exception.type !== "RangeError" || exception.value !== "Maximum call stack size exceeded.") return false; 28603 const frames = exception.stacktrace?.frames; 28604 if (!frames || frames.length < 6) return false; 28605 return [["Rk", "Tk"], ["Uk", "Wk"]].some((pair) => frames.some((first, offset) => { 28606 const start = pair.indexOf(first.function || ""); 28607 if (start === -1 || !first.filename || offset + 6 > frames.length) return false; 28608 if (!frames.slice(offset, offset + 6).every((frame, index) => { 28609 const position = (start + index) % 2; 28610 return frame.function === pair[position] && frame.lineno === 232 && frame.colno === (position === 0 ? 63 : 408) && frame.filename === first.filename; 28611 })) return false; 28612 try { 28613 const url = new URL(first.filename, window.location.href); 28614 return url.origin === window.location.origin && !/\.[cm]?js$/i.test(url.pathname); 28615 } catch { 28616 return false; 28617 } 28618 })); 28619} 28620function buildSentryIntegrations(env) { 28621 const integrations = []; 28622 if (isFunction(browserTracingIntegration)) integrations.push(browserTracingIntegration()); 28623 if (env === "development") { 28624 const spotlightFn = unsafeCast(esm_exports).spotlightBrowserIntegration; 28625 if (isFunction(spotlightFn)) integrations.push(spotlightFn()); 28626 } 28627 return integrations; 28628} 28629function scrubSensitiveUrl(value) { 28630 return value.replace(SENSITIVE_URL_PATH, "$1/[FILTERED]"); 28631} 28632function scrubBreadcrumbUrls(event) { 28633 event.breadcrumbs?.forEach((crumb) => { 28634 if (crumb.message) crumb.message = scrubSensitiveUrl(crumb.message); 28635 const data = crumb.data; 28636 if (!data) return;
28637 BREADCRUMB_URL_KEYS.forEach((key) => { 28638 const value = data[key]; 28639 if (value) data[key] = scrubSensitiveUrl(String(value)); 28640 }); 28641 }); 28642} 28643/** 28644* Initialize Sentry for the entire app (Stimulus, React, and plain JS). 28645* Call once from each entrypoint; subsequent calls are no-ops. 28646*/ 28647function initSentry() { 28648 if (isInitialized) return; 28649 const env = window.rails_env || window.gon?.environment; 28650 const dsn = window.gon?.sentry_dsn; 28651 const tracesSampleRate = env === "development" ? 1 : .1; 28652 try { 28653 init({ 28654 dsn, 28655 environment: env, 28656 integrations: buildSentryIntegrations(env), 28657 tracePropagationTargets: env === "development" ? ["localhost", /^https:\/\/[^/]*\.hunter\.io(\/|$)/] : [/^https:\/\/[^/]*\.hunter\.io(\/|$)/, /^\//], 28658 tracesSampleRate, 28659 beforeSendTransaction(event) { 28660 if (event.transaction) event.transaction = scrubSensitiveUrl(event.transaction); 28661 if (event.request?.url) event.request.url = scrubSensitiveUrl(event.request.url); 28662 event.spans?.forEach((span) => { 28663 if (span.description) span.description = scrubSensitiveUrl(span.description); 28664 SPAN_URL_ATTRIBUTES.forEach((key) => { 28665 const value = span.data?.[key]; 28666 if (value) span.data[key] = scrubSensitiveUrl(String(value)); 28667 }); 28668 }); 28669 return event; 28670 }, 28671 ignoreErrors: [ 28672 "top.GLOBALS", 28673 "Invalid call to runtime.sendMessage(). Tab not found.", 28674 "originalCreateNotification", 28675 "canvas.contentDocument", 28676 "MyApp_RemoveAllHighlights", 28677 "http://tt.epicplay.com", 28678 "Can't find variable: ZiteReader", 28679 "jigsaw is not defined", 28680 "ComboSearch is not defined", 28681 "http://loading.retry.widdit.com/", 28682 "atomicFindClose", 28683 "fb_xd_fragment", 28684 "bmi_SafeAddOnload", 28685 "EBCallBackMessageReceived", 28686 "conduitPage", 28687 "Can't execute code from freed script", 28688 "CORS error", 28689 "Object Not Found Matching Id:", 28690 "ResizeObserver loop", 28691 "ResizeObserver loop completed with undelivered notifications", 28692 "Failed to execute 'removeChild' on 'Node'", 28693 "The node to be removed is not a child of this node", 28694 "Cannot read properties of undefined (reading 'destroy')", 28695 "can't access property 'destroy'", 28696 "_pluginsLoaded is not a function", 28697 /Missing target element ".*" for ".*" controller/, 28698 "Syntax error, unrecognized expression", 28699 "Cannot read properties of null (reading 'handleSuccessResponse')", 28700 "null is not an object (evaluating 'window.Rebound.handleSuccessResponse')", 28701 "Sentry.browserTracingIntegration is not a function", 28702 /SentryBrowserTracingIntegration is not a function/, 28703 /browserTracingIntegration is not a function/, 28704 "TurnstileError", 28705 "[Cloudflare Turnstile]" 28706 ], 28707 denyUrls: [ 28708 /graph\.facebook\.com/i, 28709 /connect\.facebook\.net\/en_US\/all\.js/i, 28710 /extensions\//i, 28711 /^chrome:\/\//i, 28712 /^chrome-extension:\/\//i, 28713 /127\.0\.0\.1:4001\/isrunning/i, 28714 /webappstoolbarba\.texthelp\.com\//i, 28715 /metrics\.itunes\.apple\.com\.edgesuite\.net\//i, 28716 /v1\/risk\.js/i, 28717 /gc\.kis\.v2\.scr\.kaspersky-labs\.com\//i, 28718 /frame\..*\.js/i, 28719 /js\.intercomcdn\.com/i, 28720 /static\.cloudflareinsights\.com/i, 28721 /js\.sentry-cdn\.com/i, 28722 /challenges\.cloudflare\.com\/turnstile/i 28723 ], 28724 beforeSend(event) { 28725 if ((event.exception?.values?.[0]?.value || "").includes("browserTracingIntegration is not a function")) return null; 28726 if (isTurnstileErrorEvent(event)) return null; 28727 if (isGoogleTranslateStackOverflow(event)) return null; 28728 if (!event.tags?.source) { 28729 const hasControllerFrame = (event.exception?.values?.[0]?.stacktrace?.frames)?.some((f) => f?.filename?.includes("_controller")); 28730 event.tags = { 28731 ...event.tags, 28732 source: hasControllerFrame ? "stimulus" : "other" 28733 }; 28734 } 28735 scrubBreadcrumbUrls(event); 28736 if (event.request?.url) event.request.url = scrubSensitiveUrl(event.request.url); 28737 return event; 28738 } 28739 }); 28740 if (window.gon?.user) setUser({ id: String(window.gon.user.id) }); 28741 if (window.gon?.ip_country) setTag("ip_country", window.gon.ip_country); 28742 isInitialized = true; 28743 } catch (error) { 28744 console.error("[Sentry] Failed to initialize:", error); 28745 isInitialized = true; 28746 } 28747} 28748/** 28749* Capture an exception manually with React context 28750*/ 28751function captureReactException(error, componentName, extraContext) { 28752 withScope((scope) => { 28753 scope.setTag("source", "react"); 28754 if (componentName) scope.setTag("component", componentName); 28755 if (extraContext) scope.setExtras(extraContext); 28756 captureException(error); 28757 }); 28758} 28759var isInitialized, SENSITIVE_URL_PATH, SPAN_URL_ATTRIBUTES, BREADCRUMB_URL_KEYS; 28760function init_sentry() { 28761 return (init_sentry = __esmMin((() => { 28762 init_esm$3(); 28763 init_turnstile(); 28764 isInitialized = false;
28765 SENSITIVE_URL_PATH = /(\/email-spam-checker\/results)\/[^/?#]+/g; 28766 SPAN_URL_ATTRIBUTES = [ 28767 "url", 28768 "http.url", 28769 "url.full" 28770 ]; 28771 BREADCRUMB_URL_KEYS = [ 28772 "url", 28773 "from", 28774 "to" 28775 ]; 28776 })))(); 28777} 28778//#endregion 28779//#region app/frontend/react/components/sentry-error-boundary.tsx 28780/** 28781* Higher-order component that wraps a component with SentryErrorBoundary. 28782* This is designed to be used with Turbo Mount's registerComponent. 28783* 28784* Usage: 28785* ```tsx 28786* import { withSentryErrorBoundary } from "~/react/components/sentry-error-boundary" 28787* 28788* const MyComponentWithErrorBoundary = withSentryErrorBoundary(MyComponent, "MyComponent") 28789* registerComponent(turboMount, "MyComponent", MyComponentWithErrorBoundary) 28790* ``` 28791*/ 28792function withSentryErrorBoundary(WrappedComponent, componentName, fallback) { 28793 const WithErrorBoundary = (props) => { 28794 const $ = (0, import_compiler_runtime.c)(2); 28795 let t0; 28796 if ($[0] !== props) { 28797 t0 = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SentryErrorBoundary, { 28798 componentName, 28799 fallback, 28800 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WrappedComponent, { ...props }) 28801 }); 28802 $[0] = props; 28803 $[1] = t0; 28804 } else t0 = $[1]; 28805 return t0; 28806 }; 28807 WithErrorBoundary.displayName = `WithSentryErrorBoundary(${componentName})`; 28808 return WithErrorBoundary; 28809} 28810var import_compiler_runtime, import_react, import_jsx_runtime, SentryErrorBoundary; 28811function init_sentry_error_boundary() { 28812 return (init_sentry_error_boundary = __esmMin((() => { 28813 import_compiler_runtime = require_compiler_runtime(); 28814 import_react = /* @__PURE__ */ __toESM(require_react()); 28815 init_sentry(); 28816 init_button(); 28817 init_icon(); 28818 import_jsx_runtime = require_jsx_runtime(); 28819 SentryErrorBoundary = class extends import_react.Component { 28820 constructor(props) { 28821 super(props); 28822 this.resetError = () => { 28823 this.setState((prev) => ({ 28824 hasError: false, 28825 error: null, 28826 resetCount: prev.resetCount + 1 28827 })); 28828 }; 28829 this.state = { 28830 hasError: false, 28831 error: null, 28832 resetCount: 0, 28833 resetKey: props.resetKey 28834 }; 28835 } 28836 static getDerivedStateFromError(error) { 28837 return { 28838 hasError: true, 28839 error 28840 }; 28841 } 28842 static getDerivedStateFromProps(props, state) { 28843 if (props.resetKey === state.resetKey) return null; 28844 return { 28845 resetKey: props.resetKey, 28846 hasError: false, 28847 error: null 28848 }; 28849 } 28850 componentDidCatch(error, errorInfo) { 28851 const { componentName, context } = this.props; 28852 captureReactException(error, componentName, { 28853 componentStack: errorInfo.componentStack, 28854 componentName, 28855 ...context 28856 }); 28857 console.error(`[SentryErrorBoundary] Error in ${componentName || "unknown component"}:`, error, errorInfo); 28858 } 28859 render() { 28860 const { hasError, error, resetCount } = this.state; 28861 const { children, fallback } = this.props; 28862 if (hasError && error) { 28863 if (fallback) { 28864 if (isFunction(fallback)) return fallback(error, this.resetError); 28865 return fallback; 28866 } 28867 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 28868 className: "sentry-error-boundary-fallback", 28869 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 28870 className: "sentry-error-boundary-fallback__content", 28871 children: [ 28872 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { 28873 icon: "exclamation-triangle", 28874 size: "xl" 28875 }), 28876 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { 28877 className: "mt-2 sentry-error-boundary-fallback__message", 28878 children: "Something went wrong." 28879 }), 28880 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 28881 variant: "primary", 28882 onClick: this.resetError, 28883 className: "mt-2", 28884 children: "Try again" 28885 }) 28886 ] 28887 }) 28888 }); 28889 } 28890 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.Fragment, { children }, resetCount); 28891 } 28892 }; 28893 })))(); 28894} 28895//#endregion 28896export { initSentry as a, captureException as c, captureReactException as i, captureMessage as l, init_sentry_error_boundary as n, init_sentry as o, withSentryErrorBoundary as r, init_esm$3 as s, SentryErrorBoundary as t, init_exports as u };
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.