{"version":3,"file":"sessions-Vp9Uqi9i.js","names":["log","warn","error","debug","debug","debug","withScope","spanWithMaybeDsc","debug","debug","debug"],"sources":["../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/debug-build.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/worldwide.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/version.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/carrier.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/debug-logger.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/is.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/object.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/randomSafeContext.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/string.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/misc.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/time.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/session.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/merge.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/propagationContext.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/weakRef.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/spanOnScope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/scope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/defaultScopes.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/chain-and-copy-promiselike.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/asyncContext/index.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/attributes.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/currentScopes.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/semanticAttributes.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/utils.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/baggage.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/dsn.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/spanUtils.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/hasSpansEnabled.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/should-ignore-span.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/constants.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/spans/beforeSendSpan.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/envelope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/envelope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/logSpans.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/measurement.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/segmentSpanCaptureStrategy.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/spans/hasSpanStreamingEnabled.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/handleCallbackErrors.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/sampling.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/tracing/trace.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/scopeData.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/prepareEvent.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/exports.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/timestampSequence.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/trace-info.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/logs/constants.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/env.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/node.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/utils/isBrowser.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/logs/envelope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/logs/internal.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/metrics/envelope.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/metrics/internal.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/breadcrumbs.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/logs/public-api.js","../../node_modules/.pnpm/@sentry+core@10.70.0/node_modules/@sentry/core/build/esm/metrics/public-api.js","../../src/app/utils/sentryScrubbers.ts","../../src/app/utils/debugLogger.ts","../../src/client/localNotificationCache.ts","../../src/unstable/prefixes/msc/event_misc.ts","../../src/unstable/prefixes/msc/accountdata.ts","../../src/unstable/prefixes/msc/state_events.ts","../../src/unstable/prefixes/sable/accountdata.ts","../../src/unstable/prefixes/misc.ts","../../src/types/matrix/accountData.ts","../../src/types/matrix/room.ts","../../src/client/slidingSyncSidebarCache.ts","../../src/app/state/utils/atomWithLocalStorage.ts","../../node_modules/.pnpm/browser-encrypt-attachment@0.3.0/node_modules/browser-encrypt-attachment/index.js","../../node_modules/.pnpm/await-to-js@3.0.0/node_modules/await-to-js/dist/await-to-js.es5.js","../../src/app/utils/mediaWorker.ts","../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_u64.js","../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/utils.js","../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_md.js","../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/sha2.js","../../src/app/utils/attachmentCrypto.ts","../../src/app/utils/sort.ts","../../src/app/utils/room/relations.ts","../../src/app/utils/room/hierarchy.ts","../../src/app/plugins/custom-emoji/PackAddress.ts","../../src/app/plugins/custom-emoji/types.ts","../../src/app/plugins/custom-emoji/PackMetaReader.ts","../../src/app/plugins/custom-emoji/PackImageReader.ts","../../src/app/plugins/custom-emoji/PackImagesReader.ts","../../src/app/plugins/custom-emoji/ImagePack.ts","../../src/app/plugins/custom-emoji/utils.ts","../../src/types/wrapper/SerializableMap.ts","../../src/types/wrapper/SerializableSet.ts","../../src/app/utils/mxIdHelper.ts","../../src/app/utils/roomSupport.ts","../../src/app/plugins/via-servers.ts","../../src/app/utils/roomVisibility.ts","../../src/app/utils/msc4459helper.ts","../../src/app/utils/messageReaction.ts","../../src/app/utils/mediaUrl.ts","../../src/app/utils/matrix.ts","../../src/app/utils/debug.ts","../../src/app/state/sessions.ts"],"sourcesContent":["const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","const GLOBAL_OBJ = globalThis;\n\nexport { GLOBAL_OBJ };\n//# sourceMappingURL=worldwide.js.map\n","const SDK_VERSION = \"10.70.0\" ;\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { SDK_VERSION } from './utils/version.js';\nimport { GLOBAL_OBJ } from './utils/worldwide.js';\n\nfunction getMainCarrier() {\n  getSentryCarrier(GLOBAL_OBJ);\n  return GLOBAL_OBJ;\n}\nfunction getSentryCarrier(carrier) {\n  const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n  __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n  return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};\n}\nfunction getGlobalSingleton(name, creator, obj = GLOBAL_OBJ) {\n  const __SENTRY__ = obj.__SENTRY__ = obj.__SENTRY__ || {};\n  const carrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};\n  return carrier[name] || (carrier[name] = creator());\n}\n\nexport { getGlobalSingleton, getMainCarrier, getSentryCarrier };\n//# sourceMappingURL=carrier.js.map\n","import { getGlobalSingleton } from '../carrier.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst CONSOLE_LEVELS = [\n  \"debug\",\n  \"info\",\n  \"warn\",\n  \"error\",\n  \"log\",\n  \"assert\",\n  \"trace\"\n];\nconst PREFIX = \"Sentry Logger \";\nconst originalConsoleMethods = {};\nfunction consoleSandbox(callback) {\n  if (!(\"console\" in GLOBAL_OBJ)) {\n    return callback();\n  }\n  const console = GLOBAL_OBJ.console;\n  const wrappedFuncs = {};\n  const wrappedLevels = Object.keys(originalConsoleMethods);\n  wrappedLevels.forEach((level) => {\n    const originalConsoleMethod = originalConsoleMethods[level];\n    wrappedFuncs[level] = console[level];\n    console[level] = originalConsoleMethod;\n  });\n  try {\n    return callback();\n  } finally {\n    wrappedLevels.forEach((level) => {\n      console[level] = wrappedFuncs[level];\n    });\n  }\n}\nfunction enable() {\n  _getLoggerSettings().enabled = true;\n}\nfunction disable() {\n  _getLoggerSettings().enabled = false;\n}\nfunction isEnabled() {\n  return _getLoggerSettings().enabled;\n}\nfunction log(...args) {\n  _maybeLog(\"log\", ...args);\n}\nfunction warn(...args) {\n  _maybeLog(\"warn\", ...args);\n}\nfunction error(...args) {\n  _maybeLog(\"error\", ...args);\n}\nfunction _maybeLog(level, ...args) {\n  if (!DEBUG_BUILD) {\n    return;\n  }\n  if (isEnabled()) {\n    consoleSandbox(() => {\n      GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);\n    });\n  }\n}\nfunction _getLoggerSettings() {\n  if (!DEBUG_BUILD) {\n    return { enabled: false };\n  }\n  return getGlobalSingleton(\"loggerSettings\", () => ({ enabled: false }));\n}\nconst debug = {\n  /** Enable logging. */\n  enable,\n  /** Disable logging. */\n  disable,\n  /** Check if logging is enabled. */\n  isEnabled,\n  /** Log a message. */\n  log,\n  /** Log a warning. */\n  warn,\n  /** Log an error. */\n  error\n};\n\nexport { CONSOLE_LEVELS, consoleSandbox, debug, originalConsoleMethods };\n//# sourceMappingURL=debug-logger.js.map\n","const objectToString = Object.prototype.toString;\nfunction isError(wat) {\n  switch (objectToString.call(wat)) {\n    case \"[object Error]\":\n    case \"[object Exception]\":\n    case \"[object DOMException]\":\n    case \"[object WebAssembly.Exception]\":\n      return true;\n    default:\n      return isInstanceOf(wat, Error);\n  }\n}\nfunction isBuiltin(wat, className) {\n  return objectToString.call(wat) === `[object ${className}]`;\n}\nfunction isErrorEvent(wat) {\n  return isBuiltin(wat, \"ErrorEvent\");\n}\nfunction isDOMError(wat) {\n  return isBuiltin(wat, \"DOMError\");\n}\nfunction isDOMException(wat) {\n  return isBuiltin(wat, \"DOMException\");\n}\nfunction isString(wat) {\n  return isBuiltin(wat, \"String\");\n}\nfunction isParameterizedString(wat) {\n  return typeof wat === \"object\" && wat !== null && \"__sentry_template_string__\" in wat && \"__sentry_template_values__\" in wat;\n}\nfunction isPrimitive(wat) {\n  return wat === null || isParameterizedString(wat) || typeof wat !== \"object\" && typeof wat !== \"function\";\n}\nfunction isPlainObject(wat) {\n  return isBuiltin(wat, \"Object\");\n}\nfunction isObjectLike(wat) {\n  return typeof wat === \"object\" && wat !== null;\n}\nfunction isEvent(wat) {\n  return typeof Event !== \"undefined\" && isInstanceOf(wat, Event);\n}\nfunction isElement(wat) {\n  return typeof Element !== \"undefined\" && isInstanceOf(wat, Element);\n}\nfunction isRegExp(wat) {\n  return isBuiltin(wat, \"RegExp\");\n}\nfunction isThenable(wat) {\n  return Boolean(wat?.then && typeof wat.then === \"function\");\n}\nfunction isSyntheticEvent(wat) {\n  return isPlainObject(wat) && \"nativeEvent\" in wat && \"preventDefault\" in wat && \"stopPropagation\" in wat;\n}\nfunction isInstanceOf(wat, base) {\n  try {\n    return wat instanceof base;\n  } catch {\n    return false;\n  }\n}\nfunction isVueViewModel(wat) {\n  return !!(typeof wat === \"object\" && wat !== null && (wat.__isVue || wat._isVue || wat.__v_isVNode));\n}\nfunction isRequest(request) {\n  return typeof Request !== \"undefined\" && isInstanceOf(request, Request);\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isObjectLike, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isRequest, isString, isSyntheticEvent, isThenable, isVueViewModel };\n//# sourceMappingURL=is.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isError, isEvent, isPrimitive, isObjectLike } from './is.js';\n\nfunction fill(source, name, replacementFactory) {\n  if (!(name in source)) {\n    return;\n  }\n  const original = source[name];\n  if (typeof original !== \"function\") {\n    return;\n  }\n  const wrapped = replacementFactory(original);\n  if (typeof wrapped === \"function\") {\n    markFunctionWrapped(wrapped, original);\n  }\n  try {\n    source[name] = wrapped;\n  } catch {\n    DEBUG_BUILD && debug.log(`Failed to replace method \"${name}\" in object`, source);\n  }\n}\nfunction addNonEnumerableProperty(obj, name, value) {\n  try {\n    Object.defineProperty(obj, name, {\n      // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n      value,\n      writable: true,\n      configurable: true\n    });\n  } catch {\n    DEBUG_BUILD && debug.log(`Failed to add non-enumerable property \"${String(name)}\" to object`, obj);\n  }\n}\nfunction markFunctionWrapped(wrapped, original) {\n  try {\n    const proto = original.prototype || {};\n    wrapped.prototype = original.prototype = proto;\n    addNonEnumerableProperty(wrapped, \"__sentry_original__\", original);\n  } catch {\n  }\n}\nfunction wrapMethod(obj, field, wrapped, enumerable = true) {\n  const original = obj[field];\n  if (typeof original !== \"function\") {\n    throw new Error(`Cannot wrap method: ${field} is not a function`);\n  }\n  if (getOriginalFunction(original)) {\n    throw new Error(`Attempting to wrap method ${field} multiple times`);\n  }\n  markFunctionWrapped(wrapped, original);\n  Object.defineProperty(obj, field, {\n    writable: true,\n    configurable: true,\n    enumerable,\n    value: wrapped\n  });\n}\nfunction getOriginalFunction(func) {\n  return func.__sentry_original__;\n}\nfunction convertToPlainObject(value) {\n  if (isError(value)) {\n    return {\n      message: value.message,\n      name: value.name,\n      stack: value.stack,\n      ...getOwnProperties(value)\n    };\n  }\n  if (isEvent(value)) {\n    const { type, target, currentTarget, detail } = value;\n    return {\n      type,\n      target,\n      currentTarget,\n      ...detail ? { detail } : {},\n      ...getOwnProperties(value)\n    };\n  }\n  return value;\n}\nfunction getOwnProperties(obj) {\n  if (isObjectLike(obj)) {\n    return Object.fromEntries(Object.entries(obj));\n  }\n  return {};\n}\nfunction extractExceptionKeysForMessage(exception) {\n  const keys = Object.keys(convertToPlainObject(exception));\n  keys.sort();\n  return !keys[0] ? \"[object has no keys]\" : keys.join(\", \");\n}\nfunction dropUndefinedKeys(inputValue) {\n  const memoizationMap = /* @__PURE__ */ new Map();\n  return _dropUndefinedKeys(inputValue, memoizationMap);\n}\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n  if (inputValue === null || typeof inputValue !== \"object\") {\n    return inputValue;\n  }\n  const memoVal = memoizationMap.get(inputValue);\n  if (memoVal !== void 0) {\n    return memoVal;\n  }\n  if (Array.isArray(inputValue)) {\n    const returnValue = [];\n    memoizationMap.set(inputValue, returnValue);\n    inputValue.forEach((value) => {\n      returnValue.push(_dropUndefinedKeys(value, memoizationMap));\n    });\n    return returnValue;\n  }\n  if (isPojo(inputValue)) {\n    const returnValue = {};\n    memoizationMap.set(inputValue, returnValue);\n    const keys = Object.keys(inputValue);\n    keys.forEach((key) => {\n      const val = inputValue[key];\n      if (val !== void 0) {\n        returnValue[key] = _dropUndefinedKeys(val, memoizationMap);\n      }\n    });\n    return returnValue;\n  }\n  return inputValue;\n}\nfunction isPojo(input) {\n  const constructor = input.constructor;\n  return constructor === Object || constructor === void 0;\n}\nfunction objectify(wat) {\n  let objectified;\n  switch (true) {\n    // this will catch both undefined and null\n    case wat == void 0:\n      objectified = new String(wat);\n      break;\n    // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n    // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n    // an object in order to wrap it.\n    case (typeof wat === \"symbol\" || typeof wat === \"bigint\"):\n      objectified = Object(wat);\n      break;\n    // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n    case isPrimitive(wat):\n      objectified = new wat.constructor(wat);\n      break;\n    // by process of elimination, at this point we know that `wat` must already be an object\n    default:\n      objectified = wat;\n      break;\n  }\n  return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, wrapMethod };\n//# sourceMappingURL=object.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nlet RESOLVED_RUNNER;\nfunction withRandomSafeContext(cb) {\n  if (RESOLVED_RUNNER !== void 0) {\n    return RESOLVED_RUNNER ? RESOLVED_RUNNER(cb) : cb();\n  }\n  const sym = /* @__PURE__ */ Symbol.for(\"__SENTRY_SAFE_RANDOM_ID_WRAPPER__\");\n  const globalWithSymbol = GLOBAL_OBJ;\n  if (sym in globalWithSymbol && typeof globalWithSymbol[sym] === \"function\") {\n    RESOLVED_RUNNER = globalWithSymbol[sym];\n    return RESOLVED_RUNNER(cb);\n  }\n  RESOLVED_RUNNER = null;\n  return cb();\n}\nfunction safeMathRandom() {\n  return withRandomSafeContext(() => Math.random());\n}\nfunction safeDateNow() {\n  return withRandomSafeContext(() => Date.now());\n}\n\nexport { safeDateNow, safeMathRandom, withRandomSafeContext };\n//# sourceMappingURL=randomSafeContext.js.map\n","import { isString, isRegExp, isPrimitive } from './is.js';\nimport { stringifyValue } from './normalize.js';\n\nfunction stringify(value, fallback = \"[unserializable]\") {\n  if (typeof value === \"string\") {\n    return value;\n  }\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return typeof fallback === \"function\" ? fallback(value) : fallback;\n  }\n}\nfunction truncate(str, max = 0) {\n  if (typeof str !== \"string\" || max === 0) {\n    return str;\n  }\n  return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction snipLine(line, colno) {\n  let newLine = line;\n  const lineLength = newLine.length;\n  if (lineLength <= 150) {\n    return newLine;\n  }\n  if (colno > lineLength) {\n    colno = lineLength;\n  }\n  let start = Math.max(colno - 60, 0);\n  if (start < 5) {\n    start = 0;\n  }\n  let end = Math.min(start + 140, lineLength);\n  if (end > lineLength - 5) {\n    end = lineLength;\n  }\n  if (end === lineLength) {\n    start = Math.max(end - 140, 0);\n  }\n  newLine = newLine.slice(start, end);\n  if (start > 0) {\n    newLine = `'{snip} ${newLine}`;\n  }\n  if (end < lineLength) {\n    newLine += \" {snip}\";\n  }\n  return newLine;\n}\nfunction safeJoin(input, delimiter) {\n  if (!Array.isArray(input)) {\n    return \"\";\n  }\n  const output = [];\n  for (let i = 0; i < input.length; i++) {\n    const value = input[i];\n    if (isPrimitive(value)) {\n      output.push(String(value));\n    } else if (value instanceof Error) {\n      output.push(value.message ? `${value.name}: ${value.message}` : value.name);\n    } else {\n      output.push(stringifyValue(void 0, value));\n    }\n  }\n  return output.join(delimiter);\n}\nfunction isMatchingPattern(value, pattern, requireExactStringMatch = false) {\n  if (!isString(value)) {\n    return false;\n  }\n  if (isRegExp(pattern)) {\n    return pattern.test(value);\n  }\n  if (isString(pattern)) {\n    return requireExactStringMatch ? value === pattern : value.includes(pattern);\n  }\n  if (typeof pattern === \"function\") {\n    return pattern(value);\n  }\n  return false;\n}\nfunction stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {\n  for (const pattern of patterns) {\n    if (isMatchingPattern(testString, pattern, requireExactStringMatch)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, stringify, truncate };\n//# sourceMappingURL=string.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { withRandomSafeContext, safeMathRandom } from './randomSafeContext.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nfunction getCrypto() {\n  const gbl = GLOBAL_OBJ;\n  return gbl.crypto || gbl.msCrypto;\n}\nlet emptyUuid;\nfunction getRandomByte() {\n  return safeMathRandom() * 16;\n}\nfunction uuid4(crypto = getCrypto()) {\n  try {\n    if (crypto?.randomUUID) {\n      return withRandomSafeContext(() => crypto.randomUUID()).replace(/-/g, \"\");\n    }\n  } catch {\n  }\n  if (!emptyUuid) {\n    emptyUuid = \"10000000100040008000\" + 1e11;\n  }\n  return emptyUuid.replace(\n    /[018]/g,\n    (c) => (\n      // eslint-disable-next-line no-bitwise\n      (c ^ (getRandomByte() & 15) >> c / 4).toString(16)\n    )\n  );\n}\nfunction getFirstException(event) {\n  return event.exception?.values?.[0];\n}\nfunction getEventDescription(event) {\n  const { message, event_id: eventId } = event;\n  if (message) {\n    return message;\n  }\n  const firstException = getFirstException(event);\n  if (firstException) {\n    if (firstException.type && firstException.value) {\n      return `${firstException.type}: ${firstException.value}`;\n    }\n    return firstException.type || firstException.value || eventId || \"<unknown>\";\n  }\n  return eventId || \"<unknown>\";\n}\nfunction addExceptionTypeValue(event, value, type) {\n  const exception = event.exception = event.exception || {};\n  const values = exception.values = exception.values || [];\n  const firstException = values[0] = values[0] || {};\n  if (!firstException.value) {\n    firstException.value = value || \"\";\n  }\n  if (!firstException.type) {\n    firstException.type = type || \"Error\";\n  }\n}\nfunction addExceptionMechanism(event, newMechanism) {\n  const firstException = getFirstException(event);\n  if (!firstException) {\n    return;\n  }\n  const defaultMechanism = { type: \"generic\", handled: true };\n  const currentMechanism = firstException.mechanism;\n  firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n  if (newMechanism && \"data\" in newMechanism) {\n    const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n    firstException.mechanism.data = mergedData;\n  }\n}\nconst SEMVER_REGEXP = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\nfunction _parseInt(input) {\n  return parseInt(input || \"\", 10);\n}\nfunction parseSemver(input) {\n  const match = input.match(SEMVER_REGEXP) || [];\n  const major = _parseInt(match[1]);\n  const minor = _parseInt(match[2]);\n  const patch = _parseInt(match[3]);\n  return {\n    buildmetadata: match[5],\n    major: isNaN(major) ? void 0 : major,\n    minor: isNaN(minor) ? void 0 : minor,\n    patch: isNaN(patch) ? void 0 : patch,\n    prerelease: match[4]\n  };\n}\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n  if (frame.lineno === void 0) {\n    return;\n  }\n  const maxLines = lines.length;\n  const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n  frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0));\n  const lineIndex = Math.min(maxLines - 1, sourceLine);\n  frame.context_line = snipLine(lines[lineIndex], frame.colno || 0);\n  frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0));\n}\nfunction checkOrSetAlreadyCaught(exception) {\n  if (isAlreadyCaptured(exception)) {\n    return true;\n  }\n  try {\n    addNonEnumerableProperty(exception, \"__sentry_captured__\", true);\n  } catch {\n  }\n  return false;\n}\nfunction isAlreadyCaptured(exception) {\n  try {\n    return exception.__sentry_captured__;\n  } catch {\n  }\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, checkOrSetAlreadyCaught, getEventDescription, isAlreadyCaptured, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { safeDateNow, withRandomSafeContext } from './randomSafeContext.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst ONE_SECOND_IN_MS = 1e3;\nfunction dateTimestampInSeconds() {\n  return safeDateNow() / ONE_SECOND_IN_MS;\n}\nfunction createUnixTimestampInSecondsFunc() {\n  const { performance } = GLOBAL_OBJ;\n  if (!performance?.now || !performance.timeOrigin) {\n    return dateTimestampInSeconds;\n  }\n  const timeOrigin = performance.timeOrigin;\n  return () => {\n    return (timeOrigin + withRandomSafeContext(() => performance.now())) / ONE_SECOND_IN_MS;\n  };\n}\nlet _cachedTimestampInSeconds;\nfunction timestampInSeconds() {\n  const func = _cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc());\n  return func();\n}\nlet cachedTimeOrigin = null;\nfunction getBrowserTimeOrigin() {\n  const { performance } = GLOBAL_OBJ;\n  if (!performance?.now) {\n    return void 0;\n  }\n  const threshold = 3e5;\n  const performanceNow = withRandomSafeContext(() => performance.now());\n  const dateNow = safeDateNow();\n  const timeOrigin = performance.timeOrigin;\n  if (typeof timeOrigin === \"number\") {\n    const timeOriginDelta = Math.abs(timeOrigin + performanceNow - dateNow);\n    if (timeOriginDelta < threshold) {\n      return timeOrigin;\n    }\n  }\n  const navigationStart = performance.timing?.navigationStart;\n  if (typeof navigationStart === \"number\") {\n    const navigationStartDelta = Math.abs(navigationStart + performanceNow - dateNow);\n    if (navigationStartDelta < threshold) {\n      return navigationStart;\n    }\n  }\n  return dateNow - performanceNow;\n}\nfunction browserPerformanceTimeOrigin() {\n  if (cachedTimeOrigin === null) {\n    cachedTimeOrigin = getBrowserTimeOrigin();\n  }\n  return cachedTimeOrigin;\n}\n\nexport { browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds };\n//# sourceMappingURL=time.js.map\n","import { uuid4 } from './utils/misc.js';\nimport { timestampInSeconds } from './utils/time.js';\n\nfunction makeSession(context) {\n  const startingTime = timestampInSeconds();\n  const session = {\n    sid: uuid4(),\n    init: true,\n    timestamp: startingTime,\n    started: startingTime,\n    duration: 0,\n    status: \"ok\",\n    errors: 0,\n    ignoreDuration: false,\n    toJSON: () => sessionToJSON(session)\n  };\n  if (context) {\n    updateSession(session, context);\n  }\n  return session;\n}\nfunction updateSession(session, context = {}) {\n  if (context.user) {\n    if (!session.ipAddress && context.user.ip_address) {\n      session.ipAddress = context.user.ip_address;\n    }\n    if (!session.did && !context.did) {\n      session.did = context.user.id || context.user.email || context.user.username;\n    }\n  }\n  session.timestamp = context.timestamp || timestampInSeconds();\n  if (context.abnormal_mechanism) {\n    session.abnormal_mechanism = context.abnormal_mechanism;\n  }\n  if (context.ignoreDuration) {\n    session.ignoreDuration = context.ignoreDuration;\n  }\n  if (context.sid) {\n    session.sid = context.sid.length === 32 ? context.sid : uuid4();\n  }\n  if (context.init !== void 0) {\n    session.init = context.init;\n  }\n  if (!session.did && context.did) {\n    session.did = `${context.did}`;\n  }\n  if (typeof context.started === \"number\") {\n    session.started = context.started;\n  }\n  if (session.ignoreDuration) {\n    session.duration = void 0;\n  } else if (typeof context.duration === \"number\") {\n    session.duration = context.duration;\n  } else {\n    const duration = session.timestamp - session.started;\n    session.duration = duration >= 0 ? duration : 0;\n  }\n  if (context.release) {\n    session.release = context.release;\n  }\n  if (context.environment) {\n    session.environment = context.environment;\n  }\n  if (!session.ipAddress && context.ipAddress) {\n    session.ipAddress = context.ipAddress;\n  }\n  if (!session.userAgent && context.userAgent) {\n    session.userAgent = context.userAgent;\n  }\n  if (typeof context.errors === \"number\") {\n    session.errors = context.errors;\n  }\n  if (context.status) {\n    session.status = context.status;\n  }\n}\nfunction closeSession(session, status) {\n  let context = {};\n  if (status) {\n    context = { status };\n  } else if (session.status === \"ok\") {\n    context = { status: \"exited\" };\n  }\n  updateSession(session, context);\n}\nfunction sessionToJSON(session) {\n  return {\n    sid: `${session.sid}`,\n    init: session.init,\n    // Make sure that sec is converted to ms for date constructor\n    started: new Date(session.started * 1e3).toISOString(),\n    timestamp: new Date(session.timestamp * 1e3).toISOString(),\n    status: session.status,\n    errors: session.errors,\n    did: typeof session.did === \"number\" || typeof session.did === \"string\" ? `${session.did}` : void 0,\n    duration: session.duration,\n    abnormal_mechanism: session.abnormal_mechanism,\n    attrs: {\n      release: session.release,\n      environment: session.environment,\n      ip_address: session.ipAddress,\n      user_agent: session.userAgent\n    }\n  };\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","function merge(initialObj, mergeObj, levels = 2) {\n  if (!mergeObj || typeof mergeObj !== \"object\" || levels <= 0) {\n    return mergeObj;\n  }\n  if (initialObj && Object.keys(mergeObj).length === 0) {\n    return initialObj;\n  }\n  const output = { ...initialObj };\n  for (const key in mergeObj) {\n    if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n      output[key] = merge(output[key], mergeObj[key], levels - 1);\n    }\n  }\n  return output;\n}\n\nexport { merge };\n//# sourceMappingURL=merge.js.map\n","import { uuid4 } from './misc.js';\n\nfunction generateTraceId() {\n  return uuid4();\n}\nfunction generateSpanId() {\n  return uuid4().substring(16);\n}\n\nexport { generateSpanId, generateTraceId };\n//# sourceMappingURL=propagationContext.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nfunction makeWeakRef(value) {\n  try {\n    const WeakRefImpl = GLOBAL_OBJ.WeakRef;\n    if (typeof WeakRefImpl === \"function\") {\n      return new WeakRefImpl(value);\n    }\n  } catch {\n  }\n  return value;\n}\nfunction derefWeakRef(ref) {\n  if (!ref) {\n    return void 0;\n  }\n  if (typeof ref === \"object\" && \"deref\" in ref && typeof ref.deref === \"function\") {\n    try {\n      return ref.deref();\n    } catch {\n      return void 0;\n    }\n  }\n  return ref;\n}\n\nexport { derefWeakRef, makeWeakRef };\n//# sourceMappingURL=weakRef.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { makeWeakRef, derefWeakRef } from './weakRef.js';\n\nconst SCOPE_SPAN_FIELD = \"_sentrySpan\";\nfunction _setSpanForScope(scope, span) {\n  if (span) {\n    addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, makeWeakRef(span));\n  } else {\n    delete scope[SCOPE_SPAN_FIELD];\n  }\n}\nfunction _getSpanForScope(scope) {\n  return derefWeakRef(scope[SCOPE_SPAN_FIELD]);\n}\n\nexport { _getSpanForScope, _setSpanForScope };\n//# sourceMappingURL=spanOnScope.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { updateSession } from './session.js';\nimport { debug } from './utils/debug-logger.js';\nimport { isPlainObject } from './utils/is.js';\nimport { merge } from './utils/merge.js';\nimport { uuid4 } from './utils/misc.js';\nimport { generateTraceId } from './utils/propagationContext.js';\nimport { safeMathRandom } from './utils/randomSafeContext.js';\nimport { _setSpanForScope, _getSpanForScope } from './utils/spanOnScope.js';\nimport { truncate } from './utils/string.js';\nimport { dateTimestampInSeconds } from './utils/time.js';\n\nconst DEFAULT_MAX_BREADCRUMBS = 100;\nclass Scope {\n  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n  constructor() {\n    this._notifyingListeners = false;\n    this._scopeListeners = [];\n    this._eventProcessors = [];\n    this._breadcrumbs = [];\n    this._attachments = [];\n    this._user = {};\n    this._tags = {};\n    this._attributes = {};\n    this._extra = {};\n    this._contexts = {};\n    this._sdkProcessingMetadata = {};\n    this._propagationContext = {\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom()\n    };\n  }\n  /**\n   * Clone all data from this scope into a new scope.\n   */\n  clone() {\n    const newScope = new Scope();\n    newScope._breadcrumbs = [...this._breadcrumbs];\n    newScope._tags = { ...this._tags };\n    newScope._attributes = { ...this._attributes };\n    newScope._extra = { ...this._extra };\n    newScope._contexts = { ...this._contexts };\n    if (this._contexts.flags) {\n      newScope._contexts.flags = {\n        values: [...this._contexts.flags.values]\n      };\n    }\n    newScope._user = this._user;\n    newScope._level = this._level;\n    newScope._session = this._session;\n    newScope._transactionName = this._transactionName;\n    newScope._fingerprint = this._fingerprint;\n    newScope._eventProcessors = [...this._eventProcessors];\n    newScope._attachments = [...this._attachments];\n    newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n    newScope._propagationContext = { ...this._propagationContext };\n    newScope._client = this._client;\n    newScope._lastEventId = this._lastEventId;\n    newScope._conversationId = this._conversationId;\n    _setSpanForScope(newScope, _getSpanForScope(this));\n    return newScope;\n  }\n  /**\n   * Update the client assigned to this scope.\n   * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,\n   * as well as manually created scopes.\n   */\n  setClient(client) {\n    this._client = client;\n  }\n  /**\n   * Set the ID of the last captured error event.\n   * This is generally only captured on the isolation scope.\n   */\n  setLastEventId(lastEventId) {\n    this._lastEventId = lastEventId;\n  }\n  /**\n   * Get the client assigned to this scope.\n   */\n  getClient() {\n    return this._client;\n  }\n  /**\n   * Get the ID of the last captured error event.\n   * This is generally only available on the isolation scope.\n   */\n  lastEventId() {\n    return this._lastEventId;\n  }\n  /**\n   * @inheritDoc\n   */\n  addScopeListener(callback) {\n    this._scopeListeners.push(callback);\n  }\n  /**\n   * Add an event processor that will be called before an event is sent.\n   */\n  addEventProcessor(callback) {\n    this._eventProcessors.push(callback);\n    return this;\n  }\n  /**\n   * Set the user for this scope.\n   * Set to `null` to unset the user.\n   */\n  setUser(user) {\n    this._user = user || {\n      email: void 0,\n      id: void 0,\n      ip_address: void 0,\n      username: void 0\n    };\n    if (this._session) {\n      updateSession(this._session, { user });\n    }\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Get the user from this scope.\n   */\n  getUser() {\n    return this._user;\n  }\n  /**\n   * Set the conversation ID for this scope.\n   * Set to `null` to unset the conversation ID.\n   */\n  setConversationId(conversationId) {\n    this._conversationId = conversationId || void 0;\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Set an object that will be merged into existing tags on the scope,\n   * and will be sent as tags data with the event.\n   */\n  setTags(tags) {\n    this._tags = {\n      ...this._tags,\n      ...tags\n    };\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Set a single tag that will be sent as tags data with the event.\n   */\n  setTag(key, value) {\n    return this.setTags({ [key]: value });\n  }\n  /**\n   * Sets attributes onto the scope.\n   *\n   * These attributes are applied to logs, metrics and streamed spans.\n   *\n   * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.\n   *\n   * @param newAttributes - The attributes to set on the scope, as key-value pairs.\n   *\n   * @example\n   * ```typescript\n   * scope.setAttributes({\n   *   is_admin: true,\n   *   payment_selection: 'credit_card',\n   *   render_duration: 150,\n   * });\n   * ```\n   */\n  setAttributes(newAttributes) {\n    this._attributes = {\n      ...this._attributes,\n      ...newAttributes\n    };\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Sets an attribute onto the scope.\n   *\n   * These attributes are applied to logs, metrics and streamed spans.\n   *\n   * Supported attribute value types are `string`, `number`, `boolean`, `string[]`, `number[]` and `boolean[]`.\n   *\n   * @param key - The attribute key.\n   * @param value - The attribute value.\n   *\n   * @example\n   * ```typescript\n   * scope.setAttribute('is_admin', true);\n   * scope.setAttribute('render_duration', 150);\n   * ```\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  setAttribute(key, value) {\n    return this.setAttributes({ [key]: value });\n  }\n  /**\n   * Removes the attribute with the given key from the scope.\n   *\n   * @param key - The attribute key.\n   *\n   * @example\n   * ```typescript\n   * scope.removeAttribute('is_admin');\n   * ```\n   */\n  removeAttribute(key) {\n    if (key in this._attributes) {\n      delete this._attributes[key];\n      this._notifyScopeListeners();\n    }\n    return this;\n  }\n  /**\n   * Set an object that will be merged into existing extra on the scope,\n   * and will be sent as extra data with the event.\n   */\n  setExtras(extras) {\n    this._extra = {\n      ...this._extra,\n      ...extras\n    };\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Set a single key:value extra entry that will be sent as extra data with the event.\n   */\n  setExtra(key, extra) {\n    this._extra = { ...this._extra, [key]: extra };\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Sets the fingerprint on the scope to send with the events.\n   * @param {string[]} fingerprint Fingerprint to group events in Sentry.\n   */\n  setFingerprint(fingerprint) {\n    this._fingerprint = fingerprint;\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Sets the level on the scope for future events.\n   */\n  setLevel(level) {\n    this._level = level;\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Sets the transaction name on the scope so that the name of e.g. taken server route or\n   * the page location is attached to future events.\n   *\n   * IMPORTANT: Calling this function does NOT change the name of the currently active\n   * root span. If you want to change the name of the active root span, use\n   * `Sentry.updateSpanName(rootSpan, 'new name')` instead.\n   *\n   * By default, the SDK updates the scope's transaction name automatically on sensible\n   * occasions, such as a page navigation or when handling a new request on the server.\n   */\n  setTransactionName(name) {\n    this._transactionName = name;\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Sets context data with the given name.\n   * Data passed as context will be normalized. You can also pass `null` to unset the context.\n   * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.\n   */\n  setContext(key, context) {\n    if (context === null) {\n      delete this._contexts[key];\n    } else {\n      this._contexts[key] = context;\n    }\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Set the session for the scope.\n   */\n  setSession(session) {\n    if (!session) {\n      delete this._session;\n    } else {\n      this._session = session;\n    }\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Get the session from the scope.\n   */\n  getSession() {\n    return this._session;\n  }\n  /**\n   * Updates the scope with provided data. Can work in three variations:\n   * - plain object containing updatable attributes\n   * - Scope instance that'll extract the attributes from\n   * - callback function that'll receive the current scope as an argument and allow for modifications\n   */\n  update(captureContext) {\n    if (!captureContext) {\n      return this;\n    }\n    const scopeToMerge = typeof captureContext === \"function\" ? captureContext(this) : captureContext;\n    const scopeInstance = scopeToMerge instanceof Scope ? scopeToMerge.getScopeData() : isPlainObject(scopeToMerge) ? captureContext : void 0;\n    const {\n      tags,\n      attributes,\n      extra,\n      user,\n      contexts,\n      level,\n      fingerprint = [],\n      propagationContext,\n      conversationId\n    } = scopeInstance || {};\n    this._tags = { ...this._tags, ...tags };\n    this._attributes = { ...this._attributes, ...attributes };\n    this._extra = { ...this._extra, ...extra };\n    this._contexts = { ...this._contexts, ...contexts };\n    if (user && Object.keys(user).length) {\n      this._user = user;\n    }\n    if (level) {\n      this._level = level;\n    }\n    if (fingerprint.length) {\n      this._fingerprint = fingerprint;\n    }\n    if (propagationContext) {\n      this._propagationContext = propagationContext;\n    }\n    if (conversationId) {\n      this._conversationId = conversationId;\n    }\n    return this;\n  }\n  /**\n   * Clears the current scope and resets its properties.\n   * Note: The client will not be cleared.\n   */\n  clear() {\n    this._breadcrumbs = [];\n    this._tags = {};\n    this._attributes = {};\n    this._extra = {};\n    this._user = {};\n    this._contexts = {};\n    this._level = void 0;\n    this._transactionName = void 0;\n    this._fingerprint = void 0;\n    this._session = void 0;\n    this._conversationId = void 0;\n    _setSpanForScope(this, void 0);\n    this._attachments = [];\n    this.setPropagationContext({\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom()\n    });\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Adds a breadcrumb to the scope.\n   * By default, the last 100 breadcrumbs are kept.\n   */\n  addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n    const maxCrumbs = typeof maxBreadcrumbs === \"number\" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n    if (maxCrumbs <= 0) {\n      return this;\n    }\n    const mergedBreadcrumb = {\n      timestamp: dateTimestampInSeconds(),\n      ...breadcrumb,\n      // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory\n      message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message\n    };\n    this._breadcrumbs.push(mergedBreadcrumb);\n    if (this._breadcrumbs.length > maxCrumbs) {\n      this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);\n      this._client?.recordDroppedEvent(\"buffer_overflow\", \"log_item\");\n    }\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Get the last breadcrumb of the scope.\n   */\n  getLastBreadcrumb() {\n    return this._breadcrumbs[this._breadcrumbs.length - 1];\n  }\n  /**\n   * Clear all breadcrumbs from the scope.\n   */\n  clearBreadcrumbs() {\n    this._breadcrumbs = [];\n    this._notifyScopeListeners();\n    return this;\n  }\n  /**\n   * Add an attachment to the scope.\n   */\n  addAttachment(attachment) {\n    this._attachments.push(attachment);\n    return this;\n  }\n  /**\n   * Clear all attachments from the scope.\n   */\n  clearAttachments() {\n    this._attachments = [];\n    return this;\n  }\n  /**\n   * Get the data of this scope, which should be applied to an event during processing.\n   */\n  getScopeData() {\n    return {\n      breadcrumbs: this._breadcrumbs,\n      attachments: this._attachments,\n      contexts: this._contexts,\n      tags: this._tags,\n      attributes: this._attributes,\n      extra: this._extra,\n      user: this._user,\n      level: this._level,\n      fingerprint: this._fingerprint || [],\n      eventProcessors: this._eventProcessors,\n      propagationContext: this._propagationContext,\n      sdkProcessingMetadata: this._sdkProcessingMetadata,\n      transactionName: this._transactionName,\n      span: _getSpanForScope(this),\n      conversationId: this._conversationId\n    };\n  }\n  /**\n   * Add data which will be accessible during event processing but won't get sent to Sentry.\n   */\n  setSDKProcessingMetadata(newData) {\n    this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n    return this;\n  }\n  /**\n   * Add propagation context to the scope, used for distributed tracing\n   */\n  setPropagationContext(context) {\n    this._propagationContext = context;\n    return this;\n  }\n  /**\n   * Get propagation context from the scope, used for distributed tracing\n   */\n  getPropagationContext() {\n    return this._propagationContext;\n  }\n  /**\n   * Capture an exception for this scope.\n   *\n   * @returns {string} The id of the captured Sentry event.\n   */\n  captureException(exception, hint) {\n    const eventId = hint?.event_id || uuid4();\n    if (!this._client) {\n      DEBUG_BUILD && debug.warn(\"No client configured on scope - will not capture exception!\");\n      return eventId;\n    }\n    const syntheticException = new Error(\"Sentry syntheticException\");\n    this._client.captureException(\n      exception,\n      {\n        originalException: exception,\n        syntheticException,\n        ...hint,\n        event_id: eventId\n      },\n      this\n    );\n    return eventId;\n  }\n  /**\n   * Capture a message for this scope.\n   *\n   * @returns {string} The id of the captured message.\n   */\n  captureMessage(message, level, hint) {\n    const eventId = hint?.event_id || uuid4();\n    if (!this._client) {\n      DEBUG_BUILD && debug.warn(\"No client configured on scope - will not capture message!\");\n      return eventId;\n    }\n    const syntheticException = hint?.syntheticException ?? new Error(message);\n    this._client.captureMessage(\n      message,\n      level,\n      {\n        originalException: message,\n        syntheticException,\n        ...hint,\n        event_id: eventId\n      },\n      this\n    );\n    return eventId;\n  }\n  /**\n   * Capture a Sentry event for this scope.\n   *\n   * @returns {string} The id of the captured event.\n   */\n  captureEvent(event, hint) {\n    const eventId = event.event_id || hint?.event_id || uuid4();\n    if (!this._client) {\n      DEBUG_BUILD && debug.warn(\"No client configured on scope - will not capture event!\");\n      return eventId;\n    }\n    this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n    return eventId;\n  }\n  /**\n   * This will be called on every set call.\n   */\n  _notifyScopeListeners() {\n    if (!this._notifyingListeners) {\n      this._notifyingListeners = true;\n      this._scopeListeners.forEach((callback) => {\n        callback(this);\n      });\n      this._notifyingListeners = false;\n    }\n  }\n}\n\nexport { Scope };\n//# sourceMappingURL=scope.js.map\n","import { getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\n\nfunction getDefaultCurrentScope() {\n  return getGlobalSingleton(\"defaultCurrentScope\", () => new Scope());\n}\nfunction getDefaultIsolationScope() {\n  return getGlobalSingleton(\"defaultIsolationScope\", () => new Scope());\n}\n\nexport { getDefaultCurrentScope, getDefaultIsolationScope };\n//# sourceMappingURL=defaultScopes.js.map\n","const isActualPromise = (p) => p instanceof Promise && !p[kChainedCopy];\nconst kChainedCopy = /* @__PURE__ */ Symbol(\"chained PromiseLike\");\nconst chainAndCopyPromiseLike = (original, onSuccess, onError) => {\n  const chained = original.then(\n    (value) => {\n      onSuccess(value);\n      return value;\n    },\n    (err) => {\n      onError(err);\n      throw err;\n    }\n  );\n  return isActualPromise(chained) && isActualPromise(original) ? chained : copyProps(original, chained);\n};\nconst copyProps = (original, chained) => {\n  if (!chained) return original;\n  let mutated = false;\n  for (const key in original) {\n    if (key in chained) continue;\n    mutated = true;\n    const value = original[key];\n    if (typeof value === \"function\") {\n      Object.defineProperty(chained, key, {\n        value: (...args) => value.apply(original, args),\n        enumerable: true,\n        configurable: true,\n        writable: true\n      });\n    } else {\n      chained[key] = value;\n    }\n  }\n  if (mutated) Object.assign(chained, { [kChainedCopy]: true });\n  return chained;\n};\n\nexport { chainAndCopyPromiseLike };\n//# sourceMappingURL=chain-and-copy-promiselike.js.map\n","import { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes.js';\nimport { Scope } from '../scope.js';\nimport { chainAndCopyPromiseLike } from '../utils/chain-and-copy-promiselike.js';\nimport { isThenable } from '../utils/is.js';\nimport { getMainCarrier, getSentryCarrier } from '../carrier.js';\n\nclass AsyncContextStack {\n  constructor(scope, isolationScope) {\n    let assignedScope;\n    if (!scope) {\n      assignedScope = new Scope();\n    } else {\n      assignedScope = scope;\n    }\n    let assignedIsolationScope;\n    if (!isolationScope) {\n      assignedIsolationScope = new Scope();\n    } else {\n      assignedIsolationScope = isolationScope;\n    }\n    this._stack = [{ scope: assignedScope }];\n    this._isolationScope = assignedIsolationScope;\n  }\n  /**\n   * Fork a scope for the stack.\n   */\n  withScope(callback) {\n    const scope = this._pushScope();\n    let maybePromiseResult;\n    try {\n      maybePromiseResult = callback(scope);\n    } catch (e) {\n      this._popScope();\n      throw e;\n    }\n    if (isThenable(maybePromiseResult)) {\n      return chainAndCopyPromiseLike(\n        maybePromiseResult,\n        () => this._popScope(),\n        () => this._popScope()\n      );\n    }\n    this._popScope();\n    return maybePromiseResult;\n  }\n  /**\n   * Get the client of the stack.\n   */\n  getClient() {\n    return this.getStackTop().client;\n  }\n  /**\n   * Returns the scope of the top stack.\n   */\n  getScope() {\n    return this.getStackTop().scope;\n  }\n  /**\n   * Get the isolation scope for the stack.\n   */\n  getIsolationScope() {\n    return this._isolationScope;\n  }\n  /**\n   * Returns the topmost scope layer in the order domain > local > process.\n   */\n  getStackTop() {\n    return this._stack[this._stack.length - 1];\n  }\n  /**\n   * Push a scope to the stack.\n   */\n  _pushScope() {\n    const scope = this.getScope().clone();\n    this._stack.push({\n      client: this.getClient(),\n      scope\n    });\n    return scope;\n  }\n  /**\n   * Pop a scope from the stack.\n   */\n  _popScope() {\n    if (this._stack.length <= 1) return false;\n    return !!this._stack.pop();\n  }\n}\nfunction getAsyncContextStack() {\n  const registry = getMainCarrier();\n  const sentry = getSentryCarrier(registry);\n  return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());\n}\nfunction withScope(callback) {\n  return getAsyncContextStack().withScope(callback);\n}\nfunction withSetScope(scope, callback) {\n  const stack = getAsyncContextStack();\n  return stack.withScope(() => {\n    stack.getStackTop().scope = scope;\n    return callback(scope);\n  });\n}\nfunction withIsolationScope(callback) {\n  return getAsyncContextStack().withScope(() => {\n    return callback(getAsyncContextStack().getIsolationScope());\n  });\n}\nfunction getStackAsyncContextStrategy() {\n  return {\n    withIsolationScope,\n    withScope,\n    withSetScope,\n    withSetIsolationScope: (_isolationScope, callback) => {\n      return withIsolationScope(callback);\n    },\n    getCurrentScope: () => getAsyncContextStack().getScope(),\n    getIsolationScope: () => getAsyncContextStack().getIsolationScope()\n  };\n}\n\nexport { AsyncContextStack, getStackAsyncContextStrategy };\n//# sourceMappingURL=stackStrategy.js.map\n","import { getSentryCarrier, getMainCarrier } from '../carrier.js';\nimport { getStackAsyncContextStrategy } from './stackStrategy.js';\n\nfunction setAsyncContextStrategy(strategy) {\n  const registry = getMainCarrier();\n  const sentry = getSentryCarrier(registry);\n  sentry.acs = strategy;\n}\nfunction getAsyncContextStrategy(carrier) {\n  const sentry = getSentryCarrier(carrier);\n  if (sentry.acs) {\n    return sentry.acs;\n  }\n  return getStackAsyncContextStrategy();\n}\n\nexport { getAsyncContextStrategy, setAsyncContextStrategy };\n//# sourceMappingURL=index.js.map\n","import { isPrimitive } from './utils/is.js';\n\nfunction isAttributeObject(maybeObj) {\n  return typeof maybeObj === \"object\" && maybeObj != null && !Array.isArray(maybeObj) && Object.keys(maybeObj).includes(\"value\");\n}\nfunction attributeValueToTypedAttributeValue(rawValue, useFallback) {\n  const { value, unit } = isAttributeObject(rawValue) ? rawValue : { value: rawValue, unit: void 0 };\n  const attributeValue = getTypedAttributeValue(value);\n  const checkedUnit = unit && typeof unit === \"string\" ? { unit } : {};\n  if (attributeValue) {\n    return { ...attributeValue, ...checkedUnit };\n  }\n  if (!useFallback || useFallback === \"skip-undefined\" && value === void 0) {\n    return;\n  }\n  let stringValue = \"\";\n  try {\n    stringValue = JSON.stringify(value) ?? \"\";\n  } catch {\n  }\n  return {\n    value: stringValue,\n    type: \"string\",\n    ...checkedUnit\n  };\n}\nfunction serializeAttributes(attributes, fallback = false) {\n  const serializedAttributes = {};\n  for (const [key, value] of Object.entries(attributes ?? {})) {\n    const typedValue = attributeValueToTypedAttributeValue(value, fallback);\n    if (typedValue) {\n      serializedAttributes[key] = typedValue;\n    }\n  }\n  return serializedAttributes;\n}\nfunction estimateTypedAttributesSizeInBytes(attributes) {\n  if (!attributes) {\n    return 0;\n  }\n  let weight = 0;\n  for (const [key, attr] of Object.entries(attributes)) {\n    weight += key.length * 2;\n    weight += attr.type.length * 2;\n    weight += (attr.unit?.length ?? 0) * 2;\n    const val = attr.value;\n    if (Array.isArray(val)) {\n      weight += estimatePrimitiveSizeInBytes(val[0]) * val.length;\n    } else if (isPrimitive(val)) {\n      weight += estimatePrimitiveSizeInBytes(val);\n    } else {\n      weight += 100;\n    }\n  }\n  return weight;\n}\nfunction estimatePrimitiveSizeInBytes(value) {\n  if (typeof value === \"string\") {\n    return value.length * 2;\n  } else if (typeof value === \"boolean\") {\n    return 4;\n  } else if (typeof value === \"number\") {\n    return 8;\n  }\n  return 0;\n}\nfunction getTypedAttributeValue(value) {\n  if (Array.isArray(value)) {\n    return { value, type: \"array\" };\n  }\n  const primitiveType = typeof value === \"string\" ? \"string\" : typeof value === \"boolean\" ? \"boolean\" : typeof value === \"number\" && !Number.isNaN(value) ? Number.isInteger(value) ? \"integer\" : \"double\" : null;\n  if (primitiveType) {\n    return { value, type: primitiveType };\n  }\n}\n\nexport { attributeValueToTypedAttributeValue, estimateTypedAttributesSizeInBytes, isAttributeObject, serializeAttributes };\n//# sourceMappingURL=attributes.js.map\n","import { getAsyncContextStrategy } from './asyncContext/index.js';\nimport { getMainCarrier, getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\nimport { generateSpanId } from './utils/propagationContext.js';\n\nlet _externalPropagationContextProvider;\nfunction registerExternalPropagationContext(fn) {\n  _externalPropagationContextProvider = fn;\n}\nfunction getExternalPropagationContext() {\n  return _externalPropagationContextProvider?.();\n}\nfunction hasExternalPropagationContext() {\n  return _externalPropagationContextProvider !== void 0;\n}\nfunction getCurrentScope() {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  return acs.getCurrentScope();\n}\nfunction getIsolationScope() {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  return acs.getIsolationScope();\n}\nfunction getGlobalScope() {\n  return getGlobalSingleton(\"globalScope\", () => new Scope());\n}\nfunction withScope(...rest) {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (rest.length === 2) {\n    const [scope, callback] = rest;\n    if (!scope) {\n      return acs.withScope(callback);\n    }\n    return acs.withSetScope(scope, callback);\n  }\n  return acs.withScope(rest[0]);\n}\nfunction withIsolationScope(...rest) {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (rest.length === 2) {\n    const [isolationScope, callback] = rest;\n    if (!isolationScope) {\n      return acs.withIsolationScope(callback);\n    }\n    return acs.withSetIsolationScope(isolationScope, callback);\n  }\n  return acs.withIsolationScope(rest[0]);\n}\nfunction getClient() {\n  return getCurrentScope().getClient();\n}\nfunction getTraceContextFromScope(scope) {\n  const externalContext = getExternalPropagationContext();\n  if (externalContext) {\n    return { trace_id: externalContext.traceId, span_id: externalContext.spanId };\n  }\n  const propagationContext = scope.getPropagationContext();\n  const { traceId, parentSpanId, propagationSpanId } = propagationContext;\n  const traceContext = {\n    trace_id: traceId,\n    span_id: propagationSpanId || generateSpanId()\n  };\n  if (parentSpanId) {\n    traceContext.parent_span_id = parentSpanId;\n  }\n  return traceContext;\n}\n\nexport { getClient, getCurrentScope, getExternalPropagationContext, getGlobalScope, getIsolationScope, getTraceContextFromScope, hasExternalPropagationContext, registerExternalPropagationContext, withIsolationScope, withScope };\n//# sourceMappingURL=currentScopes.js.map\n","const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = \"sentry.source\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = \"sentry.sample_rate\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = \"sentry.previous_trace_sample_rate\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_OP = \"sentry.op\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = \"sentry.origin\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE = \"sentry.status.message\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = \"sentry.idle_span_finish_reason\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = \"sentry.measurement_unit\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = \"sentry.measurement_value\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_RELEASE = \"sentry.release\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT = \"sentry.environment\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME = \"sentry.segment.name\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID = \"sentry.segment.id\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME = \"sentry.sdk.name\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION = \"sentry.sdk.version\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS = \"sentry.sdk.integrations\";\nconst SEMANTIC_ATTRIBUTE_USER_ID = \"user.id\";\nconst SEMANTIC_ATTRIBUTE_USER_EMAIL = \"user.email\";\nconst SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS = \"user.ip_address\";\nconst SEMANTIC_ATTRIBUTE_USER_USERNAME = \"user.name\";\nconst SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = \"sentry.custom_span_name\";\nconst SEMANTIC_ATTRIBUTE_PROFILE_ID = \"sentry.profile_id\";\nconst SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = \"sentry.exclusive_time\";\nconst SEMANTIC_ATTRIBUTE_CACHE_HIT = \"cache.hit\";\nconst SEMANTIC_ATTRIBUTE_CACHE_KEY = \"cache.key\";\nconst SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = \"cache.item_size\";\nconst SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = \"http.request.method\";\nconst SEMANTIC_ATTRIBUTE_URL_FULL = \"url.full\";\nconst SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = \"sentry.link.type\";\nconst GEN_AI_CONVERSATION_ID_ATTRIBUTE = \"gen_ai.conversation.id\";\n\nexport { GEN_AI_CONVERSATION_ID_ATTRIBUTE, SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_KEY, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS, SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE, SEMANTIC_ATTRIBUTE_URL_FULL, SEMANTIC_ATTRIBUTE_USER_EMAIL, SEMANTIC_ATTRIBUTE_USER_ID, SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS, SEMANTIC_ATTRIBUTE_USER_USERNAME, SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE };\n//# sourceMappingURL=semanticAttributes.js.map\n","import { addNonEnumerableProperty } from '../utils/object.js';\nimport { derefWeakRef, makeWeakRef } from '../utils/weakRef.js';\n\nconst SCOPE_ON_START_SPAN_FIELD = \"_sentryScope\";\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = \"_sentryIsolationScope\";\nconst OTEL_SOURCE_INFERENCE_SPAN_FIELD = /* @__PURE__ */ Symbol.for(\"sentry.otelSourceInference\");\nconst OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD = /* @__PURE__ */ Symbol.for(\"sentry.otelSourceExplicitlySet\");\nconst TRACER_PROVIDER_SPAN_FIELD = /* @__PURE__ */ Symbol.for(\"sentry.tracerProviderSpan\");\nfunction setCapturedScopesOnSpan(span, scope, isolationScope) {\n  if (span) {\n    addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, makeWeakRef(isolationScope));\n    addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n  }\n}\nfunction getCapturedScopesOnSpan(span) {\n  const spanWithScopes = span;\n  return {\n    scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],\n    isolationScope: derefWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD])\n  };\n}\nfunction markSpanForOtelSourceInference(span) {\n  addNonEnumerableProperty(span, OTEL_SOURCE_INFERENCE_SPAN_FIELD, true);\n}\nfunction spanShouldInferOtelSource(span) {\n  return span[OTEL_SOURCE_INFERENCE_SPAN_FIELD] === true;\n}\nfunction markSpanSourceAsExplicit(span) {\n  addNonEnumerableProperty(span, OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD, true);\n}\nfunction spanSourceWasExplicitlySet(span) {\n  return span[OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD] === true;\n}\nfunction markSpanAsTracerProviderSpan(span) {\n  addNonEnumerableProperty(span, TRACER_PROVIDER_SPAN_FIELD, true);\n}\nfunction spanIsTracerProviderSpan(span) {\n  return span[TRACER_PROVIDER_SPAN_FIELD] === true;\n}\n\nexport { getCapturedScopesOnSpan, markSpanAsTracerProviderSpan, markSpanForOtelSourceInference, markSpanSourceAsExplicit, setCapturedScopesOnSpan, spanIsTracerProviderSpan, spanShouldInferOtelSource, spanSourceWasExplicitlySet };\n//# sourceMappingURL=utils.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isString } from './is.js';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = \"sentry-\";\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\nfunction baggageHeaderToDynamicSamplingContext(baggageHeader) {\n  const baggageObject = parseBaggageHeader(baggageHeader);\n  if (!baggageObject) {\n    return void 0;\n  }\n  const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n    if (key.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)) {\n      const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n      acc[nonPrefixedKey] = value;\n    }\n    return acc;\n  }, {});\n  if (Object.keys(dynamicSamplingContext).length > 0) {\n    return dynamicSamplingContext;\n  } else {\n    return void 0;\n  }\n}\nfunction dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {\n  if (!dynamicSamplingContext) {\n    return void 0;\n  }\n  const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n    (acc, [dscKey, dscValue]) => {\n      if (dscValue) {\n        acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n      }\n      return acc;\n    },\n    {}\n  );\n  return objectToBaggageHeader(sentryPrefixedDSC);\n}\nfunction parseBaggageHeader(baggageHeader) {\n  if (!baggageHeader || !isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n    return void 0;\n  }\n  if (Array.isArray(baggageHeader)) {\n    return baggageHeader.reduce((acc, curr) => {\n      const currBaggageObject = baggageHeaderToObject(curr);\n      Object.entries(currBaggageObject).forEach(([key, value]) => {\n        acc[key] = value;\n      });\n      return acc;\n    }, {});\n  }\n  return baggageHeaderToObject(baggageHeader);\n}\nfunction baggageHeaderToObject(baggageHeader) {\n  return baggageHeader.split(\",\").map((baggageEntry) => {\n    const eqIdx = baggageEntry.indexOf(\"=\");\n    if (eqIdx === -1) {\n      return [];\n    }\n    const key = baggageEntry.slice(0, eqIdx);\n    const value = baggageEntry.slice(eqIdx + 1);\n    return [key, value].map((keyOrValue) => {\n      try {\n        return decodeURIComponent(keyOrValue.trim());\n      } catch {\n        return;\n      }\n    });\n  }).reduce((acc, [key, value]) => {\n    if (key && value) {\n      acc[key] = value;\n    }\n    return acc;\n  }, {});\n}\nfunction objectToBaggageHeader(object) {\n  if (Object.keys(object).length === 0) {\n    return void 0;\n  }\n  return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n    const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n    const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n    if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n      DEBUG_BUILD && debug.warn(\n        `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`\n      );\n      return baggageHeader;\n    } else {\n      return newBaggageHeader;\n    }\n  }, \"\");\n}\nfunction mergeBaggageHeaders(existing, incoming) {\n  if (!existing) {\n    return incoming;\n  }\n  const existingEntries = parseBaggageHeader(existing);\n  const incomingEntries = parseBaggageHeader(incoming);\n  if (!incomingEntries) {\n    return existing;\n  }\n  const merged = {};\n  let hasNewSentryEntries = false;\n  const newSentryEntries = {};\n  const newNonSentryEntries = {};\n  for (const [key, value] of Object.entries(incomingEntries)) {\n    if (key.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)) {\n      newSentryEntries[key] = value;\n      hasNewSentryEntries = true;\n    } else {\n      newNonSentryEntries[key] = value;\n    }\n  }\n  if (existingEntries) {\n    for (const [key, value] of Object.entries(existingEntries)) {\n      if (!hasNewSentryEntries || !key.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)) {\n        merged[key] = value;\n      }\n    }\n  }\n  if (hasNewSentryEntries) {\n    Object.assign(merged, newSentryEntries);\n  }\n  for (const [key, value] of Object.entries(newNonSentryEntries)) {\n    merged[key] ?? (merged[key] = value);\n  }\n  return objectToBaggageHeader(merged);\n}\n\nexport { MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, mergeBaggageHeaders, objectToBaggageHeader, parseBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { consoleSandbox, debug } from './debug-logger.js';\n\nconst ORG_ID_REGEX = /^o(\\d+)\\./;\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)((?:\\[[:.%\\w]+\\]|[\\w.-]+))(?::(\\d+))?\\/(.+)/;\nfunction isValidProtocol(protocol) {\n  return protocol === \"http\" || protocol === \"https\";\n}\nfunction dsnToString(dsn, withPassword = false) {\n  const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n  return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : \"\"}@${host}${port ? `:${port}` : \"\"}/${path ? `${path}/` : path}${projectId}`;\n}\nfunction dsnFromString(str) {\n  const match = DSN_REGEX.exec(str);\n  if (!match) {\n    consoleSandbox(() => {\n      console.error(`Invalid Sentry Dsn: ${str}`);\n    });\n    return void 0;\n  }\n  const [protocol, publicKey, pass = \"\", host = \"\", port = \"\", lastPath = \"\"] = match.slice(1);\n  let path = \"\";\n  let projectId = lastPath;\n  const split = projectId.split(\"/\");\n  if (split.length > 1) {\n    path = split.slice(0, -1).join(\"/\");\n    projectId = split.pop();\n  }\n  if (projectId) {\n    const projectMatch = projectId.match(/^\\d+/);\n    if (projectMatch) {\n      projectId = projectMatch[0];\n    }\n  }\n  return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });\n}\nfunction dsnFromComponents(components) {\n  return {\n    protocol: components.protocol,\n    publicKey: components.publicKey || \"\",\n    pass: components.pass || \"\",\n    host: components.host,\n    port: components.port || \"\",\n    path: components.path || \"\",\n    projectId: components.projectId\n  };\n}\nfunction validateDsn(dsn) {\n  if (!DEBUG_BUILD) {\n    return true;\n  }\n  const { port, projectId, protocol } = dsn;\n  const requiredComponents = [\"protocol\", \"publicKey\", \"host\", \"projectId\"];\n  const hasMissingRequiredComponent = requiredComponents.find((component) => {\n    if (!dsn[component]) {\n      debug.error(`Invalid Sentry Dsn: ${component} missing`);\n      return true;\n    }\n    return false;\n  });\n  if (hasMissingRequiredComponent) {\n    return false;\n  }\n  if (!projectId.match(/^\\d+$/)) {\n    debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n    return false;\n  }\n  if (!isValidProtocol(protocol)) {\n    debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n    return false;\n  }\n  if (port && isNaN(parseInt(port, 10))) {\n    debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n    return false;\n  }\n  return true;\n}\nfunction extractOrgIdFromDsnHost(host) {\n  const match = host.match(ORG_ID_REGEX);\n  return match?.[1];\n}\nfunction extractOrgIdFromClient(client) {\n  const options = client.getOptions();\n  const { host } = client.getDsn() || {};\n  let org_id;\n  if (options.orgId) {\n    org_id = String(options.orgId);\n  } else if (host) {\n    org_id = extractOrgIdFromDsnHost(host);\n  }\n  return org_id;\n}\nfunction makeDsn(from) {\n  const components = typeof from === \"string\" ? dsnFromString(from) : dsnFromComponents(from);\n  if (!components || !validateDsn(components)) {\n    return void 0;\n  }\n  return components;\n}\n\nexport { dsnFromString, dsnToString, extractOrgIdFromClient, extractOrgIdFromDsnHost, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","function parseSampleRate(sampleRate) {\n  if (typeof sampleRate === \"boolean\") {\n    return Number(sampleRate);\n  }\n  const rate = typeof sampleRate === \"string\" ? parseFloat(sampleRate) : sampleRate;\n  if (typeof rate !== \"number\" || isNaN(rate) || rate < 0 || rate > 1) {\n    return void 0;\n  }\n  return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { serializeAttributes } from '../attributes.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getCurrentScope } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE } from '../semanticAttributes.js';\nimport { SPAN_STATUS_UNSET, SPAN_STATUS_OK } from '../tracing/spanstatus.js';\nimport { getCapturedScopesOnSpan } from '../tracing/utils.js';\nimport { addNonEnumerableProperty } from './object.js';\nimport { generateSpanId } from './propagationContext.js';\nimport { timestampInSeconds } from './time.js';\nimport { generateSentryTraceHeader, generateTraceparentHeader } from './tracing.js';\nimport { consoleSandbox } from './debug-logger.js';\nimport { _getSpanForScope } from './spanOnScope.js';\n\nconst TRACE_FLAG_NONE = 0;\nconst TRACE_FLAG_SAMPLED = 1;\nlet hasShownSpanDropWarning = false;\nfunction spanToTransactionTraceContext(span) {\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  const { data, op, parent_span_id, status, origin, links } = spanToJSON(span);\n  return {\n    parent_span_id,\n    span_id,\n    trace_id,\n    data,\n    op,\n    status,\n    origin,\n    links\n  };\n}\nfunction spanToTraceContext(span) {\n  const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n  const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n  const scope = getCapturedScopesOnSpan(span).scope;\n  const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;\n  return {\n    parent_span_id,\n    span_id,\n    trace_id\n  };\n}\nfunction spanToTraceHeader(span) {\n  const { traceId, spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  return generateSentryTraceHeader(traceId, spanId, sampled);\n}\nfunction spanToTraceparentHeader(span) {\n  const { traceId, spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  return generateTraceparentHeader(traceId, spanId, sampled);\n}\nfunction convertSpanLinksForEnvelope(links) {\n  if (links && links.length > 0) {\n    return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({\n      span_id: spanId,\n      trace_id: traceId,\n      sampled: traceFlags === TRACE_FLAG_SAMPLED,\n      attributes,\n      ...restContext\n    }));\n  } else {\n    return void 0;\n  }\n}\nfunction getStreamedSpanLinks(links) {\n  if (links?.length) {\n    return links.map(({ context: { spanId, traceId, traceFlags }, attributes }) => ({\n      span_id: spanId,\n      trace_id: traceId,\n      sampled: traceFlags === TRACE_FLAG_SAMPLED,\n      attributes\n    }));\n  } else {\n    return void 0;\n  }\n}\nfunction spanTimeInputToSeconds(input) {\n  if (typeof input === \"number\") {\n    return ensureTimestampInSeconds(input);\n  }\n  if (Array.isArray(input)) {\n    return input[0] + input[1] / 1e9;\n  }\n  if (input instanceof Date) {\n    return ensureTimestampInSeconds(input.getTime());\n  }\n  return timestampInSeconds();\n}\nfunction ensureTimestampInSeconds(timestamp) {\n  const isMs = timestamp > 9999999999;\n  return isMs ? timestamp / 1e3 : timestamp;\n}\nfunction spanToJSON(span) {\n  if (spanIsSentrySpan(span)) {\n    return span.getSpanJSON();\n  }\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n    const { attributes, startTime, name, endTime, status, links } = span;\n    return {\n      span_id,\n      trace_id,\n      data: attributes,\n      description: name,\n      parent_span_id: getOtelParentSpanId(span),\n      start_timestamp: spanTimeInputToSeconds(startTime),\n      // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n      timestamp: spanTimeInputToSeconds(endTime) || void 0,\n      status: getStatusMessage(status),\n      op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n      origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],\n      links: convertSpanLinksForEnvelope(links)\n    };\n  }\n  return {\n    span_id,\n    trace_id,\n    start_timestamp: 0,\n    data: {}\n  };\n}\nfunction spanToStreamedSpanJSON(span) {\n  if (spanIsSentrySpan(span)) {\n    return span.getStreamedSpanJSON();\n  }\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n    const { attributes, startTime, name, endTime, status, links } = span;\n    return {\n      name,\n      span_id,\n      trace_id,\n      parent_span_id: getOtelParentSpanId(span),\n      start_timestamp: spanTimeInputToSeconds(startTime),\n      end_timestamp: spanTimeInputToSeconds(endTime),\n      is_segment: span === INTERNAL_getSegmentSpan(span),\n      status: getSimpleStatus(status),\n      attributes: addStatusMessageAttribute(attributes, status),\n      links: getStreamedSpanLinks(links)\n    };\n  }\n  return {\n    span_id,\n    trace_id,\n    start_timestamp: 0,\n    name: \"\",\n    end_timestamp: 0,\n    status: \"ok\",\n    is_segment: span === INTERNAL_getSegmentSpan(span)\n  };\n}\nfunction getOtelParentSpanId(span) {\n  return \"parentSpanId\" in span ? span.parentSpanId : \"parentSpanContext\" in span ? span.parentSpanContext?.spanId : void 0;\n}\nfunction streamedSpanJsonToSerializedSpan(spanJson) {\n  return {\n    ...spanJson,\n    attributes: serializeAttributes(spanJson.attributes),\n    links: spanJson.links?.map((link) => ({\n      ...link,\n      attributes: serializeAttributes(link.attributes)\n    }))\n  };\n}\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span) {\n  const castSpan = span;\n  return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\nfunction spanIsSentrySpan(span) {\n  return typeof span.getSpanJSON === \"function\";\n}\nfunction spanIsSampled(span) {\n  const { traceFlags } = span.spanContext();\n  return traceFlags === TRACE_FLAG_SAMPLED;\n}\nfunction getStatusMessage(status) {\n  if (!status || status.code === SPAN_STATUS_UNSET) {\n    return void 0;\n  }\n  if (status.code === SPAN_STATUS_OK) {\n    return \"ok\";\n  }\n  return status.message || \"internal_error\";\n}\nfunction getSimpleStatus(status) {\n  return !status || status.code === SPAN_STATUS_OK || status.code === SPAN_STATUS_UNSET || status.message === \"cancelled\" ? \"ok\" : \"error\";\n}\nfunction addStatusMessageAttribute(attributes, status) {\n  const statusMessage = getSimpleStatus(status) === \"error\" ? status?.message : void 0;\n  return {\n    ...statusMessage && { [SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE]: statusMessage },\n    ...attributes\n  };\n}\nconst CHILD_SPANS_FIELD = \"_sentryChildSpans\";\nconst ROOT_SPAN_FIELD = \"_sentryRootSpan\";\nfunction addChildSpanToSpan(span, childSpan) {\n  const rootSpan = span[ROOT_SPAN_FIELD] || span;\n  addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan);\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].add(childSpan);\n  } else {\n    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan]));\n  }\n}\nfunction removeChildSpanFromSpan(span, childSpan) {\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].delete(childSpan);\n  }\n}\nfunction getSpanDescendants(span) {\n  const resultSet = /* @__PURE__ */ new Set();\n  function addSpanChildren(span2) {\n    if (resultSet.has(span2)) {\n      return;\n    } else if (spanIsSampled(span2)) {\n      resultSet.add(span2);\n      const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : [];\n      for (const childSpan of childSpans) {\n        addSpanChildren(childSpan);\n      }\n    }\n  }\n  addSpanChildren(span);\n  return Array.from(resultSet);\n}\nconst getRootSpan = INTERNAL_getSegmentSpan;\nfunction INTERNAL_getSegmentSpan(span) {\n  return span[ROOT_SPAN_FIELD] || span;\n}\nfunction getActiveSpan() {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.getActiveSpan) {\n    return acs.getActiveSpan();\n  }\n  return _getSpanForScope(getCurrentScope());\n}\nfunction showSpanDropWarning() {\n  if (!hasShownSpanDropWarning) {\n    consoleSandbox(() => {\n      console.warn(\n        \"[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.\"\n      );\n    });\n    hasShownSpanDropWarning = true;\n  }\n}\nfunction updateSpanName(span, name) {\n  span.updateName(name);\n  span.setAttributes({\n    [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: \"custom\",\n    [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name\n  });\n}\n\nexport { INTERNAL_getSegmentSpan, TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, addChildSpanToSpan, addStatusMessageAttribute, convertSpanLinksForEnvelope, getActiveSpan, getRootSpan, getSimpleStatus, getSpanDescendants, getStatusMessage, getStreamedSpanLinks, removeChildSpanFromSpan, showSpanDropWarning, spanIsSampled, spanIsSentrySpan, spanTimeInputToSeconds, spanToJSON, spanToStreamedSpanJSON, spanToTraceContext, spanToTraceHeader, spanToTraceparentHeader, spanToTransactionTraceContext, streamedSpanJsonToSerializedSpan, updateSpanName };\n//# sourceMappingURL=spanUtils.js.map\n","import { getClient } from '../currentScopes.js';\n\nfunction hasSpansEnabled(maybeOptions) {\n  if (typeof __SENTRY_TRACING__ === \"boolean\" && !__SENTRY_TRACING__) {\n    return false;\n  }\n  const options = maybeOptions || getClient()?.getOptions();\n  return !!options && // Note: This check is `!= null`, meaning \"nullish\". `0` is not \"nullish\", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)\n  (options.tracesSampleRate != null || !!options.tracesSampler);\n}\n\nexport { hasSpansEnabled };\n//# sourceMappingURL=hasSpansEnabled.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isMatchingPattern } from './string.js';\n\nfunction logIgnoredSpan(droppedSpan) {\n  debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \\`ignoreSpans\\`.`);\n}\nfunction shouldIgnoreSpan(span, ignoreSpans) {\n  if (!ignoreSpans?.length) {\n    return false;\n  }\n  for (const pattern of ignoreSpans) {\n    if (isStringOrRegExp(pattern)) {\n      if (span.description && isMatchingPattern(span.description, pattern)) {\n        DEBUG_BUILD && logIgnoredSpan(span);\n        return true;\n      }\n      continue;\n    }\n    const hasAttributes = !!pattern.attributes && Object.keys(pattern.attributes).length > 0;\n    if (!pattern.name && !pattern.op && !hasAttributes) {\n      continue;\n    }\n    const nameMatches = pattern.name ? span.description && isMatchingPattern(span.description, pattern.name) : true;\n    const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true;\n    const attrsMatch = pattern.attributes ? Object.entries(pattern.attributes).every(\n      ([key, valuePattern]) => _matchesAttributeValue(span.attributes?.[key], valuePattern)\n    ) : true;\n    if (nameMatches && opMatches && attrsMatch) {\n      DEBUG_BUILD && logIgnoredSpan(span);\n      return true;\n    }\n  }\n  return false;\n}\nfunction _matchesAttributeValue(actual, pat) {\n  if (typeof actual === \"string\" && (typeof pat === \"string\" || pat instanceof RegExp)) {\n    return isMatchingPattern(actual, pat);\n  }\n  if (Array.isArray(actual) && Array.isArray(pat)) {\n    return actual.length === pat.length && actual.every((v, i) => v === pat[i]);\n  }\n  return actual === pat;\n}\nfunction reparentChildSpans(spans, dropSpan) {\n  const droppedSpanParentId = dropSpan.parent_span_id;\n  const droppedSpanId = dropSpan.span_id;\n  if (!droppedSpanParentId) {\n    return;\n  }\n  for (const span of spans) {\n    if (span.parent_span_id === droppedSpanId) {\n      span.parent_span_id = droppedSpanParentId;\n    }\n  }\n}\nfunction isStringOrRegExp(value) {\n  return typeof value === \"string\" || value instanceof RegExp;\n}\n\nexport { reparentChildSpans, shouldIgnoreSpan };\n//# sourceMappingURL=should-ignore-span.js.map\n","import { addNonEnumerableProperty } from '../utils/object.js';\nimport { generateTraceId, generateSpanId } from '../utils/propagationContext.js';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils.js';\n\nconst NON_RECORDING_SPAN_FIELD = /* @__PURE__ */ Symbol.for(\"sentry.nonRecordingSpan\");\nclass SentryNonRecordingSpan {\n  constructor(spanContext = {}) {\n    this._traceId = spanContext.traceId || generateTraceId();\n    this._spanId = spanContext.spanId || generateSpanId();\n    this.dropReason = spanContext.dropReason;\n    addNonEnumerableProperty(this, NON_RECORDING_SPAN_FIELD, true);\n  }\n  /** @inheritdoc */\n  spanContext() {\n    return {\n      spanId: this._spanId,\n      traceId: this._traceId,\n      traceFlags: TRACE_FLAG_NONE\n    };\n  }\n  /** @inheritdoc */\n  end(_timestamp) {\n  }\n  /** @inheritdoc */\n  setAttribute(_key, _value) {\n    return this;\n  }\n  /** @inheritdoc */\n  setAttributes(_values) {\n    return this;\n  }\n  /** @inheritdoc */\n  setStatus(_status) {\n    return this;\n  }\n  /** @inheritdoc */\n  updateName(_name) {\n    return this;\n  }\n  /** @inheritdoc */\n  isRecording() {\n    return false;\n  }\n  /** @inheritdoc */\n  addEvent(_name, _attributesOrStartTime, _startTime) {\n    return this;\n  }\n  /** @inheritDoc */\n  addLink(_link) {\n    return this;\n  }\n  /** @inheritDoc */\n  addLinks(_links) {\n    return this;\n  }\n  /**\n   * This should generally not be used,\n   * but we need it for being compliant with the OTEL Span interface.\n   *\n   * @hidden\n   * @internal\n   */\n  recordException(_exception, _time) {\n  }\n}\nfunction spanIsNonRecordingSpan(span) {\n  return !!span && span[NON_RECORDING_SPAN_FIELD] === true;\n}\n\nexport { SentryNonRecordingSpan, spanIsNonRecordingSpan };\n//# sourceMappingURL=sentryNonRecordingSpan.js.map\n","const DEFAULT_ENVIRONMENT = \"production\";\nconst DEV_ENVIRONMENT = \"development\";\n\nexport { DEFAULT_ENVIRONMENT, DEV_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getClient } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage.js';\nimport { extractOrgIdFromClient } from '../utils/dsn.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { addNonEnumerableProperty } from '../utils/object.js';\nimport { getRootSpan, spanToJSON, spanIsSampled } from '../utils/spanUtils.js';\nimport { spanIsNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\nconst FROZEN_DSC_FIELD = \"_frozenDsc\";\nfunction freezeDscOnSpan(span, dsc) {\n  const spanWithMaybeDsc = span;\n  addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\nfunction getDynamicSamplingContextFromClient(trace_id, client) {\n  const options = client.getOptions();\n  const { publicKey: public_key } = client.getDsn() || {};\n  const dsc = {\n    environment: options.environment || DEFAULT_ENVIRONMENT,\n    release: options.release,\n    public_key,\n    trace_id,\n    org_id: extractOrgIdFromClient(client)\n  };\n  client.emit(\"createDsc\", dsc);\n  return dsc;\n}\nfunction getDynamicSamplingContextFromScope(client, scope) {\n  const propagationContext = scope.getPropagationContext();\n  return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\nfunction getDynamicSamplingContextFromSpan(span) {\n  const client = getClient();\n  if (!client) {\n    return {};\n  }\n  const rootSpan = getRootSpan(span);\n  const rootSpanJson = spanToJSON(rootSpan);\n  const rootSpanAttributes = rootSpanJson.data;\n  const traceState = rootSpan.spanContext().traceState;\n  const rootSpanSampleRate = traceState?.get(\"sentry.sample_rate\") ?? rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n  function applyLocalSampleRateToDsc(dsc2) {\n    if (typeof rootSpanSampleRate === \"number\" || typeof rootSpanSampleRate === \"string\") {\n      dsc2.sample_rate = `${rootSpanSampleRate}`;\n    }\n    return dsc2;\n  }\n  const frozenDsc = rootSpan[FROZEN_DSC_FIELD];\n  if (frozenDsc) {\n    return applyLocalSampleRateToDsc(frozenDsc);\n  }\n  const isNonRecordingRoot = spanIsNonRecordingSpan(rootSpan);\n  const isIgnoredRoot = isNonRecordingRoot && rootSpan.dropReason === \"ignored\";\n  if (isNonRecordingRoot && (!hasSpansEnabled(client.getOptions()) || isIgnoredRoot)) {\n    const capturedScope = getCapturedScopesOnSpan(rootSpan).scope;\n    if (capturedScope) {\n      const dsc2 = { ...getDynamicSamplingContextFromScope(client, capturedScope) };\n      if (isIgnoredRoot) {\n        dsc2.sampled = \"false\";\n      }\n      return applyLocalSampleRateToDsc(dsc2);\n    }\n  }\n  const traceStateDsc = traceState?.get(\"sentry.dsc\");\n  const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n  if (dscOnTraceState) {\n    return applyLocalSampleRateToDsc(dscOnTraceState);\n  }\n  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n  const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ?? rootSpanAttributes[\"sentry.segment.name.source\"];\n  const name = rootSpanJson.description;\n  if (source !== \"url\" && name) {\n    dsc.transaction = name;\n  }\n  if (hasSpansEnabled()) {\n    dsc.sampled = String(spanIsSampled(rootSpan));\n    dsc.sample_rand = // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n    // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n    traceState?.get(\"sentry.sample_rand\") ?? // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n    getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n  }\n  applyLocalSampleRateToDsc(dsc);\n  client.emit(\"createDsc\", dsc, rootSpan);\n  return dsc;\n}\nfunction spanToBaggageHeader(span) {\n  const dsc = getDynamicSamplingContextFromSpan(span);\n  return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n\nexport { freezeDscOnSpan, getDynamicSamplingContextFromClient, getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan, spanToBaggageHeader };\n//# sourceMappingURL=dynamicSamplingContext.js.map\n","import { addNonEnumerableProperty } from '../../utils/object.js';\n\nfunction withStreamedSpan(callback) {\n  addNonEnumerableProperty(callback, \"_streamed\", true);\n  return callback;\n}\nfunction isStreamedBeforeSendSpanCallback(callback) {\n  return !!callback && typeof callback === \"function\" && \"_streamed\" in callback && !!callback._streamed;\n}\n\nexport { isStreamedBeforeSendSpanCallback, withStreamedSpan };\n//# sourceMappingURL=beforeSendSpan.js.map\n","import { getSentryCarrier } from '../carrier.js';\nimport { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { safeDateNow } from './randomSafeContext.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nfunction createEnvelope(headers, items = []) {\n  return [headers, items];\n}\nfunction addItemToEnvelope(envelope, newItem) {\n  const [headers, items] = envelope;\n  return [headers, [...items, newItem]];\n}\nfunction forEachEnvelopeItem(envelope, callback) {\n  const envelopeItems = envelope[1];\n  for (const envelopeItem of envelopeItems) {\n    const envelopeItemType = envelopeItem[0].type;\n    const result = callback(envelopeItem, envelopeItemType);\n    if (result) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction envelopeContainsItemType(envelope, types) {\n  return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\nfunction encodeUTF8(input) {\n  const carrier = getSentryCarrier(GLOBAL_OBJ);\n  return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\nfunction decodeUTF8(input) {\n  const carrier = getSentryCarrier(GLOBAL_OBJ);\n  return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\nfunction serializeEnvelope(envelope) {\n  const [envHeaders, items] = envelope;\n  let parts = JSON.stringify(envHeaders);\n  function append(next) {\n    if (typeof parts === \"string\") {\n      parts = typeof next === \"string\" ? parts + next : [encodeUTF8(parts), next];\n    } else {\n      parts.push(typeof next === \"string\" ? encodeUTF8(next) : next);\n    }\n  }\n  for (const item of items) {\n    const [itemHeaders, payload] = item;\n    append(`\n${JSON.stringify(itemHeaders)}\n`);\n    if (typeof payload === \"string\" || payload instanceof Uint8Array) {\n      append(payload);\n    } else {\n      let stringifiedPayload;\n      try {\n        stringifiedPayload = JSON.stringify(payload);\n      } catch {\n        stringifiedPayload = JSON.stringify(normalize(payload));\n      }\n      append(stringifiedPayload);\n    }\n  }\n  return typeof parts === \"string\" ? parts : concatBuffers(parts);\n}\nfunction concatBuffers(buffers) {\n  const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n  const merged = new Uint8Array(totalLength);\n  let offset = 0;\n  for (const buffer of buffers) {\n    merged.set(buffer, offset);\n    offset += buffer.length;\n  }\n  return merged;\n}\nfunction parseEnvelope(env) {\n  let buffer = typeof env === \"string\" ? encodeUTF8(env) : env;\n  function readBinary(length) {\n    const bin = buffer.subarray(0, length);\n    buffer = buffer.subarray(length + 1);\n    return bin;\n  }\n  function readJson() {\n    let i = buffer.indexOf(10);\n    if (i < 0) {\n      i = buffer.length;\n    }\n    return JSON.parse(decodeUTF8(readBinary(i)));\n  }\n  const envelopeHeader = readJson();\n  const items = [];\n  while (buffer.length) {\n    const itemHeader = readJson();\n    const binaryLength = typeof itemHeader.length === \"number\" ? itemHeader.length : void 0;\n    items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n  }\n  return [envelopeHeader, items];\n}\nfunction createSpanEnvelopeItem(spanJson) {\n  const spanHeaders = {\n    type: \"span\"\n  };\n  return [spanHeaders, spanJson];\n}\nfunction createAttachmentEnvelopeItem(attachment) {\n  const buffer = typeof attachment.data === \"string\" ? encodeUTF8(attachment.data) : attachment.data;\n  return [\n    {\n      type: \"attachment\",\n      length: buffer.length,\n      filename: attachment.filename,\n      content_type: attachment.contentType,\n      attachment_type: attachment.attachmentType\n    },\n    buffer\n  ];\n}\nconst DATA_CATEGORY_OVERRIDES = {\n  sessions: \"session\",\n  event: \"error\",\n  client_report: \"internal\",\n  user_report: \"default\",\n  profile_chunk: \"profile\",\n  replay_event: \"replay\",\n  replay_recording: \"replay\",\n  check_in: \"monitor\",\n  raw_security: \"security\",\n  log: \"log_item\",\n  trace_metric: \"metric\"\n};\nfunction _isOverriddenType(type) {\n  return type in DATA_CATEGORY_OVERRIDES;\n}\nfunction envelopeItemTypeToDataCategory(type) {\n  return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type;\n}\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n  if (!metadataOrEvent?.sdk) {\n    return;\n  }\n  const { name, version } = metadataOrEvent.sdk;\n  return { name, version };\n}\nfunction createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {\n  const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n  return {\n    event_id: event.event_id,\n    sent_at: new Date(safeDateNow()).toISOString(),\n    ...sdkInfo && { sdk: sdkInfo },\n    ...!!tunnel && dsn && { dsn: dsnToString(dsn) },\n    ...dynamicSamplingContext && {\n      trace: dynamicSamplingContext\n    }\n  };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { isStreamedBeforeSendSpanCallback } from './tracing/spans/beforeSendSpan.js';\nimport { dsnToString } from './utils/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEventEnvelopeHeaders, createEnvelope, createSpanEnvelopeItem } from './utils/envelope.js';\nimport { safeDateNow } from './utils/randomSafeContext.js';\nimport { shouldIgnoreSpan } from './utils/should-ignore-span.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\nfunction _enhanceEventWithSdkInfo(event, newSdkInfo) {\n  if (!newSdkInfo) {\n    return event;\n  }\n  const eventSdkInfo = event.sdk || {};\n  event.sdk = {\n    ...eventSdkInfo,\n    name: eventSdkInfo.name || newSdkInfo.name,\n    version: eventSdkInfo.version || newSdkInfo.version,\n    integrations: [...event.sdk?.integrations || [], ...newSdkInfo.integrations || []],\n    packages: [...event.sdk?.packages || [], ...newSdkInfo.packages || []],\n    settings: event.sdk?.settings || newSdkInfo.settings ? {\n      ...event.sdk?.settings,\n      ...newSdkInfo.settings\n    } : void 0\n  };\n  return event;\n}\nfunction createSessionEnvelope(session, dsn, metadata, tunnel) {\n  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n  const envelopeHeaders = {\n    sent_at: new Date(safeDateNow()).toISOString(),\n    ...sdkInfo && { sdk: sdkInfo },\n    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }\n  };\n  const envelopeItem = \"aggregates\" in session ? [{ type: \"sessions\" }, session] : [{ type: \"session\" }, session.toJSON()];\n  return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\nfunction createEventEnvelope(event, dsn, metadata, tunnel) {\n  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n  const eventType = event.type && event.type !== \"replay_event\" ? event.type : \"event\";\n  _enhanceEventWithSdkInfo(event, metadata?.sdk);\n  const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n  delete event.sdkProcessingMetadata;\n  const eventItem = [{ type: eventType }, event];\n  return createEnvelope(envelopeHeaders, [eventItem]);\n}\nfunction createSpanEnvelope(spans, client) {\n  function dscHasRequiredProps(dsc2) {\n    return !!dsc2.trace_id && !!dsc2.public_key;\n  }\n  const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n  const dsn = client?.getDsn();\n  const tunnel = client?.getOptions().tunnel;\n  const headers = {\n    sent_at: new Date(safeDateNow()).toISOString(),\n    ...dscHasRequiredProps(dsc) && { trace: dsc },\n    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }\n  };\n  const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};\n  const filteredSpans = ignoreSpans?.length ? spans.filter((span) => {\n    const json = spanToJSON(span);\n    return !shouldIgnoreSpan({ description: json.description, op: json.op, attributes: json.data }, ignoreSpans);\n  }) : spans;\n  const droppedSpans = spans.length - filteredSpans.length;\n  if (droppedSpans) {\n    client?.recordDroppedEvent(\"before_send\", \"span\", droppedSpans);\n  }\n  const convertToSpanJSON = beforeSendSpan ? (span) => {\n    const spanJson = spanToJSON(span);\n    const processedSpan = !isStreamedBeforeSendSpanCallback(beforeSendSpan) ? beforeSendSpan(spanJson) : spanJson;\n    if (!processedSpan) {\n      showSpanDropWarning();\n      return spanJson;\n    }\n    return processedSpan;\n  } : spanToJSON;\n  const items = [];\n  for (const span of filteredSpans) {\n    const spanJson = convertToSpanJSON(span);\n    if (spanJson) {\n      items.push(createSpanEnvelopeItem(spanJson));\n    }\n  }\n  return createEnvelope(headers, items);\n}\n\nexport { _enhanceEventWithSdkInfo, createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { spanToJSON, getRootSpan, spanIsSampled } from '../utils/spanUtils.js';\n\nfunction logSpanStart(span) {\n  if (!DEBUG_BUILD) return;\n  const { description = \"< unknown name >\", op = \"< unknown op >\", parent_span_id: parentSpanId } = spanToJSON(span);\n  const { spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  const rootSpan = getRootSpan(span);\n  const isRootSpan = rootSpan === span;\n  const header = `[Tracing] Starting ${sampled ? \"sampled\" : \"unsampled\"} ${isRootSpan ? \"root \" : \"\"}span`;\n  const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];\n  if (parentSpanId) {\n    infoParts.push(`parent ID: ${parentSpanId}`);\n  }\n  if (!isRootSpan) {\n    const { op: op2, description: description2 } = spanToJSON(rootSpan);\n    infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);\n    if (op2) {\n      infoParts.push(`root op: ${op2}`);\n    }\n    if (description2) {\n      infoParts.push(`root description: ${description2}`);\n    }\n  }\n  debug.log(`${header}\n  ${infoParts.join(\"\\n  \")}`);\n}\nfunction logSpanEnd(span) {\n  if (!DEBUG_BUILD) return;\n  const { description = \"< unknown name >\", op = \"< unknown op >\" } = spanToJSON(span);\n  const { spanId } = span.spanContext();\n  const rootSpan = getRootSpan(span);\n  const isRootSpan = rootSpan === span;\n  const msg = `[Tracing] Finishing \"${op}\" ${isRootSpan ? \"root \" : \"\"}span \"${description}\" with ID ${spanId}`;\n  debug.log(msg);\n}\n\nexport { logSpanEnd, logSpanStart };\n//# sourceMappingURL=logSpans.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getRootSpan, getActiveSpan } from '../utils/spanUtils.js';\n\nfunction setMeasurement(name, value, unit, activeSpan = getActiveSpan()) {\n  const rootSpan = activeSpan && getRootSpan(activeSpan);\n  if (rootSpan) {\n    DEBUG_BUILD && debug.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);\n    rootSpan.addEvent(name, {\n      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,\n      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit\n    });\n  }\n}\nfunction timedEventsToMeasurements(events) {\n  if (!events || events.length === 0) {\n    return void 0;\n  }\n  const measurements = {};\n  events.forEach((event) => {\n    const attributes = event.attributes || {};\n    const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT];\n    const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];\n    if (typeof unit === \"string\" && typeof value === \"number\") {\n      measurements[event.name] = { value, unit };\n    }\n  });\n  return measurements;\n}\n\nexport { setMeasurement, timedEventsToMeasurements };\n//# sourceMappingURL=measurement.js.map\n","import { getSentryCarrier, getMainCarrier } from '../carrier.js';\n\nfunction setSegmentSpanCaptureStrategy(strategy) {\n  getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy = strategy;\n}\nfunction getSegmentSpanCaptureStrategy() {\n  return getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy;\n}\n\nexport { getSegmentSpanCaptureStrategy, setSegmentSpanCaptureStrategy };\n//# sourceMappingURL=segmentSpanCaptureStrategy.js.map\n","function hasSpanStreamingEnabled(client) {\n  return client.getOptions().traceLifecycle === \"stream\";\n}\n\nexport { hasSpanStreamingEnabled };\n//# sourceMappingURL=hasSpanStreamingEnabled.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { createSpanEnvelope } from '../envelope.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { generateTraceId, generateSpanId } from '../utils/propagationContext.js';\nimport { TRACE_FLAG_SAMPLED, TRACE_FLAG_NONE, spanTimeInputToSeconds, convertSpanLinksForEnvelope, getRootSpan, getStatusMessage, getStreamedSpanLinks, addStatusMessageAttribute, getSimpleStatus, spanToJSON, getSpanDescendants, spanToTransactionTraceContext } from '../utils/spanUtils.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext.js';\nimport { logSpanEnd } from './logSpans.js';\nimport { timedEventsToMeasurements } from './measurement.js';\nimport { getSegmentSpanCaptureStrategy } from './segmentSpanCaptureStrategy.js';\nimport { hasSpanStreamingEnabled } from './spans/hasSpanStreamingEnabled.js';\nimport { spanShouldInferOtelSource, markSpanSourceAsExplicit, spanIsTracerProviderSpan, getCapturedScopesOnSpan } from './utils.js';\n\nconst MAX_SPAN_COUNT = 1e3;\nclass SentrySpan {\n  /**\n   * You should never call the constructor manually, always use `Sentry.startSpan()`\n   * or other span methods.\n   * @internal\n   * @hideconstructor\n   * @hidden\n   */\n  constructor(spanContext = {}) {\n    this._traceId = spanContext.traceId || generateTraceId();\n    this._spanId = spanContext.spanId || generateSpanId();\n    this._startTime = spanContext.startTimestamp || timestampInSeconds();\n    this._links = spanContext.links;\n    this._attributes = {};\n    this.setAttributes({\n      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: \"manual\",\n      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n      ...spanContext.attributes\n    });\n    this._name = spanContext.name;\n    if (spanContext.parentSpanId) {\n      this._parentSpanId = spanContext.parentSpanId;\n    }\n    if (\"sampled\" in spanContext) {\n      this._sampled = spanContext.sampled;\n    }\n    if (spanContext.endTimestamp) {\n      this._endTime = spanContext.endTimestamp;\n    }\n    this._events = [];\n    this._isStandaloneSpan = spanContext.isStandalone;\n    if (this._endTime) {\n      this._onSpanEnded();\n    }\n  }\n  /** @inheritDoc */\n  addLink(link) {\n    if (this._frozen) {\n      return this;\n    }\n    if (this._links) {\n      this._links.push(link);\n    } else {\n      this._links = [link];\n    }\n    return this;\n  }\n  /** @inheritDoc */\n  addLinks(links) {\n    if (this._frozen) {\n      return this;\n    }\n    if (this._links) {\n      this._links.push(...links);\n    } else {\n      this._links = links;\n    }\n    return this;\n  }\n  /**\n   * This should generally not be used,\n   * but it is needed for being compliant with the OTEL Span interface.\n   *\n   * @hidden\n   * @internal\n   */\n  recordException(_exception, _time) {\n  }\n  /** @inheritdoc */\n  spanContext() {\n    const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n    return {\n      spanId,\n      traceId,\n      traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE\n    };\n  }\n  /** @inheritdoc */\n  setAttribute(key, value) {\n    if (this._frozen) {\n      return this;\n    }\n    if (value === void 0) {\n      delete this._attributes[key];\n    } else {\n      this._attributes[key] = value;\n    }\n    if (key === SEMANTIC_ATTRIBUTE_SENTRY_SOURCE && value !== void 0 && spanShouldInferOtelSource(this)) {\n      markSpanSourceAsExplicit(this);\n    }\n    return this;\n  }\n  /** @inheritdoc */\n  setAttributes(attributes) {\n    Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));\n    return this;\n  }\n  /**\n   * This should generally not be used,\n   * but we need it for browser tracing where we want to adjust the start time afterwards.\n   * USE THIS WITH CAUTION!\n   *\n   * @hidden\n   * @internal\n   */\n  updateStartTime(timeInput) {\n    if (this._frozen) {\n      return;\n    }\n    this._startTime = spanTimeInputToSeconds(timeInput);\n  }\n  /**\n   * @inheritDoc\n   */\n  setStatus(value) {\n    if (this._frozen) {\n      return this;\n    }\n    this._status = value;\n    return this;\n  }\n  /**\n   * @inheritDoc\n   */\n  updateName(name) {\n    if (this._frozen) {\n      return this;\n    }\n    this._name = name;\n    if (!spanShouldInferOtelSource(this)) {\n      this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, \"custom\");\n    }\n    return this;\n  }\n  /** @inheritdoc */\n  end(endTimestamp) {\n    if (this._endTime) {\n      this._frozen = spanIsTracerProviderSpan(this);\n      return;\n    }\n    this._endTime = spanTimeInputToSeconds(endTimestamp);\n    logSpanEnd(this);\n    this._onSpanEnded();\n    this._frozen = spanIsTracerProviderSpan(this);\n  }\n  /**\n   * Get JSON representation of this span.\n   *\n   * @hidden\n   * @internal This method is purely for internal purposes and should not be used outside\n   * of SDK code. If you need to get a JSON representation of a span,\n   * use `spanToJSON(span)` instead.\n   */\n  getSpanJSON() {\n    return {\n      data: this._attributes,\n      description: this._name,\n      op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n      parent_span_id: this._parentSpanId,\n      span_id: this._spanId,\n      start_timestamp: this._startTime,\n      status: getStatusMessage(this._status),\n      timestamp: this._endTime,\n      trace_id: this._traceId,\n      origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],\n      profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],\n      exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],\n      measurements: timedEventsToMeasurements(this._events),\n      is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0,\n      segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0,\n      links: convertSpanLinksForEnvelope(this._links)\n    };\n  }\n  /**\n   * Get {@link StreamedSpanJSON} representation of this span.\n   *\n   * @hidden\n   * @internal This method is purely for internal purposes and should not be used outside\n   * of SDK code. If you need to get a JSON representation of a span,\n   * use `spanToStreamedSpanJSON(span)` instead.\n   */\n  getStreamedSpanJSON() {\n    return {\n      name: this._name ?? \"\",\n      span_id: this._spanId,\n      trace_id: this._traceId,\n      parent_span_id: this._parentSpanId,\n      start_timestamp: this._startTime,\n      // just in case _endTime is not set, we use the start time (i.e. duration 0)\n      end_timestamp: this._endTime ?? this._startTime,\n      is_segment: this._isStandaloneSpan || this === getRootSpan(this),\n      status: getSimpleStatus(this._status),\n      attributes: addStatusMessageAttribute(this._attributes, this._status),\n      links: getStreamedSpanLinks(this._links)\n    };\n  }\n  /** @inheritdoc */\n  isRecording() {\n    return !this._endTime && !!this._sampled;\n  }\n  /**\n   * @inheritdoc\n   */\n  addEvent(name, attributesOrStartTime, startTime) {\n    if (this._frozen) {\n      return this;\n    }\n    DEBUG_BUILD && debug.log(\"[Tracing] Adding an event to span:\", name);\n    const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();\n    const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};\n    const event = {\n      name,\n      time: spanTimeInputToSeconds(time),\n      attributes\n    };\n    this._events.push(event);\n    return this;\n  }\n  /**\n   * This method should generally not be used,\n   * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.\n   * USE THIS WITH CAUTION!\n   * @internal\n   * @hidden\n   * @experimental\n   */\n  isStandaloneSpan() {\n    return !!this._isStandaloneSpan;\n  }\n  /** Emit `spanEnd` when the span is ended. */\n  _onSpanEnded() {\n    const client = getClient();\n    if (client) {\n      client.emit(\"spanEnd\", this);\n      if (!this._isStandaloneSpan) {\n        client.emit(\"afterSpanEnd\", this);\n      }\n    }\n    const rootSpan = getRootSpan(this);\n    const isSegmentSpan = this._isStandaloneSpan || this === rootSpan;\n    if (this._isStandaloneSpan) {\n      if (this._sampled) {\n        sendSpanEnvelope(createSpanEnvelope([this], client));\n      } else {\n        DEBUG_BUILD && debug.log(\"[Tracing] Discarding standalone span because its trace was not chosen to be sampled.\");\n        if (client) {\n          client.recordDroppedEvent(\"sample_rate\", \"span\");\n        }\n      }\n      return;\n    }\n    if (!isSegmentSpan) {\n      const strategy2 = getSegmentSpanCaptureStrategy();\n      if (strategy2) {\n        const scope2 = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n        strategy2.onChildSpanEnded(this, rootSpan, (options) => this._convertSpanToTransaction(options), scope2);\n      }\n      return;\n    }\n    if (client && hasSpanStreamingEnabled(client)) {\n      client.emit(\"afterSegmentSpanEnd\", this);\n      return;\n    }\n    const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n    const strategy = getSegmentSpanCaptureStrategy();\n    if (strategy) {\n      strategy.onSegmentSpanEnded((options) => this._convertSpanToTransaction(options), scope);\n    } else {\n      const transactionEvent = this._convertSpanToTransaction();\n      if (transactionEvent) {\n        scope.captureEvent(transactionEvent);\n      }\n    }\n  }\n  /**\n   * Finish the transaction & prepare the event to send to Sentry.\n   */\n  _convertSpanToTransaction(options = {}) {\n    if (!isFullFinishedSpan(spanToJSON(this))) {\n      return void 0;\n    }\n    if (!this._name) {\n      DEBUG_BUILD && debug.warn(\"Transaction has no name, falling back to `<unlabeled transaction>`.\");\n      this._name = \"<unlabeled transaction>\";\n    }\n    const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n    const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;\n    if (this._sampled !== true) {\n      return void 0;\n    }\n    options.onSpanCaptured?.(this);\n    const spans = [];\n    for (const descendant of getSpanDescendants(this)) {\n      if (descendant === this || isStandaloneSpan(descendant) || options.isSpanAlreadyCaptured?.(descendant)) {\n        continue;\n      }\n      const spanJSON = spanToJSON(descendant);\n      if (!isFullFinishedSpan(spanJSON)) {\n        continue;\n      }\n      options.onSpanCaptured?.(descendant);\n      spans.push(spanJSON);\n    }\n    const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n    delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n    let hasGenAiSpans = false;\n    spans.forEach((span) => {\n      delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n      if (span.op?.startsWith(\"gen_ai.\")) {\n        hasGenAiSpans = true;\n      }\n    });\n    const transaction = {\n      contexts: {\n        trace: spanToTransactionTraceContext(this)\n      },\n      spans: (\n        // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here\n        // we do not use spans anymore after this point\n        spans.length > MAX_SPAN_COUNT ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans\n      ),\n      start_timestamp: this._startTime,\n      timestamp: this._endTime,\n      transaction: this._name,\n      type: \"transaction\",\n      sdkProcessingMetadata: {\n        capturedSpanScope,\n        capturedSpanIsolationScope,\n        dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n        hasGenAiSpans\n      },\n      request: normalizedRequest,\n      ...source && {\n        transaction_info: {\n          source\n        }\n      }\n    };\n    const measurements = timedEventsToMeasurements(this._events);\n    const hasMeasurements = measurements && Object.keys(measurements).length;\n    if (hasMeasurements) {\n      DEBUG_BUILD && debug.log(\n        \"[Measurements] Adding measurements to transaction event\",\n        JSON.stringify(measurements, void 0, 2)\n      );\n      transaction.measurements = measurements;\n    }\n    return transaction;\n  }\n}\nfunction isSpanTimeInput(value) {\n  return value && typeof value === \"number\" || value instanceof Date || Array.isArray(value);\n}\nfunction isFullFinishedSpan(input) {\n  return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;\n}\nfunction isStandaloneSpan(span) {\n  return span instanceof SentrySpan && span.isStandaloneSpan();\n}\nfunction sendSpanEnvelope(envelope) {\n  const client = getClient();\n  if (!client) {\n    return;\n  }\n  const spanItems = envelope[1];\n  if (!spanItems || spanItems.length === 0) {\n    client.recordDroppedEvent(\"before_send\", \"span\");\n    return;\n  }\n  client.sendEnvelope(envelope);\n}\n\nexport { SentrySpan };\n//# sourceMappingURL=sentrySpan.js.map\n","import { chainAndCopyPromiseLike } from './chain-and-copy-promiselike.js';\nimport { isThenable } from './is.js';\n\nfunction handleCallbackErrors(fn, onError, onFinally = () => {\n}, onSuccess = () => {\n}) {\n  let maybePromiseResult;\n  try {\n    maybePromiseResult = fn();\n  } catch (e) {\n    onError(e);\n    onFinally();\n    throw e;\n  }\n  return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);\n}\nfunction maybeHandlePromiseRejection(value, onError, onFinally, onSuccess) {\n  if (isThenable(value)) {\n    return chainAndCopyPromiseLike(\n      value,\n      (result) => {\n        onFinally();\n        onSuccess(result);\n      },\n      (err) => {\n        onError(err);\n        onFinally();\n      }\n    );\n  }\n  onFinally();\n  onSuccess(value);\n  return value;\n}\n\nexport { handleCallbackErrors };\n//# sourceMappingURL=handleCallbackErrors.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\n\nfunction sampleSpan(options, samplingContext, sampleRand) {\n  if (!hasSpansEnabled(options)) {\n    return [false];\n  }\n  let localSampleRateWasApplied = void 0;\n  let sampleRate;\n  if (typeof options.tracesSampler === \"function\") {\n    sampleRate = options.tracesSampler({\n      ...samplingContext,\n      inheritOrSampleWith: (fallbackSampleRate) => {\n        if (typeof samplingContext.parentSampleRate === \"number\") {\n          return samplingContext.parentSampleRate;\n        }\n        if (typeof samplingContext.parentSampled === \"boolean\") {\n          return Number(samplingContext.parentSampled);\n        }\n        return fallbackSampleRate;\n      }\n    });\n    localSampleRateWasApplied = true;\n  } else if (samplingContext.parentSampled !== void 0) {\n    sampleRate = samplingContext.parentSampled;\n  } else if (typeof options.tracesSampleRate !== \"undefined\") {\n    sampleRate = options.tracesSampleRate;\n    localSampleRateWasApplied = true;\n  }\n  const parsedSampleRate = parseSampleRate(sampleRate);\n  if (parsedSampleRate === void 0) {\n    DEBUG_BUILD && debug.warn(\n      `[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(\n        sampleRate\n      )} of type ${JSON.stringify(typeof sampleRate)}.`\n    );\n    return [false];\n  }\n  if (!parsedSampleRate) {\n    DEBUG_BUILD && debug.log(\n      `[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\"}`\n    );\n    return [false, parsedSampleRate, localSampleRateWasApplied];\n  }\n  const shouldSample = sampleRand < parsedSampleRate;\n  if (!shouldSample) {\n    DEBUG_BUILD && debug.log(\n      `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n        sampleRate\n      )})`\n    );\n  }\n  return [shouldSample, parsedSampleRate, localSampleRateWasApplied];\n}\n\nexport { sampleSpan };\n//# sourceMappingURL=sampling.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getClient, withScope, getCurrentScope, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext } from '../utils/baggage.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span.js';\nimport { hasSpanStreamingEnabled } from './spans/hasSpanStreamingEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\nimport { generateTraceId } from '../utils/propagationContext.js';\nimport { safeMathRandom } from '../utils/randomSafeContext.js';\nimport { _getSpanForScope, _setSpanForScope } from '../utils/spanOnScope.js';\nimport { spanTimeInputToSeconds, getRootSpan, addChildSpanToSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils.js';\nimport { shouldContinueTrace, propagationContextFromHeaders } from '../utils/tracing.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { logSpanStart } from './logSpans.js';\nimport { sampleSpan } from './sampling.js';\nimport { spanIsNonRecordingSpan, SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SentrySpan } from './sentrySpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { setCapturedScopesOnSpan } from './utils.js';\n\nconst SUPPRESS_TRACING_KEY = \"__SENTRY_SUPPRESS_TRACING__\";\nfunction startSpan(options, callback) {\n  const acs = getAcs();\n  if (acs.startSpan) {\n    return acs.startSpan(options, callback);\n  }\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n  const customForkedScope = customScope?.clone();\n  return withScope(customForkedScope, () => {\n    const wrapper = getActiveSpanWrapper(customParentSpan);\n    return wrapper(() => {\n      const scope = getCurrentScope();\n      const parentSpan = getParentSpan(scope, customParentSpan);\n      const client = getClient();\n      const missingRequiredParent = options.onlyIfParent && !parentSpan;\n      const activeSpan = missingRequiredParent ? startMissingRequiredParentSpan(scope, client) : createChildOrRootSpan({\n        parentSpan,\n        spanArguments,\n        forceTransaction,\n        scope\n      });\n      if (!spanIsIgnored(activeSpan) || !parentSpan) {\n        _setSpanForScope(scope, activeSpan);\n      }\n      return handleCallbackErrors(\n        () => callback(activeSpan),\n        () => {\n          const { status } = spanToJSON(activeSpan);\n          if (activeSpan.isRecording() && (!status || status === \"ok\")) {\n            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: \"internal_error\" });\n          }\n        },\n        () => {\n          activeSpan.end();\n        }\n      );\n    });\n  });\n}\nfunction startSpanManual(options, callback) {\n  const acs = getAcs();\n  if (acs.startSpanManual) {\n    return acs.startSpanManual(options, callback);\n  }\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n  const customForkedScope = customScope?.clone();\n  return withScope(customForkedScope, () => {\n    const wrapper = getActiveSpanWrapper(customParentSpan);\n    return wrapper(() => {\n      const scope = getCurrentScope();\n      const parentSpan = getParentSpan(scope, customParentSpan);\n      const missingRequiredParent = options.onlyIfParent && !parentSpan;\n      const activeSpan = missingRequiredParent ? startMissingRequiredParentSpan(scope, getClient()) : createChildOrRootSpan({\n        parentSpan,\n        spanArguments,\n        forceTransaction,\n        scope\n      });\n      if (!spanIsIgnored(activeSpan) || !parentSpan) {\n        _setSpanForScope(scope, activeSpan);\n      }\n      return handleCallbackErrors(\n        // We pass the `finish` function to the callback, so the user can finish the span manually\n        // this is mainly here for historic purposes because previously, we instructed users to call\n        // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`\n        // or `finish` has the same effect and we simply leave it here to avoid breaking user code.\n        () => callback(activeSpan, () => activeSpan.end()),\n        () => {\n          const { status } = spanToJSON(activeSpan);\n          if (activeSpan.isRecording() && (!status || status === \"ok\")) {\n            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: \"internal_error\" });\n          }\n        }\n      );\n    });\n  });\n}\nfunction startInactiveSpan(options) {\n  const acs = getAcs();\n  if (acs.startInactiveSpan) {\n    return acs.startInactiveSpan(options);\n  }\n  return _startInactiveSpanImpl(options);\n}\nfunction _INTERNAL_startInactiveSpan(options) {\n  return _startInactiveSpanImpl(options);\n}\nfunction _startInactiveSpanImpl(options) {\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan } = options;\n  const wrapper = options.scope ? (callback) => withScope(options.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback();\n  return wrapper(() => {\n    const scope = getCurrentScope();\n    const parentSpan = getParentSpan(scope, customParentSpan);\n    const client = getClient();\n    const missingRequiredParent = options.onlyIfParent && !parentSpan;\n    if (missingRequiredParent) {\n      return startMissingRequiredParentSpan(scope, client);\n    }\n    return createChildOrRootSpan({\n      parentSpan,\n      spanArguments,\n      forceTransaction,\n      scope\n    });\n  });\n}\nconst continueTrace = (options, callback) => {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.continueTrace) {\n    return acs.continueTrace(options, callback);\n  }\n  const { sentryTrace, baggage } = options;\n  const client = getClient();\n  const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);\n  if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) {\n    return startNewTrace(callback);\n  }\n  return withScope((scope) => {\n    const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n    scope.setPropagationContext(propagationContext);\n    _setSpanForScope(scope, void 0);\n    return callback();\n  });\n};\nfunction withActiveSpan(span, callback) {\n  const acs = getAcs();\n  if (acs.withActiveSpan) {\n    return acs.withActiveSpan(span, callback);\n  }\n  return withScope((scope) => {\n    _setSpanForScope(scope, span || void 0);\n    return callback(scope);\n  });\n}\nfunction suppressTracing(callback) {\n  const acs = getAcs();\n  if (acs.suppressTracing) {\n    return acs.suppressTracing(callback);\n  }\n  return withScope((scope) => {\n    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n    const res = callback();\n    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: void 0 });\n    return res;\n  });\n}\nfunction isTracingSuppressed(scope = getCurrentScope()) {\n  const acs = getAcs();\n  if (acs.isTracingSuppressed) {\n    return acs.isTracingSuppressed(scope);\n  }\n  return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true;\n}\nfunction startNewTrace(callback) {\n  const acs = getAcs();\n  if (acs.startNewTrace) {\n    return acs.startNewTrace(callback);\n  }\n  return withScope((scope) => {\n    scope.setPropagationContext({\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom()\n    });\n    DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);\n    return withActiveSpan(null, callback);\n  });\n}\nfunction startMissingRequiredParentSpan(scope, client) {\n  client?.recordDroppedEvent(\"no_parent_span\", \"span\");\n  const span = new SentryNonRecordingSpan({ traceId: scope.getPropagationContext().traceId });\n  setCapturedScopesOnSpan(span, scope, getIsolationScope());\n  return span;\n}\nfunction createChildOrRootSpan({\n  parentSpan,\n  spanArguments,\n  forceTransaction,\n  scope\n}) {\n  const isolationScope = getIsolationScope();\n  if (!hasSpansEnabled()) {\n    const scopePropagationContext = { ...isolationScope.getPropagationContext(), ...scope.getPropagationContext() };\n    const traceId = parentSpan ? parentSpan.spanContext().traceId : scopePropagationContext.traceId;\n    const span2 = new SentryNonRecordingSpan({ traceId });\n    if (parentSpan && !forceTransaction) {\n      addChildSpanToSpan(parentSpan, span2);\n    }\n    setCapturedScopesOnSpan(span2, scope, isolationScope);\n    return span2;\n  }\n  const client = getClient();\n  if (_shouldIgnoreStreamedSpan(client, spanArguments)) {\n    if (!isTracingSuppressed(scope)) {\n      client?.recordDroppedEvent(\"ignored\", \"span\");\n    }\n    const ignoredSpan = new SentryNonRecordingSpan({\n      dropReason: \"ignored\",\n      traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId\n    });\n    if (parentSpan && !forceTransaction) {\n      addChildSpanToSpan(parentSpan, ignoredSpan);\n    }\n    setCapturedScopesOnSpan(ignoredSpan, scope, isolationScope);\n    return ignoredSpan;\n  }\n  let span;\n  if (parentSpan && !forceTransaction) {\n    span = _startChildSpan(parentSpan, scope, spanArguments, isolationScope);\n    addChildSpanToSpan(parentSpan, span);\n  } else if (parentSpan) {\n    const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n    const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n    const parentSampled = spanIsSampled(parentSpan);\n    span = _startRootSpan(\n      {\n        traceId,\n        parentSpanId,\n        ...spanArguments\n      },\n      scope,\n      isolationScope,\n      parentSampled\n    );\n    freezeDscOnSpan(span, dsc);\n  } else {\n    const {\n      traceId,\n      dsc,\n      parentSpanId,\n      sampled: parentSampled\n    } = {\n      ...isolationScope.getPropagationContext(),\n      ...scope.getPropagationContext()\n    };\n    span = _startRootSpan(\n      {\n        traceId,\n        parentSpanId,\n        ...spanArguments\n      },\n      scope,\n      isolationScope,\n      parentSampled\n    );\n    if (dsc) {\n      freezeDscOnSpan(span, dsc);\n    }\n  }\n  logSpanStart(span);\n  return span;\n}\nfunction parseSentrySpanArguments(options) {\n  const exp = options.experimental || {};\n  const initialCtx = {\n    isStandalone: exp.standalone,\n    ...options\n  };\n  if (options.startTime) {\n    const ctx = { ...initialCtx };\n    ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n    delete ctx.startTime;\n    return ctx;\n  }\n  return initialCtx;\n}\nfunction getAcs() {\n  const carrier = getMainCarrier();\n  return getAsyncContextStrategy(carrier);\n}\nfunction _startRootSpan(spanArguments, scope, isolationScope, parentSampled) {\n  const client = getClient();\n  const options = client?.getOptions() || {};\n  const { name = \"\" } = spanArguments;\n  const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };\n  client?.emit(\"beforeSampling\", mutableSpanSamplingData, { decision: false });\n  const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;\n  const finalAttributes = mutableSpanSamplingData.spanAttributes;\n  const currentPropagationContext = scope.getPropagationContext();\n  const _isTracingSuppressed = isTracingSuppressed(scope);\n  const [sampled, sampleRate, localSampleRateWasApplied] = _isTracingSuppressed ? [false] : sampleSpan(\n    options,\n    {\n      name,\n      parentSampled: finalParentSampled,\n      attributes: finalAttributes,\n      normalizedRequest: isolationScope.getScopeData().sdkProcessingMetadata.normalizedRequest,\n      parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate)\n    },\n    currentPropagationContext.sampleRand\n  );\n  const rootSpan = new SentrySpan({\n    ...spanArguments,\n    attributes: {\n      [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: \"custom\",\n      [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate !== void 0 && localSampleRateWasApplied ? sampleRate : void 0,\n      ...finalAttributes\n    },\n    sampled\n  });\n  if (!sampled && client && !_isTracingSuppressed) {\n    DEBUG_BUILD && debug.log(\"[Tracing] Discarding root span because its trace was not chosen to be sampled.\");\n    client.recordDroppedEvent(\"sample_rate\", hasSpanStreamingEnabled(client) ? \"span\" : \"transaction\");\n  }\n  setCapturedScopesOnSpan(rootSpan, scope, isolationScope);\n  if (client) {\n    client.emit(\"spanStart\", rootSpan);\n  }\n  return rootSpan;\n}\nfunction _startChildSpan(parentSpan, scope, spanArguments, isolationScope) {\n  const { spanId, traceId } = parentSpan.spanContext();\n  const _isTracingSuppressed = isTracingSuppressed(scope);\n  const sampled = _isTracingSuppressed ? false : spanIsSampled(parentSpan);\n  const childSpan = sampled ? new SentrySpan({\n    ...spanArguments,\n    parentSpanId: spanId,\n    traceId,\n    sampled\n  }) : new SentryNonRecordingSpan({ traceId });\n  addChildSpanToSpan(parentSpan, childSpan);\n  setCapturedScopesOnSpan(childSpan, scope, isolationScope);\n  const client = getClient();\n  if (!client) {\n    return childSpan;\n  }\n  if (hasSpanStreamingEnabled(client) && spanIsNonRecordingSpan(childSpan)) {\n    if (spanIsNonRecordingSpan(parentSpan) && parentSpan.dropReason) {\n      childSpan.dropReason = parentSpan.dropReason;\n      client.recordDroppedEvent(parentSpan.dropReason, \"span\");\n    } else if (!_isTracingSuppressed) {\n      childSpan.dropReason = \"sample_rate\";\n      client.recordDroppedEvent(\"sample_rate\", \"span\");\n    }\n  }\n  client.emit(\"spanStart\", childSpan);\n  if (spanArguments.endTimestamp) {\n    client.emit(\"spanEnd\", childSpan);\n    client.emit(\"afterSpanEnd\", childSpan);\n  }\n  return childSpan;\n}\nfunction getParentSpan(scope, customParentSpan) {\n  if (customParentSpan) {\n    return customParentSpan;\n  }\n  if (customParentSpan === null) {\n    return void 0;\n  }\n  const span = _getSpanForScope(scope);\n  if (!span) {\n    return void 0;\n  }\n  const client = getClient();\n  const options = client ? client.getOptions() : {};\n  if (options.parentSpanIsAlwaysRootSpan) {\n    return getRootSpan(span);\n  }\n  return span;\n}\nfunction getActiveSpanWrapper(parentSpan) {\n  return parentSpan !== void 0 ? (callback) => {\n    return withActiveSpan(parentSpan, callback);\n  } : (callback) => callback();\n}\nfunction _shouldIgnoreStreamedSpan(client, spanArguments) {\n  const ignoreSpans = client?.getOptions().ignoreSpans;\n  if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) {\n    return false;\n  }\n  return shouldIgnoreSpan(\n    {\n      description: spanArguments.name || \"\",\n      op: spanArguments.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP] || spanArguments.op,\n      attributes: spanArguments.attributes\n    },\n    ignoreSpans\n  );\n}\nfunction spanIsIgnored(span) {\n  return spanIsNonRecordingSpan(span) && span.dropReason === \"ignored\";\n}\n\nexport { SUPPRESS_TRACING_KEY, _INTERNAL_startInactiveSpan, continueTrace, isTracingSuppressed, spanIsIgnored, startInactiveSpan, startNewTrace, startSpan, startSpanManual, suppressTracing, withActiveSpan };\n//# sourceMappingURL=trace.js.map\n","import { getGlobalScope } from '../currentScopes.js';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext.js';\nimport { merge } from './merge.js';\nimport { spanToTraceContext, getRootSpan, spanToJSON } from './spanUtils.js';\n\nfunction applyScopeDataToEvent(event, data) {\n  const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n  applyDataToEvent(event, data);\n  if (span) {\n    applySpanToEvent(event, span);\n  }\n  applyFingerprintToEvent(event, fingerprint);\n  applyBreadcrumbsToEvent(event, breadcrumbs);\n  applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\nfunction mergeScopeData(data, mergeData) {\n  const {\n    extra,\n    tags,\n    attributes,\n    user,\n    contexts,\n    level,\n    sdkProcessingMetadata,\n    breadcrumbs,\n    fingerprint,\n    eventProcessors,\n    attachments,\n    propagationContext,\n    transactionName,\n    span\n  } = mergeData;\n  mergeAndOverwriteScopeData(data, \"extra\", extra);\n  mergeAndOverwriteScopeData(data, \"tags\", tags);\n  mergeAndOverwriteScopeData(data, \"attributes\", attributes);\n  mergeAndOverwriteScopeData(data, \"user\", user);\n  mergeAndOverwriteScopeData(data, \"contexts\", contexts);\n  data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n  if (level) {\n    data.level = level;\n  }\n  if (transactionName) {\n    data.transactionName = transactionName;\n  }\n  if (span) {\n    data.span = span;\n  }\n  if (breadcrumbs.length) {\n    data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n  }\n  if (fingerprint.length) {\n    data.fingerprint = [...data.fingerprint, ...fingerprint];\n  }\n  if (eventProcessors.length) {\n    data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n  }\n  if (attachments.length) {\n    data.attachments = [...data.attachments, ...attachments];\n  }\n  data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\nfunction mergeAndOverwriteScopeData(data, prop, mergeVal) {\n  data[prop] = merge(data[prop], mergeVal, 1);\n}\nfunction getCombinedScopeData(isolationScope, currentScope) {\n  const scopeData = getGlobalScope().getScopeData();\n  isolationScope && mergeScopeData(scopeData, isolationScope.getScopeData());\n  currentScope && mergeScopeData(scopeData, currentScope.getScopeData());\n  return scopeData;\n}\nfunction applyDataToEvent(event, data) {\n  const { extra, tags, user, contexts, level, transactionName } = data;\n  if (Object.keys(extra).length) {\n    event.extra = { ...extra, ...event.extra };\n  }\n  if (Object.keys(tags).length) {\n    event.tags = { ...tags, ...event.tags };\n  }\n  if (Object.keys(user).length) {\n    event.user = { ...user, ...event.user };\n  }\n  if (Object.keys(contexts).length) {\n    event.contexts = { ...contexts, ...event.contexts };\n  }\n  if (level) {\n    event.level = level;\n  }\n  if (transactionName && event.type !== \"transaction\") {\n    event.transaction = transactionName;\n  }\n}\nfunction applyBreadcrumbsToEvent(event, breadcrumbs) {\n  const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs];\n  event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0;\n}\nfunction applySdkMetadataToEvent(event, sdkProcessingMetadata) {\n  event.sdkProcessingMetadata = {\n    ...event.sdkProcessingMetadata,\n    ...sdkProcessingMetadata\n  };\n}\nfunction applySpanToEvent(event, span) {\n  event.contexts = {\n    trace: spanToTraceContext(span),\n    ...event.contexts\n  };\n  event.sdkProcessingMetadata = {\n    dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n    ...event.sdkProcessingMetadata\n  };\n  const rootSpan = getRootSpan(span);\n  const transactionName = spanToJSON(rootSpan).description;\n  if (transactionName && !event.transaction && event.type === \"transaction\") {\n    event.transaction = transactionName;\n  }\n}\nfunction applyFingerprintToEvent(event, fingerprint) {\n  event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : [];\n  if (fingerprint) {\n    event.fingerprint = event.fingerprint.concat(fingerprint);\n  }\n  if (!event.fingerprint.length) {\n    delete event.fingerprint;\n  }\n}\n\nexport { applyScopeDataToEvent, getCombinedScopeData, mergeAndOverwriteScopeData, mergeScopeData };\n//# sourceMappingURL=scopeData.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { notifyEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\nimport { getFilenameToDebugIdMap } from './debug-ids.js';\nimport { uuid4, addExceptionMechanism } from './misc.js';\nimport { normalize } from './normalize.js';\nimport { getCombinedScopeData, applyScopeDataToEvent } from './scopeData.js';\nimport { truncate } from './string.js';\nimport { resolvedSyncPromise } from './syncpromise.js';\nimport { dateTimestampInSeconds } from './time.js';\n\nfunction prepareEvent(options, event, hint, scope, client, isolationScope) {\n  const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;\n  const prepared = {\n    ...event,\n    event_id: event.event_id || hint.event_id || uuid4(),\n    timestamp: event.timestamp || dateTimestampInSeconds()\n  };\n  const integrations = hint.integrations || options.integrations.map((i) => i.name);\n  applyClientOptions(prepared, options);\n  applyIntegrationsMetadata(prepared, integrations);\n  if (client) {\n    client.emit(\"applyFrameMetadata\", event);\n  }\n  if (event.type === void 0) {\n    applyDebugIds(prepared, options.stackParser);\n  }\n  const finalScope = getFinalScope(scope, hint.captureContext);\n  if (hint.mechanism) {\n    addExceptionMechanism(prepared, hint.mechanism);\n  }\n  const clientEventProcessors = client ? client.getEventProcessors() : [];\n  const data = getCombinedScopeData(isolationScope, finalScope);\n  const attachments = [...hint.attachments || [], ...data.attachments];\n  if (attachments.length) {\n    hint.attachments = attachments;\n  }\n  applyScopeDataToEvent(prepared, data);\n  const eventProcessors = [\n    ...clientEventProcessors,\n    // Run scope event processors _after_ all other processors\n    ...data.eventProcessors\n  ];\n  const isInternalException = hint.data && hint.data.__sentry__ === true;\n  const result = isInternalException ? resolvedSyncPromise(prepared) : notifyEventProcessors(eventProcessors, prepared, hint);\n  return result.then((evt) => {\n    if (evt) {\n      applyDebugMeta(evt);\n    }\n    if (typeof normalizeDepth === \"number\" && normalizeDepth > 0) {\n      return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n    }\n    return evt;\n  });\n}\nfunction applyClientOptions(event, options) {\n  const { environment, release, dist, maxValueLength } = options;\n  event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n  if (!event.release && release) {\n    event.release = release;\n  }\n  if (!event.dist && dist) {\n    event.dist = dist;\n  }\n  const request = event.request;\n  if (request?.url && maxValueLength) {\n    request.url = truncate(request.url, maxValueLength);\n  }\n  if (maxValueLength) {\n    event.exception?.values?.forEach((exception) => {\n      if (exception.value) {\n        exception.value = truncate(exception.value, maxValueLength);\n      }\n    });\n  }\n}\nfunction applyDebugIds(event, stackParser) {\n  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n  event.exception?.values?.forEach((exception) => {\n    exception.stacktrace?.frames?.forEach((frame) => {\n      if (frame.filename) {\n        frame.debug_id = filenameDebugIdMap[frame.filename];\n      }\n    });\n  });\n}\nfunction applyDebugMeta(event) {\n  const filenameDebugIdMap = {};\n  event.exception?.values?.forEach((exception) => {\n    exception.stacktrace?.frames?.forEach((frame) => {\n      if (frame.debug_id) {\n        if (frame.abs_path) {\n          filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n        } else if (frame.filename) {\n          filenameDebugIdMap[frame.filename] = frame.debug_id;\n        }\n        delete frame.debug_id;\n      }\n    });\n  });\n  if (Object.keys(filenameDebugIdMap).length === 0) {\n    return;\n  }\n  event.debug_meta = event.debug_meta || {};\n  event.debug_meta.images = event.debug_meta.images || [];\n  const images = event.debug_meta.images;\n  Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {\n    images.push({\n      type: \"sourcemap\",\n      code_file: filename,\n      debug_id\n    });\n  });\n}\nfunction applyIntegrationsMetadata(event, integrationNames) {\n  if (integrationNames.length > 0) {\n    event.sdk = event.sdk || {};\n    event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames];\n  }\n}\nfunction normalizeEvent(event, depth, maxBreadth) {\n  if (!event) {\n    return null;\n  }\n  const normalized = {\n    ...event,\n    ...event.breadcrumbs && {\n      breadcrumbs: event.breadcrumbs.map((b) => ({\n        ...b,\n        ...b.data && {\n          data: normalize(b.data, depth, maxBreadth)\n        }\n      }))\n    },\n    ...event.user && {\n      user: normalize(event.user, depth, maxBreadth)\n    },\n    ...event.contexts && {\n      contexts: normalize(event.contexts, depth, maxBreadth)\n    },\n    ...event.extra && {\n      extra: normalize(event.extra, depth, maxBreadth)\n    }\n  };\n  if (event.contexts?.trace && normalized.contexts) {\n    normalized.contexts.trace = event.contexts.trace;\n    if (event.contexts.trace.data) {\n      normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n    }\n  }\n  if (event.spans) {\n    normalized.spans = event.spans.map((span) => {\n      return {\n        ...span,\n        ...span.data && {\n          data: normalize(span.data, depth, maxBreadth)\n        }\n      };\n    });\n  }\n  if (event.contexts?.flags && normalized.contexts) {\n    normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n  }\n  return normalized;\n}\nfunction getFinalScope(scope, captureContext) {\n  if (!captureContext) {\n    return scope;\n  }\n  const finalScope = scope ? scope.clone() : new Scope();\n  finalScope.update(captureContext);\n  return finalScope;\n}\nfunction parseEventHintOrCaptureContext(hint) {\n  if (!hint) {\n    return void 0;\n  }\n  if (hintIsScopeOrFunction(hint)) {\n    return { captureContext: hint };\n  }\n  if (hintIsScopeContext(hint)) {\n    return {\n      captureContext: hint\n    };\n  }\n  return hint;\n}\nfunction hintIsScopeOrFunction(hint) {\n  return hint instanceof Scope || typeof hint === \"function\";\n}\nconst captureContextKeys = [\n  \"user\",\n  \"level\",\n  \"extra\",\n  \"contexts\",\n  \"tags\",\n  \"fingerprint\",\n  \"propagationContext\"\n];\nfunction hintIsScopeContext(hint) {\n  return Object.keys(hint).some((key) => captureContextKeys.includes(key));\n}\n\nexport { applyClientOptions, applyDebugIds, applyDebugMeta, parseEventHintOrCaptureContext, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { getIsolationScope, getCurrentScope, getClient, withIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { closeSession, makeSession, updateSession } from './session.js';\nimport { startNewTrace } from './tracing/trace.js';\nimport { debug } from './utils/debug-logger.js';\nimport { isThenable } from './utils/is.js';\nimport { uuid4 } from './utils/misc.js';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent.js';\nimport { getCombinedScopeData } from './utils/scopeData.js';\nimport { timestampInSeconds } from './utils/time.js';\nimport { GLOBAL_OBJ } from './utils/worldwide.js';\n\nfunction captureException(exception, hint) {\n  return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\nfunction captureMessage(message, captureContext) {\n  const level = typeof captureContext === \"string\" ? captureContext : void 0;\n  const hint = typeof captureContext !== \"string\" ? { captureContext } : void 0;\n  return getCurrentScope().captureMessage(message, level, hint);\n}\nfunction captureEvent(event, hint) {\n  return getCurrentScope().captureEvent(event, hint);\n}\nfunction setContext(name, context) {\n  getIsolationScope().setContext(name, context);\n}\nfunction setExtras(extras) {\n  getIsolationScope().setExtras(extras);\n}\nfunction setExtra(key, extra) {\n  getIsolationScope().setExtra(key, extra);\n}\nfunction setTags(tags) {\n  getIsolationScope().setTags(tags);\n}\nfunction setTag(key, value) {\n  getIsolationScope().setTag(key, value);\n}\nfunction setAttributes(attributes) {\n  getIsolationScope().setAttributes(attributes);\n}\nfunction setAttribute(key, value) {\n  getIsolationScope().setAttribute(key, value);\n}\nfunction setUser(user) {\n  getIsolationScope().setUser(user);\n}\nfunction setConversationId(conversationId) {\n  getIsolationScope().setConversationId(conversationId);\n}\nfunction lastEventId() {\n  return getIsolationScope().lastEventId();\n}\nfunction captureCheckIn(checkIn, upsertMonitorConfig) {\n  const scope = getCurrentScope();\n  const client = getClient();\n  if (!client) {\n    DEBUG_BUILD && debug.warn(\"Cannot capture check-in. No client defined.\");\n  } else if (!client.captureCheckIn) {\n    DEBUG_BUILD && debug.warn(\"Cannot capture check-in. Client does not support sending check-ins.\");\n  } else {\n    return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n  }\n  return uuid4();\n}\nfunction withMonitor(monitorSlug, callback, upsertMonitorConfig) {\n  function runCallback() {\n    const checkInId = captureCheckIn({ monitorSlug, status: \"in_progress\" }, upsertMonitorConfig);\n    const now = timestampInSeconds();\n    function finishCheckIn(status) {\n      captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n    }\n    let maybePromiseResult;\n    try {\n      maybePromiseResult = callback();\n    } catch (e) {\n      finishCheckIn(\"error\");\n      throw e;\n    }\n    if (isThenable(maybePromiseResult)) {\n      return maybePromiseResult.then(\n        (r) => {\n          finishCheckIn(\"ok\");\n          return r;\n        },\n        (e) => {\n          finishCheckIn(\"error\");\n          throw e;\n        }\n      );\n    }\n    finishCheckIn(\"ok\");\n    return maybePromiseResult;\n  }\n  return withIsolationScope(() => upsertMonitorConfig?.isolateTrace ? startNewTrace(runCallback) : runCallback());\n}\nasync function flush(timeout) {\n  const client = getClient();\n  if (client) {\n    return client.flush(timeout);\n  }\n  DEBUG_BUILD && debug.warn(\"Cannot flush events. No client defined.\");\n  return Promise.resolve(false);\n}\nasync function close(timeout) {\n  const client = getClient();\n  if (client) {\n    return client.close(timeout);\n  }\n  DEBUG_BUILD && debug.warn(\"Cannot flush events and disable SDK. No client defined.\");\n  return Promise.resolve(false);\n}\nfunction isInitialized() {\n  return !!getClient();\n}\nfunction isEnabled() {\n  const client = getClient();\n  return client?.getOptions().enabled !== false && !!client?.getTransport();\n}\nfunction addEventProcessor(callback) {\n  getIsolationScope().addEventProcessor(callback);\n}\nfunction startSession(context) {\n  const isolationScope = getIsolationScope();\n  const { user } = getCombinedScopeData(isolationScope, getCurrentScope());\n  const { userAgent } = GLOBAL_OBJ.navigator || {};\n  const session = makeSession({\n    user,\n    ...userAgent && { userAgent },\n    ...context\n  });\n  const currentSession = isolationScope.getSession();\n  if (currentSession?.status === \"ok\") {\n    updateSession(currentSession, { status: \"exited\" });\n  }\n  endSession();\n  isolationScope.setSession(session);\n  return session;\n}\nfunction endSession() {\n  const isolationScope = getIsolationScope();\n  const currentScope = getCurrentScope();\n  const session = currentScope.getSession() || isolationScope.getSession();\n  if (session) {\n    closeSession(session);\n  }\n  _sendSessionUpdate();\n  isolationScope.setSession();\n}\nfunction _sendSessionUpdate() {\n  const isolationScope = getIsolationScope();\n  const client = getClient();\n  const session = isolationScope.getSession();\n  if (session && client) {\n    client.captureSession(session);\n  }\n}\nfunction captureSession(end = false) {\n  if (end) {\n    endSession();\n    return;\n  }\n  _sendSessionUpdate();\n}\n\nexport { addEventProcessor, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, endSession, flush, isEnabled, isInitialized, lastEventId, setAttribute, setAttributes, setContext, setConversationId, setExtra, setExtras, setTag, setTags, setUser, startSession, withMonitor };\n//# sourceMappingURL=exports.js.map\n","const SEQUENCE_ATTR_KEY = \"sentry.timestamp.sequence\";\nlet _sequenceNumber = 0;\nlet _previousTimestampMs;\nfunction getSequenceAttribute(timestampInSeconds) {\n  const nowMs = Math.floor(timestampInSeconds * 1e3);\n  if (_previousTimestampMs !== void 0 && nowMs !== _previousTimestampMs) {\n    _sequenceNumber = 0;\n  }\n  const value = _sequenceNumber;\n  _sequenceNumber++;\n  _previousTimestampMs = nowMs;\n  return {\n    key: SEQUENCE_ATTR_KEY,\n    value: { value, type: \"integer\" }\n  };\n}\n\nexport { getSequenceAttribute };\n//# sourceMappingURL=timestampSequence.js.map\n","import { withScope, getTraceContextFromScope } from '../currentScopes.js';\nimport { getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromScope } from '../tracing/dynamicSamplingContext.js';\nimport { getActiveSpan, spanToTraceContext } from './spanUtils.js';\n\nfunction _getTraceInfoFromScope(client, scope) {\n  if (!scope) {\n    return [void 0, void 0];\n  }\n  return withScope(scope, () => {\n    const span = getActiveSpan();\n    const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);\n    const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);\n    return [dynamicSamplingContext, traceContext];\n  });\n}\n\nexport { _getTraceInfoFromScope };\n//# sourceMappingURL=trace-info.js.map\n","const SEVERITY_TEXT_TO_SEVERITY_NUMBER = {\n  trace: 1,\n  debug: 5,\n  info: 9,\n  warn: 13,\n  error: 17,\n  fatal: 21\n};\n\nexport { SEVERITY_TEXT_TO_SEVERITY_NUMBER };\n//# sourceMappingURL=constants.js.map\n","function isBrowserBundle() {\n  return typeof __SENTRY_BROWSER_BUNDLE__ !== \"undefined\" && !!__SENTRY_BROWSER_BUNDLE__;\n}\nfunction getSDKSource() {\n  /*! __SENTRY_SDK_SOURCE__ */\n  return \"npm\";\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\nfunction isNodeEnv() {\n  return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== \"undefined\" ? process : 0) === \"[object process]\";\n}\nfunction dynamicRequire(mod, request) {\n  return mod.require(request);\n}\nfunction loadModule(moduleName, existingModule = module) {\n  let mod;\n  try {\n    mod = dynamicRequire(existingModule, moduleName);\n  } catch {\n  }\n  if (!mod) {\n    try {\n      const { cwd } = dynamicRequire(existingModule, \"process\");\n      mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`);\n    } catch {\n    }\n  }\n  return mod;\n}\n\nexport { isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { isNodeEnv } from './node.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nfunction isBrowser() {\n  return typeof window !== \"undefined\" && (!isNodeEnv() || isElectronNodeRenderer());\n}\nfunction isElectronNodeRenderer() {\n  const process = GLOBAL_OBJ.process;\n  return process?.type === \"renderer\";\n}\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\nimport { isBrowser } from '../utils/isBrowser.js';\n\nfunction createLogContainerEnvelopeItem(items, inferUserData) {\n  const inferSetting = inferUserData ? \"auto\" : \"never\";\n  return [\n    {\n      type: \"log\",\n      item_count: items.length,\n      content_type: \"application/vnd.sentry.items.log+json\"\n    },\n    {\n      version: 2,\n      ...isBrowser() && {\n        ingest_settings: { infer_ip: inferSetting, infer_user_agent: inferSetting }\n      },\n      items\n    }\n  ];\n}\nfunction createLogEnvelope(logs, metadata, tunnel, dsn, inferUserData) {\n  const headers = {};\n  if (metadata?.sdk) {\n    headers.sdk = {\n      name: metadata.sdk.name,\n      version: metadata.sdk.version\n    };\n  }\n  if (!!tunnel && !!dsn) {\n    headers.dsn = dsnToString(dsn);\n  }\n  return createEnvelope(headers, [createLogContainerEnvelopeItem(logs, inferUserData)]);\n}\n\nexport { createLogContainerEnvelopeItem, createLogEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { serializeAttributes } from '../attributes.js';\nimport { getGlobalSingleton } from '../carrier.js';\nimport { getClient, getIsolationScope, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { debug, consoleSandbox } from '../utils/debug-logger.js';\nimport { isParameterizedString } from '../utils/is.js';\nimport { getCombinedScopeData } from '../utils/scopeData.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { getSequenceAttribute } from '../utils/timestampSequence.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from './constants.js';\nimport { createLogEnvelope } from './envelope.js';\n\nconst MAX_LOG_BUFFER_SIZE = 100;\nfunction setLogAttribute(logAttributes, key, value, setEvenIfPresent = true) {\n  if (value && (!logAttributes[key] || setEvenIfPresent)) {\n    logAttributes[key] = value;\n  }\n}\nfunction _INTERNAL_captureSerializedLog(client, serializedLog) {\n  const bufferMap = _getBufferMap();\n  const logBuffer = _INTERNAL_getLogBuffer(client);\n  if (logBuffer === void 0) {\n    bufferMap.set(client, [serializedLog]);\n  } else {\n    if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {\n      _INTERNAL_flushLogsBuffer(client, logBuffer);\n      bufferMap.set(client, [serializedLog]);\n    } else {\n      bufferMap.set(client, [...logBuffer, serializedLog]);\n    }\n  }\n}\nfunction _INTERNAL_captureLog(beforeLog, currentScope = getCurrentScope(), captureSerializedLog = _INTERNAL_captureSerializedLog) {\n  const client = currentScope?.getClient() ?? getClient();\n  if (!client) {\n    DEBUG_BUILD && debug.warn(\"No client available to capture log.\");\n    return;\n  }\n  const { release, environment, enableLogs = false, beforeSendLog } = client.getOptions();\n  if (!enableLogs) {\n    DEBUG_BUILD && debug.warn(\"logging option not enabled, log will not be captured.\");\n    return;\n  }\n  const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n  const processedLogAttributes = {\n    ...beforeLog.attributes\n  };\n  const {\n    user: { id, email, username },\n    attributes: scopeAttributes = {}\n  } = getCombinedScopeData(getIsolationScope(), currentScope);\n  setLogAttribute(processedLogAttributes, \"user.id\", id, false);\n  setLogAttribute(processedLogAttributes, \"user.email\", email, false);\n  setLogAttribute(processedLogAttributes, \"user.name\", username, false);\n  setLogAttribute(processedLogAttributes, \"sentry.release\", release);\n  setLogAttribute(processedLogAttributes, \"sentry.environment\", environment);\n  const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n  setLogAttribute(processedLogAttributes, \"sentry.sdk.name\", name);\n  setLogAttribute(processedLogAttributes, \"sentry.sdk.version\", version);\n  const replay = client.getIntegrationByName(\"Replay\");\n  const replayId = replay?.getReplayId(true);\n  setLogAttribute(processedLogAttributes, \"sentry.replay_id\", replayId);\n  if (replayId && replay?.getRecordingMode() === \"buffer\") {\n    setLogAttribute(processedLogAttributes, \"sentry._internal.replay_is_buffering\", true);\n  }\n  const beforeLogMessage = beforeLog.message;\n  if (isParameterizedString(beforeLogMessage)) {\n    const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;\n    if (__sentry_template_values__?.length) {\n      processedLogAttributes[\"sentry.message.template\"] = __sentry_template_string__;\n    }\n    __sentry_template_values__.forEach((param, index) => {\n      processedLogAttributes[`sentry.message.parameter.${index}`] = param;\n    });\n  }\n  const span = _getSpanForScope(currentScope);\n  setLogAttribute(processedLogAttributes, \"sentry.trace.parent_span_id\", span?.spanContext().spanId);\n  const processedLog = { ...beforeLog, attributes: processedLogAttributes };\n  client.emit(\"beforeCaptureLog\", processedLog);\n  const log = beforeSendLog ? consoleSandbox(() => beforeSendLog(processedLog)) : processedLog;\n  if (!log) {\n    client.recordDroppedEvent(\"before_send\", \"log_item\", 1);\n    DEBUG_BUILD && debug.warn(\"beforeSendLog returned null, log will not be captured.\");\n    return;\n  }\n  const { level, message, attributes: logAttributes = {}, severityNumber } = log;\n  const timestamp = timestampInSeconds();\n  const sequenceAttr = getSequenceAttribute(timestamp);\n  const serializedLog = {\n    timestamp,\n    level,\n    body: _removeLoneSurrogates(String(message)),\n    trace_id: traceContext?.trace_id,\n    severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],\n    attributes: sanitizeLogAttributes({\n      ...serializeAttributes(scopeAttributes),\n      ...serializeAttributes(logAttributes, true),\n      [sequenceAttr.key]: sequenceAttr.value\n    })\n  };\n  captureSerializedLog(client, serializedLog);\n  client.emit(\"afterCaptureLog\", log);\n}\nfunction _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) {\n  const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];\n  if (logBuffer.length === 0) {\n    return;\n  }\n  const clientOptions = client.getOptions();\n  const envelope = createLogEnvelope(\n    logBuffer,\n    clientOptions._metadata,\n    clientOptions.tunnel,\n    client.getDsn(),\n    client.getDataCollectionOptions().userInfo\n  );\n  _getBufferMap().set(client, []);\n  client.emit(\"flushLogs\");\n  client.sendEnvelope(envelope);\n}\nfunction _INTERNAL_getLogBuffer(client) {\n  return _getBufferMap().get(client);\n}\nfunction _getBufferMap() {\n  return getGlobalSingleton(\"clientToLogBufferMap\", () => /* @__PURE__ */ new WeakMap());\n}\nfunction sanitizeLogAttributes(attributes) {\n  const sanitized = {};\n  for (const [key, attr] of Object.entries(attributes)) {\n    const sanitizedKey = _removeLoneSurrogates(key);\n    if (attr.type === \"string\") {\n      sanitized[sanitizedKey] = { ...attr, value: _removeLoneSurrogates(attr.value) };\n    } else {\n      sanitized[sanitizedKey] = attr;\n    }\n  }\n  return sanitized;\n}\nfunction _removeLoneSurrogates(str) {\n  const strObj = Object(str);\n  const isWellFormed = strObj[\"isWellFormed\"];\n  const toWellFormed = strObj[\"toWellFormed\"];\n  if (typeof isWellFormed === \"function\" && typeof toWellFormed === \"function\") {\n    return isWellFormed.call(str) ? str : toWellFormed.call(str);\n  }\n  return str;\n}\n\nexport { _INTERNAL_captureLog, _INTERNAL_captureSerializedLog, _INTERNAL_flushLogsBuffer, _INTERNAL_getLogBuffer, _removeLoneSurrogates };\n//# sourceMappingURL=internal.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\nimport { isBrowser } from '../utils/isBrowser.js';\n\nfunction createMetricContainerEnvelopeItem(items, inferUserData) {\n  const inferSetting = inferUserData ? \"auto\" : \"never\";\n  return [\n    {\n      type: \"trace_metric\",\n      item_count: items.length,\n      content_type: \"application/vnd.sentry.items.trace-metric+json\"\n    },\n    {\n      version: 2,\n      ...isBrowser() && {\n        ingest_settings: { infer_ip: inferSetting, infer_user_agent: inferSetting }\n      },\n      items\n    }\n  ];\n}\nfunction createMetricEnvelope(metrics, metadata, tunnel, dsn, inferUserData) {\n  const headers = {};\n  if (metadata?.sdk) {\n    headers.sdk = {\n      name: metadata.sdk.name,\n      version: metadata.sdk.version\n    };\n  }\n  if (!!tunnel && !!dsn) {\n    headers.dsn = dsnToString(dsn);\n  }\n  return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics, inferUserData)]);\n}\n\nexport { createMetricContainerEnvelopeItem, createMetricEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { serializeAttributes } from '../attributes.js';\nimport { getGlobalSingleton } from '../carrier.js';\nimport { getCurrentScope, getClient, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getCombinedScopeData } from '../utils/scopeData.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { getSequenceAttribute } from '../utils/timestampSequence.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { createMetricEnvelope } from './envelope.js';\n\nconst MAX_METRIC_BUFFER_SIZE = 1e3;\nfunction setMetricAttribute(metricAttributes, key, value, setEvenIfPresent = true) {\n  if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n    metricAttributes[key] = value;\n  }\n}\nfunction _INTERNAL_captureSerializedMetric(client, serializedMetric) {\n  const bufferMap = _getBufferMap();\n  const metricBuffer = _INTERNAL_getMetricBuffer(client);\n  if (metricBuffer === void 0) {\n    bufferMap.set(client, [serializedMetric]);\n  } else {\n    if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n      _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n      bufferMap.set(client, [serializedMetric]);\n    } else {\n      bufferMap.set(client, [...metricBuffer, serializedMetric]);\n    }\n  }\n}\nfunction _enrichMetricAttributes(beforeMetric, client, user) {\n  const { release, environment } = client.getOptions();\n  const processedMetricAttributes = {\n    ...beforeMetric.attributes\n  };\n  setMetricAttribute(processedMetricAttributes, \"user.id\", user.id, false);\n  setMetricAttribute(processedMetricAttributes, \"user.email\", user.email, false);\n  setMetricAttribute(processedMetricAttributes, \"user.name\", user.username, false);\n  setMetricAttribute(processedMetricAttributes, \"sentry.release\", release);\n  setMetricAttribute(processedMetricAttributes, \"sentry.environment\", environment);\n  const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n  setMetricAttribute(processedMetricAttributes, \"sentry.sdk.name\", name);\n  setMetricAttribute(processedMetricAttributes, \"sentry.sdk.version\", version);\n  const replay = client.getIntegrationByName(\"Replay\");\n  const replayId = replay?.getReplayId(true);\n  setMetricAttribute(processedMetricAttributes, \"sentry.replay_id\", replayId);\n  if (replayId && replay?.getRecordingMode() === \"buffer\") {\n    setMetricAttribute(processedMetricAttributes, \"sentry._internal.replay_is_buffering\", true);\n  }\n  return {\n    ...beforeMetric,\n    attributes: processedMetricAttributes\n  };\n}\nfunction _buildSerializedMetric(metric, client, currentScope, scopeAttributes) {\n  const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n  const span = _getSpanForScope(currentScope);\n  const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n  const spanId = span ? span.spanContext().spanId : void 0;\n  const timestamp = timestampInSeconds();\n  const sequenceAttr = getSequenceAttribute(timestamp);\n  return {\n    timestamp,\n    trace_id: traceId ?? \"\",\n    span_id: spanId,\n    name: metric.name,\n    type: metric.type,\n    unit: metric.unit,\n    value: metric.value,\n    attributes: {\n      ...serializeAttributes(scopeAttributes),\n      ...serializeAttributes(metric.attributes, \"skip-undefined\"),\n      [sequenceAttr.key]: sequenceAttr.value\n    }\n  };\n}\nfunction _INTERNAL_captureMetric(beforeMetric, options) {\n  const currentScope = options?.scope ?? getCurrentScope();\n  const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n  const client = currentScope?.getClient() ?? getClient();\n  if (!client) {\n    DEBUG_BUILD && debug.warn(\"No client available to capture metric.\");\n    return;\n  }\n  const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n  const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n  if (!metricsEnabled) {\n    DEBUG_BUILD && debug.warn(\"metrics option not enabled, metric will not be captured.\");\n    return;\n  }\n  const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);\n  const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);\n  client.emit(\"processMetric\", enrichedMetric);\n  const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n  const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n  if (!processedMetric) {\n    DEBUG_BUILD && debug.log(\"`beforeSendMetric` returned `null`, will not send metric.\");\n    return;\n  }\n  const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);\n  DEBUG_BUILD && debug.log(\"[Metric]\", serializedMetric);\n  captureSerializedMetric(client, serializedMetric);\n  client.emit(\"afterCaptureMetric\", processedMetric);\n}\nfunction _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {\n  const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n  if (metricBuffer.length === 0) {\n    return;\n  }\n  const clientOptions = client.getOptions();\n  const envelope = createMetricEnvelope(\n    metricBuffer,\n    clientOptions._metadata,\n    clientOptions.tunnel,\n    client.getDsn(),\n    client.getDataCollectionOptions().userInfo\n  );\n  _getBufferMap().set(client, []);\n  client.emit(\"flushMetrics\");\n  client.sendEnvelope(envelope);\n}\nfunction _INTERNAL_getMetricBuffer(client) {\n  return _getBufferMap().get(client);\n}\nfunction _getBufferMap() {\n  return getGlobalSingleton(\"clientToMetricBufferMap\", () => /* @__PURE__ */ new WeakMap());\n}\n\nexport { _INTERNAL_captureMetric, _INTERNAL_captureSerializedMetric, _INTERNAL_flushMetricsBuffer, _INTERNAL_getMetricBuffer };\n//# sourceMappingURL=internal.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils/debug-logger.js';\nimport { dateTimestampInSeconds } from './utils/time.js';\n\nconst DEFAULT_BREADCRUMBS = 100;\nfunction addBreadcrumb(breadcrumb, hint) {\n  const client = getClient();\n  const isolationScope = getIsolationScope();\n  if (!client) return;\n  const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n  if (maxBreadcrumbs <= 0) return;\n  const timestamp = dateTimestampInSeconds();\n  const mergedBreadcrumb = { timestamp, ...breadcrumb };\n  const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;\n  if (finalBreadcrumb === null) return;\n  if (client.emit) {\n    client.emit(\"beforeAddBreadcrumb\", finalBreadcrumb, hint);\n  }\n  isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { _INTERNAL_captureLog } from './internal.js';\nexport { fmt } from '../utils/parameterize.js';\n\nfunction captureLog(level, message, attributes, scope, severityNumber) {\n  _INTERNAL_captureLog({ level, message, attributes, severityNumber }, scope);\n}\nfunction trace(message, attributes, { scope } = {}) {\n  captureLog(\"trace\", message, attributes, scope);\n}\nfunction debug(message, attributes, { scope } = {}) {\n  captureLog(\"debug\", message, attributes, scope);\n}\nfunction info(message, attributes, { scope } = {}) {\n  captureLog(\"info\", message, attributes, scope);\n}\nfunction warn(message, attributes, { scope } = {}) {\n  captureLog(\"warn\", message, attributes, scope);\n}\nfunction error(message, attributes, { scope } = {}) {\n  captureLog(\"error\", message, attributes, scope);\n}\nfunction fatal(message, attributes, { scope } = {}) {\n  captureLog(\"fatal\", message, attributes, scope);\n}\n\nexport { debug, error, fatal, info, trace, warn };\n//# sourceMappingURL=public-api.js.map\n","import { _INTERNAL_captureMetric } from './internal.js';\n\nfunction captureMetric(type, name, value, options) {\n  _INTERNAL_captureMetric(\n    { type, name, value, unit: options?.unit, attributes: options?.attributes },\n    { scope: options?.scope }\n  );\n}\nfunction count(name, value = 1, options) {\n  captureMetric(\"counter\", name, value, options);\n}\nfunction gauge(name, value, options) {\n  captureMetric(\"gauge\", name, value, options);\n}\nfunction distribution(name, value, options) {\n  captureMetric(\"distribution\", name, value, options);\n}\n\nexport { count, distribution, gauge };\n//# sourceMappingURL=public-api.js.map\n","/**\n * Pure scrubbing helpers shared by the Sentry instrumentation layer.\n *\n * Extracted from src/instrument.ts so they can be unit-tested independently\n * of the Sentry initialisation side-effects.\n */\n\n/** Hosts that identify the app shell, not a user's homeserver. Never redacted. */\nconst LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]', 'tauri.localhost']);\n\n// Also preserve the app's own origin so Sentry can show which page an error occurred on.\nif (typeof window !== 'undefined' && window.location) {\n  try {\n    const appHost = new URL(window.location.origin).hostname.toLowerCase();\n    if (appHost) LOCAL_HOSTS.add(appHost);\n  } catch {\n    /* invalid origin, ignore */\n  }\n}\n\n/** Replace the origin of any external http(s) URL with [HOMESERVER], keeping path/query/hash. */\nexport function scrubExternalHosts(value: string): string {\n  return value.replace(/\\bhttps?:\\/\\/[^/?#\\s]+/gi, (match) => {\n    const schemeEnd = match.indexOf('://') + 3;\n    const hostname = (match.slice(schemeEnd).split(':')[0] ?? '').toLowerCase();\n    if (LOCAL_HOSTS.has(hostname)) return match;\n    return `${match.slice(0, schemeEnd)}[HOMESERVER]`;\n  });\n}\n\n/**\n * Scrub Matrix entity IDs, credential tokens, and external http(s) hosts from a\n * plain string value. Used for structured log attribute values and breadcrumb\n * data fields.\n */\nexport function scrubMatrixIds(value: string): string {\n  return scrubExternalHosts(value)\n    .replace(\n      /(access_token|password|token|refresh_token|session_id|sync_token|next_batch)([=:\\s]+)([^\\s&]+)/gi,\n      '$1$2[REDACTED]'\n    )\n    .replace(/@[^\\s:@]+:[^\\s,'\"(){}[\\]]+/g, '@[USER_ID]')\n    .replace(/![^\\s:]+:[^\\s,'\"(){}[\\]]+/g, '![ROOM_ID]')\n    .replace(/#[^\\s:@]+:[^\\s,'\"(){}[\\]]+/g, '#[ROOM_ALIAS]')\n    .replace(/\\$[A-Za-z0-9_+/-]{10,}/g, '$[EVENT_ID]');\n}\n\n/**\n * Recursively scrub Matrix entity IDs from all string values in a plain object.\n * Handles one level of nesting (objects and arrays of primitives).\n */\nexport function scrubDataObject(data: unknown): unknown {\n  if (typeof data === 'string') return scrubMatrixIds(data);\n  if (Array.isArray(data)) return data.map(scrubDataObject);\n  if (data !== null && typeof data === 'object') {\n    return Object.fromEntries(\n      Object.entries(data as Record<string, unknown>).map(([k, v]) => [k, scrubDataObject(v)])\n    );\n  }\n  return data;\n}\n\n/** Structured fields that should never be sent to Sentry, even redacted. */\nconst SENTRY_IDENTIFIER_KEYS = new Set([\n  'roomId',\n  'notificationEventId',\n  'refEventId',\n  'senderId',\n  'declineEventId',\n  'eventId',\n  'userId',\n  'targetEventId',\n  'deviceId',\n  'activeNotificationId',\n  'activeRefEventId',\n  'callerId',\n  'recipientId',\n]);\n\n/** Drop identifier-bearing keys before values are scrubbed for Sentry export. */\nexport function omitSentryIdentifierFields(data: unknown): unknown {\n  if (Array.isArray(data)) {\n    return data.map(omitSentryIdentifierFields);\n  }\n  if (data !== null && typeof data === 'object') {\n    return Object.fromEntries(\n      Object.entries(data as Record<string, unknown>)\n        .filter(([key]) => !SENTRY_IDENTIFIER_KEYS.has(key))\n        .map(([key, value]) => [key, omitSentryIdentifierFields(value)])\n    );\n  }\n  return data;\n}\n\n/** Full sanitization pass for Sentry breadcrumbs, logs, and contexts. */\nexport function sanitizeSentryPayload(data: unknown): unknown {\n  return scrubDataObject(omitSentryIdentifierFields(data));\n}\n\n/**\n * Scrub Matrix-specific identifiers from URLs that appear in Sentry spans, breadcrumbs,\n * transaction names, and page URLs. Covers both Matrix API paths and client-side app routes.\n * Room IDs, user IDs, event IDs, media paths, and deep-link parameters are replaced with\n * safe placeholders so no PII leaks into Sentry.\n */\nexport function scrubMatrixUrl(url: string): string {\n  return (\n    scrubExternalHosts(url)\n      // ── Matrix Client-Server API paths ──────────────────────────────────────────────\n      // /rooms/!roomId:server/...\n      .replace(/\\/rooms\\/![^/?#\\s]*/g, '/rooms/![ROOM_ID]')\n      // /event/$eventId and /relations/$eventId\n      .replace(/\\/event\\/(?:\\$|%24)[^/?#\\s]*/g, '/event/$[EVENT_ID]')\n      .replace(/\\/relations\\/(?:\\$|%24)[^/?#\\s]*/g, '/relations/$[EVENT_ID]')\n      // /profile/@user:server  or  /profile/%40user%3Aserver\n      .replace(/\\/profile\\/(?:%40|@)[^/?#\\s]*/gi, '/profile/[USER_ID]')\n      // /user/@user:server/...  and  /presence/@user:server/status\n      .replace(/\\/(user|presence)\\/(?:%40|@)[^/?#\\s]*/gi, '/$1/[USER_ID]')\n      // /room_keys/keys/{version}/{roomId}/{sessionId}\n      .replace(/\\/room_keys\\/keys\\/[^/?#\\s]*/gi, '/room_keys/keys/[REDACTED]')\n      // /sendToDevice/{eventType}/{txnId}\n      .replace(/\\/sendToDevice\\/([^/?#\\s]+)\\/[^/?#\\s]+/gi, '/sendToDevice/$1/[TXN_ID]')\n      // Media – MSC3916 (/media/thumbnail|download/{server}/{mediaId}) and legacy (v1/v3)\n      .replace(\n        /(\\/media\\/(?:thumbnail|download)\\/)(?:[^/?#\\s]+)\\/(?:[^/?#\\s]+)/gi,\n        '$1[SERVER]/[MEDIA_ID]'\n      )\n      .replace(\n        /(\\/media\\/v\\d+\\/(?:thumbnail|download)\\/)(?:[^/?#\\s]+)\\/(?:[^/?#\\s]+)/gi,\n        '$1[SERVER]/[MEDIA_ID]'\n      )\n      // ── App route path segments ─────────────────────────────────────────────────────\n      // Bare/partially-decoded Matrix IDs in URL path segments.\n      // Browsers decode %21→! and %40→@ for display but often keep %3A encoded,\n      // so we see hybrid forms like /!localpart%3Aserver/ or /!localpart:server/.\n      // Each pattern accepts either a literal colon or the %3A encoding.\n      // Bare room IDs: /!localpart:server/ or /!localpart%3Aserver/\n      .replace(/\\/![^/?#\\s:%]+(?:%3A|:)[^/?#\\s]*/gi, '/![ROOM_ID]')\n      // Bare user IDs: /@user:server/ or /@user%3Aserver/\n      .replace(/\\/@[^/?#\\s:%]+(?:%3A|:)[^/?#\\s]*/gi, '/@[USER_ID]')\n      // Bare room aliases: /#alias:server/ or /#alias%3Aserver/\n      .replace(/\\/#[^/?#\\s:%]+(?:%3A|:)[^/?#\\s]*/gi, '/[ROOM_ALIAS]')\n      // ── Deep-link / app-route URLs (percent-encoded via encodeURIComponent) ─────────\n      // URL-encoded user IDs: /%40user%3Aserver  (%40 = @)\n      .replace(/\\/%40[^/?#\\s]*/gi, '/[USER_ID]')\n      // URL-encoded room IDs: /%21room%3Aserver  (%21 = !)\n      .replace(/\\/%21[^/?#\\s]*/gi, '/![ROOM_ID]')\n      // URL-encoded room aliases: /%23alias%3Aserver  (%23 = #)\n      // App routes like /:spaceIdOrAlias/ use encodeURIComponent() so #alias:server\n      // appears as %23alias%3Aserver in the URL path / Sentry transaction name.\n      .replace(/\\/%23[^/?#\\s]*/gi, '/[ROOM_ALIAS]')\n      // URL-encoded event IDs as bare path segments: /%24eventId  (%24 = $)\n      .replace(/\\/%24[^/?#\\s]*/gi, '/[EVENT_ID]')\n      //  Opaque Matrix IDs with percent-encoded colon (%3A)\n      // Catches device IDs, filter tokens, and other bare Matrix IDs that lack a sigil\n      // prefix but still follow the localpart%3Aserver pattern in URL paths.\n      // e.g. /Gj3Wy2D8gAi8jTIyR%3Asable.moe  (decoded: Gj3Wy2D8gAi8jTIyR:sable.moe)\n      .replace(/\\/[A-Za-z0-9+_-]{5,}%3A[A-Za-z0-9._-]+[^/?#\\s]*/gi, '/[MATRIX_ID]')\n      // ── Long opaque base64url path segments (access tokens, crypto keys, push tokens) ─\n      // Catches 30+ character base64url strings that appear as standalone path segments.\n      // These are typically Curve25519 keys, MSC3575 session tokens, or push endpoints.\n      // e.g. /vI02CuiDNpaYEhUIVLbqE8vdKqm2ZwqIR5Y6NwNY_Rg/\n      // Runs last so earlier patterns already replaced known Matrix IDs.\n      .replace(/\\/[A-Za-z0-9+_-]{30,}(\\/|$)/g, '/[REDACTED]$1')\n      // ── Preview URL endpoint ────────────────────────────────────────────────────────\n      // The ?url= query parameter on preview_url contains the full external URL being\n      // previewed — strip the entire query string so browsing habits cannot be inferred.\n      .replace(/(\\/preview_url)\\?[^#\\s]*/gi, '$1')\n      // ── Auth callback credentials ────────────────────────────────────────────────────\n      // OAuth code/state and the legacy SSO loginToken are single-use login credentials.\n      .replace(/([?&#](?:code|state|loginToken)=)[^&#\\s]+/gi, '$1[REDACTED]')\n  );\n}\n\ntype DiagnosticsJsonValue =\n  | null\n  | boolean\n  | number\n  | string\n  | DiagnosticsJsonObject\n  | DiagnosticsJsonValue[];\ntype DiagnosticsJsonObject = { [key: string]: DiagnosticsJsonValue };\n\nconst DIAGNOSTICS_REDACTED = '[REDACTED]';\nconst DIAGNOSTICS_REDACTED_CREDENTIAL = '[REDACTED_CREDENTIAL]';\nconst DIAGNOSTICS_REDACTED_MATRIX_ID = '[REDACTED_MATRIX_ID]';\nconst DIAGNOSTICS_REDACTED_PATH = '[REDACTED_PATH]';\nconst DIAGNOSTICS_REDACTED_URL = '[REDACTED_URL]';\n\nconst DIAGNOSTICS_SENSITIVE_KEY_PATTERN =\n  /(?:authorization|cookie|token|secret|password|passwd|credential|api[-_]?key)/i;\nconst DIAGNOSTICS_URL_PATTERN = /\\b[a-z][a-z0-9+.-]{1,15}:\\/\\/[^\\s<>\"']+/gi;\nconst DIAGNOSTICS_AUTH_PATTERN = /\\b(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst DIAGNOSTICS_SENSITIVE_VALUE_PATTERN =\n  /([\"']?(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|access[-_]?token|refresh[-_]?token|id[-_]?token|x[-_]?auth[-_]?token|x[-_]?access[-_]?token|api[-_]?key|client[-_]?secret|password|passwd|secret|credential|token)[\"']?\\s*[:=]\\s*)(?:\"[^\"]*\"|'[^']*'|[^\\s,;}\\]]+)/gi;\nconst DIAGNOSTICS_MATRIX_ID_PATTERN = /(?:[@!#$]\\S+?:\\S+|\\$\\S+?:\\S+)/g;\nconst DIAGNOSTICS_ABSOLUTE_PATH_PATTERN =\n  /(?:\\/(?:home|Users|tmp|var\\/tmp|private\\/tmp|var\\/folders)\\/[^\\s<>\"']+|[A-Za-z]:[\\\\/](?:Users|Temp|Windows[\\\\/]Temp)[^\\s<>\"']*)/g;\n\nconst redactDiagnosticsText = (text: string): string =>\n  text\n    .replace(DIAGNOSTICS_URL_PATTERN, DIAGNOSTICS_REDACTED_URL)\n    .replace(DIAGNOSTICS_AUTH_PATTERN, DIAGNOSTICS_REDACTED_CREDENTIAL)\n    .replace(DIAGNOSTICS_SENSITIVE_VALUE_PATTERN, `$1${DIAGNOSTICS_REDACTED}`)\n    .replace(DIAGNOSTICS_MATRIX_ID_PATTERN, DIAGNOSTICS_REDACTED_MATRIX_ID)\n    .replace(DIAGNOSTICS_ABSOLUTE_PATH_PATTERN, DIAGNOSTICS_REDACTED_PATH);\n\nconst sanitizeDiagnosticsHeaders = (value: DiagnosticsJsonValue): DiagnosticsJsonValue => {\n  if (Array.isArray(value)) {\n    return value.map((header) => {\n      if (Array.isArray(header) && header.length >= 2) {\n        return [\n          typeof header[0] === 'string' ? redactDiagnosticsText(header[0]) : 'header',\n          DIAGNOSTICS_REDACTED,\n        ];\n      }\n      return sanitizeDiagnosticsJsonValue(header) ?? null;\n    });\n  }\n  if (value !== null && typeof value === 'object') {\n    return Object.fromEntries(Object.keys(value).map((key) => [key, DIAGNOSTICS_REDACTED]));\n  }\n  return sanitizeDiagnosticsJsonValue(value) ?? null;\n};\n\nconst sanitizeDiagnosticsJsonValue = (\n  value: DiagnosticsJsonValue\n): DiagnosticsJsonValue | undefined => {\n  if (typeof value === 'string') return redactDiagnosticsText(value);\n  if (value === null || typeof value === 'boolean' || typeof value === 'number') return value;\n  if (Array.isArray(value))\n    return value.map(sanitizeDiagnosticsJsonValue).filter((item) => item !== undefined);\n\n  const sanitized: DiagnosticsJsonObject = {};\n  for (const [key, child] of Object.entries(value)) {\n    if (key.toLowerCase() === 'data') continue;\n    if (key.toLowerCase() === 'headers') {\n      sanitized[key] = sanitizeDiagnosticsHeaders(child);\n      continue;\n    }\n    if (DIAGNOSTICS_SENSITIVE_KEY_PATTERN.test(key)) {\n      sanitized[key] = DIAGNOSTICS_REDACTED;\n      continue;\n    }\n    const safeChild = sanitizeDiagnosticsJsonValue(child);\n    if (safeChild !== undefined) sanitized[key] = safeChild;\n  }\n  return sanitized;\n};\n\n/** Strict sanitizer for frontend diagnostics exports sent from the web client. */\nexport const sanitizeDiagnosticsLogs = (rawLogs: string): string | null => {\n  try {\n    const parsed: unknown = JSON.parse(rawLogs);\n    if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n    const sanitized = sanitizeDiagnosticsJsonValue(parsed as DiagnosticsJsonObject);\n    return sanitized === undefined ? null : JSON.stringify(sanitized, null, 2);\n  } catch {\n    return null;\n  }\n};\n","/**\n * Enhanced debug logger for Sable with circular buffer storage and categorization.\n *\n * Enable via Developer Tools UI or with:\n *   localStorage.setItem('sable_internal_debug', '1'); location.reload();\n */\n\nimport * as Sentry from '@sentry/react';\nimport { versionLabel } from '$utils/platform';\nimport { sanitizeDiagnosticsLogs, sanitizeSentryPayload } from './sentryScrubbers';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport type LogCategory =\n  | 'sync'\n  | 'network'\n  | 'notification'\n  | 'message'\n  | 'media'\n  | 'call'\n  | 'ui'\n  | 'timeline'\n  | 'error'\n  | 'general';\n\nexport interface LogEntry {\n  timestamp: number;\n  level: LogLevel;\n  category: LogCategory;\n  namespace: string;\n  message: string;\n  data?: unknown;\n}\n\ntype LogListener = (entry: LogEntry) => void;\n\nconst BREADCRUMB_DISABLED_KEY = 'sable_sentry_breadcrumb_disabled';\n\ntype ConsoleMethod = 'error' | 'warn' | 'info' | 'log' | 'debug';\n\nconst CONSOLE_METHODS: ConsoleMethod[] = ['error', 'warn', 'info', 'log', 'debug'];\n\nconst MAX_CONSOLE_MESSAGE_LENGTH = 1000;\n\nconst formatConsoleArgs = (args: unknown[]): string => {\n  const text = args\n    .map((arg) => {\n      if (typeof arg === 'string') return arg;\n      if (arg instanceof Error) return arg.stack ?? arg.message;\n      try {\n        return JSON.stringify(arg);\n      } catch {\n        return String(arg);\n      }\n    })\n    .join(' ');\n  return text.length > MAX_CONSOLE_MESSAGE_LENGTH\n    ? `${text.slice(0, MAX_CONSOLE_MESSAGE_LENGTH)}…`\n    : text;\n};\n\nclass DebugLoggerService {\n  private logs: LogEntry[] = [];\n\n  private maxLogs = 1000; // Circular buffer size\n\n  private enabled = false;\n\n  private captureActive = false;\n\n  private captureSince: number | undefined;\n\n  private listeners: Set<LogListener> = new Set();\n\n  private disabledBreadcrumbCategories: Set<LogCategory>;\n\n  private sentryStats = { errors: 0, warnings: 0 };\n\n  private originalConsole: Partial<Record<ConsoleMethod, (...args: unknown[]) => void>> = {};\n\n  private consoleIntercepted = false;\n\n  private writingToConsole = false;\n\n  constructor() {\n    // Check if debug logging is enabled from localStorage\n    this.enabled = localStorage.getItem('sable_internal_debug') === '1';\n    // Load disabled breadcrumb categories\n    try {\n      const stored = localStorage.getItem(BREADCRUMB_DISABLED_KEY);\n      this.disabledBreadcrumbCategories = new Set(\n        stored ? (JSON.parse(stored) as LogCategory[]) : []\n      );\n    } catch {\n      this.disabledBreadcrumbCategories = new Set();\n    }\n  }\n\n  public isEnabled(): boolean {\n    return this.enabled;\n  }\n\n  public setEnabled(enabled: boolean): void {\n    this.enabled = enabled;\n    if (enabled) {\n      localStorage.setItem('sable_internal_debug', '1');\n    } else {\n      localStorage.removeItem('sable_internal_debug');\n    }\n  }\n\n  public isCaptureActive(): boolean {\n    return this.captureActive;\n  }\n\n  public getCaptureSince(): number | undefined {\n    return this.captureSince;\n  }\n\n  public startCapture(): number {\n    this.clear();\n    this.captureActive = true;\n    this.captureSince = Date.now();\n    this.interceptConsole();\n    this.log('info', 'general', 'diagnostics', 'Diagnostic capture started');\n    return this.captureSince;\n  }\n\n  public stopCapture(): number | undefined {\n    if (!this.captureActive) return this.captureSince;\n    this.log('info', 'general', 'diagnostics', 'Diagnostic capture stopped');\n    this.captureActive = false;\n    this.restoreConsole();\n    return this.captureSince;\n  }\n\n  /**\n   * Funnels console output (including matrix-js-sdk's logger, which writes to the\n   * console) into the capture buffer for the duration of a diagnostics session.\n   */\n  private interceptConsole(): void {\n    if (this.consoleIntercepted) return;\n    this.consoleIntercepted = true;\n    CONSOLE_METHODS.forEach((method) => {\n      const original = console[method] as (...args: unknown[]) => void;\n      this.originalConsole[method] = original;\n      console[method] = (...args: unknown[]) => {\n        original.apply(console, args);\n        if (this.writingToConsole) return;\n        const level: LogLevel = method === 'log' ? 'debug' : method;\n        this.log(\n          level,\n          level === 'error' ? 'error' : 'general',\n          'console',\n          formatConsoleArgs(args)\n        );\n      };\n    });\n  }\n\n  private restoreConsole(): void {\n    if (!this.consoleIntercepted) return;\n    this.consoleIntercepted = false;\n    CONSOLE_METHODS.forEach((method) => {\n      const original = this.originalConsole[method];\n      if (original) console[method] = original;\n    });\n    this.originalConsole = {};\n  }\n\n  public addListener(listener: LogListener): () => void {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  private notifyListeners(entry: LogEntry): void {\n    this.listeners.forEach((listener) => {\n      try {\n        listener(entry);\n      } catch (error) {\n        // Silently catch listener errors to prevent debug logging from breaking the app\n        console.error('[DebugLogger] Listener error:', error);\n      }\n    });\n  }\n\n  public log(\n    level: LogLevel,\n    category: LogCategory,\n    namespace: string,\n    message: string,\n    data?: unknown\n  ): void {\n    const operationalCategory =\n      category === 'sync' ||\n      category === 'network' ||\n      category === 'notification' ||\n      category === 'media' ||\n      category === 'call' ||\n      category === 'error';\n    if (\n      !this.enabled &&\n      !this.captureActive &&\n      level !== 'error' &&\n      !(operationalCategory && level === 'warn')\n    )\n      return;\n\n    const rawEntry: LogEntry = {\n      timestamp: Date.now(),\n      level,\n      category,\n      namespace,\n      message,\n      data,\n    };\n    // Omit arbitrary data before serialization; it may be circular or contain BigInts.\n    const sanitized = sanitizeDiagnosticsLogs(\n      JSON.stringify({ logs: [{ ...rawEntry, data: undefined }] })\n    );\n    if (!sanitized) return;\n    const parsed = JSON.parse(sanitized) as { logs?: LogEntry[] };\n    const entry = parsed.logs?.[0];\n    if (!entry) return;\n    // Preserve the original Error for Sentry exception capture.\n    if (rawEntry.data instanceof Error) entry.data = rawEntry.data;\n\n    // Add to circular buffer\n    if (this.logs.length >= this.maxLogs) {\n      this.logs.shift(); // Remove oldest entry\n    }\n    this.logs.push(entry);\n\n    if (!this.enabled && level !== 'error') return;\n\n    // Notify listeners\n    this.notifyListeners(entry);\n\n    // Send to Sentry\n    this.sendToSentry(entry);\n\n    // Also log to console for developer convenience\n    const prefix = `[sable:${category}:${namespace}]`;\n    const consoleLevel = level === 'debug' ? 'log' : level;\n    this.writingToConsole = true;\n    try {\n      console[consoleLevel](prefix, message, data !== undefined ? data : '');\n    } finally {\n      this.writingToConsole = false;\n    }\n  }\n\n  public getBreadcrumbCategoryEnabled(category: LogCategory): boolean {\n    return !this.disabledBreadcrumbCategories.has(category);\n  }\n\n  public setBreadcrumbCategoryEnabled(category: LogCategory, enabled: boolean): void {\n    if (enabled) {\n      this.disabledBreadcrumbCategories.delete(category);\n    } else {\n      this.disabledBreadcrumbCategories.add(category);\n    }\n    const disabledArray = Array.from(this.disabledBreadcrumbCategories);\n    if (disabledArray.length > 0) {\n      localStorage.setItem(BREADCRUMB_DISABLED_KEY, JSON.stringify(disabledArray));\n    } else {\n      localStorage.removeItem(BREADCRUMB_DISABLED_KEY);\n    }\n  }\n\n  public getSentryStats(): { errors: number; warnings: number } {\n    return { ...this.sentryStats };\n  }\n\n  /**\n   * Send log entries to Sentry for error tracking and breadcrumbs\n   */\n  private sendToSentry(entry: LogEntry): void {\n    // Map log levels to Sentry severity\n    const sentryLevelMap: Record<string, Sentry.SeverityLevel> = {\n      debug: 'debug',\n      info: 'info',\n      warn: 'warning',\n      error: 'error',\n    };\n    const sentryLevel: Sentry.SeverityLevel = sentryLevelMap[entry.level] ?? 'error';\n\n    let sanitizedData: unknown;\n    if (entry.data !== undefined && !(entry.data instanceof Error)) {\n      try {\n        sanitizedData = sanitizeSentryPayload(entry.data);\n      } catch {\n        // Sentry data is best-effort and must not break logging.\n        sanitizedData = undefined;\n      }\n    }\n\n    // Add breadcrumb for all logs (helps with debugging in Sentry), unless category is disabled\n    if (!this.disabledBreadcrumbCategories.has(entry.category))\n      Sentry.addBreadcrumb({\n        category: `${entry.category}.${entry.namespace}`,\n        message: entry.message,\n        level: sentryLevel,\n        data:\n          sanitizedData !== undefined && sanitizedData !== null\n            ? { data: sanitizedData }\n            : undefined,\n        timestamp: entry.timestamp / 1000, // Sentry expects seconds\n      });\n\n    // Send as structured log to the Sentry Logs product (requires enableLogs: true)\n    const logMsg = `[${entry.category}:${entry.namespace}] ${entry.message}`;\n    // Flatten primitive values from entry.data so they become searchable attributes in Sentry Logs\n    const logDataAttrs: Record<string, string | number | boolean> = {};\n    if (sanitizedData && typeof sanitizedData === 'object' && !(sanitizedData instanceof Error)) {\n      Object.entries(sanitizedData as Record<string, unknown>).forEach(([k, v]) => {\n        if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n          logDataAttrs[k] = v;\n        }\n      });\n    }\n    const logAttrs = {\n      category: entry.category,\n      namespace: entry.namespace,\n      ...logDataAttrs,\n    };\n    if (entry.level === 'debug') Sentry.logger.debug(logMsg, logAttrs);\n    else if (entry.level === 'info') Sentry.logger.info(logMsg, logAttrs);\n    else if (entry.level === 'warn') Sentry.logger.warn(logMsg, logAttrs);\n    else Sentry.logger.error(logMsg, logAttrs);\n\n    // Track error/warn rates as metrics, tagged by category for filtering in Sentry dashboards\n    if (entry.level === 'error' || entry.level === 'warn') {\n      Sentry.metrics.count(`sable.${entry.level}s`, 1, {\n        attributes: { category: entry.category, namespace: entry.namespace },\n      });\n    }\n\n    // Capture errors and warnings as Sentry events\n    if (entry.level === 'error') {\n      this.sentryStats.errors += 1;\n      // If data is an Error object, capture it as an exception\n      if (entry.data instanceof Error) {\n        Sentry.captureException(entry.data, {\n          level: 'error',\n          tags: {\n            category: entry.category,\n            namespace: entry.namespace,\n          },\n          contexts: {\n            debugLog: {\n              message: entry.message,\n              timestamp: new Date(entry.timestamp).toISOString(),\n            },\n          },\n        });\n      } else {\n        // Otherwise capture as a message\n        Sentry.captureMessage(`[${entry.category}:${entry.namespace}] ${entry.message}`, {\n          level: 'error',\n          tags: {\n            category: entry.category,\n            namespace: entry.namespace,\n          },\n          contexts: {\n            debugLog: {\n              data: sanitizedData,\n              timestamp: new Date(entry.timestamp).toISOString(),\n            },\n          },\n        });\n      }\n    } else if (entry.level === 'warn' && Math.random() < 0.1) {\n      // Capture 10% of warnings to avoid overwhelming Sentry\n      this.sentryStats.warnings += 1;\n      Sentry.captureMessage(`[${entry.category}:${entry.namespace}] ${entry.message}`, {\n        level: 'warning',\n        tags: {\n          category: entry.category,\n          namespace: entry.namespace,\n        },\n        contexts: {\n          debugLog: {\n            data: sanitizedData,\n            timestamp: new Date(entry.timestamp).toISOString(),\n          },\n        },\n      });\n    }\n  }\n\n  public getLogs(): LogEntry[] {\n    return [...this.logs];\n  }\n\n  public getFilteredLogs(filters?: {\n    level?: LogLevel;\n    category?: LogCategory;\n    since?: number;\n  }): LogEntry[] {\n    let filtered = [...this.logs];\n\n    if (filters?.level) {\n      filtered = filtered.filter((log) => log.level === filters.level);\n    }\n\n    if (filters?.category) {\n      filtered = filtered.filter((log) => log.category === filters.category);\n    }\n\n    if (filters?.since) {\n      const { since } = filters;\n      filtered = filtered.filter((log) => log.timestamp >= since);\n    }\n\n    return filtered;\n  }\n\n  public clear(): void {\n    this.logs = [];\n  }\n\n  public exportLogs(options?: { since?: number }): string {\n    const logs = options?.since ? this.getFilteredLogs({ since: options.since }) : this.logs;\n    return JSON.stringify(\n      {\n        exportedAt: new Date().toISOString(),\n        build: versionLabel({ includeNightly: false }),\n        logsCount: logs.length,\n        logs: logs.map((log) => ({\n          ...log,\n          ...(log.data instanceof Error ? { data: undefined } : {}),\n          timestamp: new Date(log.timestamp).toISOString(),\n        })),\n      },\n      null,\n      2\n    );\n  }\n\n  /**\n   * Export logs in a format suitable for attaching to Sentry reports\n   */\n  public exportLogsForSentry(): Record<string, unknown>[] {\n    return this.logs.map((log) => ({\n      timestamp: new Date(log.timestamp).toISOString(),\n      level: log.level,\n      category: log.category,\n      namespace: log.namespace,\n      message: log.message,\n      data: log.data,\n    }));\n  }\n\n  /**\n   * Attach recent logs to the next Sentry event\n   * Useful for bug reports to include context\n   */\n  public attachLogsToSentry(limit = 100): void {\n    const recentLogs = this.logs.slice(-limit);\n    const logsData = recentLogs.map((log) => ({\n      time: new Date(log.timestamp).toISOString(),\n      level: log.level,\n      category: log.category,\n      namespace: log.namespace,\n      message: log.message,\n      // Only include data for errors/warnings to avoid excessive payload\n      ...(log.level === 'error' || log.level === 'warn' ? { data: log.data } : {}),\n    }));\n\n    // Add to context\n    Sentry.setContext('recentLogs', {\n      count: recentLogs.length,\n      logs: logsData,\n    });\n\n    // Also add as extra data for better visibility in Sentry UI\n    Sentry.getCurrentScope().setExtra('debugLogs', logsData);\n\n    const logsText = JSON.stringify(logsData, null, 2);\n    // Add as attachment for download\n    Sentry.getCurrentScope().addAttachment({\n      filename: 'debug-logs.json',\n      data: logsText,\n      contentType: 'application/json',\n    });\n  }\n}\n\n// Singleton instance\nconst debugLoggerService = new DebugLoggerService();\n\nexport const getDebugLogger = (): DebugLoggerService => debugLoggerService;\n\n/**\n * Creates a logger for a specific namespace\n */\nexport const createDebugLogger = (namespace: string) => ({\n  debug: (category: LogCategory, message: string, data?: unknown) =>\n    debugLoggerService.log('debug', category, namespace, message, data),\n  info: (category: LogCategory, message: string, data?: unknown) =>\n    debugLoggerService.log('info', category, namespace, message, data),\n  warn: (category: LogCategory, message: string, data?: unknown) =>\n    debugLoggerService.log('warn', category, namespace, message, data),\n  error: (category: LogCategory, message: string, data?: unknown) =>\n    debugLoggerService.log('error', category, namespace, message, data),\n});\n","import type { NotificationTab, StoredNotification } from '$utils/localNotifications';\n\nexport const NOTIFICATION_CACHE_KEY_PREFIX = 'sable.notificationCache.';\n\nconst CACHE_VERSION = 4;\nconst MAX_ENTRIES = 5_000;\n\ntype CacheData = {\n  version: number;\n  entries: StoredNotification[];\n  historyCutoffs?: Partial<Record<NotificationTab, number>>;\n};\n\nconst storageKeyFor = (userId: string): string =>\n  `${NOTIFICATION_CACHE_KEY_PREFIX}v${CACHE_VERSION}.${encodeURIComponent(userId)}`;\n\nconst emptyCache = (): CacheData => ({ version: CACHE_VERSION, entries: [] });\n\nconst readCache = (key: string): CacheData => {\n  try {\n    const value = globalThis.localStorage?.getItem(key);\n    if (!value) return emptyCache();\n    const data = JSON.parse(value) as Partial<CacheData>;\n    return data.version === CACHE_VERSION && Array.isArray(data.entries)\n      ? {\n          version: CACHE_VERSION,\n          entries: data.entries,\n          historyCutoffs: data.historyCutoffs,\n        }\n      : emptyCache();\n  } catch {\n    return emptyCache();\n  }\n};\n\nexport class LocalNotificationCache {\n  private data: CacheData;\n  private readonly key: string;\n  private readonly listeners = new Set<() => void>();\n\n  constructor(readonly userId: string) {\n    this.key = storageKeyFor(userId);\n    this.data = readCache(this.key);\n    globalThis.addEventListener?.('storage', this.onStorage);\n  }\n\n  merge(entry: StoredNotification): void {\n    this.mergeMany([entry]);\n  }\n\n  mergeMany(entries: StoredNotification[]): void {\n    if (entries.length === 0) return;\n    const merged = new Map(\n      [...this.data.entries, ...entries].map((entry) => [entry.event.event_id, entry])\n    );\n    this.data.entries = [...merged.values()].toSorted((a, b) => b.ts - a.ts).slice(0, MAX_ENTRIES);\n    this.write();\n    this.notify();\n  }\n\n  getEntries(): StoredNotification[] {\n    return this.data.entries.map((entry) => ({ ...entry }));\n  }\n\n  getHistoryCutoff(tab: NotificationTab): number | undefined {\n    return this.data.historyCutoffs?.[tab];\n  }\n\n  extendHistoryTo(tab: NotificationTab, timestamp: number): void {\n    const current = this.data.historyCutoffs?.[tab];\n    if (current !== undefined && timestamp >= current) return;\n    this.data.historyCutoffs = { ...this.data.historyCutoffs, [tab]: timestamp };\n    this.write();\n    this.notify();\n  }\n\n  subscribe(listener: () => void): () => void {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  destroy(): void {\n    globalThis.removeEventListener?.('storage', this.onStorage);\n    this.listeners.clear();\n  }\n\n  private write(): void {\n    let entries = this.data.entries;\n    for (;;) {\n      try {\n        globalThis.localStorage?.setItem(this.key, JSON.stringify({ ...this.data, entries }));\n        this.data.entries = entries;\n        return;\n      } catch {\n        if (entries.length === 0) return;\n        entries = entries.slice(0, Math.floor(entries.length / 2));\n      }\n    }\n  }\n\n  private notify(): void {\n    this.listeners.forEach((listener) => listener());\n  }\n\n  private onStorage = (event: StorageEvent): void => {\n    if (event.key !== this.key) return;\n    this.data = readCache(this.key);\n    this.notify();\n  };\n}\n\nconst instances = new Map<string, LocalNotificationCache>();\n\nexport const getLocalNotificationCache = (userId: string): LocalNotificationCache => {\n  const existing = instances.get(userId);\n  if (existing) return existing;\n  const cache = new LocalNotificationCache(userId);\n  instances.set(userId, cache);\n  return cache;\n};\n\nexport const destroyLocalNotificationCache = (userId: string): void => {\n  instances.get(userId)?.destroy();\n  instances.delete(userId);\n};\n\nexport const clearLocalNotificationCache = (userId: string): void => {\n  destroyLocalNotificationCache(userId);\n  try {\n    globalThis.localStorage?.removeItem(storageKeyFor(userId));\n  } catch {\n    // Storage may be disabled; logout should still finish.\n  }\n};\n","// event related unstable prefixes\n// don't import this file directly, import '$unstable/prefixes'\n\n/**\n * unstable prefix for blur hashes\n */\nexport const MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME = 'xyz.amorgan.blurhash';\n/**\n * unstable prefix for media spoilers\n * defined in MSC4193 https://github.com/matrix-org/matrix-spec-proposals/pull/4193\n */\nexport const MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME = 'page.codeberg.everypizza.msc4193.spoiler';\n/**\n * unstable prefix for media spoilers reasons\n * defined in MSC4193 https://github.com/matrix-org/matrix-spec-proposals/pull/4193\n */\nexport const MATRIX_UNSTABLE_SPOILER_REASON_PROPERTY_NAME =\n  'page.codeberg.everypizza.msc4193.spoiler.reason';\n/**\n * unstable prefix for image pack references\n * defined in MSC4459 https://github.com/matrix-org/matrix-spec-proposals/pull/4259\n */\nexport const MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME =\n  'com.beeper.msc4459.image_source_packs';\n/**\n * unstable prefix for per-message profiles\n * defined in MSC4144 https://github.com/matrix-org/matrix-spec-proposals/pull/4144\n */\nexport const MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME = 'com.beeper.per_message_profile';\n/**\n * unstable prefix for embedded link previews\n */\nexport const MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME = 'com.beeper.linkpreviews';\n\n/**\n * unstable prefix for message forwards meta\n * defined in MSC2723 https://github.com/matrix-org/matrix-spec-proposals/pull/2723\n */\nexport const MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME = 'com.famedly.app.forwarded';\n","// account data related unstable prefixes\n// don't import this file directly, import '$unstable/prefixes'\n// partly migrated from src/types/matrix/accountData.ts\n\n/**\n * @deprecated no longer part of MSC\n */\nexport const MATRIX_UNSTABLE_ACCOUNT_USER_EMOTES_PROPERTY_NAME = 'im.ponies.user_emotes';\n\nexport const MATRIX_ACCOUNT_EMOTE_ROOMS_PROPERTY_NAME = 'm.image_pack.rooms';\nexport const MATRIX_UNSTABLE_ACCOUNT_EMOTE_ROOMS_PROPERTY_NAME = 'im.ponies.emote_rooms';\n","// state event related unstable prefixes\n// don't import this file directly, import '$unstable/prefixes'\n\nexport const MATRIX_STATE_ROOM_IMAGE_PACK_PROPERTY_NAME = 'm.room.image_pack';\nexport const MATRIX_UNSTABLE_STATE_ROOM_EMOTES_PROPERTY_NAME = 'im.ponies.room_emotes';\n/**\n * unstable prefix for call rooms\n * defined in MSC3401 https://github.com/matrix-org/matrix-spec-proposals/pull/3401\n */\nexport const MATRIX_UNSTABLE_ROOM_TYPE_CALL_PROPERTY_NAME = 'org.matrix.msc3401.call';\n\nexport const MATRIX_UNSTABLE_ROOM_STYLING = 'eu.she-a.powerlevels_style';\n","// account data related unstable prefixes\n// don't import this file directly, import '$unstable/prefixes'\n// partly migrated from src/types/matrix/accountData.ts\n\nexport const MATRIX_SABLE_UNSTABLE_ACCOUNT_NICKNAMES_PROPERTY_NAME = 'moe.sable.app.nicknames';\nexport const MATRIX_SABLE_UNSTABLE_ACCOUNT_PIN_STATUS_PROPERTY_NAME =\n  'moe.sable.app.pins_read_marker';\nexport const MATRIX_SABLE_UNSTABLE_ACCOUNT_SETTINGS_PROPERTY_NAME = 'moe.sable.app.settings';\n/**\n * the prefix which is used to save used per message profiles to the account data\n */\nexport const MATRIX_SABLE_UNSTABLE_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME =\n  'fyi.cisnt.permessageprofile';\nexport const MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME_V2 =\n  'fi.mau.msc4461.per_message_profiles.v2';\nexport const MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME =\n  'fi.mau.msc4461.per_message_profiles.v3';\n\nexport const MATRIX_SABLE_UNSTABLE_DISMISSED_INVITES = 'moe.sable.dismissed_invites';\nexport const MATRIX_SABLE_UNSTABLE_ACCOUNT_ADDED_SERVERS_PROPERTY_NAME = 'moe.sable.added_servers';\nexport const MATRIX_SABLE_UNSTABLE_BOOKMARKS_INDEX_EVENT = 'pl.chrome.bookmarks.index';\nexport const MATRIX_SABLE_UNSTABLE_BOOKMARK_ITEM_EVENT_PREFIX = 'pl.chrome.bookmark.';\nexport const MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS = 'moe.sable.favorite_gifs';\n","/**\n * unstable prefix for profile banners\n */\nexport const MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME = 'chat.commet.profile_banner';\nexport const MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME =\n  'chat.commet.profile_color_scheme';\n/**\n * @deprecated\n */\nexport const MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME = 'chat.commet.profile_bio';\nexport const MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME = 'chat.commet.profile_status';\nexport const MATRIX_CINNY_UNSTABLE_ACCOUNT_SPACES_PROPERTY_NAME = 'in.cinny.spaces';\nexport const MATRIX_CINNY_UNSTABLE_STATE_ROOM_POWER_LEVELS_LABEL_PROPERTY_NAME =\n  'in.cinny.room.power_level_tags';\nexport const MATRIX_LEGACY_ELEMENT_UNSTABLE_ACCOUNT_RECENT_EMOJIS_PROPERTY_NAME =\n  'io.element.recent_emoji';\nexport const MATRIX_ACCOUNT_RECENT_EMOJIS_PROPERTY_NAME = 'm.recent_emoji';\nexport const MATRIX_ELEMENT_UNSTABLE_STATE_ROOM_WIDGET_PROPERTY_NAME = 'im.vector.modular.widgets';\n\nexport const MATRIX_UNSTABLE_STATE_ROOM_BANNER_PROPERTY_NAME =\n  'page.codeberg.everypizza.room.banner';\n","import * as prefix from '$unstable/prefixes';\n\nexport const CustomAccountDataEvent = {\n  CinnySpaces: prefix.MATRIX_CINNY_UNSTABLE_ACCOUNT_SPACES_PROPERTY_NAME,\n  LegacyElementRecentEmoji:\n    prefix.MATRIX_LEGACY_ELEMENT_UNSTABLE_ACCOUNT_RECENT_EMOJIS_PROPERTY_NAME,\n  RecentEmoji: prefix.MATRIX_ACCOUNT_RECENT_EMOJIS_PROPERTY_NAME,\n  ImagePackRooms: prefix.MATRIX_ACCOUNT_EMOTE_ROOMS_PROPERTY_NAME,\n  PoniesUserEmotes: prefix.MATRIX_UNSTABLE_ACCOUNT_USER_EMOTES_PROPERTY_NAME,\n  PoniesEmoteRooms: prefix.MATRIX_UNSTABLE_ACCOUNT_EMOTE_ROOMS_PROPERTY_NAME,\n  SableNicknames: prefix.MATRIX_SABLE_UNSTABLE_ACCOUNT_NICKNAMES_PROPERTY_NAME,\n  SablePinStatus: prefix.MATRIX_SABLE_UNSTABLE_ACCOUNT_PIN_STATUS_PROPERTY_NAME,\n  SablePerProfileMessageProfiles:\n    prefix.MATRIX_SABLE_UNSTABLE_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME,\n  SableSettings: prefix.MATRIX_SABLE_UNSTABLE_ACCOUNT_SETTINGS_PROPERTY_NAME,\n  SableDismissedInvites: prefix.MATRIX_SABLE_UNSTABLE_DISMISSED_INVITES,\n  SableAddedServers: prefix.MATRIX_SABLE_UNSTABLE_ACCOUNT_ADDED_SERVERS_PROPERTY_NAME,\n} as const;\nexport type CustomAccountDataEvent =\n  (typeof CustomAccountDataEvent)[keyof typeof CustomAccountDataEvent];\n\nexport type AddedServersContent = {\n  servers: string[];\n};\n\nexport type SecretStorageDefaultKeyContent = {\n  key: string;\n};\n\nexport type SecretStoragePassphraseContent = {\n  algorithm: string;\n  salt: string;\n  iterations: number;\n  bits?: number;\n};\n\nexport type SecretStorageKeyContent = {\n  name?: string;\n  algorithm: string;\n  iv?: string;\n  mac?: string;\n  passphrase?: SecretStoragePassphraseContent;\n};\n\nexport type SecretContent = {\n  iv: string;\n  ciphertext: string;\n  mac: string;\n};\n\n/**\n * type to save compatibility information\n */\nexport type AccountDataCompatVersion = {\n  /**\n   * a simple version number, for example 1\n   */\n  version: number;\n  /**\n   * the date where it was added\n   */\n  compatDate: string;\n  /**\n   * version number which is the oldest compatible, this attribute is optional\n   */\n  incompatBefore?: number;\n};\n\nexport type SecretAccountData = {\n  encrypted: Record<string, SecretContent>;\n};\n","import type { IImageInfo } from './common';\nimport * as prefix from '$unstable/prefixes';\nimport type { ColorSet } from '$hooks/useUserProfile';\n\nexport type IMemberContent = {\n  avatar_url?: string;\n  displayname?: string;\n  membership?: string;\n  reason?: string;\n  is_direct?: boolean;\n};\n\nexport const CustomStateEvent = {\n  ImagePack: prefix.MATRIX_STATE_ROOM_IMAGE_PACK_PROPERTY_NAME,\n  PoniesRoomEmotes: 'im.ponies.room_emotes',\n  PowerLevelTags: 'in.cinny.room.power_level_tags',\n  RoomWidget: 'im.vector.modular.widgets',\n  RoomCosmeticsColor: 'moe.sable.room.cosmetics.color',\n  RoomCosmeticsFont: 'moe.sable.room.cosmetics.font',\n  RoomCosmeticsPronouns: 'moe.sable.room.cosmetics.pronouns',\n  RoomAbbreviations: 'moe.sable.room.abbreviations',\n  RoomBanner: 'page.codeberg.everypizza.room.banner',\n} as const;\nexport type CustomStateEvent = (typeof CustomStateEvent)[keyof typeof CustomStateEvent];\n\nexport const CustomRoomType = {\n  Forum: 'pl.chrome.forum',\n} as const;\nexport type CustomRoomType = (typeof CustomRoomType)[keyof typeof CustomRoomType];\n\nexport type MSpaceChildContent = {\n  via: string[];\n  suggested?: boolean;\n  order?: string;\n};\n\nexport enum NotificationType {\n  Default = 'default',\n  AllMessages = 'all_messages',\n  MentionsAndKeywords = 'mentions_and_keywords',\n  Mute = 'mute',\n}\n\nexport type IRoomCreateContent = {\n  creator?: string;\n  ['m.federate']?: boolean;\n  room_version: string;\n  type?: string;\n  additional_creators?: string[];\n  predecessor?: {\n    event_id?: string;\n    room_id: string;\n  };\n};\n\nexport type GetContentCallback = () => unknown;\n\nexport type RoomToParents = Map<string, Set<string>>;\nexport type Unread = {\n  total: number;\n  highlight: number;\n  from: Set<string> | null;\n};\nexport type RoomToUnread = Map<string, Unread>;\nexport type UnreadInfo = {\n  roomId: string;\n  total: number;\n  highlight: number;\n  /** Count is a placeholder; read evidence is not loaded yet. */\n  estimated?: boolean;\n};\n\nexport type MemberPowerTagIcon = {\n  key?: string;\n  info?: IImageInfo;\n};\nexport type MemberPowerTag = {\n  name: string;\n  color?: string;\n  icon?: MemberPowerTagIcon;\n};\n\nexport type MemberPowerStyle = {\n  name: string;\n  color?: ColorSet;\n};\n","import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk';\nimport {\n  EventType,\n  KnownMembership,\n  MatrixEvent,\n  SlidingSyncEvent,\n  UNSTABLE_ELEMENT_FUNCTIONAL_USERS,\n} from '$types/matrix-sdk';\nimport { CustomAccountDataEvent } from '$types/matrix/accountData';\nimport { CustomStateEvent } from '$types/matrix/room';\n\nconst CACHE_VERSION = 1;\nexport const SIDEBAR_CACHE_KEY_PREFIX = 'sable.slidingSyncSidebarCache.';\nconst CACHE_WRITE_DELAY_MS = 500;\nconst MAX_CACHED_ROOMS = 2000;\nconst HYDRATION_BATCH_SIZE = 50;\n\ntype IdleWindow = Window &\n  typeof globalThis & {\n    requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;\n    cancelIdleCallback?: (handle: number) => void;\n  };\n\ntype StateEvent = MSC3575RoomData['required_state'][number];\n\ntype SidebarCacheData = {\n  version: number;\n  rooms: Record<string, MSC3575RoomData>;\n  accountData: Record<string, Record<string, unknown>>;\n};\n\nconst CACHED_ACCOUNT_DATA_TYPES = new Set<string>([\n  EventType.Direct,\n  CustomAccountDataEvent.CinnySpaces,\n]);\n\nconst CACHED_STATE_TYPES = new Set<string>([\n  EventType.RoomCreate,\n  EventType.RoomName,\n  EventType.RoomTopic,\n  EventType.RoomAvatar,\n  EventType.RoomCanonicalAlias,\n  EventType.RoomJoinRules,\n  EventType.RoomHistoryVisibility,\n  EventType.RoomGuestAccess,\n  EventType.RoomEncryption,\n  EventType.RoomTombstone,\n  EventType.RoomPowerLevels,\n  EventType.RoomPinnedEvents,\n  EventType.RoomServerAcl,\n  EventType.SpaceChild,\n  EventType.SpaceParent,\n  UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,\n  CustomStateEvent.PowerLevelTags,\n  CustomStateEvent.RoomWidget,\n  CustomStateEvent.RoomAbbreviations,\n  CustomStateEvent.RoomBanner,\n]);\n\nconst emptyCache = (): SidebarCacheData => ({\n  version: CACHE_VERSION,\n  rooms: {},\n  accountData: {},\n});\n\nconst stateEventKey = (event: StateEvent): string => `${event.type}\\u0000${event.state_key}`;\n\nconst mergeStateEvents = (\n  previous: StateEvent[] | undefined,\n  incoming: StateEvent[] | undefined,\n  userId: string\n): StateEvent[] => {\n  const merged = new Map<string, StateEvent>();\n  previous?.forEach((event) => merged.set(stateEventKey(event), event));\n  incoming?.forEach((event) => {\n    const cacheMember =\n      event.type === (EventType.RoomMember as string) && event.state_key === userId;\n    if (cacheMember || CACHED_STATE_TYPES.has(event.type)) {\n      merged.set(stateEventKey(event), event);\n    }\n  });\n  return [...merged.values()];\n};\n\nconst selfMembership = (events: StateEvent[] | undefined, userId: string): string | undefined => {\n  const event = events?.find(\n    (e) => e.type === (EventType.RoomMember as string) && e.state_key === userId\n  );\n  const content = event?.content;\n  return content && typeof content === 'object'\n    ? (content as { membership?: string }).membership\n    : undefined;\n};\n\n// The SDK derives an invite from invite_state and ignores required_state, so a\n// server that keeps sending invite_state after a join (Continuwuity) would\n// resurrect a stale invite. required_state membership is authoritative here.\nconst resolveInviteState = (\n  requiredState: StateEvent[] | undefined,\n  inviteState: StateEvent[] | undefined,\n  userId: string\n): StateEvent[] | undefined =>\n  selfMembership(requiredState, userId) === KnownMembership.Join ? undefined : inviteState;\n\nconst mergeRoomData = (\n  previous: MSC3575RoomData | undefined,\n  incoming: MSC3575RoomData,\n  userId: string\n): MSC3575RoomData => {\n  const required_state = mergeStateEvents(\n    previous?.required_state,\n    incoming.required_state,\n    userId\n  );\n  const invite_state = incoming.invite_state\n    ? mergeStateEvents(previous?.invite_state, incoming.invite_state, userId)\n    : previous?.invite_state;\n\n  return {\n    ...previous,\n    ...incoming,\n    name: incoming.name ?? previous?.name ?? '',\n    heroes: incoming.heroes ?? previous?.heroes,\n    notification_count: incoming.notification_count ?? previous?.notification_count,\n    highlight_count: incoming.highlight_count ?? previous?.highlight_count,\n    joined_count: incoming.joined_count ?? previous?.joined_count,\n    invited_count: incoming.invited_count ?? previous?.invited_count,\n    is_dm: incoming.is_dm ?? previous?.is_dm,\n    bump_stamp: incoming.bump_stamp ?? previous?.bump_stamp,\n    required_state,\n    invite_state: resolveInviteState(required_state, invite_state, userId),\n    timeline: [],\n    initial: true,\n    limited: false,\n    num_live: 0,\n    prev_batch: undefined,\n  };\n};\n\nconst parseCache = (value: string | null): SidebarCacheData => {\n  if (!value) return emptyCache();\n  try {\n    const parsed = JSON.parse(value) as Partial<SidebarCacheData>;\n    if (parsed.version !== CACHE_VERSION || !parsed.rooms || !parsed.accountData) {\n      return emptyCache();\n    }\n    return parsed as SidebarCacheData;\n  } catch {\n    return emptyCache();\n  }\n};\n\nconst hydrateRoomBatch = async (\n  slidingSync: SlidingSync,\n  rooms: [string, MSC3575RoomData][],\n  startIndex = 0\n): Promise<void> => {\n  const batch = rooms.slice(startIndex, startIndex + HYDRATION_BATCH_SIZE);\n  await Promise.all(\n    batch.map(([roomId, roomData]) =>\n      slidingSync.emitPromised(SlidingSyncEvent.RoomData, roomId, roomData)\n    )\n  );\n  if (startIndex + HYDRATION_BATCH_SIZE < rooms.length) {\n    await hydrateRoomBatch(slidingSync, rooms, startIndex + HYDRATION_BATCH_SIZE);\n  }\n};\n\nexport class SlidingSyncSidebarCache {\n  public static clear(userId: string): void {\n    try {\n      globalThis.localStorage?.removeItem(\n        `${SIDEBAR_CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`\n      );\n    } catch {\n      // Storage can be disabled for this origin.\n    }\n  }\n\n  private readonly storageKey: string;\n\n  private data: SidebarCacheData;\n\n  private writeTimer: ReturnType<typeof globalThis.setTimeout> | undefined;\n\n  private idleWriteHandle: number | undefined;\n\n  public constructor(private readonly userId: string) {\n    this.storageKey = `${SIDEBAR_CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`;\n    let stored: string | null = null;\n    try {\n      stored = globalThis.localStorage?.getItem(this.storageKey) ?? null;\n    } catch {\n      // Storage can be disabled for this origin.\n    }\n    this.data = parseCache(stored);\n  }\n\n  public cacheRoom(roomId: string, roomData: MSC3575RoomData): void {\n    this.data.rooms[roomId] = mergeRoomData(this.data.rooms[roomId], roomData, this.userId);\n    this.scheduleWrite();\n  }\n\n  public removeRoom(roomId: string): void {\n    if (!this.data.rooms[roomId]) return;\n    delete this.data.rooms[roomId];\n    this.scheduleWrite();\n  }\n\n  public reconcileRooms(validRoomIds: ReadonlySet<string>): string[] {\n    const removedRoomIds = Object.keys(this.data.rooms).filter(\n      (roomId) => !validRoomIds.has(roomId)\n    );\n    if (removedRoomIds.length === 0) return removedRoomIds;\n\n    removedRoomIds.forEach((roomId) => delete this.data.rooms[roomId]);\n    this.scheduleWrite();\n    return removedRoomIds;\n  }\n\n  // Backstop for rooms the server confirms joined but whose required_state still\n  // reads invite (e.g. joined on another client), which resolveInviteState misses.\n  public clearInviteStateForRooms(roomIds: readonly string[]): void {\n    let changed = false;\n    for (const roomId of roomIds) {\n      const room = this.data.rooms[roomId];\n      if (room?.invite_state !== undefined) {\n        room.invite_state = undefined;\n        changed = true;\n      }\n    }\n    if (changed) this.scheduleWrite();\n  }\n\n  // Heal a cache that persisted invite_state for a room required_state already\n  // shows as joined, so recovery happens offline on hydration.\n  private sanitizeInviteState(): void {\n    let changed = false;\n    for (const room of Object.values(this.data.rooms)) {\n      if (room.invite_state === undefined) continue;\n      if (resolveInviteState(room.required_state, room.invite_state, this.userId) === undefined) {\n        room.invite_state = undefined;\n        changed = true;\n      }\n    }\n    if (changed) this.scheduleWrite();\n  }\n\n  public cacheAccountData(event: MatrixEvent): void {\n    if (!CACHED_ACCOUNT_DATA_TYPES.has(event.getType())) return;\n    this.data.accountData[event.getType()] = event.getContent<Record<string, unknown>>();\n    this.scheduleWrite();\n  }\n\n  public async hydrate(mx: MatrixClient, slidingSync: SlidingSync): Promise<boolean> {\n    this.sanitizeInviteState();\n    const rooms = Object.entries(this.data.rooms);\n    const accountData = Object.entries(this.data.accountData);\n    if (rooms.length === 0 && accountData.length === 0) return false;\n\n    if (accountData.length > 0) {\n      mx.store.storeAccountDataEvents(\n        accountData.map(([type, content]) => new MatrixEvent({ type, content }))\n      );\n    }\n\n    await hydrateRoomBatch(slidingSync, rooms);\n    return rooms.length > 0;\n  }\n\n  public dispose(): void {\n    let shouldWrite = false;\n    if (this.writeTimer !== undefined) {\n      globalThis.clearTimeout(this.writeTimer);\n      this.writeTimer = undefined;\n      shouldWrite = true;\n    }\n    if (this.idleWriteHandle !== undefined) {\n      (globalThis as IdleWindow).cancelIdleCallback?.(this.idleWriteHandle);\n      this.idleWriteHandle = undefined;\n      shouldWrite = true;\n    }\n    if (shouldWrite) this.write();\n  }\n\n  private scheduleWrite(): void {\n    if (this.writeTimer !== undefined || this.idleWriteHandle !== undefined) return;\n    this.writeTimer = globalThis.setTimeout(() => {\n      this.writeTimer = undefined;\n      const idleWindow = globalThis as IdleWindow;\n      if (typeof idleWindow.requestIdleCallback === 'function') {\n        this.idleWriteHandle = idleWindow.requestIdleCallback(\n          () => {\n            this.idleWriteHandle = undefined;\n            this.write();\n          },\n          { timeout: 2000 }\n        );\n        return;\n      }\n      this.write();\n    }, CACHE_WRITE_DELAY_MS);\n  }\n\n  private write(): void {\n    let rooms = Object.entries(this.data.rooms)\n      .toSorted(([, a], [, b]) => (b.bump_stamp ?? 0) - (a.bump_stamp ?? 0))\n      .slice(0, MAX_CACHED_ROOMS);\n\n    while (true) {\n      const nextData = { ...this.data, rooms: Object.fromEntries(rooms) };\n      try {\n        globalThis.localStorage?.setItem(this.storageKey, JSON.stringify(nextData));\n        this.data = nextData;\n        return;\n      } catch {\n        if (rooms.length <= 1) return;\n        rooms = rooms.slice(0, Math.floor(rooms.length / 2));\n      }\n    }\n  }\n}\n","import { atom } from 'jotai';\nimport { NOTIFICATION_CACHE_KEY_PREFIX } from '$client/localNotificationCache';\nimport { SIDEBAR_CACHE_KEY_PREFIX } from '$client/slidingSyncSidebarCache';\n\nconst EVICTABLE_KEY_PREFIXES = [NOTIFICATION_CACHE_KEY_PREFIX, SIDEBAR_CACHE_KEY_PREFIX];\n\nexport const getLocalStorageItem = <T>(key: string, defaultValue: T): T => {\n  const item = localStorage.getItem(key);\n  if (item === null) return defaultValue;\n  if (item === 'undefined') return undefined as T;\n  try {\n    return JSON.parse(item) as T;\n  } catch {\n    return defaultValue;\n  }\n};\n\nexport const setLocalStorageItem = (key: string, value: unknown) => {\n  localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Losing a rotated token leaves an already-invalidated one on disk, which logs\n// the user out on next start. Evict non-essential caches and retry instead.\nexport const setEssentialLocalStorageItem = (key: string, value: unknown) => {\n  const serialized = JSON.stringify(value);\n  try {\n    localStorage.setItem(key, serialized);\n    return;\n  } catch {\n    for (const candidate of Object.keys(localStorage)) {\n      if (candidate !== key && EVICTABLE_KEY_PREFIXES.some((p) => candidate.startsWith(p))) {\n        localStorage.removeItem(candidate);\n      }\n    }\n  }\n  localStorage.setItem(key, serialized);\n};\n\nexport type GetLocalStorageItem<T> = (key: string) => T;\nexport type SetLocalStorageItem<T> = (key: string, value: T) => void;\n\nexport const atomWithLocalStorage = <T>(\n  key: string,\n  getItem: GetLocalStorageItem<T>,\n  setItem: SetLocalStorageItem<T>\n) => {\n  const value = getItem(key);\n\n  const baseAtom = atom(value);\n\n  baseAtom.onMount = (setAtom) => {\n    const handleChange = (evt: StorageEvent) => {\n      if (evt.key !== key) return;\n      setAtom(getItem(key));\n    };\n\n    window.addEventListener('storage', handleChange);\n    return () => {\n      window.removeEventListener('storage', handleChange);\n    };\n  };\n\n  const localStorageAtom = atom<T, [T | ((prev: T) => T)], undefined>(\n    (get) => get(baseAtom),\n    (get, set, newValue) => {\n      const resolved =\n        typeof newValue === 'function' ? (newValue as (prev: T) => T)(get(baseAtom)) : newValue;\n      set(baseAtom, resolved);\n      setItem(key, resolved);\n    }\n  );\n\n  return localStorageAtom;\n};\n","/**\n * Encrypt an attachment.\n * @param {ArrayBuffer} plaintextBuffer The attachment data buffer.\n * @return {Promise} A promise that resolves with an object when the attachment is encrypted.\n *      The object has a \"data\" key with an ArrayBuffer of encrypted data and an \"info\" key\n *      with an object containing the info needed to decrypt the data.\n */\nfunction encryptAttachment(plaintextBuffer) {\n    var cryptoKey; // The AES key object.\n    var exportedKey; // The AES key exported as JWK.\n    var ciphertextBuffer; // ArrayBuffer of encrypted data.\n    var sha256Buffer; // ArrayBuffer of digest.\n    var ivArray; // Uint8Array of AES IV\n    // Generate an IV where the first 8 bytes are random and the high 8 bytes\n    // are zero. We set the counter low bits to 0 since it makes it unlikely\n    // that the 64 bit counter will overflow.\n    ivArray = new Uint8Array(16);\n    window.crypto.getRandomValues(ivArray.subarray(0,8));\n    // Load the encryption key.\n    return window.crypto.subtle.generateKey(\n        {\"name\": \"AES-CTR\", length: 256}, true, [\"encrypt\", \"decrypt\"]\n    ).then(function(generateKeyResult) {\n        cryptoKey = generateKeyResult;\n        // Export the Key as JWK.\n        return window.crypto.subtle.exportKey(\"jwk\", cryptoKey);\n    }).then(function(exportKeyResult) {\n        exportedKey = exportKeyResult;\n        // Encrypt the input ArrayBuffer.\n        // Use half of the iv as the counter by setting the \"length\" to 64.\n        return window.crypto.subtle.encrypt(\n            {name: \"AES-CTR\", counter: ivArray, length: 64}, cryptoKey, plaintextBuffer\n        );\n    }).then(function(encryptResult) {\n        ciphertextBuffer = encryptResult;\n        // SHA-256 the encrypted data.\n        return window.crypto.subtle.digest(\"SHA-256\", ciphertextBuffer);\n    }).then(function (digestResult) {\n        sha256Buffer = digestResult;\n\n        return {\n            data: ciphertextBuffer,\n            info: {\n                v: \"v2\",\n                key: exportedKey,\n                iv: encodeBase64(ivArray),\n                hashes: {\n                    sha256: encodeBase64(new Uint8Array(sha256Buffer)),\n                },\n            },\n        };\n    });\n}\n\n/**\n * Decrypt an attachment.\n * @param {ArrayBuffer} ciphertextBuffer The encrypted attachment data buffer.\n * @param {Object} info The information needed to decrypt the attachment.\n * @param {Object} info.key AES-CTR JWK key object.\n * @param {string} info.iv Base64 encoded 16 byte AES-CTR IV.\n * @param {string} info.hashes.sha256 Base64 encoded SHA-256 hash of the ciphertext.\n * @return {Promise} A promise that resolves with an ArrayBuffer when the attachment is decrypted.\n */\nfunction decryptAttachment(ciphertextBuffer, info) {\n\n    if (info === undefined || info.key === undefined || info.iv === undefined\n        || info.hashes === undefined || info.hashes.sha256 === undefined) {\n       throw new Error(\"Invalid info. Missing info.key, info.iv or info.hashes.sha256 key\");\n    }\n\n    var cryptoKey; // The AES key object.\n    var ivArray = decodeBase64(info.iv);\n    var expectedSha256base64 = info.hashes.sha256;\n    // Load the AES from the \"key\" key of the info object.\n    return window.crypto.subtle.importKey(\n        \"jwk\", info.key, {\"name\": \"AES-CTR\"}, false, [\"encrypt\", \"decrypt\"]\n    ).then(function (importKeyResult) {\n        cryptoKey = importKeyResult;\n        // Check the sha256 hash\n        return window.crypto.subtle.digest(\"SHA-256\", ciphertextBuffer);\n    }).then(function (digestResult) {\n        if (encodeBase64(new Uint8Array(digestResult)) != expectedSha256base64) {\n            throw new Error(\"Mismatched SHA-256 digest\");\n        }\n        var counterLength;\n        if (info.v == \"v1\" || info.v == \"v2\") {\n            // Version 1 and 2 use a 64 bit counter.\n            counterLength = 64;\n        } else {\n            // Version 0 uses a 128 bit counter.\n            counterLength = 128;\n        }\n        return window.crypto.subtle.decrypt(\n            {name: \"AES-CTR\", counter: ivArray, length: counterLength}, cryptoKey, ciphertextBuffer\n        );\n    });\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param {Uint8Array} uint8Array The data to encode.\n * @return {string} The base64 without padding.\n */\nfunction encodeBase64(uint8Array) {\n    // Misinterpt the Uint8Array as Latin-1.\n    // window.btoa expects a unicode string with codepoints in the range 0-255.\n    var latin1String = String.fromCharCode.apply(null, uint8Array);\n    // Use the builtin base64 encoder.\n    var paddedBase64 = window.btoa(latin1String);\n    // Calculate the unpadded length.\n    var inputLength = uint8Array.length;\n    var outputLength = 4 * Math.floor((inputLength + 2) / 3) + (inputLength + 2) % 3 - 2;\n    // Return the unpadded base64.\n    return paddedBase64.slice(0, outputLength);\n}\n\n/**\n * Decode a base64 string to a typed array of uint8.\n * This will decode unpadded base64, but will also accept base64 with padding.\n * @param {string} base64 The unpadded base64 to decode.\n * @return {Uint8Array} The decoded data.\n */\nfunction decodeBase64(base64) {\n    // Pad the base64 up to the next multiple of 4.\n    var paddedBase64 = base64 + \"===\".slice(0, (4 - base64.length % 4) % 4);\n    // Decode the base64 as a misinterpreted Latin-1 string.\n    // window.atob returns a unicode string with codepoints in the range 0-255.\n    var latin1String = window.atob(paddedBase64);\n    // Encode the string as a Uint8Array as Latin-1.\n    var uint8Array = new Uint8Array(latin1String.length);\n    for (var i = 0; i < latin1String.length; i++) {\n        uint8Array[i] = latin1String.charCodeAt(i);\n    }\n    return uint8Array;\n}\n\ntry {\n    exports.encryptAttachment = encryptAttachment;\n    exports.decryptAttachment = decryptAttachment;\n}\ncatch (e) {\n    // Ignore unknown variable \"exports\" errors when this is loaded directly into a browser\n    // This means that we can test it without having to use browserify.\n    // The intention is that the library is used using browserify.\n}\n","/**\n * @param { Promise } promise\n * @param { Object= } errorExt - Additional Information you can pass to the err object\n * @return { Promise }\n */\nfunction to(promise, errorExt) {\n    return promise\n        .then(function (data) { return [null, data]; })\n        .catch(function (err) {\n        if (errorExt) {\n            Object.assign(err, errorExt);\n        }\n        return [err, undefined];\n    });\n}\n\nexport { to };\nexport default to;\n//# sourceMappingURL=await-to-js.es5.js.map\n","import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';\n\ntype Pending = { resolve: (value: unknown) => void; reject: (reason?: unknown) => void };\n\nlet worker: Worker | undefined;\nlet disabled = false;\nlet seq = 0;\nconst pending = new Map<number, Pending>();\n\nconst rejectAll = (reason: Error): void => {\n  for (const entry of pending.values()) entry.reject(reason);\n  pending.clear();\n};\n\nconst getWorker = (): Worker | undefined => {\n  if (disabled) return undefined;\n  if (worker) return worker;\n  if (typeof Worker === 'undefined') {\n    disabled = true;\n    return undefined;\n  }\n  try {\n    worker = new Worker(new URL('../workers/media.worker.ts', import.meta.url), { type: 'module' });\n  } catch {\n    disabled = true;\n    return undefined;\n  }\n  worker.addEventListener('message', (event: MessageEvent) => {\n    const { id, error, ...rest } = event.data as { id: number; error?: string };\n    const entry = pending.get(id);\n    if (!entry) return;\n    pending.delete(id);\n    if (error) entry.reject(new Error(error));\n    else entry.resolve(rest);\n  });\n  worker.addEventListener('error', () => {\n    rejectAll(new Error('media worker crashed'));\n    worker?.terminate();\n    worker = undefined;\n    disabled = true;\n  });\n  return worker;\n};\n\nconst call = <T>(message: object, transfer: Transferable[] = []): Promise<T> => {\n  const active = getWorker();\n  if (!active) return Promise.reject(new Error('media worker unavailable'));\n  const id = (seq += 1);\n  return new Promise<T>((resolve, reject) => {\n    pending.set(id, { resolve: resolve as (value: unknown) => void, reject });\n    active.postMessage({ id, ...message }, transfer);\n  });\n};\n\nexport const blurHashWorkerSupported = (): boolean =>\n  typeof Worker !== 'undefined' &&\n  typeof OffscreenCanvas !== 'undefined' &&\n  typeof createImageBitmap === 'function';\n\nexport const encryptBlobInWorker = (\n  file: Blob\n): Promise<{ blob: Blob; info: EncryptedAttachmentInfo }> =>\n  call<{ blob: Blob; info: EncryptedAttachmentInfo }>({ type: 'encrypt', file });\n\nexport const encodeBlurHashInWorker = (\n  bitmap: ImageBitmap,\n  width: number,\n  height: number\n): Promise<string | undefined> =>\n  call<{ hash: string | undefined }>({ type: 'blurhash', bitmap, width, height }, [bitmap]).then(\n    (result) => result.hash\n  );\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n    if (le)\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n    const len = lst.length;\n    let Ah = new Uint32Array(len);\n    let Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n    const h = fromNumH(n);\n    const l = fromNumL(n);\n    view.setUint32(byteOffset, isLE ? l : h, isLE);\n    view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n    // The fallback still requires a real ArrayBuffer view, so plain\n    // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n    // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n    return (a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) &&\n            a.constructor.name === 'Uint8Array' &&\n            'BYTES_PER_ELEMENT' in a &&\n            a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n    if (typeof n !== 'number')\n        throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n    if (!Number.isSafeInteger(n) || n < 0)\n        throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n    return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n    if (typeof value !== 'boolean')\n        throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n    return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n    // Success path first: this runs at the start of every update() / digestInto(), and the\n    // common `abytes(data)` form must not pay for length handling it does not use.\n    if (isBytes(value) && (length === undefined || value.length === length))\n        return value;\n    // Error path: recompute freely to build the exact message.\n    if (length !== undefined)\n        anumber(length, 'length');\n    const bytes = isBytes(value);\n    const ofLen = length !== undefined ? ` of length ${length}` : '';\n    const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n    const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n    if (!bytes)\n        throw new TypeError(message);\n    throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n    // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n    // because callers use it at byte-validation boundaries before mutating the detached copy.\n    return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n    if (typeof h !== 'function' || typeof h.create !== 'function')\n        throw new TypeError('expected hash wrapped by utils.createHasher');\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n    // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n    // validation and can produce empty outputs instead of failing fast.\n    if (h.outputLen < 1 || h.blockLen < 1)\n        throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n    if (value === null || typeof value !== 'object' || Array.isArray(value))\n        throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n    // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n    // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n    if (instance.destroyed)\n        throw new Error('hash was destroyed');\n    if (checkFinished && instance.finished)\n        throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n    abytes(out, undefined, 'output');\n    // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n    // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n    const min = instance.outputLen;\n    if (!(out.length >= min)) {\n        throw new RangeError('\"output\" expected length >= ' + min);\n    }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n    return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n    ? (n) => n\n    : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n *   On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n    ? (u) => u\n    : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n    return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n        : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n            : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n                : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new TypeError('hex string expected, got ' + typeof hex);\n    if (hasHexBuiltin) {\n        try {\n            return Uint8Array.fromHex(hex);\n        }\n        catch (error) {\n            if (error instanceof SyntaxError)\n                throw new RangeError(error.message);\n            throw error;\n        }\n    }\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n    }\n    return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async () => { };\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb) {\n    anumber(iters, 'iters');\n    anumber(tick, 'tick');\n    if (typeof cb !== 'function')\n        throw new TypeError('callback must be a function');\n    // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n    let ts = Date.now();\n    for (let i = 0; i < iters; i++) {\n        cb(i);\n        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n        const diff = Date.now() - ts;\n        if (diff >= 0 && diff < tick)\n            continue;\n        await nextTick();\n        // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n        ts += diff;\n    }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new TypeError('string expected');\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n    if (typeof data === 'string')\n        return utf8ToBytes(data);\n    return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n    aobject(object, title);\n    aobject(fields, 'fields');\n    aobject(optFields, 'optFields');\n    function checkField(fieldName, expectedType, isOpt) {\n        const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n        // Config fields must be explicit own properties. Optional inherited values are rejected too\n        // because callers keep reading the same options object after validation.\n        const val = object[fieldName];\n        // Runtime objects such as Field instances intentionally satisfy required method slots\n        // via their shared prototype.\n        if (!Object.hasOwn(object, fieldName) &&\n            (isOpt ? val !== undefined : expectedType !== 'function')) {\n            throw new TypeError(`${label} is invalid: expected own property`);\n        }\n        if (isOpt && val === undefined)\n            return;\n        const current = typeof val;\n        if (current !== expectedType || val === null)\n            throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n    }\n    const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n    iter(fields, false);\n    iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n    aobject(defaults, 'defaults');\n    if (opts !== undefined)\n        aobject(opts, title);\n    const merged = Object.assign(defaults, opts);\n    return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n *   Wrapper construction eagerly calls `hashCons(undefined)` once to read\n *   `outputLen` / `blockLen`, so constructor side effects happen at module\n *   init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n    if (typeof hashCons !== 'function')\n        throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n    info = checkOpts({}, info, 'info');\n    const hashC = (msg, opts) => hashCons(opts)\n        .update(msg)\n        .digest();\n    const tmp = hashCons(undefined);\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.canXOF = tmp.canXOF;\n    hashC.create = (opts) => hashCons(opts);\n    Object.assign(hashC, info);\n    return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n    // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n    anumber(bytesLength, 'bytesLength');\n    const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n    if (typeof cr?.getRandomValues !== 'function')\n        throw new Error('crypto.getRandomValues must be defined');\n    // Web Cryptography API Level 2 §10.1.1:\n    // if `byteLength > 65536`, throw `QuotaExceededError`.\n    // Keep the guard explicit so callers can see the quota in code\n    // instead of discovering it by reading the spec or host errors.\n    // This wrapper surfaces the same quota as a stable library RangeError.\n    if (bytesLength > 65536)\n        throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n    return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n *   The helper accepts any byte even though only the documented NIST hash\n *   suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n    // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n    // Larger suffix values would need base-128 OID encoding and a different length byte.\n    oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n    return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n    return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n    blockLen;\n    outputLen;\n    canXOF = false;\n    padOffset;\n    isLE;\n    // For partial updates less than block size\n    buffer;\n    view;\n    finished = false;\n    length = 0;\n    pos = 0;\n    destroyed = false;\n    constructor(blockLen, outputLen, padOffset, isLE) {\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.padOffset = padOffset;\n        this.isLE = isLE;\n        this.buffer = new Uint8Array(blockLen);\n        this.view = createView(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        const { view, buffer, blockLen } = this;\n        const len = data.length;\n        let processed = false;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path only when there is no buffered partial block: `take === blockLen` implies\n            // `this.pos === 0`, so we can process full blocks directly from the input view.\n            if (take === blockLen) {\n                const dataView = createView(data);\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(dataView, pos);\n                processed = true;\n                continue;\n            }\n            // When the whole input is buffered in one go (common for short messages), passing `data`\n            // directly avoids allocating a subarray view.\n            buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(view, 0);\n                this.pos = 0;\n                processed = true;\n            }\n        }\n        this.length += data.length;\n        // Shared schedule buffers only pick up input-derived words inside process(); if everything\n        // was buffered without processing, there is nothing to zero.\n        if (processed)\n            this.roundClean();\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        // Padding\n        // We can avoid allocation of buffer for padding completely if it\n        // was previously not allocated here. But it won't change performance.\n        const { buffer, view, blockLen, isLE } = this;\n        let { pos } = this;\n        // append the bit '1' to the message, then zero-pad the rest of the block\n        buffer[pos++] = 0b10000000;\n        buffer.fill(0, pos);\n        // we have less than padOffset left in buffer, so we cannot put length in\n        // current block, need process it and pad again\n        if (this.padOffset > blockLen - pos) {\n            this.process(view, 0);\n            buffer.fill(0);\n        }\n        // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n        // the padding fill above, and JS will overflow before user input can make that half non-zero.\n        // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n        // integer below 2**53, so the split inside the helper stays exact).\n        setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n        this.process(view, 0);\n        // The final block above is processed outside update(), so the shared message-schedule\n        // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n        this.roundClean();\n        // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n        const oview = out === buffer ? view : createView(out);\n        const len = this.outputLen;\n        // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n        const outLen = len / 4;\n        const state = this.get();\n        // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n        if (len % 4 || outLen > state.length)\n            throw new Error('invalid outputLen');\n        for (let i = 0; i < outLen; i++)\n            oview.setUint32(4 * i, state[i], isLE);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n        // fresh bytes to the caller.\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneIntoMeta(to) {\n        const { buffer, length, finished, destroyed, pos } = this;\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n        // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n        if (pos)\n            to.buffer.set(buffer); // Avoid a hot modulo guard.\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n    // We cannot use array here since array allows indexing by variable\n    // which means optimizer/compiler cannot use registers.\n    // Numeric initializers matter: starting the fields as `undefined` changes\n    // V8's field representation and makes sha256 3x slower (measured).\n    A = 0;\n    B = 0;\n    C = 0;\n    D = 0;\n    E = 0;\n    F = 0;\n    G = 0;\n    H = 0;\n    constructor(outputLen, IV) {\n        super(64, outputLen, 8, false);\n        this.A = IV[0] | 0;\n        this.B = IV[1] | 0;\n        this.C = IV[2] | 0;\n        this.D = IV[3] | 0;\n        this.E = IV[4] | 0;\n        this.F = IV[5] | 0;\n        this.G = IV[6] | 0;\n        this.H = IV[7] | 0;\n    }\n    get() {\n        const { A, B, C, D, E, F, G, H } = this;\n        return [A, B, C, D, E, F, G, H];\n    }\n    // prettier-ignore\n    set(A, B, C, D, E, F, G, H) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n        this.E = E | 0;\n        this.F = F | 0;\n        this.G = G | 0;\n        this.H = H | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4)\n            SHA256_W[i] = view.getUint32(offset, false);\n        for (let i = 16; i < 64; i++) {\n            const W15 = SHA256_W[i - 15];\n            const W2 = SHA256_W[i - 2];\n            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n        }\n        // Compression function main loop, 64 rounds\n        let { A, B, C, D, E, F, G, H } = this;\n        for (let i = 0; i < 64; i++) {\n            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n            const T2 = (sigma0 + Maj(A, B, C)) | 0;\n            H = G;\n            G = F;\n            F = E;\n            E = (D + T1) | 0;\n            D = C;\n            C = B;\n            B = A;\n            A = (T1 + T2) | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        E = (E + this.E) | 0;\n        F = (F + this.F) | 0;\n        G = (G + this.G) | 0;\n        H = (H + this.H) | 0;\n        this.set(A, B, C, D, E, F, G, H);\n    }\n    roundClean() {\n        clean(SHA256_W);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        this.set(0, 0, 0, 0, 0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n    constructor() {\n        super(32, SHA256_IV);\n    }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n    constructor() {\n        super(28, SHA224_IV);\n    }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n    // We cannot use array here since array allows indexing by variable\n    // which means optimizer/compiler cannot use registers.\n    // h -- high 32 bits, l -- low 32 bits\n    // Numeric initializers matter: starting the fields as `undefined` changes\n    // V8's field representation and slows hashing down (measured on sha256).\n    Ah = 0;\n    Al = 0;\n    Bh = 0;\n    Bl = 0;\n    Ch = 0;\n    Cl = 0;\n    Dh = 0;\n    Dl = 0;\n    Eh = 0;\n    El = 0;\n    Fh = 0;\n    Fl = 0;\n    Gh = 0;\n    Gl = 0;\n    Hh = 0;\n    Hl = 0;\n    constructor(outputLen, IV) {\n        super(128, outputLen, 16, false);\n        this.Ah = IV[0] | 0;\n        this.Al = IV[1] | 0;\n        this.Bh = IV[2] | 0;\n        this.Bl = IV[3] | 0;\n        this.Ch = IV[4] | 0;\n        this.Cl = IV[5] | 0;\n        this.Dh = IV[6] | 0;\n        this.Dl = IV[7] | 0;\n        this.Eh = IV[8] | 0;\n        this.El = IV[9] | 0;\n        this.Fh = IV[10] | 0;\n        this.Fl = IV[11] | 0;\n        this.Gh = IV[12] | 0;\n        this.Gl = IV[13] | 0;\n        this.Hh = IV[14] | 0;\n        this.Hl = IV[15] | 0;\n    }\n    // prettier-ignore\n    get() {\n        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n    }\n    // prettier-ignore\n    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n        this.Ah = Ah | 0;\n        this.Al = Al | 0;\n        this.Bh = Bh | 0;\n        this.Bl = Bl | 0;\n        this.Ch = Ch | 0;\n        this.Cl = Cl | 0;\n        this.Dh = Dh | 0;\n        this.Dl = Dl | 0;\n        this.Eh = Eh | 0;\n        this.El = El | 0;\n        this.Fh = Fh | 0;\n        this.Fl = Fl | 0;\n        this.Gh = Gh | 0;\n        this.Gl = Gl | 0;\n        this.Hh = Hh | 0;\n        this.Hl = Hl | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4) {\n            SHA512_W_H[i] = view.getUint32(offset);\n            SHA512_W_L[i] = view.getUint32((offset += 4));\n        }\n        for (let i = 16; i < 80; i++) {\n            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n            const W15h = SHA512_W_H[i - 15] | 0;\n            const W15l = SHA512_W_L[i - 15] | 0;\n            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n            const W2h = SHA512_W_H[i - 2] | 0;\n            const W2l = SHA512_W_L[i - 2] | 0;\n            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n            // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n            SHA512_W_H[i] = SUMh | 0;\n            SHA512_W_L[i] = SUMl | 0;\n        }\n        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        // Compression function main loop, 80 rounds\n        for (let i = 0; i < 80; i++) {\n            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n            const CHIl = (El & Fl) ^ (~El & Gl);\n            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n            // prettier-ignore\n            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n            const T1l = T1ll | 0;\n            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n            Hh = Gh | 0;\n            Hl = Gl | 0;\n            Gh = Fh | 0;\n            Gl = Fl | 0;\n            Fh = Eh | 0;\n            Fl = El | 0;\n            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n            Dh = Ch | 0;\n            Dl = Cl | 0;\n            Ch = Bh | 0;\n            Cl = Bl | 0;\n            Bh = Ah | 0;\n            Bl = Al | 0;\n            const All = u64.add3L(T1l, sigma0l, MAJl);\n            Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n            Al = All | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n    }\n    roundClean() {\n        clean(SHA512_W_H, SHA512_W_L);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        clean(this.buffer);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n    constructor() {\n        super(64, SHA512_IV);\n    }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n    constructor() {\n        super(48, SHA384_IV);\n    }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n    constructor() {\n        super(28, T224_IV);\n    }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n    constructor() {\n        super(32, T256_IV);\n    }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","import { sha256 } from '@noble/hashes/sha2.js';\nimport type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';\n\nconst CHUNK_SIZE = 4 * 1024 * 1024;\n\nconst encodeUnpaddedBase64 = (bytes: Uint8Array): string =>\n  btoa(String.fromCharCode(...bytes)).replace(/=+$/, '');\n\nconst counterForBlock = (nonce: Uint8Array, blockIndex: number): Uint8Array<ArrayBuffer> => {\n  const counter = new Uint8Array(16);\n  counter.set(nonce, 0);\n  const view = new DataView(counter.buffer);\n  view.setUint32(8, Math.floor(blockIndex / 2 ** 32));\n  view.setUint32(12, blockIndex >>> 0);\n  return counter;\n};\n\nexport const encryptAttachmentStreaming = async (\n  file: Blob\n): Promise<{ blob: Blob; info: EncryptedAttachmentInfo }> => {\n  const key = await crypto.subtle.generateKey({ name: 'AES-CTR', length: 256 }, true, [\n    'encrypt',\n    'decrypt',\n  ]);\n  const exportedKey = (await crypto.subtle.exportKey('jwk', key)) as EncryptedAttachmentInfo['key'];\n\n  const iv = new Uint8Array(16);\n  crypto.getRandomValues(iv.subarray(0, 8));\n  const nonce = iv.subarray(0, 8);\n\n  const hasher = sha256.create();\n  const parts: BlobPart[] = [];\n\n  for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {\n    // eslint-disable-next-line no-await-in-loop -- stream chunks to cap peak memory\n    const plainChunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();\n    const counter = counterForBlock(nonce, offset / 16);\n    // eslint-disable-next-line no-await-in-loop -- stream chunks to cap peak memory\n    const cipherChunk = await crypto.subtle.encrypt(\n      { name: 'AES-CTR', counter, length: 64 },\n      key,\n      plainChunk\n    );\n    const bytes = new Uint8Array(cipherChunk);\n    hasher.update(bytes);\n    parts.push(new Blob([bytes]));\n  }\n\n  const info: EncryptedAttachmentInfo = {\n    v: 'v2',\n    key: exportedKey,\n    iv: encodeUnpaddedBase64(iv),\n    hashes: { sha256: encodeUnpaddedBase64(hasher.digest()) },\n  };\n\n  return { blob: new Blob(parts, { type: file.type }), info };\n};\n","import type { MatrixClient } from '$types/matrix-sdk';\n\nexport type SortFunc<T> = (a: T, b: T) => number;\n\nconst getRoomActivity = (mx: MatrixClient, roomId: string): number => {\n  const room = mx.getRoom(roomId);\n  if (!room) return Number.MIN_SAFE_INTEGER;\n  const timelineTimestamp = room.getLastActiveTimestamp();\n  return timelineTimestamp === Number.MIN_SAFE_INTEGER\n    ? (room.getBumpStamp() ?? Number.MIN_SAFE_INTEGER)\n    : timelineTimestamp;\n};\n\nexport const factoryRoomIdByActivity =\n  (mx: MatrixClient): SortFunc<string> =>\n  (a, b) => {\n    return getRoomActivity(mx, b) - getRoomActivity(mx, a);\n  };\n\nexport const factoryRoomIdByAtoZ =\n  (mx: MatrixClient): SortFunc<string> =>\n  (a, b) => {\n    let aName = mx.getRoom(a)?.name ?? '';\n    let bName = mx.getRoom(b)?.name ?? '';\n\n    // remove \"#\" from the room name\n    // To ignore it in sorting\n    aName = aName.replace(/#/g, '');\n    bName = bName.replace(/#/g, '');\n\n    if (aName.toLowerCase() < bName.toLowerCase()) {\n      return -1;\n    }\n    if (aName.toLowerCase() > bName.toLowerCase()) {\n      return 1;\n    }\n    return 0;\n  };\n\nexport const factoryRoomIdByUnreadCount =\n  (getUnreadCount: (roomId: string) => number): SortFunc<string> =>\n  (a, b) => {\n    const aT = getUnreadCount(a) ?? 0;\n    const bT = getUnreadCount(b) ?? 0;\n    return bT - aT;\n  };\n\nexport const byTsOldToNew: SortFunc<number> = (a, b) => a - b;\n\nexport const byOrderKey: SortFunc<string | undefined> = (a, b) => {\n  if (!a && !b) {\n    return 0;\n  }\n\n  if (!b) return -1;\n  if (!a) return 1;\n\n  if (a < b) {\n    return -1;\n  }\n  if (a > b) {\n    return 1;\n  }\n  return 0;\n};\n","import type {\n  EventTimelineSet,\n  EventTimeline,\n  IMentions,\n  IThreadBundledRelationship,\n  MatrixClient,\n  MatrixEvent,\n  Room,\n} from '$types/matrix-sdk';\nimport { EventType, KnownMembership, MsgType, RelationType } from '$types/matrix-sdk';\n\n// Local copy to avoid circular dependency with display.ts (which imports from $utils/matrix)\nconst trimReplyFromBodyLocal = (body: string): string => {\n  const match = body.match(/^> <.+?> .+\\n(>.*\\n)*?\\n/m);\n  if (!match) return body;\n  return body.slice(match[0].length);\n};\n\nexport const isMembershipChanged = (mEvent: MatrixEvent): boolean =>\n  mEvent.getContent().membership !== mEvent.getPrevContent().membership ||\n  mEvent.getContent().reason !== mEvent.getPrevContent().reason;\n\nexport const getEventReactions = (timelineSet: EventTimelineSet, eventId: string) =>\n  timelineSet.relations.getChildEventsForEvent(\n    eventId,\n    RelationType.Annotation,\n    EventType.Reaction\n  );\n\nexport const getEventEdits = (timelineSet: EventTimelineSet, eventId: string, eventType: string) =>\n  timelineSet.relations.getChildEventsForEvent(eventId, RelationType.Replace, eventType);\n\nconst getLatestEdit = (\n  targetEvent: MatrixEvent,\n  editEvents: MatrixEvent[]\n): MatrixEvent | undefined => {\n  const eventByTargetSender = (rEvent: MatrixEvent) =>\n    rEvent.getSender() === targetEvent.getSender();\n  return editEvents.toSorted((m1, m2) => m2.getTs() - m1.getTs()).find(eventByTargetSender);\n};\n\nexport const getEditedEvent = (\n  mEventId: string,\n  mEvent: MatrixEvent,\n  timelineSet: EventTimelineSet\n): MatrixEvent | undefined => {\n  const edits = getEventEdits(timelineSet, mEventId, mEvent.getType());\n  return edits && getLatestEdit(mEvent, edits.getRelations());\n};\n\nexport const isEditEvent = (mEvent: MatrixEvent): boolean => {\n  const relType = mEvent.getRelation()?.rel_type;\n  if (relType === (RelationType.Replace as string)) return true;\n  if (mEvent.getContent()['m.new_content'] !== undefined) return true;\n  return false;\n};\n\nexport const isReactionEvent = (mEvent: MatrixEvent): boolean =>\n  mEvent.getType() === (EventType.Reaction as string);\n\nconst FORWARDABLE_EVENT_TYPES = new Set<string>([\n  EventType.RoomMessage as string,\n  EventType.RoomMessageEncrypted as string,\n  EventType.Sticker as string,\n]);\n\nexport const canForwardEvent = (mEvent: MatrixEvent): boolean => {\n  if (mEvent.isRedacted()) return false;\n  if (isEditEvent(mEvent)) return false;\n  if (mEvent.getType() === (EventType.RoomRedaction as string)) return false;\n  if (isReactionEvent(mEvent)) return false;\n  if (typeof mEvent.getStateKey() === 'string') return false;\n  if (mEvent.isRedaction()) return false;\n  return FORWARDABLE_EVENT_TYPES.has(mEvent.getType());\n};\n\nexport const getReactionKey = (mEvent: MatrixEvent): string | undefined => {\n  const key = mEvent.getRelation()?.key;\n  if (typeof key === 'string' && key.length > 0) return key;\n\n  const contentRelatesTo = mEvent.getContent()['m.relates_to'] as { key?: string } | undefined;\n  if (typeof contentRelatesTo?.key === 'string' && contentRelatesTo.key.length > 0) {\n    return contentRelatesTo.key;\n  }\n\n  const originalRelatesTo = mEvent.getOriginalContent?.()?.['m.relates_to'] as\n    | { key?: string }\n    | undefined;\n  if (typeof originalRelatesTo?.key === 'string' && originalRelatesTo.key.length > 0) {\n    return originalRelatesTo.key;\n  }\n\n  return undefined;\n};\n\nconst readReactionShortcode = (\n  content: Record<string, unknown> | undefined\n): string | undefined => {\n  if (!content) return undefined;\n  const shortcode = content.shortcode ?? content['com.beeper.reaction.shortcode'];\n  return typeof shortcode === 'string' && shortcode.length > 0 ? shortcode : undefined;\n};\n\nexport const getReactionShortcode = (mEvent: MatrixEvent): string | undefined =>\n  readReactionShortcode(mEvent.getContent()) ??\n  readReactionShortcode(mEvent.getOriginalContent?.());\n\nexport const getReactionAnnotationTargetId = (reactionEvent: MatrixEvent): string | undefined => {\n  const eventId = reactionEvent.getRelation()?.event_id;\n  if (typeof eventId === 'string' && eventId.length > 0) return eventId;\n\n  const contentRelatesTo = reactionEvent.getContent()['m.relates_to'] as\n    | { event_id?: string }\n    | undefined;\n  if (typeof contentRelatesTo?.event_id === 'string' && contentRelatesTo.event_id.length > 0) {\n    return contentRelatesTo.event_id;\n  }\n\n  const originalRelatesTo = reactionEvent.getOriginalContent?.()?.['m.relates_to'] as\n    | { event_id?: string }\n    | undefined;\n  if (typeof originalRelatesTo?.event_id === 'string' && originalRelatesTo.event_id.length > 0) {\n    return originalRelatesTo.event_id;\n  }\n\n  return undefined;\n};\n\nexport const getRedactionReason = (mEvent: MatrixEvent): string | undefined => {\n  const reason = mEvent.getUnsigned()?.redacted_because?.content?.reason;\n  return typeof reason === 'string' && reason.length > 0 ? reason : undefined;\n};\n\nexport const collectRelationReactionEvents = (\n  linkedTimelines: EventTimeline[],\n  existingIds: ReadonlySet<string>,\n  ignoredUsersSet: Set<string>,\n  showReactions: boolean,\n  showReactionTombstones: boolean\n): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => {\n  if (!showReactions && !showReactionTombstones) return [];\n\n  const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = [];\n  const seen = new Set(existingIds);\n\n  for (const timeline of linkedTimelines) {\n    const timelineSet = timeline.getTimelineSet();\n    for (const parent of timeline.getEvents()) {\n      const parentId = parent.getId();\n      if (!parentId) continue;\n\n      const reactions = getEventReactions(timelineSet, parentId);\n      if (!reactions) continue;\n\n      for (const reaction of reactions.getRelations()) {\n        const reactionId = reaction.getId();\n        if (!reactionId || seen.has(reactionId)) continue;\n        seen.add(reactionId);\n\n        const sender = reaction.getSender();\n        if (sender && ignoredUsersSet.has(sender)) continue;\n\n        const redacted = reaction.isRedacted();\n        if (redacted && !showReactionTombstones) continue;\n        if (!redacted && !showReactions) continue;\n\n        extras.push({ mEvent: reaction, timelineSet, parentId });\n      }\n    }\n  }\n\n  return extras;\n};\n\nexport const collectRelationEditEvents = (\n  linkedTimelines: EventTimeline[],\n  existingIds: ReadonlySet<string>,\n  ignoredUsersSet: Set<string>,\n  showEdits: boolean\n): { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] => {\n  if (!showEdits) return [];\n\n  const extras: { mEvent: MatrixEvent; timelineSet: EventTimelineSet; parentId: string }[] = [];\n  const seen = new Set(existingIds);\n\n  for (const timeline of linkedTimelines) {\n    const timelineSet = timeline.getTimelineSet();\n    for (const parent of timeline.getEvents()) {\n      const parentId = parent.getId();\n      if (!parentId || isEditEvent(parent)) continue;\n\n      const edits = getEventEdits(timelineSet, parentId, parent.getType());\n      if (!edits) continue;\n\n      for (const editEvent of edits.getRelations()) {\n        const editId = editEvent.getId();\n        if (!editId || seen.has(editId)) continue;\n        seen.add(editId);\n\n        const sender = editEvent.getSender();\n        if (sender && ignoredUsersSet.has(sender)) continue;\n\n        extras.push({ mEvent: editEvent, timelineSet, parentId });\n      }\n    }\n  }\n\n  return extras;\n};\n\nexport const isRedactableMessageType = (type: string): boolean =>\n  type === (EventType.RoomMessage as string) ||\n  type === (EventType.RoomMessageEncrypted as string) ||\n  type === (EventType.Sticker as string);\n\nexport const getRedactionTargetId = (redactionEvent: MatrixEvent): string | undefined => {\n  const redacts = redactionEvent.event?.redacts;\n  if (typeof redacts === 'string') return redacts;\n  const associated = redactionEvent.getAssociatedId?.();\n  return typeof associated === 'string' ? associated : undefined;\n};\n\nexport const getRedactionTargetEvent = (\n  timelineSet: EventTimelineSet,\n  redactionEvent: MatrixEvent\n): MatrixEvent | undefined => {\n  const targetId = getRedactionTargetId(redactionEvent);\n  if (!targetId) return undefined;\n  return timelineSet.findEventById(targetId);\n};\n\nexport const shouldShowRedactionTimelineEvent = (\n  mEvent: MatrixEvent,\n  timelineSet: EventTimelineSet,\n  hiddenEventRedactionTimeline: boolean,\n  hiddenEventReactionRedactionTimeline: boolean\n): boolean => {\n  if (!mEvent.isRedaction()) return false;\n  const target = getRedactionTargetEvent(timelineSet, mEvent);\n  if (target?.getType() === (EventType.Reaction as string)) {\n    return hiddenEventReactionRedactionTimeline;\n  }\n  return hiddenEventRedactionTimeline;\n};\n\nconst readReplaceTargetId = (\n  relatesTo: { rel_type?: string; event_id?: string } | undefined\n): string | undefined => {\n  if (relatesTo?.rel_type !== (RelationType.Replace as string)) return undefined;\n  const eventId = relatesTo.event_id;\n  return typeof eventId === 'string' && eventId.length > 0 ? eventId : undefined;\n};\n\nexport const getEditTargetId = (editEvent: MatrixEvent): string | undefined => {\n  const relationEventId = editEvent.getRelation()?.event_id;\n  if (typeof relationEventId === 'string' && relationEventId.length > 0) {\n    return relationEventId;\n  }\n\n  const content = editEvent.getContent();\n  const fromContent = readReplaceTargetId(\n    content['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined\n  );\n  if (fromContent) return fromContent;\n\n  const wireContent = editEvent.getWireContent?.() as Record<string, unknown> | undefined;\n  const fromWire = readReplaceTargetId(\n    wireContent?.['m.relates_to'] as { rel_type?: string; event_id?: string } | undefined\n  );\n  if (fromWire) return fromWire;\n\n  return readReplaceTargetId(\n    editEvent.getOriginalContent?.()?.['m.relates_to'] as\n      | { rel_type?: string; event_id?: string }\n      | undefined\n  );\n};\n\nexport const getEditChain = (\n  timelineSet: EventTimelineSet,\n  eventId: string,\n  eventType: string,\n  room?: Room\n): { original: MatrixEvent; edits: MatrixEvent[] } | undefined => {\n  let original = timelineSet.findEventById(eventId);\n  if (!original && room) {\n    original = room.findEventById(eventId) ?? undefined;\n  }\n  if (!original) return undefined;\n\n  const editsRelation = getEventEdits(timelineSet, eventId, original.getType() ?? eventType);\n  const edits = editsRelation\n    ? [...editsRelation.getRelations()].toSorted((a, b) => a.getTs() - b.getTs())\n    : [];\n  return { original, edits };\n};\n\nconst getEditChainEvents = (\n  currentEditEvent: MatrixEvent,\n  chain: { original: MatrixEvent; edits: MatrixEvent[] }\n): MatrixEvent[] => {\n  const currentId = currentEditEvent.getId();\n  const edits =\n    currentId && !chain.edits.some((editEvent) => editEvent.getId() === currentId)\n      ? [...chain.edits, currentEditEvent].toSorted((a, b) => a.getTs() - b.getTs())\n      : chain.edits;\n  return [chain.original, ...edits];\n};\n\nexport const getPreviousEditId = (\n  currentEditEvent: MatrixEvent,\n  chain: { original: MatrixEvent; edits: MatrixEvent[] }\n): string | undefined => {\n  const currentId = currentEditEvent.getId();\n  if (!currentId) return undefined;\n\n  const allEvents = getEditChainEvents(currentEditEvent, chain);\n  const idx = allEvents.findIndex((e) => e.getId() === currentId);\n  if (idx <= 0) return undefined;\n  return allEvents[idx - 1]?.getId();\n};\n\nconst getPreviousEditEvent = (\n  currentEditEvent: MatrixEvent,\n  chain: { original: MatrixEvent; edits: MatrixEvent[] }\n): MatrixEvent | undefined => {\n  const currentId = currentEditEvent.getId();\n  if (!currentId) return undefined;\n\n  const allEvents = getEditChainEvents(currentEditEvent, chain);\n  const idx = allEvents.findIndex((e) => e.getId() === currentId);\n  if (idx <= 0) return undefined;\n  return allEvents[idx - 1];\n};\n\nconst EDIT_DIFF_MSGTYPES = new Set<string>([MsgType.Text, MsgType.Emote, MsgType.Notice]);\n\nconst getMessageVersionBody = (mEvent: MatrixEvent): string | undefined => {\n  const content = mEvent.getContent();\n  const wireContent = mEvent.getWireContent?.() as Record<string, unknown> | undefined;\n\n  let versionContent: Record<string, unknown> | undefined;\n  if (isEditEvent(mEvent)) {\n    versionContent =\n      (content['m.new_content'] as Record<string, unknown> | undefined) ??\n      (wireContent?.['m.new_content'] as Record<string, unknown> | undefined);\n  } else {\n    versionContent =\n      (mEvent.getOriginalContent?.() as Record<string, unknown> | undefined) ??\n      (content as Record<string, unknown>);\n  }\n\n  const fallbackContent =\n    (!versionContent || typeof versionContent.body !== 'string') && mEvent.getOriginalContent?.()\n      ? (mEvent.getOriginalContent?.() as Record<string, unknown>)\n      : undefined;\n  const resolvedContent =\n    versionContent && typeof versionContent === 'object' ? versionContent : fallbackContent;\n  if (!resolvedContent || typeof resolvedContent !== 'object') return undefined;\n\n  const msgtype = resolvedContent.msgtype;\n  if (typeof msgtype === 'string' && !EDIT_DIFF_MSGTYPES.has(msgtype)) {\n    return undefined;\n  }\n\n  const body = resolvedContent.body;\n  return typeof body === 'string' ? trimReplyFromBodyLocal(body) : undefined;\n};\n\nexport const getEditDiffBodies = (\n  editEvent: MatrixEvent,\n  timelineSet: EventTimelineSet,\n  room?: Room\n): { oldBody?: string; newBody?: string } => {\n  const newBody = getMessageVersionBody(editEvent);\n  const editTargetId = getEditTargetId(editEvent);\n  if (!editTargetId) {\n    return { newBody };\n  }\n\n  const chain = getEditChain(timelineSet, editTargetId, editEvent.getType(), room);\n  let previousEvent = chain ? getPreviousEditEvent(editEvent, chain) : undefined;\n  if (!previousEvent) {\n    previousEvent =\n      chain?.original ??\n      timelineSet.findEventById(editTargetId) ??\n      room?.findEventById(editTargetId);\n  }\n\n  const oldBody =\n    previousEvent && previousEvent.getId() !== editEvent.getId()\n      ? getMessageVersionBody(previousEvent)\n      : undefined;\n\n  return { oldBody, newBody };\n};\n\nexport const canEditEvent = (mx: MatrixClient, mEvent: MatrixEvent) => {\n  const content = mEvent.getContent();\n  const relationType = content['m.relates_to']?.rel_type;\n  return (\n    mEvent.getSender() === mx.getUserId() &&\n    mEvent.getType() === (EventType.RoomMessage as string) &&\n    (!relationType || relationType === (RelationType.Thread as string)) &&\n    (content.msgtype === MsgType.Text ||\n      content.msgtype === MsgType.Emote ||\n      content.msgtype === MsgType.Notice ||\n      content.msgtype === MsgType.Image ||\n      content.msgtype === MsgType.Video ||\n      content.msgtype === MsgType.Audio ||\n      content.msgtype === MsgType.File)\n  );\n};\n\nexport const reactionOrEditEvent = (mEvent: MatrixEvent): boolean => {\n  const relType = mEvent.getRelation()?.rel_type;\n  if (\n    relType === (RelationType.Annotation as string) ||\n    relType === (RelationType.Replace as string)\n  )\n    return true;\n\n  // Sliding sync proxies may omit m.relates_to on the initial delivery of timeline\n  // events.  Detect edit events by the presence of m.new_content in the event\n  // content even when the relation metadata is absent, so they are filtered from\n  // the rendered timeline rather than falling through as unsupported messages.\n  if (mEvent.getContent()['m.new_content'] !== undefined) return true;\n\n  return false;\n};\n\nexport const isThreadRelationEvent = (mEvent: MatrixEvent, threadRootId?: string): boolean => {\n  const relation =\n    mEvent.getRelation?.() ??\n    (\n      mEvent.getWireContent?.() as {\n        'm.relates_to'?: { rel_type?: unknown; event_id?: unknown };\n      }\n    )?.['m.relates_to'] ??\n    (\n      mEvent.getContent?.() as {\n        'm.relates_to'?: { rel_type?: unknown; event_id?: unknown };\n      }\n    )?.['m.relates_to'];\n\n  return (\n    relation?.rel_type === (RelationType.Thread as string) &&\n    (threadRootId === undefined || relation.event_id === threadRootId)\n  );\n};\n\nexport const hasThreadRootAggregation = (mEvent: MatrixEvent): boolean =>\n  (mEvent.getServerAggregatedRelation?.<IThreadBundledRelationship>(RelationType.Thread as string)\n    ?.count ?? 0) > 0;\n\n/**\n * Resolve the list of reply events to show for a thread.\n *\n * Prefers events from the SDK Thread object (authoritative, full history) but\n * falls back to scanning the main room timeline when the Thread object was\n * created without `initialEvents` (as happens with classic sync).  In that\n * case `thread.events` contains only the root event, so filtering it yields an\n * empty array — we must fall back rather than showing nothing.\n */\nexport const getThreadReplyEvents = (room: Room, threadRootId: string): MatrixEvent[] => {\n  const isReply = (ev: MatrixEvent) =>\n    ev.getId() !== threadRootId &&\n    !reactionOrEditEvent(ev) &&\n    isThreadRelationEvent(ev, threadRootId);\n\n  const thread = room.getThread(threadRootId);\n  const fromThread = (thread?.events ?? []).filter(isReply);\n  if (fromThread.length > 0) return fromThread;\n\n  return room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter(isReply);\n};\n\n/**\n * Timeline rows skip reactions, edits, and other relation-only events.  When jumping\n * to a reply target, unwrap to the event that is actually rendered (root of an\n * edit chain, message for a reaction annotation, etc.).\n */\nexport const unwrapRelationJumpTarget = (room: Room, eventId: string, maxHops = 24): string => {\n  let current = eventId;\n  for (let hop = 0; hop < maxHops; hop += 1) {\n    const ev = room.findEventById(current);\n    if (!ev) return current;\n    if (!reactionOrEditEvent(ev)) return current;\n    const related = ev.getRelation()?.event_id;\n    if (typeof related !== 'string' || related === current) return current;\n    current = related;\n  }\n  return current;\n};\n\nconst findRelationChildEvent = (\n  timelineSet: EventTimelineSet,\n  eventId: string\n): MatrixEvent | undefined => {\n  for (const timeline of timelineSet.getTimelines()) {\n    for (const parent of timeline.getEvents()) {\n      const parentId = parent.getId();\n      if (!parentId) continue;\n\n      const reactionRelations = getEventReactions(timelineSet, parentId);\n      if (reactionRelations) {\n        const reaction = reactionRelations\n          .getRelations()\n          .find((candidate) => candidate.getId() === eventId);\n        if (reaction) return reaction;\n      }\n\n      const editRelations = getEventEdits(timelineSet, parentId, parent.getType());\n      if (editRelations) {\n        const edit = editRelations\n          .getRelations()\n          .find((candidate) => candidate.getId() === eventId);\n        if (edit) return edit;\n      }\n    }\n  }\n  return undefined;\n};\n\nexport const findRoomEventById = (\n  room: Room,\n  eventId: string,\n  timelineSet?: EventTimelineSet\n): MatrixEvent | undefined => {\n  const set = timelineSet ?? room.getUnfilteredTimelineSet();\n  return (\n    set.findEventById(eventId) ??\n    room.findEventById(eventId) ??\n    findRelationChildEvent(set, eventId)\n  );\n};\n\nexport type ResolvedReplyDraftTarget = {\n  eventId: string;\n  replyEvt: MatrixEvent;\n};\n\nexport const extractReplyDraftBody = (\n  replyEvt: MatrixEvent,\n  timelineSet: EventTimelineSet\n): { body: string; formattedBody: string } => {\n  const replyId = replyEvt.getId();\n  const editedReply =\n    replyId !== undefined && !isEditEvent(replyEvt)\n      ? getEditedEvent(replyId, replyEvt, timelineSet)\n      : undefined;\n  const editedNewContent = editedReply?.getContent()['m.new_content'];\n  const content = (editedNewContent ?? replyEvt.getContent()) as Record<string, unknown>;\n  const { body, formatted_body: formattedBody } = content;\n  const msc1767body = content['m.text'];\n\n  const resolvedBody =\n    (typeof body === 'string' ? body : undefined) ??\n    (typeof msc1767body === 'string'\n      ? msc1767body\n      : (msc1767body as { body?: string } | undefined)?.body) ??\n    getMessageVersionBody(replyEvt) ??\n    '';\n\n  return {\n    body: resolvedBody,\n    formattedBody: typeof formattedBody === 'string' ? formattedBody : '',\n  };\n};\n\nexport const resolveReplyDraftTarget = (\n  room: Room,\n  clickedEventId: string,\n  timelineSet?: EventTimelineSet\n): ResolvedReplyDraftTarget | undefined => {\n  const set = timelineSet ?? room.getUnfilteredTimelineSet();\n  const replyEvt = findRoomEventById(room, clickedEventId, set);\n  if (!replyEvt) return undefined;\n\n  const eventId = replyEvt.getId();\n  if (!eventId) return undefined;\n\n  return { eventId, replyEvt };\n};\n\nexport const getMentionContent = (userIds: string[], room: boolean): IMentions => {\n  const mMentions: IMentions = {};\n  if (userIds.length > 0) {\n    mMentions.user_ids = userIds;\n  }\n  if (room) {\n    mMentions.room = true;\n  }\n\n  return mMentions;\n};\n\nexport const getCommonRooms = (\n  mx: MatrixClient,\n  rooms: string[],\n  otherUserId: string\n): string[] => {\n  const commonRooms: string[] = [];\n\n  rooms.forEach((roomId) => {\n    const room = mx.getRoom(roomId);\n    if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return;\n\n    const common = room.hasMembershipState(otherUserId, KnownMembership.Join);\n    if (common) {\n      commonRooms.push(roomId);\n    }\n  });\n\n  return commonRooms;\n};\n\nexport const bannedInRooms = (mx: MatrixClient, rooms: string[], otherUserId: string): boolean =>\n  rooms.some((roomId) => {\n    const room = mx.getRoom(roomId);\n    if (!room || room.getMyMembership() !== (KnownMembership.Join as string)) return false;\n\n    return room.hasMembershipState(otherUserId, KnownMembership.Ban);\n  });\n","import type {\n  AccountDataEvents,\n  IPowerLevelsContent,\n  MatrixClient,\n  MatrixEvent,\n  Room,\n  StateEvents,\n} from '$types/matrix-sdk';\nimport { EventTimeline, EventType, KnownMembership, RoomType } from '$types/matrix-sdk';\n\nimport type { IRoomCreateContent, RoomToParents } from '$types/matrix/room';\n\nexport const getStateEvent = (\n  room: Room,\n  eventType: keyof StateEvents,\n  stateKey = ''\n): MatrixEvent | undefined =>\n  room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType, stateKey) ??\n  undefined;\n\nexport const getStateEvents = (room: Room, eventType: keyof StateEvents): MatrixEvent[] =>\n  room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(eventType) ?? [];\n\nexport const getAccountData = (\n  mx: MatrixClient,\n  eventType: keyof AccountDataEvents\n): MatrixEvent | undefined => mx.getAccountData(eventType);\n\nexport const isSpace = (room: Room | null): boolean => {\n  if (!room) return false;\n  const event = getStateEvent(room, EventType.RoomCreate);\n  if (!event) return false;\n  return event.getContent().type === RoomType.Space;\n};\n\nexport const isRoom = (room: Room | null): boolean => {\n  if (!room) return false;\n  const event = getStateEvent(room, EventType.RoomCreate);\n  if (!event) return true;\n  return event.getContent().type !== RoomType.Space;\n};\n\nexport const isUnsupportedRoom = (room: Room | null): boolean => {\n  if (!room) return false;\n  const event = getStateEvent(room, EventType.RoomCreate);\n  if (!event) return true; // Consider room unsupported if m.room.create event doesn't exist\n  return event.getContent().type !== undefined && event.getContent().type !== RoomType.Space;\n};\n\nexport function isValidChild(mEvent: MatrixEvent): boolean {\n  return (\n    mEvent.getType() === (EventType.SpaceChild as string) &&\n    Array.isArray(mEvent.getContent<{ via: string[] }>().via)\n  );\n}\n\nexport const getAllParents = (roomToParents: RoomToParents, roomId: string): Set<string> => {\n  const allParents = new Set<string>();\n\n  const addAllParentIds = (rId: string) => {\n    if (allParents.has(rId)) return;\n    allParents.add(rId);\n\n    const parents = roomToParents.get(rId);\n    parents?.forEach((id) => addAllParentIds(id));\n  };\n  addAllParentIds(roomId);\n  allParents.delete(roomId);\n  return allParents;\n};\n\nexport const getSpaceChildren = (room: Room) =>\n  getStateEvents(room, EventType.SpaceChild).reduce<string[]>((filtered, mEvent) => {\n    const stateKey = mEvent.getStateKey();\n    if (isValidChild(mEvent) && stateKey) {\n      filtered.push(stateKey);\n    }\n    return filtered;\n  }, []);\n\nexport const getJoinedSpaceChildrenLeaveOrder = (\n  mx: MatrixClient,\n  rootSpaceId: string\n): string[] => {\n  const leaveOrder: string[] = [];\n  const visited = new Set<string>();\n\n  const isJoinedChild = (room: Room): boolean =>\n    room.getMyMembership() === (KnownMembership.Join as string) &&\n    !getStateEvent(room, EventType.RoomTombstone);\n\n  const visitSpace = (spaceId: string) => {\n    if (visited.has(spaceId)) return;\n    visited.add(spaceId);\n\n    const space = mx.getRoom(spaceId);\n    if (!space || !isJoinedChild(space)) return;\n\n    getSpaceChildren(space).forEach((childId) => {\n      if (visited.has(childId)) return;\n\n      const child = mx.getRoom(childId);\n      if (!child || !isJoinedChild(child)) return;\n\n      if (child.isSpaceRoom()) {\n        visitSpace(childId);\n        return;\n      }\n\n      visited.add(childId);\n      leaveOrder.push(childId);\n    });\n\n    if (spaceId !== rootSpaceId) {\n      leaveOrder.push(spaceId);\n    }\n  };\n\n  visitSpace(rootSpaceId);\n\n  return leaveOrder.filter((id) => id !== rootSpaceId);\n};\n\nexport type JoinedSpaceChildrenSummary = {\n  leaveOrder: string[];\n  roomCount: number;\n  subspaceCount: number;\n};\n\nexport const getJoinedSpaceChildrenSummary = (\n  mx: MatrixClient,\n  rootSpaceId: string\n): JoinedSpaceChildrenSummary => {\n  const leaveOrder = getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId);\n  let roomCount = 0;\n  let subspaceCount = 0;\n\n  leaveOrder.forEach((id) => {\n    const room = mx.getRoom(id);\n    if (room?.isSpaceRoom()) {\n      subspaceCount += 1;\n    } else {\n      roomCount += 1;\n    }\n  });\n\n  return { leaveOrder, roomCount, subspaceCount };\n};\n\nexport const getRecursiveSpaceLeaveOrder = (mx: MatrixClient, rootSpaceId: string): string[] => [\n  ...getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId),\n  rootSpaceId,\n];\n\nexport const mapParentWithChildren = (\n  roomToParents: RoomToParents,\n  roomId: string,\n  children: string[]\n) => {\n  const allParents = getAllParents(roomToParents, roomId);\n  children.forEach((childId) => {\n    if (allParents.has(childId)) {\n      // Space cycle detected.\n      return;\n    }\n    const parents = roomToParents.get(childId) ?? new Set<string>();\n    parents.add(roomId);\n    roomToParents.set(childId, parents);\n  });\n};\n\nexport const getRoomToParents = (mx: MatrixClient): RoomToParents => {\n  const map: RoomToParents = new Map();\n  mx.getRooms()\n    .filter((room) => isSpace(room) && room.getMyMembership() === (KnownMembership.Join as string))\n    .forEach((room) => mapParentWithChildren(map, room.roomId, getSpaceChildren(room)));\n\n  return map;\n};\n\nexport const getOrphanParents = (roomToParents: RoomToParents, roomId: string): string[] => {\n  const parents = getAllParents(roomToParents, roomId);\n  return Array.from(parents).filter((parentRoomId) => !roomToParents.has(parentRoomId));\n};\n\nconst getAllVersionsRoomCreator = (room: Room): Set<string> => {\n  const creators = new Set<string>();\n\n  const createEvent = getStateEvent(room, EventType.RoomCreate);\n  const createContent = createEvent?.getContent<IRoomCreateContent>();\n  const creator = createEvent?.getSender();\n  if (typeof creator === 'string') creators.add(creator);\n\n  if (createContent && Array.isArray(createContent.additional_creators)) {\n    createContent.additional_creators.forEach((c) => {\n      creators.add(c);\n    });\n  }\n\n  return creators;\n};\n\nexport const guessPerfectParent = (\n  mx: MatrixClient,\n  roomId: string,\n  parents: string[]\n): string | undefined => {\n  if (parents.length === 1) {\n    return parents[0];\n  }\n\n  const getSpecialUsers = (rId: string): string[] => {\n    const specialUsers: Set<string> = new Set();\n\n    const r = mx.getRoom(rId);\n    if (!r) return [];\n\n    getAllVersionsRoomCreator(r).forEach((c) => specialUsers.add(c));\n\n    const powerLevels = getStateEvent(\n      r,\n      EventType.RoomPowerLevels\n    )?.getContent<IPowerLevelsContent>();\n\n    const { users_default: usersDefault, users } = powerLevels ?? {};\n    const defaultPower = typeof usersDefault === 'number' ? usersDefault : 0;\n\n    if (typeof users === 'object')\n      Object.keys(users).forEach((userId) => {\n        if (users[userId]! > defaultPower) {\n          specialUsers.add(userId);\n        }\n      });\n\n    return Array.from(specialUsers);\n  };\n\n  let perfectParent: string | undefined;\n  let score = 0;\n\n  const roomSpecialUsers = getSpecialUsers(roomId);\n  parents.forEach((parentId) => {\n    const parentSpecialUsers = getSpecialUsers(parentId);\n    const matchedUsersCount = parentSpecialUsers.filter((userId) =>\n      roomSpecialUsers.includes(userId)\n    ).length;\n\n    if (matchedUsersCount > score) {\n      score = matchedUsersCount;\n      perfectParent = parentId;\n    }\n  });\n\n  return perfectParent;\n};\n","export class PackAddress {\n  public readonly roomId: string;\n\n  public readonly stateKey: string;\n\n  constructor(roomId: string, stateKey: string) {\n    this.roomId = roomId;\n    this.stateKey = stateKey;\n  }\n}\n","import type { IImageInfo } from '$types/matrix/common';\n\n// https://github.com/Sorunome/matrix-doc/blob/soru/emotes/proposals/2545-emotes.md\n\n/**\n * im.ponies.emote_rooms content\n */\nexport type PackStateKeyToObject = Record<string, object>;\nexport type RoomIdToStateKey = Record<string, PackStateKeyToObject>;\nexport type EmoteRoomsContent = {\n  rooms?: RoomIdToStateKey;\n};\n\n/**\n * Pack\n */\nexport enum ImageUsage {\n  Emoticon = 'emoticon',\n  Sticker = 'sticker',\n}\n\nexport type PackImage = {\n  url: string;\n  body?: string;\n  usage?: ImageUsage[];\n  info?: IImageInfo;\n};\n\nexport type PackImages = Record<string, PackImage>;\n\nexport type PackMeta = {\n  display_name?: string;\n  avatar_url?: string;\n  attribution?: string;\n  usage?: ImageUsage[];\n};\n\nexport type PackContent = {\n  pack?: PackMeta;\n  images?: PackImages;\n};\n","import type { PackMeta } from './types';\nimport { ImageUsage } from './types';\n\nexport class PackMetaReader {\n  private readonly meta: PackMeta;\n\n  public readonly fallbackUsage: ImageUsage[] = [ImageUsage.Emoticon, ImageUsage.Sticker];\n\n  constructor(meta: PackMeta) {\n    this.meta = meta;\n  }\n\n  get name(): string | undefined {\n    const displayName = this.meta.display_name;\n    if (typeof displayName === 'string') return displayName;\n    return undefined;\n  }\n\n  get avatar(): string | undefined {\n    const avatarURL = this.meta.avatar_url;\n    if (typeof avatarURL === 'string') return avatarURL;\n    return undefined;\n  }\n\n  get attribution(): string | undefined {\n    const { attribution } = this.meta;\n    if (typeof this.meta.attribution === 'string') return attribution;\n    return undefined;\n  }\n\n  get usage(): ImageUsage[] {\n    if (!Array.isArray(this.meta.usage)) return this.fallbackUsage;\n\n    const knownUsage = this.meta.usage.filter(\n      (u) => u === ImageUsage.Emoticon || u === ImageUsage.Sticker\n    );\n\n    if (knownUsage.length === 0) return this.fallbackUsage;\n\n    return knownUsage;\n  }\n\n  get content(): PackMeta {\n    return this.meta;\n  }\n}\n","import type { IImageInfo } from '$types/matrix/common';\nimport type { PackImage } from './types';\nimport { ImageUsage } from './types';\n\nexport class PackImageReader {\n  public readonly shortcode: string;\n\n  public readonly url: string;\n\n  private readonly image: Omit<PackImage, 'url'>;\n\n  constructor(shortcode: string, url: string, image: Omit<PackImage, 'url'>) {\n    this.shortcode = shortcode;\n    this.url = url;\n\n    this.image = image;\n  }\n\n  static fromPackImage(shortcode: string, image: PackImage): PackImageReader | undefined {\n    const { url } = image;\n\n    if (typeof url !== 'string') return undefined;\n\n    return new PackImageReader(shortcode, url, image);\n  }\n\n  get body(): string | undefined {\n    const { body } = this.image;\n    return typeof body === 'string' ? body : undefined;\n  }\n\n  get info(): IImageInfo | undefined {\n    return this.image.info;\n  }\n\n  get usage(): ImageUsage[] | undefined {\n    const usg = this.image.usage;\n    if (!Array.isArray(usg)) return undefined;\n\n    const knownUsage = usg.filter((u) => u === ImageUsage.Emoticon || u === ImageUsage.Sticker);\n\n    return knownUsage.length > 0 ? knownUsage : undefined;\n  }\n\n  get content(): PackImage {\n    return {\n      url: this.url,\n      body: this.image.body,\n      usage: this.image.usage,\n      info: this.image.info,\n    };\n  }\n}\n","import { PackImageReader } from './PackImageReader';\nimport type { PackImages } from './types';\n\nexport class PackImagesReader {\n  private readonly rawImages: PackImages;\n\n  private shortcodeToImages: Map<string, PackImageReader> | undefined;\n\n  constructor(images: PackImages) {\n    this.rawImages = images;\n  }\n\n  get collection(): Map<string, PackImageReader> {\n    if (this.shortcodeToImages) return this.shortcodeToImages;\n\n    const shortcodeToImages: Map<string, PackImageReader> = new Map();\n\n    Object.entries(this.rawImages).forEach(([shortcode, image]) => {\n      const imageReader = PackImageReader.fromPackImage(shortcode, image);\n      if (imageReader) {\n        shortcodeToImages.set(shortcode, imageReader);\n      }\n    });\n\n    this.shortcodeToImages = shortcodeToImages;\n    return this.shortcodeToImages;\n  }\n}\n","import type { MatrixEvent } from '$types/matrix-sdk';\nimport { PackAddress } from './PackAddress';\nimport type { PackImageReader } from './PackImageReader';\nimport { PackImagesReader } from './PackImagesReader';\nimport { PackMetaReader } from './PackMetaReader';\nimport type { PackContent } from './types';\nimport { ImageUsage } from './types';\n\nexport class ImagePack {\n  public readonly id: string;\n\n  public readonly deleted: boolean;\n\n  public readonly address: PackAddress | undefined;\n\n  public readonly meta: PackMetaReader;\n\n  public readonly images: PackImagesReader;\n\n  private emoticonMemo: PackImageReader[] | undefined;\n\n  private stickerMemo: PackImageReader[] | undefined;\n\n  constructor(id: string, content: PackContent, address: PackAddress | undefined) {\n    this.id = id;\n\n    this.address = address;\n\n    this.deleted = content.pack === undefined && content.images === undefined;\n\n    this.meta = new PackMetaReader(content.pack ?? {});\n    this.images = new PackImagesReader(content.images ?? {});\n  }\n\n  static fromMatrixEvent(id: string, matrixEvent: MatrixEvent) {\n    const roomId = matrixEvent.getRoomId();\n    const stateKey = matrixEvent.getStateKey();\n\n    const address =\n      roomId && typeof stateKey === 'string' ? new PackAddress(roomId, stateKey) : undefined;\n\n    const content = matrixEvent.getContent<PackContent>();\n\n    const imagePack: ImagePack = new ImagePack(id, content, address);\n\n    return imagePack;\n  }\n\n  public getImages(usage: ImageUsage): PackImageReader[] {\n    if (usage === ImageUsage.Emoticon && this.emoticonMemo) {\n      return this.emoticonMemo;\n    }\n    if (usage === ImageUsage.Sticker && this.stickerMemo) {\n      return this.stickerMemo;\n    }\n\n    const images = Array.from(this.images.collection.values()).filter((image) => {\n      const usg = image.usage ?? this.meta.usage;\n      return usg.includes(usage);\n    });\n\n    if (usage === ImageUsage.Emoticon) {\n      this.emoticonMemo = images;\n    }\n    if (usage === ImageUsage.Sticker) {\n      this.stickerMemo = images;\n    }\n\n    return images;\n  }\n\n  public getAvatarUrl(usage: ImageUsage): string | undefined {\n    if (this.meta.avatar) return this.meta.avatar;\n    const images = this.getImages(usage);\n    const firstImage = images[0];\n    if (firstImage) return firstImage.url;\n    return undefined;\n  }\n}\n","import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';\n\nimport { getAccountData, getStateEvent, getStateEvents } from '$utils/room/hierarchy';\n\nimport type { IImageInfo } from '$types/matrix/common';\nimport type { ImageUsage } from './types';\nimport { ImagePack } from './ImagePack';\nimport type { PackMetaReader } from './PackMetaReader';\nimport type { PackAddress } from './PackAddress';\nimport { CustomAccountDataEvent } from '$types/matrix/accountData';\nimport { CustomStateEvent } from '$types/matrix/room';\n\nexport function packAddressEqual(a1?: PackAddress, a2?: PackAddress): boolean {\n  if (!a1 && !a2) return true;\n  if (!a1 || !a2) return false;\n  return a1.roomId === a2.roomId && a1.stateKey === a2.stateKey;\n}\n\nexport function imageUsageEqual(u1: ImageUsage[], u2: ImageUsage[]) {\n  return u1.length === u2.length && u1.every((u) => u2.includes(u));\n}\n\nexport function packMetaEqual(a: PackMetaReader, b: PackMetaReader): boolean {\n  return (\n    a.name === b.name &&\n    a.avatar === b.avatar &&\n    a.attribution === b.attribution &&\n    imageUsageEqual(a.usage, b.usage)\n  );\n}\n\nfunction makeImagePacks(packEvents: MatrixEvent[]): ImagePack[] {\n  return packEvents.reduce<ImagePack[]>((imagePacks, packEvent) => {\n    const packId = packEvent.getId();\n    if (!packId) return imagePacks;\n    imagePacks.push(ImagePack.fromMatrixEvent(packId, packEvent));\n    return imagePacks;\n  }, []);\n}\n\nexport function getRoomImagePack(room: Room, stateKey: string): ImagePack | undefined {\n  const packEvent =\n    getStateEvent(room, CustomStateEvent.ImagePack, stateKey) ||\n    getStateEvent(room, CustomStateEvent.PoniesRoomEmotes, stateKey);\n  if (!packEvent) return undefined;\n  const packId = packEvent.getId();\n  if (!packId) return undefined;\n  return ImagePack.fromMatrixEvent(packId, packEvent);\n}\n\nexport function getRoomImagePacks(room: Room): ImagePack[] {\n  const packEventsStable = getStateEvents(room, CustomStateEvent.ImagePack);\n  const packEventsUnstable = getStateEvents(room, CustomStateEvent.PoniesRoomEmotes);\n\n  const uniquePackEvents = new Map<string, MatrixEvent>();\n  packEventsUnstable.forEach((ev) => {\n    const key = ev.getStateKey();\n    if (typeof key === 'string') uniquePackEvents.set(key, ev);\n  });\n  packEventsStable.forEach((ev) => {\n    const key = ev.getStateKey();\n    if (typeof key === 'string') uniquePackEvents.set(key, ev);\n  });\n\n  return makeImagePacks(Array.from(uniquePackEvents.values()));\n}\n\nexport function getGlobalImagePacks(mx: MatrixClient): ImagePack[] {\n  const emoteRoomsContent =\n    getAccountData(mx, CustomAccountDataEvent.ImagePackRooms)?.getContent() ||\n    getAccountData(mx, CustomAccountDataEvent.PoniesEmoteRooms)?.getContent();\n\n  if (typeof emoteRoomsContent !== 'object') return [];\n\n  const { rooms: roomIdToPackInfo } = emoteRoomsContent;\n  if (typeof roomIdToPackInfo !== 'object') return [];\n\n  const roomIds = Object.keys(roomIdToPackInfo);\n\n  const packs = roomIds.flatMap((roomId) => {\n    if (typeof roomIdToPackInfo[roomId] !== 'object') return [];\n    const room = mx.getRoom(roomId);\n    if (!room) return [];\n    const packStateKeyToUnknown = roomIdToPackInfo[roomId];\n\n    const packEventsStable = getStateEvents(room, CustomStateEvent.ImagePack);\n    const packEventsUnstable = getStateEvents(room, CustomStateEvent.PoniesRoomEmotes);\n\n    const uniquePackEvents = new Map<string, MatrixEvent>();\n    packEventsUnstable.forEach((ev) => {\n      const key = ev.getStateKey();\n      if (typeof key === 'string' && !!packStateKeyToUnknown[key]) {\n        uniquePackEvents.set(key, ev);\n      }\n    });\n    packEventsStable.forEach((ev) => {\n      const key = ev.getStateKey();\n      if (typeof key === 'string' && !!packStateKeyToUnknown[key]) {\n        uniquePackEvents.set(key, ev);\n      }\n    });\n\n    return makeImagePacks(Array.from(uniquePackEvents.values()));\n  });\n\n  return packs;\n}\n\nexport function getGlobalImagePackRoomIds(mx: MatrixClient): string[] {\n  const emoteRoomsContent =\n    getAccountData(mx, CustomAccountDataEvent.ImagePackRooms)?.getContent() ||\n    getAccountData(mx, CustomAccountDataEvent.PoniesEmoteRooms)?.getContent();\n\n  if (typeof emoteRoomsContent !== 'object' || !emoteRoomsContent) return [];\n  const { rooms: roomIdToPackInfo } = emoteRoomsContent as { rooms?: unknown };\n  if (typeof roomIdToPackInfo !== 'object' || !roomIdToPackInfo) return [];\n\n  return Object.keys(roomIdToPackInfo);\n}\n\nexport function getUserImagePack(mx: MatrixClient): ImagePack | undefined {\n  const packEvent = getAccountData(mx, CustomAccountDataEvent.PoniesUserEmotes);\n  const userId = mx.getUserId();\n  if (!packEvent || !userId) {\n    return undefined;\n  }\n\n  const userImagePack = ImagePack.fromMatrixEvent(userId, packEvent);\n  return userImagePack;\n}\n\n/**\n * The info a pack declares for one of its images: dimensions, mimetype and size, so sending a pack\n * image never requires downloading it first.\n */\nexport function getPackImageInfo(\n  mx: MatrixClient,\n  room: Room,\n  usage: ImageUsage,\n  mxcUrl: string\n): IImageInfo | undefined {\n  const userPack = getUserImagePack(mx);\n  const packs = [\n    ...getRoomImagePacks(room),\n    ...(userPack ? [userPack] : []),\n    ...getGlobalImagePacks(mx),\n  ];\n  for (const pack of packs) {\n    const info = pack.getImages(usage).find((image) => image.url === mxcUrl)?.info;\n    if (info) return info;\n  }\n  return undefined;\n}\n","/**\n * a simple wrapper to make a map seriazable to json\n *\n * @export\n * @class SerializableMap\n * @extends {Map<KeyType, ItemType>}\n * @template KeyType the type of the key\n * @template ItemType the type of the item\n */\nexport class SerializableMap<KeyType, ItemType> extends Map<KeyType, ItemType> {\n  toJSON() {\n    return Object.fromEntries(this);\n  }\n}\n","/**\n * a simple wrapper to make a set seriazable to json\n *\n * @export\n * @class SerializableSet\n * @extends {Set<ItemType>}\n * @template ItemType the type of the items in the set\n */\nexport class SerializableSet<ItemType> extends Set<ItemType> {\n  toJSON() {\n    return Array.from(this);\n  }\n}\n","export const matchMxId = (id: string): RegExpMatchArray | null =>\n  id.match(/^([@$+#])([^\\s:]*):(\\S+)$/);\nexport const validMxId = (id: string): boolean => !!matchMxId(id);\nexport const getMxIdServer = (userId: string): string | undefined => matchMxId(userId)?.[3];\n","export const knockSupported = (version: string): boolean => {\n  const unsupportedVersion = ['1', '2', '3', '4', '5', '6'];\n  return !unsupportedVersion.includes(version);\n};\nexport const restrictedSupported = (version: string): boolean => {\n  const unsupportedVersion = ['1', '2', '3', '4', '5', '6', '7'];\n  return !unsupportedVersion.includes(version);\n};\nexport const knockRestrictedSupported = (version: string): boolean => {\n  const unsupportedVersion = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];\n  return !unsupportedVersion.includes(version);\n};\nexport const creatorsSupported = (version: string): boolean => {\n  const unsupportedVersion = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];\n  return !unsupportedVersion.includes(version);\n};\n","import { getMxIdServer } from '$utils/mxIdHelper';\nimport { creatorsSupported } from '$utils/roomSupport';\nimport type { Room } from '$types/matrix-sdk';\nimport type { IRoomCreateContent } from '$types/matrix/room';\nimport type { IPowerLevels } from '$hooks/usePowerLevels';\nimport { getStateEvent } from '$utils/room/hierarchy';\nimport { EventType } from '$types/matrix-sdk';\n\nexport const getViaServers = (room: Room): string[] => {\n  const getHighestPowerUserId = (): string | undefined => {\n    const creatorEvent = getStateEvent(room, EventType.RoomCreate);\n    if (\n      creatorEvent &&\n      creatorsSupported(creatorEvent.getContent<IRoomCreateContent>().room_version)\n    ) {\n      return creatorEvent.getSender();\n    }\n\n    const powerLevels = getStateEvent(room, EventType.RoomPowerLevels)?.getContent<IPowerLevels>();\n\n    if (!powerLevels) return undefined;\n    const userIdToPower = powerLevels.users;\n    if (!userIdToPower) return undefined;\n    let powerUserId: string | undefined;\n\n    Object.keys(userIdToPower).forEach((userId) => {\n      const userPower = userIdToPower[userId];\n      if (userPower === undefined || userPower <= (powerLevels.users_default ?? 0)) return;\n\n      if (!powerUserId) {\n        powerUserId = userId;\n        return;\n      }\n      const currentPower = userIdToPower[powerUserId];\n      if (currentPower !== undefined && userPower > currentPower) {\n        powerUserId = userId;\n      }\n    });\n    return powerUserId;\n  };\n\n  const getServerToPopulation = (): Record<string, number> => {\n    const members = room.getMembers();\n    const serverToPop: Record<string, number> = {};\n\n    members?.forEach((member) => {\n      const { userId } = member;\n      const server = getMxIdServer(userId);\n      if (!server) return;\n      const serverPop = serverToPop[server];\n      if (serverPop === undefined) {\n        serverToPop[server] = 1;\n        return;\n      }\n      serverToPop[server] = serverPop + 1;\n    });\n\n    return serverToPop;\n  };\n\n  const via: string[] = [];\n  const userId = getHighestPowerUserId();\n  if (userId) {\n    const server = getMxIdServer(userId);\n    if (server) via.push(server);\n  }\n  const serverToPop = getServerToPopulation();\n  const sortedServers = Object.keys(serverToPop).toSorted(\n    (svrA, svrB) => (serverToPop[svrB] ?? 0) - (serverToPop[svrA] ?? 0)\n  );\n  const mostPop3 = sortedServers.slice(0, 3);\n  if (via.length === 0) return mostPop3;\n  const firstVia = via[0];\n  if (firstVia && mostPop3.includes(firstVia)) {\n    mostPop3.splice(mostPop3.indexOf(firstVia), 1);\n  }\n  return via.concat(mostPop3.slice(0, 2));\n};\n","import { EventType, JoinRule } from 'matrix-js-sdk';\nimport type { MatrixClient, Room } from 'matrix-js-sdk';\nimport { getStateEvents } from './room/hierarchy';\n\n/**\n * simple check to see if a room can be considered private\n *\n * @export\n * @param {MatrixClient} mx the matrix client\n * @param {Room} room the room to check\n * @return {*}  {boolean} true if the room is considered private\n */\nexport function isRoomPrivate(mx: MatrixClient, room: Room): boolean {\n  // detect if it's a public room or not\n  const joinRule = room.getJoinRule() ?? JoinRule.Invite;\n\n  const parentSpaceIds = getStateEvents(room, EventType.SpaceParent)\n    .map((e) => e.getStateKey())\n    .filter((id): id is string => Boolean(id));\n  const isInPublicSpace = parentSpaceIds.some((spaceId) => {\n    const space = mx.getRoom(spaceId);\n    return Boolean(space?.isSpaceRoom()) && space?.getJoinRule() === JoinRule.Public;\n  });\n\n  return (\n    joinRule === JoinRule.Invite ||\n    (joinRule === JoinRule.Restricted && !isInPublicSpace) ||\n    (joinRule !== JoinRule.Public &&\n      joinRule !== JoinRule.Knock &&\n      joinRule !== JoinRule.Restricted)\n  );\n}\n","import { getGlobalImagePacks, getRoomImagePacks } from '$plugins/custom-emoji/utils';\nimport type { ImagePack } from '$plugins/custom-emoji/ImagePack';\nimport type { MSC4459ImagePackReference } from '$types/matrix/common';\nimport { SerializableMap } from '$types/wrapper/SerializableMap';\nimport type { MatrixClient, Room } from 'matrix-js-sdk';\nimport type { ImageUsage } from '$plugins/custom-emoji';\nimport { SerializableSet } from '$types/wrapper/SerializableSet';\nimport { getViaServers } from '$plugins/via-servers';\nimport { getMxIdServer } from './mxIdHelper';\nimport { isRoomPrivate } from './roomVisibility';\n\n/**\n * lookup table for global mxc => MSC4459ImagePackReference\n * TODO this is far from a perfect solution\n */\nconst globalLookupTable = new Map<string, MSC4459ImagePackReference>();\n/**\n * lookup table for room local mxc => MSC4459ImagePackReference\n * TODO this is far from a perfect solution\n */\nconst roomLookupTable = new Map<string, Map<string, MSC4459ImagePackReference>>();\n\nexport function getImagePackReferencesForMxcWrappedInMap(\n  mxcUrl: string,\n  matrixClient: MatrixClient,\n  imageUsage: ImageUsage,\n  room: Room\n): SerializableMap<string, MSC4459ImagePackReference> {\n  const retMap = new SerializableMap<string, MSC4459ImagePackReference>();\n  if (!mxcUrl.startsWith('mxc')) return retMap;\n  const result = getImagePackReferencesForMxc(mxcUrl, matrixClient, imageUsage, room);\n  // if the result is undefined return the empty map, to not produce invalid entries\n  if (!result?.room_id || !result?.state_key || !result?.shortcode) return retMap;\n  retMap.set(mxcUrl, result);\n  return retMap;\n}\n\nfunction getImagePackReferencesForMxcInternal(\n  mxcUrl: string,\n  matrixClient: MatrixClient,\n  packs: ImagePack[],\n  imageUsage: ImageUsage,\n  bypassPrivateFilter = false\n) {\n  return packs\n    .filter((val) => val.getImages(imageUsage).find((img) => img.url === mxcUrl))\n    .map((pack) => {\n      const img = pack.getImages(imageUsage).find((val) => val.url === mxcUrl);\n      const room = matrixClient.getRoom(pack.address?.roomId);\n      if (!room || (isRoomPrivate(matrixClient, room) && !bypassPrivateFilter)) return undefined;\n      const viaServers = new SerializableSet<string>();\n      if (room)\n        getViaServers(room).forEach((via) => {\n          viaServers.add(via);\n        });\n      // add ones own hs as via server, as that server evidently is alive\n      const ownViaHS = getMxIdServer(matrixClient.getSafeUserId());\n      if (ownViaHS) viaServers.add(ownViaHS);\n      return {\n        room_id: pack.address?.roomId,\n        state_key: pack.address?.stateKey,\n        via: viaServers,\n        shortcode: img?.shortcode,\n      } satisfies MSC4459ImagePackReference;\n    })\n    .find((val) => val != undefined);\n}\n\nexport function getImagePackReferencesForMxc(\n  mxcUrl: string,\n  matrixClient: MatrixClient,\n  imageUsage: ImageUsage,\n  room: Room\n): MSC4459ImagePackReference {\n  if (!mxcUrl.startsWith('mxc')) return {};\n  if (roomLookupTable.get(room.roomId)?.has(mxcUrl))\n    return roomLookupTable.get(room.roomId)!.get(mxcUrl)!;\n  const roomLocalImgPacks: ImagePack[] = getRoomImagePacks(room);\n  const roomLocalMatch = getImagePackReferencesForMxcInternal(\n    mxcUrl,\n    matrixClient,\n    roomLocalImgPacks,\n    imageUsage,\n    true\n  );\n  if (roomLocalMatch) {\n    const roomLookupTabRes =\n      roomLookupTable.get(room.roomId) ?? new Map<string, MSC4459ImagePackReference>();\n    roomLookupTabRes.set(mxcUrl, roomLocalMatch);\n    roomLookupTable.set(room.roomId, roomLookupTabRes);\n  }\n  // prefer room local match as they're probably often more relevant\n  if (roomLocalMatch?.room_id && roomLocalMatch?.shortcode) return roomLocalMatch;\n  // simple caching\n  if (globalLookupTable.has(mxcUrl)) return globalLookupTable.get(mxcUrl)!;\n  const globalImgPacks: ImagePack[] = getGlobalImagePacks(matrixClient);\n  const globalMatch = getImagePackReferencesForMxcInternal(\n    mxcUrl,\n    matrixClient,\n    globalImgPacks,\n    imageUsage,\n    false\n  );\n  if (globalMatch?.room_id && globalMatch?.shortcode) {\n    globalLookupTable.set(mxcUrl, globalMatch);\n    return globalMatch;\n  }\n\n  return {};\n}\n","import type { MatrixReactionEvent } from '$types/matrix/common';\nimport type { MatrixClient, Room } from '$types/matrix-sdk';\nimport { RelationType } from '$types/matrix-sdk';\nimport { ImageUsage } from '$plugins/custom-emoji';\nimport { getImagePackReferencesForMxcWrappedInMap } from './msc4459helper';\nimport { MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME } from '$unstable/prefixes';\n\nexport const getReactionContent = (\n  eventId: string,\n  key: string,\n  matrixClient: MatrixClient,\n  room: Room,\n  shortcode?: string\n): MatrixReactionEvent => ({\n  'm.relates_to': {\n    event_id: eventId,\n    key,\n    rel_type: RelationType.Annotation,\n  },\n  shortcode,\n  'com.beeper.reaction.shortcode': shortcode,\n  [MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME]: getImagePackReferencesForMxcWrappedInMap(\n    key,\n    matrixClient,\n    ImageUsage.Emoticon,\n    room\n  ),\n});\n","import { convertFileSrc, invoke, isTauri } from '@tauri-apps/api/core';\nimport type { MatrixClient } from '$types/matrix-sdk';\nimport { webviewStripsCustomProtocolCache } from './platform';\nimport { getCurrentMediaSessionScope } from './mediaTransport';\nimport { getTauriMediaSourceUrl } from './mediaSourceUrl';\n\nconst TAURI_MEDIA_CACHE_VERSION = '__sable_media_cache=3';\nconst TAURI_MEDIA_PATH_PREFIXES = [\n  '/_matrix/client/v1/media/',\n  '/_matrix/media/v3/download/',\n  '/_matrix/media/v3/thumbnail/',\n  '/_matrix/media/r0/download/',\n  '/_matrix/media/r0/thumbnail/',\n];\n\nexport const rewriteAuthenticatedMediaUrl = (httpUrl: string | null): string | null => {\n  if (!httpUrl) return null;\n  if (!isTauri()) return httpUrl;\n  const sourceUrl = httpUrl.startsWith('sable-media://')\n    ? httpUrl.slice('sable-media://'.length)\n    : httpUrl;\n  let parsedUrl: URL;\n  try {\n    parsedUrl = new URL(sourceUrl);\n  } catch {\n    return httpUrl;\n  }\n  if (\n    (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') ||\n    parsedUrl.origin === 'null' ||\n    !TAURI_MEDIA_PATH_PREFIXES.some((path) => parsedUrl.pathname.startsWith(path))\n  ) {\n    return httpUrl;\n  }\n  if (httpUrl.includes(TAURI_MEDIA_CACHE_VERSION)) return httpUrl;\n  const mediaUrl = httpUrl.startsWith('sable-media://')\n    ? httpUrl\n    : convertFileSrc(httpUrl, 'sable-media');\n  // Session-scoped so the cacheable response is never shared across accounts.\n  const sessionScope = encodeURIComponent(getCurrentMediaSessionScope());\n  const separator = mediaUrl.includes('?') ? '&' : '?';\n  return `${mediaUrl}${separator}${TAURI_MEDIA_CACHE_VERSION}&__sable_media_session=${sessionScope}`;\n};\n\n// Kept in step with MEDIA_RETRY_MARKER in mediaTransport.ts, which strips it from cache keys.\nconst MEDIA_RETRY_MARKER = '__sable_media_retry';\nconst TAURI_MEDIA_OUTER_QUERY_PARAMS = ['__sable_media_cache', '__sable_media_session'];\n\n// Embeds a retry revision as a fragment on the inner http(s) target (stripping the\n// outer cache/session markers, which the rewrite re-adds). The fragment makes Rust's\n// cache_key(scope, target) distinct but is stripped natively before the upstream\n// request and the encryption lookup. Undefined for the first attempt, outside Tauri,\n// or when there is no http(s) inner target (e.g. blob: URLs).\nexport const getTauriMediaRetryTarget = (\n  mediaUrl: string,\n  revision: number\n): string | undefined => {\n  if (revision <= 0 || !isTauri()) return undefined;\n  const innerTarget = getTauriMediaSourceUrl(mediaUrl);\n  if (!innerTarget) return undefined;\n  let parsedUrl: URL;\n  try {\n    parsedUrl = new URL(innerTarget);\n  } catch {\n    return undefined;\n  }\n  if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') return undefined;\n  TAURI_MEDIA_OUTER_QUERY_PARAMS.forEach((param) => parsedUrl.searchParams.delete(param));\n  parsedUrl.hash = `${MEDIA_RETRY_MARKER}=${revision}`;\n  return parsedUrl.toString();\n};\n\nexport const addTauriMediaRetryRevision = (mediaUrl: string, revision: number): string => {\n  const target = getTauriMediaRetryTarget(mediaUrl, revision);\n  if (!target) return mediaUrl;\n  return rewriteAuthenticatedMediaUrl(target) ?? mediaUrl;\n};\n\n// Without it the retried `src` is identical, so the browser never re-requests.\nconst addWebMediaRetryRevision = (mediaUrl: string, revision: number): string => {\n  let parsedUrl: URL;\n  try {\n    parsedUrl = new URL(mediaUrl);\n  } catch {\n    return mediaUrl;\n  }\n  if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') return mediaUrl;\n  parsedUrl.searchParams.set(MEDIA_RETRY_MARKER, String(revision));\n  return parsedUrl.toString();\n};\n\nexport const addMediaRetryRevision = (mediaUrl: string, revision: number): string => {\n  if (revision <= 0) return mediaUrl;\n  return isTauri()\n    ? addTauriMediaRetryRevision(mediaUrl, revision)\n    : addWebMediaRetryRevision(mediaUrl, revision);\n};\n\n// A media element cannot play from the `sable-media` scheme (MEDIA_ERR_SRC_NOT_SUPPORTED),\n// so video/audio sources go through the loopback HTTP origin.\nexport const prepareLoopbackMedia = async (source: string): Promise<string> => {\n  if (!isTauri()) return source;\n  return invoke<string>('prepare_loopback_media', { url: source });\n};\n\n// Awaited by the caller's own load so an element's src never changes mid-flight. An image\n// renders from the custom protocol too, so a loopback failure costs caching, not the image.\nexport const prepareLoopbackImageSource = async (source: string): Promise<string> => {\n  if (!isTauri()) return source;\n  if (!webviewStripsCustomProtocolCache()) return rewriteAuthenticatedMediaUrl(source) ?? source;\n  try {\n    return await prepareLoopbackMedia(source);\n  } catch {\n    return source;\n  }\n};\n\nexport const mxcUrlToHttp = (\n  mx: MatrixClient,\n  mxcUrl: string,\n  useAuthentication?: boolean,\n  width?: number,\n  height?: number,\n  resizeMethod?: string,\n  allowDirectLinks?: boolean\n): string | null => {\n  const httpUrl = mx.mxcUrlToHttp(\n    mxcUrl.replace(/^[\"']|[\"']$/g, ''),\n    width,\n    height,\n    resizeMethod,\n    allowDirectLinks,\n    undefined,\n    useAuthentication\n  );\n\n  if (httpUrl && isTauri()) {\n    return rewriteAuthenticatedMediaUrl(httpUrl);\n  }\n  return httpUrl;\n};\n","import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';\nimport { decryptAttachment } from 'browser-encrypt-attachment';\nimport { Channel, invoke, isTauri } from '@tauri-apps/api/core';\nimport type {\n  AccountDataEvents,\n  EventTimelineSet,\n  MatrixClient,\n  MatrixEvent,\n  Room,\n  RoomMember,\n  TimelineEvents,\n  UploadProgress,\n  UploadResponse,\n} from '$types/matrix-sdk';\nimport {\n  EventTimeline,\n  MatrixError,\n  EventType,\n  KnownMembership,\n  MediaPrefix,\n} from '$types/matrix-sdk';\nimport to from 'await-to-js';\nimport type { IImageInfo, IThumbnailContent, IVideoInfo } from '$types/matrix/common';\n\nimport * as Sentry from '@sentry/react';\nimport { encryptBlobInWorker } from '$utils/mediaWorker';\nimport { encryptAttachmentStreaming } from '$utils/attachmentCrypto';\nimport { factoryRoomIdByActivity } from './sort';\nimport { getEventReactions } from './room/relations';\nimport { getStateEvent } from './room/hierarchy';\nimport { getReactionContent } from './messageReaction';\nimport { matchMxId, validMxId } from './mxIdHelper';\n\nexport { mxcUrlToHttp, rewriteAuthenticatedMediaUrl } from './mediaUrl';\nimport { fetchMediaBlob, type MediaTransportOptions } from './mediaTransport';\n\nconst DOMAIN_REGEX = /\\b(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}\\b/;\n\nexport const isServerName = (serverName: string): boolean => DOMAIN_REGEX.test(serverName);\n\nexport const getMxIdLocalPart = (userId: string): string | undefined => matchMxId(userId)?.[2];\n\nexport const isUserId = (id: string): boolean => validMxId(id) && id.startsWith('@');\n\nexport const isRoomId = (id: string): boolean => id.startsWith('!');\n\nexport const isRoomAlias = (id: string): boolean => validMxId(id) && id.startsWith('#');\n\nexport const isEventId = (id: string): boolean => id.startsWith('$');\n\nexport const getCanonicalAliasRoomId = (mx: MatrixClient, alias: string): string | undefined =>\n  mx\n    .getRooms()\n    ?.find(\n      (room) =>\n        room.getCanonicalAlias() === alias &&\n        getStateEvent(room, EventType.RoomTombstone) === undefined\n    )?.roomId;\n\nexport const getCanonicalAliasOrRoomId = (mx: MatrixClient, roomId: string): string => {\n  const room = mx.getRoom(roomId);\n  if (!room) return roomId;\n  if (getStateEvent(room, EventType.RoomTombstone) !== undefined) return roomId;\n  const alias = room.getCanonicalAlias();\n  if (alias && getCanonicalAliasRoomId(mx, alias) === roomId) {\n    return alias;\n  }\n  return roomId;\n};\n\nexport const getImageInfo = (img: HTMLImageElement, fileOrBlob: File | Blob): IImageInfo => {\n  const info: IImageInfo = {};\n  info.w = img.width;\n  info.h = img.height;\n  info.mimetype = fileOrBlob.type;\n  info.size = fileOrBlob.size;\n  return info;\n};\n\nexport const getVideoInfo = (video: HTMLVideoElement, fileOrBlob: File | Blob): IVideoInfo => {\n  const info: IVideoInfo = {};\n  info.duration = Number.isNaN(video.duration) ? undefined : Math.floor(video.duration * 1000);\n  info.w = video.videoWidth;\n  info.h = video.videoHeight;\n  info.mimetype = fileOrBlob.type;\n  info.size = fileOrBlob.size;\n  return info;\n};\n\nexport const getThumbnailContent = (thumbnailInfo: {\n  thumbnail: File | Blob;\n  encInfo: EncryptedAttachmentInfo | undefined;\n  mxc: string;\n  width: number;\n  height: number;\n}): IThumbnailContent => {\n  const { thumbnail, encInfo, mxc, width, height } = thumbnailInfo;\n\n  const content: IThumbnailContent = {\n    thumbnail_info: {\n      mimetype: thumbnail.type,\n      size: thumbnail.size,\n      w: width,\n      h: height,\n    },\n  };\n  if (encInfo) {\n    content.thumbnail_file = {\n      ...encInfo,\n      url: mxc,\n    };\n  } else {\n    content.thumbnail_url = mxc;\n  }\n  return content;\n};\n\nconst getUploadFileName = (content: File | Blob): string => {\n  if (content instanceof File) return content.name;\n\n  const mimeSuffix = content.type.split('/')[1]?.split('+')[0]?.toLowerCase();\n  const extension = mimeSuffix && /^[a-z0-9]+$/.test(mimeSuffix) ? mimeSuffix : undefined;\n\n  return `upload-${Date.now()}${extension ? `.${extension}` : ''}`;\n};\n\nexport const encryptFile = async <T extends File | Blob>(\n  file: T\n): Promise<{\n  encInfo: EncryptedAttachmentInfo;\n  file: File;\n  originalFile: T;\n}> => {\n  let blob: Blob;\n  let info: EncryptedAttachmentInfo;\n  try {\n    ({ blob, info } = await encryptBlobInWorker(file));\n  } catch {\n    ({ blob, info } = await encryptAttachmentStreaming(file));\n  }\n  const fileName = getUploadFileName(file);\n  const encFile = new File([blob], fileName, {\n    type: file.type,\n  });\n  return {\n    encInfo: info,\n    file: encFile,\n    originalFile: file,\n  };\n};\n\nexport const decryptFile = async (\n  dataBuffer: ArrayBuffer,\n  type: string,\n  encInfo: EncryptedAttachmentInfo\n): Promise<Blob> => {\n  const dataArray = await decryptAttachment(dataBuffer, encInfo);\n  const blob = new Blob([dataArray], { type });\n  return blob;\n};\n\nexport type TUploadContent = File;\n\nexport type UploadContentOpts = {\n  name?: string;\n  type?: string;\n  includeFilename?: boolean;\n  progressHandler?: (progress: UploadProgress) => void;\n  abortController?: AbortController;\n};\n\n/**\n * matrix-js-sdk's `MatrixClient.uploadContent` uploads via `XMLHttpRequest` (to\n * expose progress events), which bypasses the client's configured `fetchFn`. In\n * the Tauri webview that XHR is subject to CORS / Private Network Access checks\n * and gets blocked, so uploads to the homeserver fail. Route the upload through\n * our Tauri-aware `fetch` instead, keeping the SDK path (with progress) on web.\n */\nconst UPLOAD_CHUNK_SIZE = 2 * 1024 * 1024;\n\nconst blobToBase64 = (blob: Blob): Promise<string> =>\n  new Promise((resolve, reject) => {\n    const reader = new FileReader();\n    reader.addEventListener('load', () => {\n      const result = reader.result as string;\n      resolve(result.slice(result.indexOf(',') + 1));\n    });\n    reader.addEventListener('error', () => reject(reader.error));\n    reader.readAsDataURL(blob);\n  });\n\nconst tauriUploadAbortControllers = new WeakMap<Promise<UploadResponse>, AbortController>();\n\ntype UploadFileType = TUploadContent | Blob | XMLHttpRequestBodyInit;\n\nexport const uploadContentToServer = (\n  mx: MatrixClient,\n  file: UploadFileType,\n  opts: UploadContentOpts = {}\n): Promise<UploadResponse> => {\n  if (!isTauri()) {\n    return mx.uploadContent(file, opts);\n  }\n\n  const abortController = opts.abortController ?? new AbortController();\n  const includeFilename = opts.includeFilename ?? true;\n  const isFile = file instanceof File;\n  const contentType =\n    opts.type || (file instanceof Blob ? file.type : '') || 'application/octet-stream';\n  const fileName = opts.name ?? (isFile ? file.name : undefined);\n\n  const url = new URL(`${mx.baseUrl}${MediaPrefix.V3}/upload`);\n  if (includeFilename && fileName) {\n    url.searchParams.set('filename', fileName);\n  }\n\n  const accessToken = mx.getAccessToken();\n  const requestId =\n    globalThis.crypto?.randomUUID?.() ??\n    `upload-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n\n  const promise = (async (): Promise<UploadResponse> => {\n    const blob = file instanceof Blob ? file : new Blob([file as BlobPart]);\n    const total = blob.size;\n\n    const throwIfAborted = () => {\n      if (abortController.signal.aborted) {\n        throw new DOMException('The operation was aborted', 'AbortError');\n      }\n    };\n    const onAbort = () => {\n      void invoke('abort_native_upload', { requestId });\n    };\n    abortController.signal.addEventListener('abort', onAbort, { once: true });\n\n    const half = Math.floor(total / 2);\n    const onProgress = new Channel<{ loaded: number; total: number }>();\n    if (opts.progressHandler) {\n      // eslint-disable-next-line unicorn/prefer-add-event-listener -- Channel only exposes onmessage\n      onProgress.onmessage = (payload) => {\n        const sent = payload.total ? payload.loaded / payload.total : 0;\n        opts.progressHandler?.({ loaded: half + Math.floor(sent * (total - half)), total });\n      };\n    }\n\n    const writeChunk = async (start: number) => {\n      const chunk = await blobToBase64(blob.slice(start, start + UPLOAD_CHUNK_SIZE));\n      await invoke('upload_write_chunk', { requestId, chunk });\n    };\n\n    try {\n      for (let offset = 0; offset < total; offset += UPLOAD_CHUNK_SIZE) {\n        throwIfAborted();\n        const end = Math.min(offset + UPLOAD_CHUNK_SIZE, total);\n        // eslint-disable-next-line no-await-in-loop -- sequential chunks bound webview memory\n        await writeChunk(offset);\n        opts.progressHandler?.({ loaded: Math.floor(end / 2), total });\n      }\n      throwIfAborted();\n\n      const result = await invoke<{ status: number; body: string }>('native_upload', {\n        requestId,\n        url: url.toString(),\n        contentType,\n        authorization: accessToken ? `Bearer ${accessToken}` : null,\n        onProgress,\n      });\n      if (result.status < 200 || result.status >= 300) {\n        let parsed: { errcode?: string; error?: string } = {};\n        try {\n          parsed = JSON.parse(result.body);\n        } catch {\n          // Non-JSON error body; fall back to the status code.\n        }\n        throw new MatrixError({\n          errcode: parsed.errcode,\n          error: parsed.error ?? `Upload failed with status ${result.status}`,\n        });\n      }\n      return JSON.parse(result.body) as UploadResponse;\n    } catch (err) {\n      void invoke('abort_native_upload', { requestId });\n      throw err;\n    } finally {\n      abortController.signal.removeEventListener('abort', onAbort);\n    }\n  })();\n\n  tauriUploadAbortControllers.set(promise, abortController);\n  void promise.finally(() => tauriUploadAbortControllers.delete(promise));\n  return promise;\n};\n\nexport const cancelUploadContent = (\n  mx: MatrixClient,\n  promise: Promise<UploadResponse>\n): boolean => {\n  const abortController = tauriUploadAbortControllers.get(promise);\n  if (abortController) {\n    abortController.abort();\n    return true;\n  }\n  return mx.cancelUpload(promise);\n};\n\nexport type ContentUploadOptions = {\n  name?: string;\n  fileType?: string;\n  hideFilename?: boolean;\n  onPromise?: (promise: Promise<UploadResponse>) => void;\n  onProgress?: (progress: UploadProgress) => void;\n  onSuccess: (mxc: string) => void;\n  onError: (error: MatrixError) => void;\n};\n\nexport const uploadContent = async (\n  mx: MatrixClient,\n  file: TUploadContent,\n  options: ContentUploadOptions\n) => {\n  const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options;\n\n  const uploadStart = performance.now();\n  const uploadPromise = uploadContentToServer(mx, file, {\n    name,\n    type: fileType,\n    includeFilename: !hideFilename,\n    progressHandler: onProgress,\n  });\n  onPromise?.(uploadPromise);\n  try {\n    const data = await uploadPromise;\n    const mxc = data.content_uri;\n    if (mxc) {\n      const mediaType = file.type.split('/')[0] || 'unknown';\n      Sentry.metrics.distribution(\n        'sable.media.upload_latency_ms',\n        performance.now() - uploadStart,\n        {\n          attributes: { type: mediaType },\n        }\n      );\n      Sentry.metrics.distribution('sable.media.upload_bytes', file.size, {\n        attributes: { type: mediaType },\n      });\n      onSuccess(mxc);\n    } else {\n      Sentry.metrics.count('sable.media.upload_error', 1, {\n        attributes: { reason: 'no_uri' },\n      });\n      onError(new MatrixError(data));\n    }\n  } catch (e: unknown) {\n    Sentry.metrics.count('sable.media.upload_error', 1, {\n      attributes: { reason: 'exception' },\n    });\n    const err = e as { message?: string; name?: string };\n    const error = typeof err?.message === 'string' ? err.message : undefined;\n    const errcode = typeof err?.name === 'string' ? err.name : undefined;\n    onError(new MatrixError({ error, errcode }));\n  }\n};\n\nexport const matrixEventByRecency = (m1: MatrixEvent, m2: MatrixEvent) => m2.getTs() - m1.getTs();\n\nexport const factoryEventSentBy = (senderId: string) => (ev: MatrixEvent) =>\n  ev.getSender() === senderId;\n\nexport const eventWithShortcode = (ev: MatrixEvent) =>\n  typeof ev.getContent().shortcode === 'string';\n\nconst PRESENT_MEMBERSHIPS = new Set<string>([KnownMembership.Join, KnownMembership.Invite]);\n\n/**\n * \"m.direct\" is the reliable signal, the member count heuristic below is only a\n * fallback: it misses direct rooms which are unencrypted or hold members who left.\n */\nexport const getDMRoomFor = (mx: MatrixClient, userId: string): Room | undefined => {\n  const mDirects = mx.getAccountData(\n    EventType.Direct as string as unknown as keyof AccountDataEvents\n  );\n  const directRoomIds: unknown = mDirects?.getContent()[userId];\n  const tagged = (Array.isArray(directRoomIds) ? (directRoomIds as string[]) : [])\n    .toSorted(factoryRoomIdByActivity(mx))\n    .map((roomId) => mx.getRoom(roomId))\n    .filter((room): room is Room => room?.getMyMembership() === (KnownMembership.Join as string));\n\n  if (tagged.length > 0) {\n    // Prefer a room the other user is still part of over an abandoned one.\n    return (\n      tagged.find((room) => PRESENT_MEMBERSHIPS.has(room.getMember(userId)?.membership ?? '')) ??\n      tagged[0]\n    );\n  }\n\n  const dmLikeRooms = mx\n    .getRooms()\n    .filter(\n      (room) =>\n        room.getMyMembership() === (KnownMembership.Join as string) &&\n        room.hasEncryptionStateEvent() &&\n        room.getMembers().length <= 2\n    );\n\n  return dmLikeRooms.find((room) => room.getMember(userId));\n};\n\nexport const guessDmRoomUserId = (room: Room, myUserId: string): string => {\n  const getOldestMember = (members: RoomMember[]): RoomMember | undefined => {\n    let oldestMemberTs: number | undefined;\n    let oldestMember: RoomMember | undefined;\n\n    const pickOldestMember = (member: RoomMember) => {\n      if (member.userId === myUserId) return;\n\n      if (\n        oldestMemberTs === undefined ||\n        (member.events.member && member.events.member.getTs() < oldestMemberTs)\n      ) {\n        oldestMember = member;\n        oldestMemberTs = member.events.member?.getTs();\n      }\n    };\n\n    members.forEach(pickOldestMember);\n\n    return oldestMember;\n  };\n\n  // Pick the joined user who's been here longest (and isn't us),\n  const member = getOldestMember(room.getJoinedMembers());\n  if (member) return member.userId;\n\n  // if there are no joined members other than us, use the oldest member\n  const member1 = getOldestMember(\n    room.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getMembers() ?? []\n  );\n  return member1?.userId ?? myUserId;\n};\n\nexport const addRoomIdToMDirect = async (\n  mx: MatrixClient,\n  roomId: string,\n  userId: string\n): Promise<void> => {\n  const mDirectsEvent = mx.getAccountData(\n    EventType.Direct as string as unknown as keyof AccountDataEvents\n  );\n  let userIdToRoomIds: Record<string, string[]> = {};\n\n  if (typeof mDirectsEvent !== 'undefined')\n    userIdToRoomIds = structuredClone(mDirectsEvent.getContent());\n\n  // remove it from the lists of any others users\n  // (it can only be a DM room for one person)\n  Object.keys(userIdToRoomIds).forEach((targetUserId) => {\n    const roomIds = userIdToRoomIds[targetUserId]!;\n\n    if (targetUserId !== userId) {\n      const indexOfRoomId = roomIds.indexOf(roomId);\n      if (indexOfRoomId > -1) {\n        roomIds.splice(indexOfRoomId, 1);\n      }\n    }\n  });\n\n  const roomIds = userIdToRoomIds[userId] || [];\n  if (roomIds.indexOf(roomId) === -1) {\n    roomIds.push(roomId);\n  }\n  userIdToRoomIds[userId] = roomIds;\n\n  await mx.setAccountData(\n    EventType.Direct as string as unknown as keyof AccountDataEvents,\n    userIdToRoomIds\n  );\n};\n\nexport const removeRoomIdFromMDirect = async (mx: MatrixClient, roomId: string): Promise<void> => {\n  const mDirectsEvent = mx.getAccountData(\n    EventType.Direct as string as unknown as keyof AccountDataEvents\n  );\n  let userIdToRoomIds: Record<string, string[]> = {};\n\n  if (typeof mDirectsEvent !== 'undefined')\n    userIdToRoomIds = structuredClone(mDirectsEvent.getContent());\n\n  Object.keys(userIdToRoomIds).forEach((targetUserId) => {\n    const roomIds = userIdToRoomIds[targetUserId]!;\n    const indexOfRoomId = roomIds.indexOf(roomId);\n    if (indexOfRoomId > -1) {\n      roomIds.splice(indexOfRoomId, 1);\n    }\n  });\n\n  await mx.setAccountData(\n    EventType.Direct as string as unknown as keyof AccountDataEvents,\n    userIdToRoomIds\n  );\n};\n\nexport const downloadMedia = async (src: string, options?: MediaTransportOptions): Promise<Blob> =>\n  fetchMediaBlob(src, options);\n\nexport const downloadEncryptedMedia = async (\n  src: string,\n  decryptContent: (buf: ArrayBuffer) => Promise<Blob>\n): Promise<Blob> => {\n  const encryptedContent = await downloadMedia(src);\n  return decryptContent(await encryptedContent.arrayBuffer());\n};\n\nconst sleepForMs = (ms: number) =>\n  new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n\nexport const rateLimitedActions = async <T, R = void>(\n  data: T[],\n  callback: (item: T, index: number) => Promise<R>,\n  maxRetryCount?: number\n) => {\n  let retryCount = 0;\n\n  let actionInterval = 0;\n\n  const performAction = async (dataItem: T, index: number) => {\n    const [err] = await to<R, MatrixError>(callback(dataItem, index));\n\n    if (err?.httpStatus === 429) {\n      if (retryCount === maxRetryCount) {\n        return;\n      }\n\n      const waitMS = err.getRetryAfterMs() ?? 3000;\n      actionInterval = waitMS * 1.5;\n      await sleepForMs(waitMS);\n      retryCount += 1;\n\n      await performAction(dataItem, index);\n    }\n  };\n\n  for (let i = 0; i < data.length; i += 1) {\n    const dataItem = data[i]!;\n    retryCount = 0;\n    // oxlint-disable-next-line no-await-in-loop\n    await performAction(dataItem, i);\n    if (actionInterval > 0) {\n      // oxlint-disable-next-line no-await-in-loop\n      await sleepForMs(actionInterval);\n    }\n  }\n};\n\nexport const toggleReaction = (\n  mx: MatrixClient,\n  room: Room,\n  targetEventId: string,\n  key: string,\n  shortcode?: string,\n  timelineSet?: EventTimelineSet\n) => {\n  const relations = getEventReactions(\n    timelineSet ?? room.getUnfilteredTimelineSet(),\n    targetEventId\n  );\n  const allReactions = relations?.getSortedAnnotationsByKey() ?? [];\n  const [, reactionsSet] = allReactions.find(([k]) => k === key) ?? [];\n  const reactions: MatrixEvent[] = reactionsSet ? Array.from(reactionsSet) : [];\n  const myReaction = reactions.find(factoryEventSentBy(mx.getUserId()!));\n\n  if (myReaction) {\n    const eventId = myReaction.getId();\n    if (eventId) mx.redactEvent(room.roomId, eventId);\n    return;\n  }\n  const rShortcode =\n    shortcode || (reactions.find(eventWithShortcode)?.getContent().shortcode as string | undefined);\n  // send the reaction\n  mx.sendEvent(\n    room.roomId,\n    EventType.Reaction as string as unknown as keyof TimelineEvents,\n    getReactionContent(\n      targetEventId,\n      key,\n      mx,\n      room,\n      rShortcode\n    ) as TimelineEvents[keyof TimelineEvents]\n  );\n};\n","/**\n * Lightweight debug logger for the account switcher (and other features).\n *\n * Enable in the browser console:\n *   localStorage.setItem('sable_debug', '1'); location.reload();\n *\n * Disable:\n *   localStorage.removeItem('sable_debug'); location.reload();\n */\n\nconst isDebug = (): boolean => import.meta.env.DEV || localStorage.getItem('sable_debug') === '1';\n\ntype LogLevel = 'log' | 'warn' | 'error';\n\nconst fmt = (namespace: string, level: LogLevel, ...args: unknown[]): void => {\n  if (!isDebug() && level === 'log') return;\n  const prefix = `[sable:${namespace}]`;\n  console[level](prefix, ...args);\n};\n\nexport const createLogger = (namespace: string) => ({\n  log: (...args: unknown[]) => fmt(namespace, 'log', ...args),\n  warn: (...args: unknown[]) => fmt(namespace, 'warn', ...args),\n  error: (...args: unknown[]) => fmt(namespace, 'error', ...args),\n});\n","import { atom } from 'jotai';\nimport type { MatrixEvent, Room } from '$types/matrix-sdk';\nimport { createLogger } from '$utils/debug';\nimport {\n  atomWithLocalStorage,\n  getLocalStorageItem,\n  setEssentialLocalStorageItem,\n  setLocalStorageItem,\n} from './utils/atomWithLocalStorage';\n\nconst log = createLogger('sessions');\n\nconst notifySessionChanged = (): void => {\n  if (typeof window === 'undefined') return;\n  window.dispatchEvent(new Event('sable-session-changed'));\n};\n\nexport type OidcSessionInfo = {\n  issuer: string;\n  clientId: string;\n};\n\nexport type Session = {\n  baseUrl: string;\n  userId: string;\n  deviceId: string;\n  accessToken: string;\n  expiresInMs?: number;\n  refreshToken?: string;\n  fallbackSdkStores?: boolean;\n  slidingSyncOptIn?: boolean;\n  oidc?: OidcSessionInfo;\n};\n\nexport type Sessions = Session[];\nexport type SessionStoreName = {\n  sync: string;\n  crypto: string;\n  /** Prefix for the Rust crypto IndexedDB: the actual DB is `${rustCryptoPrefix}::matrix-sdk-crypto` */\n  rustCryptoPrefix: string;\n};\n\n/**\n * Migration code for old session\n */\nconst FALLBACK_STORE_NAME: SessionStoreName = {\n  sync: 'web-sync-store',\n  crypto: 'crypto-store',\n  rustCryptoPrefix: 'matrix-js-sdk',\n} as const;\n\nexport function setFallbackSession(\n  accessToken: string,\n  deviceId: string,\n  userId: string,\n  baseUrl: string\n) {\n  localStorage.setItem('cinny_access_token', accessToken);\n  localStorage.setItem('cinny_device_id', deviceId);\n  localStorage.setItem('cinny_user_id', userId);\n  localStorage.setItem('cinny_hs_base_url', baseUrl);\n  notifySessionChanged();\n}\nconst removeFallbackSession = () => {\n  localStorage.removeItem('cinny_hs_base_url');\n  localStorage.removeItem('cinny_user_id');\n  localStorage.removeItem('cinny_device_id');\n  localStorage.removeItem('cinny_access_token');\n  notifySessionChanged();\n};\nexport const getFallbackSession = (): Session | undefined => {\n  const baseUrl = localStorage.getItem('cinny_hs_base_url');\n  const userId = localStorage.getItem('cinny_user_id');\n  const deviceId = localStorage.getItem('cinny_device_id');\n  const accessToken = localStorage.getItem('cinny_access_token');\n\n  if (baseUrl && userId && deviceId && accessToken) {\n    return {\n      baseUrl,\n      userId,\n      deviceId,\n      accessToken,\n      fallbackSdkStores: true,\n    };\n  }\n\n  return undefined;\n};\n/**\n * End of migration code for old session\n */\n\nexport const getSessionStoreName = (session: Session): SessionStoreName => {\n  if (session.fallbackSdkStores) {\n    return FALLBACK_STORE_NAME;\n  }\n\n  return {\n    sync: `sync${session.userId}`,\n    crypto: `crypto${session.userId}`,\n    rustCryptoPrefix: `sync${session.userId}`,\n  };\n};\n\nexport const MATRIX_SESSIONS_KEY = 'matrixSessions';\nconst baseSessionsAtom = atomWithLocalStorage<Sessions>(\n  MATRIX_SESSIONS_KEY,\n  (key) => {\n    const defaultSessions: Sessions = [];\n    const sessions = getLocalStorageItem(key, defaultSessions);\n\n    // Before multi account support session was stored\n    // as multiple item in local storage.\n    // So we need these migration code.\n    const fallbackSession = getFallbackSession();\n    if (fallbackSession) {\n      removeFallbackSession();\n      sessions.push(fallbackSession);\n      setLocalStorageItem(key, sessions);\n    }\n    return sessions;\n  },\n  (key, value) => {\n    setLocalStorageItem(key, value);\n  }\n);\n\nexport type SessionsAction =\n  | {\n      type: 'PUT';\n      session: Session;\n    }\n  | {\n      // Merge a field change into an existing session without clobbering rotated tokens.\n      type: 'UPDATE';\n      userId: string;\n      patch: Partial<Session>;\n    }\n  | {\n      type: 'DELETE';\n      session: Session;\n    };\n\nexport const sessionsAtom = atom<Sessions, [SessionsAction], void>(\n  (get) => get(baseSessionsAtom),\n  (get, set, action) => {\n    if (action.type === 'PUT') {\n      const sessions = [...get(baseSessionsAtom)];\n      const sessionIndex = sessions.findIndex(\n        (session) => session.userId === action.session.userId\n      );\n      if (sessionIndex === -1) {\n        log.log('PUT new session', action.session.userId);\n        sessions.push(action.session);\n      } else {\n        log.log('PUT update session', action.session.userId);\n        sessions.splice(sessionIndex, 1, action.session);\n      }\n      set(baseSessionsAtom, sessions);\n      return;\n    }\n    if (action.type === 'UPDATE') {\n      const sessions = [...get(baseSessionsAtom)];\n      const sessionIndex = sessions.findIndex((session) => session.userId === action.userId);\n      if (sessionIndex === -1) return;\n      sessions.splice(sessionIndex, 1, { ...sessions[sessionIndex]!, ...action.patch });\n      set(baseSessionsAtom, sessions);\n      return;\n    }\n    if (action.type === 'DELETE') {\n      log.log('DELETE session', action.session.userId);\n      const sessions = get(baseSessionsAtom).filter(\n        (session) => session.userId !== action.session.userId\n      );\n      set(baseSessionsAtom, sessions);\n      notifySessionChanged();\n    }\n  }\n);\n\n// Runs outside React (token refresher), so it writes localStorage directly; the synthetic storage\n// event makes the mounted atom re-read so its in-memory copy cannot later clobber the new tokens.\nexport const updateSessionTokens = (\n  userId: string,\n  tokens: { accessToken: string; refreshToken?: string; expiresInMs?: number }\n): void => {\n  const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);\n  const index = sessions.findIndex((session) => session.userId === userId);\n  if (index === -1) return;\n  sessions[index] = {\n    ...sessions[index]!,\n    accessToken: tokens.accessToken,\n    refreshToken: tokens.refreshToken ?? sessions[index]!.refreshToken,\n    expiresInMs: tokens.expiresInMs ?? sessions[index]!.expiresInMs,\n  };\n  setEssentialLocalStorageItem(MATRIX_SESSIONS_KEY, sessions);\n  window.dispatchEvent(new StorageEvent('storage', { key: MATRIX_SESSIONS_KEY }));\n  notifySessionChanged();\n};\n\nexport const getStoredSession = (userId: string): Session | undefined =>\n  getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []).find(\n    (session) => session.userId === userId\n  );\n\nexport const getStoredSessionRefreshToken = (userId: string): string | undefined =>\n  getStoredSession(userId)?.refreshToken;\n\nexport const ACTIVE_SESSION_KEY = 'matrixActiveSession';\nconst baseActiveSessionAtom = atomWithLocalStorage<string | undefined>(\n  ACTIVE_SESSION_KEY,\n  (key) => getLocalStorageItem<string | undefined>(key, undefined),\n  (key, value) => setLocalStorageItem(key, value)\n);\n\n/** Stores the userId of the currently active session. */\nexport const activeSessionIdAtom = atom<string | undefined, [string | undefined], void>(\n  (get) => get(baseActiveSessionAtom),\n  (_get, set, value) => {\n    const previous = _get(baseActiveSessionAtom);\n    set(baseActiveSessionAtom, value);\n    if (previous !== value) notifySessionChanged();\n  }\n);\n\ntype PendingNotification = {\n  roomId: string;\n  eventId?: string;\n  targetSessionId?: string;\n};\n\nexport const pendingNotificationAtom = atom<PendingNotification | null>(null);\n\n// ─── In-app notification banner ────────────────────────────────────────────\n\nexport type InAppBannerNotification = {\n  /** Unique id; used to deduplicate rapid-fire events. */\n  id: string;\n  /** Primary title line – kept for backwards-compat (background accounts). */\n  title: string;\n  /** Room display name (used as the #channel part of the subtitle). */\n  roomName?: string;\n  /** Homeserver extracted from the canonical alias or room ID (e.g. matrix.org). */\n  serverName?: string;\n  /** Display name of the sender. */\n  senderName?: string;\n  body?: string;\n  /** Full event context for rendering the same rich preview used elsewhere. */\n  room?: Room;\n  event?: MatrixEvent;\n  /** URL of an avatar or room icon to display inside the banner. */\n  icon?: string;\n  onClick: () => void;\n};\n\nexport const inAppBannerAtom = atom<InAppBannerNotification | null>(null);\n\n// ─── Per-background-account unread counts ──────────────────────────────────\n\nexport type BackgroundUnread = {\n  total: number;\n  highlight: number;\n};\n\n/**\n * Keyed by userId.  Counts accumulate while a session is in the background\n * and are cleared when the user switches to that account.\n */\nexport const backgroundUnreadCountsAtom = atom<Record<string, BackgroundUnread>>({});\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,73,74,76,77,78,79],"mappings":"0WAAA,IAAM,EAAe,OAAO,iBAAqB,KAAe,iBCA1D,EAAa,WCAb,GAAc,UCGpB,SAAS,GAAiB,CAExB,OADA,EAAiB,CAAU,EACpB,CACT,CACA,SAAS,EAAiB,EAAS,CACjC,IAAM,EAAa,EAAQ,WAAa,EAAQ,YAAc,CAAC,EAE/D,MADA,GAAW,QAAU,EAAW,SAAA,UACzB,EAAW,IAAe,EAAA,YAA2B,CAAC,CAC/D,CACA,SAAS,EAAmB,EAAM,EAAS,EAAM,EAAY,CAC3D,IAAM,EAAa,EAAI,WAAa,EAAI,YAAc,CAAC,EACjD,EAAU,EAAW,IAAe,EAAA,YAA2B,CAAC,EACtE,OAAO,EAAQ,KAAU,EAAQ,GAAQ,EAAQ,EACnD,CCHA,IAAM,GAAS,iBACT,GAAyB,CAAC,EAChC,SAAS,GAAe,EAAU,CAChC,GAAI,EAAE,YAAa,GACjB,OAAO,EAAS,EAElB,IAAM,EAAU,EAAW,QACrB,EAAe,CAAC,EAChB,EAAgB,OAAO,KAAK,EAAsB,EACxD,EAAc,QAAS,GAAU,CAC/B,IAAM,EAAwB,GAAuB,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