@element-hq/element-call-embedded 0.12.2 → 0.13.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/assets/IndexedDBWorker-whz4J8_U.js.map +1 -1
  2. package/dist/assets/{en-app-DpvT44u_.json → en-app-oq6NTBpJ.json} +6 -0
  3. package/dist/assets/index-BFG1A6hV.js +9 -0
  4. package/dist/assets/index-BFG1A6hV.js.map +1 -0
  5. package/dist/assets/index-DKNt5H0S.css +1 -0
  6. package/dist/assets/index-DWWUme-R.js +340 -0
  7. package/dist/assets/{index-BQv1OC6W.js.map → index-DWWUme-R.js.map} +1 -1
  8. package/dist/assets/{index-BQ3oe8uL.js → index-y97NXMOv.js} +2 -2
  9. package/dist/assets/{index-BQ3oe8uL.js.map → index-y97NXMOv.js.map} +1 -1
  10. package/dist/assets/livekit-client.e2ee.worker-B0tndz1T.js +2 -0
  11. package/dist/assets/livekit-client.e2ee.worker-B0tndz1T.js.map +1 -0
  12. package/dist/assets/{polyfill-force-CzShxH5l.js → polyfill-force-B6TMcLRE.js} +2 -2
  13. package/dist/assets/{polyfill-force-CzShxH5l.js.map → polyfill-force-B6TMcLRE.js.map} +1 -1
  14. package/dist/assets/{polyfill-force-C-Pa3wDT.js → polyfill-force-KcHJ8IvO.js} +2 -2
  15. package/dist/assets/{polyfill-force-C-Pa3wDT.js.map → polyfill-force-KcHJ8IvO.js.map} +1 -1
  16. package/dist/assets/{spa-_3kkJMwV.js → spa-BSD0eE2w.js} +2 -2
  17. package/dist/assets/{spa-_3kkJMwV.js.map → spa-BSD0eE2w.js.map} +1 -1
  18. package/dist/config.json +1 -1
  19. package/dist/index.html +1 -1
  20. package/package.json +1 -1
  21. package/dist/assets/index-BQv1OC6W.js +0 -340
  22. package/dist/assets/index-BtY3MdEn.css +0 -1
  23. package/dist/assets/index-W4jTSiQP.js +0 -9
  24. package/dist/assets/index-W4jTSiQP.js.map +0 -1
  25. package/dist/assets/livekit-client.e2ee.worker-D7jue42X.js +0 -2
  26. package/dist/assets/livekit-client.e2ee.worker-D7jue42X.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"IndexedDBWorker-whz4J8_U.js","sources":["../node_modules/matrix-js-sdk/node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/matrix-js-sdk/node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/matrix-js-sdk/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/matrix-js-sdk/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/matrix-js-sdk/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","../node_modules/loglevel/lib/loglevel.js","../node_modules/matrix-js-sdk/lib/logger.js","../node_modules/unhomoglyph/index.js","../node_modules/retry/lib/retry_operation.js","../node_modules/retry/lib/retry.js","../node_modules/retry/index.js","../node_modules/p-retry/index.js","../node_modules/matrix-js-sdk/lib/NamespacedValue.js","../node_modules/matrix-js-sdk/lib/@types/location.js","../node_modules/matrix-js-sdk/lib/@types/read_receipts.js","../node_modules/matrix-js-sdk/lib/utils.js","../node_modules/matrix-js-sdk/lib/@types/sync.js","../node_modules/matrix-js-sdk/lib/@types/event.js","../node_modules/matrix-js-sdk/lib/receipt-accumulator.js","../node_modules/matrix-js-sdk/lib/sync-accumulator.js","../node_modules/matrix-js-sdk/lib/indexeddb-helpers.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-local-backend.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-store-worker.js","../src/IndexedDBWorker.ts"],"sourcesContent":["function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nexport { _typeof as default };","import _typeof from \"./typeof.js\";\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nexport { toPrimitive as default };","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nexport { _defineProperty as default };","function asyncGeneratorStep(n, t, e, r, o, a, c) {\n try {\n var i = n[a](c),\n u = i.value;\n } catch (n) {\n return void e(n);\n }\n i.done ? t(u) : Promise.resolve(u).then(r, o);\n}\nfunction _asyncToGenerator(n) {\n return function () {\n var t = this,\n e = arguments;\n return new Promise(function (r, o) {\n var a = n.apply(t, e);\n function _next(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n);\n }\n function _throw(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n);\n }\n _next(void 0);\n });\n };\n}\nexport { _asyncToGenerator as default };","/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n var _loggersByName = {};\n var defaultLogger = null;\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods() {\n /*jshint validthis:true */\n var level = this.getLevel();\n\n // Replace the actual methods.\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, this.name);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n\n // Return any important warnings.\n if (typeof console === undefinedType && level < this.levels.SILENT) {\n return \"No console available for logging\";\n }\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, _level, _loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, factory) {\n // Private instance variables.\n var self = this;\n /**\n * The level inherited from a parent logger (or a global default). We\n * cache this here rather than delegating to the parent so that it stays\n * in sync with the actual logging methods that we have installed (the\n * parent could change levels but we might not have rebuilt the loggers\n * in this child yet).\n * @type {number}\n */\n var inheritedLevel;\n /**\n * The default level for this logger, if any. If set, this overrides\n * `inheritedLevel`.\n * @type {number|null}\n */\n var defaultLevel;\n /**\n * A user-specific level for this logger. If set, this overrides\n * `defaultLevel`.\n * @type {number|null}\n */\n var userLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var cookieName = encodeURIComponent(storageKey);\n var location = cookie.indexOf(cookieName + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(\n cookie.slice(location + cookieName.length + 1)\n )[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n function normalizeLevel(input) {\n var level = input;\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n return level;\n } else {\n throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n }\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n if (userLevel != null) {\n return userLevel;\n } else if (defaultLevel != null) {\n return defaultLevel;\n } else {\n return inheritedLevel;\n }\n };\n\n self.setLevel = function (level, persist) {\n userLevel = normalizeLevel(level);\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(userLevel);\n }\n\n // NOTE: in v2, this should call rebuild(), which updates children.\n return replaceLoggingMethods.call(self);\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = normalizeLevel(level);\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n userLevel = null;\n clearPersistedLevel();\n replaceLoggingMethods.call(self);\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n self.rebuild = function () {\n if (defaultLogger !== self) {\n inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n }\n replaceLoggingMethods.call(self);\n\n if (defaultLogger === self) {\n for (var childName in _loggersByName) {\n _loggersByName[childName].rebuild();\n }\n }\n };\n\n // Initialize all the internal levels.\n inheritedLevel = normalizeLevel(\n defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n );\n var initialLevel = getPersistedLevel();\n if (initialLevel != null) {\n userLevel = normalizeLevel(initialLevel);\n }\n replaceLoggingMethods.call(self);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n defaultLogger = new Logger();\n\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name,\n defaultLogger.methodFactory\n );\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2018 André Jaenisch\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\n\n/** Logger interface used within the js-sdk codebase */\n\n/** The basic interface for a logger which doesn't support children */\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nvar DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n var supportedByConsole = methodName === \"error\" || methodName === \"warn\" || methodName === \"trace\" || methodName === \"info\" || methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix) {\n var loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : \"-\".concat(prefix));\n var prefixLogger = loglevel.getLogger(loggerName);\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = childPrefix => {\n // create the new child logger\n var childLogger = getPrefixedLogger((prefix !== null && prefix !== void 0 ? prefix : \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n */\nexport var logger = getPrefixedLogger();\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan {\n constructor(parent, name) {\n this.parent = parent;\n _defineProperty(this, \"name\", void 0);\n this.name = name + \":\";\n }\n trace() {\n for (var _len2 = arguments.length, msg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n msg[_key2] = arguments[_key2];\n }\n this.parent.trace(this.name, ...msg);\n }\n debug() {\n for (var _len3 = arguments.length, msg = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n msg[_key3] = arguments[_key3];\n }\n this.parent.debug(this.name, ...msg);\n }\n info() {\n for (var _len4 = arguments.length, msg = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n msg[_key4] = arguments[_key4];\n }\n this.parent.info(this.name, ...msg);\n }\n warn() {\n for (var _len5 = arguments.length, msg = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n msg[_key5] = arguments[_key5];\n }\n this.parent.warn(this.name, ...msg);\n }\n error() {\n for (var _len6 = arguments.length, msg = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n msg[_key6] = arguments[_key6];\n }\n this.parent.error(this.name, ...msg);\n }\n}\n//# sourceMappingURL=logger.js.map","'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n return data[match];\n}\n\nfunction unhomoglyph(str) {\n return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","module.exports = require('./lib/retry');","'use strict';\nconst retry = require('retry');\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports.default = pRetry;\n\nmodule.exports.AbortError = AbortError;\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nexport class NamespacedValue {\n // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n // Goal is to to have developers explicitly say there is no stable value (if applicable).\n\n constructor(stable, unstable) {\n this.stable = stable;\n this.unstable = unstable;\n if (!this.unstable && !this.stable) {\n throw new Error(\"One of stable or unstable values must be supplied\");\n }\n }\n get name() {\n if (this.stable) {\n return this.stable;\n }\n return this.unstable;\n }\n get altName() {\n if (!this.stable) {\n return null;\n }\n return this.unstable;\n }\n get names() {\n var names = [this.name];\n var altName = this.altName;\n if (altName) names.push(altName);\n return names;\n }\n matches(val) {\n return this.name === val || this.altName === val;\n }\n\n // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.\n findIn(obj) {\n var val = undefined;\n if (this.name) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.name];\n }\n if (!val && this.altName) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.altName];\n }\n return val;\n }\n includedIn(arr) {\n var included = false;\n if (this.name) {\n included = arr.includes(this.name);\n }\n if (!included && this.altName) {\n included = arr.includes(this.altName);\n }\n return included;\n }\n}\nexport class ServerControlledNamespacedValue extends NamespacedValue {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"preferUnstable\", false);\n }\n setPreferUnstable(preferUnstable) {\n this.preferUnstable = preferUnstable;\n }\n get name() {\n if (this.stable && !this.preferUnstable) {\n return this.stable;\n }\n return this.unstable;\n }\n}\n\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\nexport class UnstableValue extends NamespacedValue {\n // Note: Constructor difference is that `unstable` is *required*.\n constructor(stable, unstable) {\n super(stable, unstable);\n if (!this.unstable) {\n throw new Error(\"Unstable value must be supplied\");\n }\n }\n get name() {\n return this.unstable;\n }\n get altName() {\n return this.stable;\n }\n}\n//# sourceMappingURL=NamespacedValue.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types for MSC3488 - m.location: Extending events with location data\n\nimport { UnstableValue } from \"../NamespacedValue.js\";\nexport var LocationAssetType = /*#__PURE__*/function (LocationAssetType) {\n LocationAssetType[\"Self\"] = \"m.self\";\n LocationAssetType[\"Pin\"] = \"m.pin\";\n return LocationAssetType;\n}({});\nexport var M_ASSET = new UnstableValue(\"m.asset\", \"org.matrix.msc3488.asset\");\n\n/**\n * The event definition for an m.asset event (in content)\n */\n\nexport var M_TIMESTAMP = new UnstableValue(\"m.ts\", \"org.matrix.msc3488.ts\");\n/**\n * The event definition for an m.ts event (in content)\n */\n\nexport var M_LOCATION = new UnstableValue(\"m.location\", \"org.matrix.msc3488.location\");\n\n/* From the spec at:\n * https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md\n{\n \"type\": \"m.room.message\",\n \"content\": {\n \"body\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"msgtype\": \"m.location\",\n \"geo_uri\": \"geo:51.5008,0.1247;u=35\",\n \"m.location\": {\n \"uri\": \"geo:51.5008,0.1247;u=35\",\n \"description\": \"Matthew's whereabouts\",\n },\n \"m.asset\": {\n \"type\": \"m.self\"\n },\n \"m.text\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"m.ts\": 1636829458432,\n }\n}\n*/\n\n/**\n * The content for an m.location event\n */\n\n/**\n * Possible content for location events as sent over the wire\n */\n//# sourceMappingURL=location.js.map","/*\nCopyright 2022 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var ReceiptType = /*#__PURE__*/function (ReceiptType) {\n ReceiptType[\"Read\"] = \"m.read\";\n ReceiptType[\"FullyRead\"] = \"m.fully_read\";\n ReceiptType[\"ReadPrivate\"] = \"m.read.private\";\n return ReceiptType;\n}({});\nexport var MAIN_ROOM_TIMELINE = \"main\";\n\n// We will only hold a synthetic receipt if we do not have a real receipt or the synthetic is newer.\n// map: receipt type → user Id → receipt\n//# sourceMappingURL=read_receipts.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\n/*\nCopyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport { M_TIMESTAMP } from \"./@types/location.js\";\nimport { ReceiptType } from \"./@types/read_receipts.js\";\nvar interns = new Map();\n\n/**\n * Internalises a string, reusing a known pointer or storing the pointer\n * if needed for future strings.\n * @param str - The string to internalise.\n * @returns The internalised string.\n */\nexport function internaliseString(str) {\n // Unwrap strings before entering the map, if we somehow got a wrapped\n // string as our input. This should only happen from tests.\n if (str instanceof String) {\n str = str.toString();\n }\n\n // Check the map to see if we can store the value\n if (!interns.has(str)) {\n interns.set(str, str);\n }\n\n // Return any cached string reference\n return interns.get(str);\n}\n\n/**\n * Encode a dictionary of query parameters.\n * Omits any undefined/null values.\n * @param params - A dict of key/values to encode e.g.\n * `{\"foo\": \"bar\", \"baz\": \"taz\"}`\n * @returns The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params, urlSearchParams) {\n var searchParams = urlSearchParams !== null && urlSearchParams !== void 0 ? urlSearchParams : new URLSearchParams();\n var _loop = function _loop(key) {\n if (val !== undefined && val !== null) {\n if (Array.isArray(val)) {\n val.forEach(v => {\n searchParams.append(key, String(v));\n });\n } else {\n searchParams.append(key, String(val));\n }\n }\n };\n for (var [key, val] of Object.entries(params)) {\n _loop(key);\n }\n return searchParams;\n}\n/**\n * Replace a stable parameter with the unstable naming for params\n */\nexport function replaceParam(stable, unstable, dict) {\n var result = _objectSpread(_objectSpread({}, dict), {}, {\n [unstable]: dict[stable]\n });\n delete result[stable];\n return result;\n}\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param query - A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @returns The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query) {\n var o = {};\n var params = new URLSearchParams(query);\n for (var key of params.keys()) {\n var val = params.getAll(key);\n o[key] = val.length === 1 ? val[0] : val;\n }\n return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param pathTemplate - The path with template variables e.g. '/foo/$bar'.\n * @param variables - The key/value pairs to replace the template\n * variables with. E.g. `{ \"$bar\": \"baz\" }`.\n * @returns The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate, variables) {\n for (var key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n var value = variables[key];\n if (value === undefined || value === null) {\n continue;\n }\n pathTemplate = pathTemplate.replace(key, encodeURIComponent(value));\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param array - The array.\n * @param fn - Function to execute on each value in the array, with the\n * function signature `fn(element, index, array)`. Return true to\n * remove this element and break.\n * @param reverse - True to search in reverse order.\n * @returns True if an element was removed.\n */\nexport function removeElement(array, fn, reverse) {\n var i;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param value - The thing to check.\n * @returns True if it is a function.\n */\nexport function isFunction(value) {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param obj - The object to check.\n * @param keys - The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj, keys) {\n for (var key of keys) {\n if (!obj.hasOwnProperty(key)) {\n throw new Error(\"Missing required key: \" + key);\n }\n }\n}\n\n/**\n * Deep copy the given object. The object MUST NOT have circular references and\n * MUST NOT have functions.\n * @param obj - The object to deep copy.\n * @returns A copy of the object without any references to the original.\n */\nexport function deepCopy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Compare two objects for equality. The objects MUST NOT have circular references.\n *\n * @param x - The first object to compare.\n * @param y - The second object to compare.\n *\n * @returns true if the two objects are equal\n */\nexport function deepCompare(x, y) {\n // Inspired by\n // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249\n\n // Compare primitives and functions.\n // Also check if both arguments link to the same object.\n if (x === y) {\n return true;\n }\n if (typeof x !== typeof y) {\n return false;\n }\n\n // special-case NaN (since NaN !== NaN)\n if (typeof x === \"number\" && isNaN(x) && isNaN(y)) {\n return true;\n }\n\n // special-case null (since typeof null == 'object', but null.constructor\n // throws)\n if (x === null || y === null) {\n return x === y;\n }\n\n // everything else is either an unequal primitive, or an object\n if (!(x instanceof Object)) {\n return false;\n }\n\n // check they are the same type of object\n if (x.constructor !== y.constructor || x.prototype !== y.prototype) {\n return false;\n }\n\n // special-casing for some special types of object\n if (x instanceof RegExp || x instanceof Date) {\n return x.toString() === y.toString();\n }\n\n // the object algorithm works for Array, but it's sub-optimal.\n if (Array.isArray(x)) {\n if (x.length !== y.length) {\n return false;\n }\n for (var i = 0; i < x.length; i++) {\n if (!deepCompare(x[i], y[i])) {\n return false;\n }\n }\n } else {\n // check that all of y's direct keys are in x\n for (var p in y) {\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n return false;\n }\n }\n\n // finally, compare each of x's keys with y\n for (var _p in x) {\n if (y.hasOwnProperty(_p) !== x.hasOwnProperty(_p) || !deepCompare(x[_p], y[_p])) {\n return false;\n }\n }\n }\n return true;\n}\n\n// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703\n/**\n * Creates an array of object properties/values (entries) then\n * sorts the result by key, recursively. The input object must\n * ensure it does not have loops. If the input is not an object\n * then it will be returned as-is.\n * @param obj - The object to get entries of\n * @returns The entries, sorted by key.\n */\nexport function deepSortedObjectEntries(obj) {\n if (typeof obj !== \"object\") return obj;\n\n // Apparently these are object types...\n if (obj === null || obj === undefined || Array.isArray(obj)) return obj;\n var pairs = [];\n for (var [k, v] of Object.entries(obj)) {\n pairs.push([k, deepSortedObjectEntries(v)]);\n }\n\n // lexicographicCompare is faster than localeCompare, so let's use that.\n pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));\n return pairs;\n}\n\n/**\n * Returns whether the given value is a finite number without type-coercion\n *\n * @param value - the value to test\n * @returns whether or not value is a finite number without type-coercion\n */\nexport function isNumber(value) {\n return typeof value === \"number\" && isFinite(value);\n}\n\n/**\n * Removes zero width chars, diacritics and whitespace from the string\n * Also applies an unhomoglyph on the string, to prevent similar looking chars\n * @param str - the string to remove hidden characters from\n * @returns a string with the hidden characters removed\n */\nexport function removeHiddenChars(str) {\n if (typeof str === \"string\") {\n return unhomoglyph(str.normalize(\"NFD\").replace(removeHiddenCharsRegex, \"\"));\n }\n return \"\";\n}\n\n/**\n * Removes the direction override characters from a string\n * @returns string with chars removed\n */\nexport function removeDirectionOverrideChars(str) {\n if (typeof str === \"string\") {\n return str.replace(/[\\u202d-\\u202e]/g, \"\");\n }\n return \"\";\n}\nexport function normalize(str) {\n // Note: we have to match the filter with the removeHiddenChars() because the\n // function strips spaces and other characters (M becomes RN for example, in lowercase).\n return removeHiddenChars(str.toLowerCase())\n // Strip all punctuation\n .replace(/[\\\\'!\"#$%&()*+,\\-./:;<=>?@[\\]^_`{|}~\\u2000-\\u206f\\u2e00-\\u2e7f]/g, \"\")\n // We also doubly convert to lowercase to work around oddities of the library.\n .toLowerCase();\n}\n\n// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.\n// Includes:\n// various width spaces U+2000 - U+200D\n// LTR and RTL marks U+200E and U+200F\n// LTR/RTL and other directional formatting marks U+202A - U+202F\n// Arabic Letter RTL mark U+061C\n// Combining characters U+0300 - U+036F\n// Zero width no-break space (BOM) U+FEFF\n// Blank/invisible characters (U2800, U2062-U2063)\n// eslint-disable-next-line no-misleading-character-class\nvar removeHiddenCharsRegex = /[\\u2000-\\u200F\\u202A-\\u202F\\u0300-\\u036F\\uFEFF\\u061C\\u2800\\u2062-\\u2063\\s]/g;\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Converts Matrix glob-style string to a regular expression\n * https://spec.matrix.org/v1.7/appendices/#glob-style-matching\n * @param glob - Matrix glob-style string\n * @returns regular expression\n */\nexport function globToRegexp(glob) {\n return escapeRegExp(glob).replace(/\\\\\\*/g, \".*\").replace(/\\?/g, \".\");\n}\nexport function ensureNoTrailingSlash(url) {\n if (url !== null && url !== void 0 && url.endsWith(\"/\")) {\n return url.slice(0, -1);\n } else {\n return url;\n }\n}\n\n/**\n * Returns a promise which resolves with a given value after the given number of ms\n */\nexport function sleep(ms, value) {\n return new Promise(resolve => {\n setTimeout(resolve, ms, value);\n });\n}\n\n/**\n * Utility to log the duration of a promise.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nexport function logDuration(_x, _x2, _x3) {\n return _logDuration.apply(this, arguments);\n}\n\n/**\n * Utility to log the duration of a synchronous block.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nfunction _logDuration() {\n _logDuration = _asyncToGenerator(function* (logger, name, block) {\n var start = Date.now();\n try {\n return yield block();\n } finally {\n var end = Date.now();\n logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n }\n });\n return _logDuration.apply(this, arguments);\n}\nexport function logDurationSync(logger, name, block) {\n var start = Date.now();\n try {\n return block();\n } finally {\n var end = Date.now();\n logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n }\n}\n\n/**\n * Promise/async version of {@link setImmediate}.\n *\n * Implementation is based on `setTimeout` for wider compatibility.\n * @deprecated Use {@link sleep} instead.\n */\nexport function immediate() {\n return new Promise(resolve => setTimeout(resolve));\n}\nexport function isNullOrUndefined(val) {\n return val === null || val === undefined;\n}\n/**\n * Creates a deferred promise. This is a promise that can be resolved or rejected.\n * @deprecated use {@link Promise.withResolvers} instead.\n */\nexport function defer() {\n return Promise.withResolvers();\n}\nexport function promiseMapSeries(_x4, _x5) {\n return _promiseMapSeries.apply(this, arguments);\n}\nfunction _promiseMapSeries() {\n _promiseMapSeries = _asyncToGenerator(function* (promises, fn // if async we don't care about the type as we only await resolution\n ) {\n for (var o of promises) {\n yield fn(yield o);\n }\n });\n return _promiseMapSeries.apply(this, arguments);\n}\nexport function promiseTry(fn) {\n return Promise.resolve(fn());\n}\n\n// Creates and awaits all promises, running no more than `chunkSize` at the same time\nexport function chunkPromises(_x6, _x7) {\n return _chunkPromises.apply(this, arguments);\n}\n\n/**\n * Retries the function until it succeeds or is interrupted. The given function must return\n * a promise which throws/rejects on error, otherwise the retry will assume the request\n * succeeded. The promise chain returned will contain the successful promise. The given function\n * should always return a new promise.\n * @param promiseFn - The function to call to get a fresh promise instance. Takes an\n * attempt count as an argument, for logging/debugging purposes.\n * @returns The promise for the retried operation.\n */\nfunction _chunkPromises() {\n _chunkPromises = _asyncToGenerator(function* (fns, chunkSize) {\n var results = [];\n for (var i = 0; i < fns.length; i += chunkSize) {\n results.push(...(yield Promise.all(fns.slice(i, i + chunkSize).map(fn => fn()))));\n }\n return results;\n });\n return _chunkPromises.apply(this, arguments);\n}\nexport function simpleRetryOperation(promiseFn) {\n return promiseRetry(attempt => {\n return promiseFn(attempt);\n }, {\n forever: true,\n factor: 2,\n minTimeout: 3000,\n // ms\n maxTimeout: 15000 // ms\n });\n}\n\n// String averaging inspired by https://stackoverflow.com/a/2510816\n// Dev note: We make the alphabet a string because it's easier to write syntactically\n// than arrays. Thankfully, strings implement the useful parts of the Array interface\n// anyhow.\n\n/**\n * The default alphabet used by string averaging in this SDK. This matches\n * all usefully printable ASCII characters (0x20-0x7E, inclusive).\n */\nexport var DEFAULT_ALPHABET = (() => {\n var str = \"\";\n for (var c = 0x20; c <= 0x7e; c++) {\n str += String.fromCharCode(c);\n }\n return str;\n})();\n\n/**\n * Pads a string using the given alphabet as a base. The returned string will be\n * padded at the end with the first character in the alphabet.\n *\n * This is intended for use with string averaging.\n * @param s - The string to pad.\n * @param n - The length to pad to.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The padded string.\n */\nexport function alphabetPad(s, n) {\n var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n return s.padEnd(n, alphabet[0]);\n}\n\n/**\n * Converts a baseN number to a string, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param n - The baseN number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number encoded as a string from the alphabet.\n */\nexport function baseToString(n) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n // Developer note: the stringToBase() function offsets the character set by 1 so that repeated\n // characters (ie: \"aaaaaa\" in a..z) don't come out as zero. We have to reverse this here as\n // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun\n // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a\n // sane state. This also means we have to do rollover detection: see below.\n\n var len = BigInt(alphabet.length);\n if (n <= len) {\n var _alphabet;\n return (_alphabet = alphabet[Number(n) - 1]) !== null && _alphabet !== void 0 ? _alphabet : \"\";\n }\n var d = n / len;\n var r = Number(n % len) - 1;\n\n // Rollover detection: if the remainder is negative, it means that the string needs\n // to roll over by 1 character downwards (ie: in a..z, the previous to \"aaa\" would be\n // \"zz\").\n if (r < 0) {\n d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.\n r = Number(len) - 1;\n }\n return baseToString(d, alphabet) + alphabet[r];\n}\n\n/**\n * Converts a string to a baseN number, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param s - The string to convert to a number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number.\n */\nexport function stringToBase(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n var len = BigInt(alphabet.length);\n\n // In our conversion to baseN we do a couple performance optimizations to avoid using\n // excess CPU and such. To create baseN numbers, the input string needs to be reversed\n // so the exponents stack up appropriately, as the last character in the unreversed\n // string has less impact than the first character (in \"abc\" the A is a lot more important\n // for lexicographic sorts). We also do a trick with the character codes to optimize the\n // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know\n // that the alphabet and (theoretically) the input string are constrained on character sets\n // and thus can do simple subtraction to end up with the same result.\n\n // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot\n // rely on Math.pow() (for example) to be capable of handling our insane numbers.\n\n var result = BigInt(0);\n for (var i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {\n var charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);\n\n // We add 1 to the char index to offset the whole numbering scheme. We unpack this in\n // the baseToString() function.\n result += BigInt(1 + charIndex) * len ** j;\n }\n return result;\n}\n\n/**\n * Averages two strings, returning the midpoint between them. This is accomplished by\n * converting both to baseN numbers (where N is the alphabet's length) then averaging\n * those before re-encoding as a string.\n * @param a - The first string.\n * @param b - The second string.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The midpoint between the strings, as a string.\n */\nexport function averageBetweenStrings(a, b) {\n var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n var padN = Math.max(a.length, b.length);\n var baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);\n var baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);\n var avg = (baseA + baseB) / BigInt(2);\n\n // Detect integer division conflicts. This happens when two numbers are divided too close so\n // we lose a .5 precision. We need to add a padding character in these cases.\n if (avg === baseA || avg == baseB) {\n return baseToString(avg, alphabet) + alphabet[0];\n }\n return baseToString(avg, alphabet);\n}\n\n/**\n * Finds the next string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then adding 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which follows the input string.\n */\nexport function nextString(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);\n}\n\n/**\n * Finds the previous string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then subtracting 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which precedes the input string.\n */\nexport function prevString(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);\n}\n\n/**\n * Compares strings lexicographically as a sort-safe function.\n * @param a - The first (reference) string.\n * @param b - The second (compare) string.\n * @returns Negative if the reference string is before the compare string;\n * positive if the reference string is after; and zero if equal.\n */\nexport function lexicographicCompare(a, b) {\n // Dev note: this exists because I'm sad that you can use math operators on strings, so I've\n // hidden the operation in this function.\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n}\n\n/**\n * This function is similar to Object.assign() but it assigns recursively and\n * allows you to ignore nullish values from the source\n *\n * @returns the target object\n */\nexport function recursivelyAssign(target, source) {\n var ignoreNullish = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n for (var [sourceKey, sourceValue] of Object.entries(source)) {\n if (target[sourceKey] instanceof Object && sourceValue) {\n recursivelyAssign(target[sourceKey], sourceValue);\n continue;\n }\n if (sourceValue !== null && sourceValue !== undefined || !ignoreNullish) {\n safeSet(target, sourceKey, sourceValue);\n continue;\n }\n }\n return target;\n}\nfunction getContentTimestampWithFallback(event) {\n var _M_TIMESTAMP$findIn;\n return (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(event.getContent())) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : -1;\n}\n\n/**\n * Sort events by their content m.ts property\n * Latest timestamp first\n */\nexport function sortEventsByLatestContentTimestamp(left, right) {\n return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);\n}\nexport function isSupportedReceiptType(receiptType) {\n return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType);\n}\n\n/**\n * Determines whether two maps are equal.\n * @param eq - The equivalence relation to compare values by. Defaults to strict equality.\n */\nexport function mapsEqual(x, y) {\n var eq = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (v1, v2) => v1 === v2;\n if (x.size !== y.size) return false;\n for (var [k, v1] of x) {\n var v2 = y.get(k);\n if (v2 === undefined || !eq(v1, v2)) return false;\n }\n return true;\n}\nfunction processMapToObjectValue(value) {\n if (value instanceof Map) {\n // Value is a Map. Recursively map it to an object.\n return recursiveMapToObject(value);\n } else if (Array.isArray(value)) {\n // Value is an Array. Recursively map the value (e.g. to cover Array of Arrays).\n return value.map(v => processMapToObjectValue(v));\n } else {\n return value;\n }\n}\n\n/**\n * Recursively converts Maps to plain objects.\n * Also supports sub-lists of Maps.\n */\nexport function recursiveMapToObject(map) {\n var targetMap = new Map();\n for (var [key, value] of map) {\n targetMap.set(key, processMapToObjectValue(value));\n }\n return Object.fromEntries(targetMap.entries());\n}\nexport function unsafeProp(prop) {\n return prop === \"__proto__\" || prop === \"prototype\" || prop === \"constructor\";\n}\nexport function safeSet(obj, prop, value) {\n if (unsafeProp(prop)) {\n throw new Error(\"Trying to modify prototype or constructor\");\n }\n obj[prop] = value;\n}\nexport function noUnsafeEventProps(event) {\n return !(unsafeProp(event.room_id) || unsafeProp(event.sender) || unsafeProp(event.event_id));\n}\nexport class MapWithDefault extends Map {\n constructor(createDefault) {\n super();\n this.createDefault = createDefault;\n }\n\n /**\n * Returns the value if the key already exists.\n * If not, it creates a new value under that key using the ctor callback and returns it.\n */\n getOrCreate(key) {\n if (!this.has(key)) {\n this.set(key, this.createDefault());\n }\n return this.get(key);\n }\n}\n//# sourceMappingURL=utils.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.js\";\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3773\n *\n * @experimental\n */\nexport var UNREAD_THREAD_NOTIFICATIONS = new ServerControlledNamespacedValue(\"unread_thread_notifications\", \"org.matrix.msc3773.unread_thread_notifications\");\n//# sourceMappingURL=sync.js.map","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NamespacedValue, UnstableValue } from \"../NamespacedValue.js\";\nexport var EventType = /*#__PURE__*/function (EventType) {\n // Room state events\n EventType[\"RoomCanonicalAlias\"] = \"m.room.canonical_alias\";\n EventType[\"RoomCreate\"] = \"m.room.create\";\n EventType[\"RoomJoinRules\"] = \"m.room.join_rules\";\n EventType[\"RoomMember\"] = \"m.room.member\";\n EventType[\"RoomThirdPartyInvite\"] = \"m.room.third_party_invite\";\n EventType[\"RoomPowerLevels\"] = \"m.room.power_levels\";\n EventType[\"RoomName\"] = \"m.room.name\";\n EventType[\"RoomTopic\"] = \"m.room.topic\";\n EventType[\"RoomAvatar\"] = \"m.room.avatar\";\n EventType[\"RoomPinnedEvents\"] = \"m.room.pinned_events\";\n EventType[\"RoomEncryption\"] = \"m.room.encryption\";\n EventType[\"RoomHistoryVisibility\"] = \"m.room.history_visibility\";\n EventType[\"RoomGuestAccess\"] = \"m.room.guest_access\";\n EventType[\"RoomServerAcl\"] = \"m.room.server_acl\";\n EventType[\"RoomTombstone\"] = \"m.room.tombstone\";\n EventType[\"RoomPredecessor\"] = \"org.matrix.msc3946.room_predecessor\";\n // Moderation policy lists\n EventType[\"PolicyRuleUser\"] = \"m.policy.rule.user\";\n EventType[\"PolicyRuleRoom\"] = \"m.policy.rule.room\";\n EventType[\"PolicyRuleServer\"] = \"m.policy.rule.server\";\n EventType[\"SpaceChild\"] = \"m.space.child\";\n EventType[\"SpaceParent\"] = \"m.space.parent\";\n // Room timeline events\n EventType[\"RoomRedaction\"] = \"m.room.redaction\";\n EventType[\"RoomMessage\"] = \"m.room.message\";\n EventType[\"RoomMessageEncrypted\"] = \"m.room.encrypted\";\n EventType[\"Sticker\"] = \"m.sticker\";\n EventType[\"CallInvite\"] = \"m.call.invite\";\n EventType[\"CallCandidates\"] = \"m.call.candidates\";\n EventType[\"CallAnswer\"] = \"m.call.answer\";\n EventType[\"CallHangup\"] = \"m.call.hangup\";\n EventType[\"CallReject\"] = \"m.call.reject\";\n EventType[\"CallSelectAnswer\"] = \"m.call.select_answer\";\n EventType[\"CallNegotiate\"] = \"m.call.negotiate\";\n EventType[\"CallSDPStreamMetadataChanged\"] = \"m.call.sdp_stream_metadata_changed\";\n EventType[\"CallSDPStreamMetadataChangedPrefix\"] = \"org.matrix.call.sdp_stream_metadata_changed\";\n EventType[\"CallReplaces\"] = \"m.call.replaces\";\n EventType[\"CallAssertedIdentity\"] = \"m.call.asserted_identity\";\n EventType[\"CallAssertedIdentityPrefix\"] = \"org.matrix.call.asserted_identity\";\n EventType[\"CallEncryptionKeysPrefix\"] = \"io.element.call.encryption_keys\";\n EventType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n EventType[\"KeyVerificationStart\"] = \"m.key.verification.start\";\n EventType[\"KeyVerificationCancel\"] = \"m.key.verification.cancel\";\n EventType[\"KeyVerificationMac\"] = \"m.key.verification.mac\";\n EventType[\"KeyVerificationDone\"] = \"m.key.verification.done\";\n EventType[\"KeyVerificationKey\"] = \"m.key.verification.key\";\n EventType[\"KeyVerificationAccept\"] = \"m.key.verification.accept\";\n // Not used directly - see READY_TYPE in VerificationRequest.\n EventType[\"KeyVerificationReady\"] = \"m.key.verification.ready\";\n // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n EventType[\"RoomMessageFeedback\"] = \"m.room.message.feedback\";\n EventType[\"Reaction\"] = \"m.reaction\";\n EventType[\"PollStart\"] = \"org.matrix.msc3381.poll.start\";\n // Room ephemeral events\n EventType[\"Typing\"] = \"m.typing\";\n EventType[\"Receipt\"] = \"m.receipt\";\n EventType[\"Presence\"] = \"m.presence\";\n // Room account_data events\n EventType[\"FullyRead\"] = \"m.fully_read\";\n EventType[\"Tag\"] = \"m.tag\";\n EventType[\"SpaceOrder\"] = \"org.matrix.msc3230.space_order\";\n // MSC3230\n // User account_data events\n EventType[\"PushRules\"] = \"m.push_rules\";\n EventType[\"Direct\"] = \"m.direct\";\n EventType[\"IgnoredUserList\"] = \"m.ignored_user_list\";\n // to_device events\n EventType[\"RoomKey\"] = \"m.room_key\";\n EventType[\"RoomKeyRequest\"] = \"m.room_key_request\";\n EventType[\"ForwardedRoomKey\"] = \"m.forwarded_room_key\";\n EventType[\"Dummy\"] = \"m.dummy\";\n EventType[\"SecretRequest\"] = \"m.secret.request\";\n EventType[\"SecretSend\"] = \"m.secret.send\";\n // Group call events\n EventType[\"GroupCallPrefix\"] = \"org.matrix.msc3401.call\";\n EventType[\"GroupCallMemberPrefix\"] = \"org.matrix.msc3401.call.member\";\n // MatrixRTC events\n EventType[\"CallNotify\"] = \"org.matrix.msc4075.call.notify\";\n return EventType;\n}({});\nexport var RelationType = /*#__PURE__*/function (RelationType) {\n RelationType[\"Annotation\"] = \"m.annotation\";\n RelationType[\"Replace\"] = \"m.replace\";\n RelationType[\"Reference\"] = \"m.reference\";\n // Don't use this yet: it's only the stable version. The code still assumes we support the unstable prefix and,\n // moreover, our tests currently use the unstable prefix. Use THREAD_RELATION_TYPE.name.\n // Once we support *only* the stable prefix, THREAD_RELATION_TYPE can die and we can switch to this.\n RelationType[\"Thread\"] = \"m.thread\";\n return RelationType;\n}({});\nexport var MsgType = /*#__PURE__*/function (MsgType) {\n MsgType[\"Text\"] = \"m.text\";\n MsgType[\"Emote\"] = \"m.emote\";\n MsgType[\"Notice\"] = \"m.notice\";\n MsgType[\"Image\"] = \"m.image\";\n MsgType[\"File\"] = \"m.file\";\n MsgType[\"Audio\"] = \"m.audio\";\n MsgType[\"Location\"] = \"m.location\";\n MsgType[\"Video\"] = \"m.video\";\n MsgType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n return MsgType;\n}({});\nexport var RoomCreateTypeField = \"type\";\nexport var RoomType = /*#__PURE__*/function (RoomType) {\n RoomType[\"Space\"] = \"m.space\";\n RoomType[\"UnstableCall\"] = \"org.matrix.msc3417.call\";\n RoomType[\"ElementVideo\"] = \"io.element.video\";\n return RoomType;\n}({});\nexport var ToDeviceMessageId = \"org.matrix.msgid\";\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_LEAF = new UnstableValue(\"m.leaf\", \"org.matrix.msc3089.leaf\");\n\n/**\n * Branch (Leaf Reference) type for the index approach in a\n * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is\n * UNSTABLE and subject to breaking changes, including its eventual removal.\n */\nexport var UNSTABLE_MSC3089_BRANCH = new UnstableValue(\"m.branch\", \"org.matrix.msc3089.branch\");\n\n/**\n * Marker event type to point back at imported historical content in a room. See\n * [MSC2716](https://github.com/matrix-org/matrix-spec-proposals/pull/2716).\n * Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC2716_MARKER = new UnstableValue(\"m.room.marker\", \"org.matrix.msc2716.marker\");\n\n/**\n * Name of the request property for relation based redactions.\n * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}\n */\nexport var MSC3912_RELATION_BASED_REDACTIONS_PROP = new UnstableValue(\"with_rel_types\", \"org.matrix.msc3912.with_relations\");\n\n/**\n * Functional members type for declaring a purpose of room members (e.g. helpful bots).\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n *\n * Schema (TypeScript):\n * ```\n * {\n * service_members?: string[]\n * }\n * ```\n *\n * @example\n * ```\n * {\n * \"service_members\": [\n * \"@helperbot:localhost\",\n * \"@reminderbot:alice.tdl\"\n * ]\n * }\n * ```\n */\nexport var UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new UnstableValue(\"io.element.functional_members\", \"io.element.functional_members\");\n\n/**\n * A type of message that affects visibility of a message,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * @experimental\n */\nexport var EVENT_VISIBILITY_CHANGE_TYPE = new UnstableValue(\"m.visibility\", \"org.matrix.msc3531.visibility\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_ENABLED = new UnstableValue(\"enabled\", \"org.matrix.msc3881.enabled\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_DEVICE_ID = new UnstableValue(\"device_id\", \"org.matrix.msc3881.device_id\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3890\n *\n * @experimental\n */\nexport var LOCAL_NOTIFICATION_SETTINGS_PREFIX = new UnstableValue(\"m.local_notification_settings\", \"org.matrix.msc3890.local_notification_settings\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/4023\n *\n * @experimental\n */\nexport var UNSIGNED_THREAD_ID_FIELD = new UnstableValue(\"thread_id\", \"org.matrix.msc4023.thread_id\");\n\n/**\n * https://github.com/matrix-org/matrix-spec-proposals/pull/4115\n *\n * @experimental\n */\nexport var UNSIGNED_MEMBERSHIP_FIELD = new NamespacedValue(\"membership\", \"io.element.msc4115.membership\");\n\n/**\n * Mapped type from event type to content type for all specified non-state room events.\n */\n\n/**\n * Mapped type from event type to content type for all specified room state events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global account_data events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global events encrypted by secret storage.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\n//# sourceMappingURL=event.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"./@types/event.js\";\nimport { isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils.js\";\n/**\n * Summarises the read receipts within a room. Used by the sync accumulator.\n *\n * Given receipts for users, picks the most recently-received one and provides\n * the results in a new fake receipt event returned from\n * buildAccumulatedReceiptEvent().\n *\n * Handles unthreaded receipts and receipts in each thread separately, so the\n * returned event contains the most recently received unthreaded receipt, and\n * the most recently received receipt in each thread.\n */\nexport class ReceiptAccumulator {\n constructor() {\n /** user_id -\\> most-recently-received unthreaded receipt */\n _defineProperty(this, \"unthreadedReadReceipts\", new Map());\n /** thread_id -\\> user_id -\\> most-recently-received receipt for this thread */\n _defineProperty(this, \"threadedReadReceipts\", new MapWithDefault(() => new Map()));\n }\n /**\n * Provide an unthreaded receipt for this user. Overwrites any other\n * unthreaded receipt we have for this user.\n */\n setUnthreaded(userId, receipt) {\n this.unthreadedReadReceipts.set(userId, receipt);\n }\n\n /**\n * Provide a receipt for this user in this thread. Overwrites any other\n * receipt we have for this user in this thread.\n */\n setThreaded(threadId, userId, receipt) {\n this.threadedReadReceipts.getOrCreate(threadId).set(userId, receipt);\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received unthreaded receipts for each user.\n */\n allUnthreaded() {\n return this.unthreadedReadReceipts.entries();\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received threaded receipts for each user, in all\n * threads.\n */\n *allThreaded() {\n for (var receiptsForThread of this.threadedReadReceipts.values()) {\n for (var e of receiptsForThread.entries()) {\n yield e;\n }\n }\n }\n\n /**\n * Given a list of ephemeral events, find the receipts and store the\n * relevant ones to be returned later from buildAccumulatedReceiptEvent().\n */\n consumeEphemeralEvents(events) {\n events === null || events === void 0 || events.forEach(e => {\n if (e.type !== EventType.Receipt || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach(eventId => {\n Object.entries(e.content[eventId]).forEach(_ref => {\n var [key, value] = _ref;\n if (!isSupportedReceiptType(key)) return;\n for (var userId of Object.keys(value)) {\n var data = e.content[eventId][key][userId];\n var receipt = {\n data: e.content[eventId][key][userId],\n type: key,\n eventId\n };\n\n // In a world that supports threads, read receipts normally have\n // a `thread_id` which is either the thread they belong in or\n // `MAIN_ROOM_TIMELINE`, so we normally use `setThreaded(...)`\n // here. The `MAIN_ROOM_TIMELINE` is just treated as another\n // thread.\n //\n // We still encounter read receipts that are \"unthreaded\"\n // (missing the `thread_id` property). These come from clients\n // that don't support threads, and from threaded clients that\n // are doing a \"Mark room as read\" operation. Unthreaded\n // receipts mark everything \"before\" them as read, in all\n // threads, where \"before\" means in Sync Order i.e. the order\n // the events were received from the homeserver in a sync.\n // [Note: we have some bugs where we use timestamp order instead\n // of Sync Order, because we don't correctly remember the Sync\n // Order. See #3325.]\n //\n // Calling the wrong method will cause incorrect behavior like\n // messages re-appearing as \"new\" when you already read them\n // previously.\n if (!data.thread_id) {\n this.setUnthreaded(userId, receipt);\n } else {\n this.setThreaded(data.thread_id, userId, receipt);\n }\n }\n });\n });\n });\n }\n\n /**\n * Build a receipt event that contains all relevant information for this\n * room, taking the most recently received receipt for each user in an\n * unthreaded context, and in each thread.\n */\n buildAccumulatedReceiptEvent(roomId) {\n var receiptEvent = {\n type: EventType.Receipt,\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n }\n };\n var receiptEventContent = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n for (var [userId, receiptData] of this.allUnthreaded()) {\n receiptEventContent.getOrCreate(receiptData.eventId).getOrCreate(receiptData.type).set(userId, receiptData.data);\n }\n for (var [_userId, _receiptData] of this.allThreaded()) {\n receiptEventContent.getOrCreate(_receiptData.eventId).getOrCreate(_receiptData.type).set(_userId, _receiptData.data);\n }\n receiptEvent.content = recursiveMapToObject(receiptEventContent);\n return receiptEventContent.size > 0 ? receiptEvent : null;\n }\n}\n//# sourceMappingURL=receipt-accumulator.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n */\n\nimport { logger } from \"./logger.js\";\nimport { deepCopy } from \"./utils.js\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.js\";\nimport { ReceiptAccumulator } from \"./receipt-accumulator.js\";\n\n/* eslint-disable camelcase */\n\n/* eslint-enable camelcase */\n\nexport var Category = /*#__PURE__*/function (Category) {\n Category[\"Invite\"] = \"invite\";\n Category[\"Leave\"] = \"leave\";\n Category[\"Join\"] = \"join\";\n Category[\"Knock\"] = \"knock\";\n return Category;\n}({});\nfunction isTaggedEvent(event) {\n return \"_localTs\" in event && event[\"_localTs\"] !== undefined;\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n constructor() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.opts = opts;\n _defineProperty(this, \"accountData\", {});\n // $event_type: Object\n _defineProperty(this, \"inviteRooms\", {});\n // $roomId: { ... sync 'invite' json data ... }\n _defineProperty(this, \"knockRooms\", {});\n // $roomId: { ... sync 'knock' json data ... }\n _defineProperty(this, \"joinRooms\", {});\n // the /sync token which corresponds to the last time rooms were\n // accumulated. We remember this so that any caller can obtain a\n // coherent /sync response and know at what point they should be\n // streaming from without losing events.\n _defineProperty(this, \"nextBatch\", null);\n this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;\n }\n accumulate(syncResponse) {\n var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n this.accumulateRooms(syncResponse, fromDatabase);\n this.accumulateAccountData(syncResponse);\n this.nextBatch = syncResponse.next_batch;\n }\n accumulateAccountData(syncResponse) {\n if (!syncResponse.account_data || !syncResponse.account_data.events) {\n return;\n }\n // Clobbers based on event type.\n syncResponse.account_data.events.forEach(e => {\n this.accountData[e.type] = e;\n });\n }\n\n /**\n * Accumulate incremental /sync room data.\n * @param syncResponse - the complete /sync JSON\n * @param fromDatabase - True if the sync response is one saved to the database\n */\n accumulateRooms(syncResponse) {\n var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (!syncResponse.rooms) {\n return;\n }\n if (syncResponse.rooms.invite) {\n Object.keys(syncResponse.rooms.invite).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.join) {\n Object.keys(syncResponse.rooms.join).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.leave) {\n Object.keys(syncResponse.rooms.leave).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.knock) {\n Object.keys(syncResponse.rooms.knock).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Knock, syncResponse.rooms.knock[roomId], fromDatabase);\n });\n }\n }\n accumulateRoom(roomId, category, data) {\n var fromDatabase = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n // Valid /sync state transitions\n // +--------+ <======+ 1: Accept an invite\n // +== | INVITE | | (5) 2: Leave a room\n // | +--------+ =====+ | 3: Join a public room previously\n // |(1) (4) | | left (handle as if new room)\n // V (2) V | 4: Reject an invite\n // +------+ ========> +--------+ 5: Invite to a room previously\n // | JOIN | (3) | LEAVE* | left (handle as if new room)\n // +------+ <======== +--------+\n //\n // * equivalent to \"no state\"\n switch (category) {\n case Category.Invite:\n // (5)\n if (this.knockRooms[roomId]) {\n // was previously knock, now invite, need to delete knock state\n delete this.knockRooms[roomId];\n }\n this.accumulateInviteState(roomId, data);\n break;\n case Category.Knock:\n this.accumulateKnockState(roomId, data);\n break;\n case Category.Join:\n if (this.inviteRooms[roomId]) {\n // (1)\n // was previously invite, now join. We expect /sync to give\n // the entire state and timeline on 'join', so delete previous\n // invite state\n delete this.inviteRooms[roomId];\n }\n // (3)\n this.accumulateJoinState(roomId, data, fromDatabase);\n break;\n case Category.Leave:\n if (this.knockRooms[roomId]) {\n // delete knock state on leave\n delete this.knockRooms[roomId];\n } else if (this.inviteRooms[roomId]) {\n // (4)\n delete this.inviteRooms[roomId];\n } else {\n // (2)\n delete this.joinRooms[roomId];\n }\n break;\n default:\n logger.error(\"Unknown cateogory: \", category);\n }\n }\n accumulateInviteState(roomId, data) {\n if (!data.invite_state || !data.invite_state.events) {\n // no new data\n return;\n }\n if (!this.inviteRooms[roomId]) {\n this.inviteRooms[roomId] = {\n invite_state: data.invite_state\n };\n return;\n }\n // accumulate extra keys for invite->invite transitions\n // clobber based on event type / state key\n // We expect invite_state to be small, so just loop over the events\n var currentData = this.inviteRooms[roomId];\n data.invite_state.events.forEach(e => {\n var hasAdded = false;\n for (var i = 0; i < currentData.invite_state.events.length; i++) {\n var current = currentData.invite_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.invite_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.invite_state.events.push(e);\n }\n });\n }\n accumulateKnockState(roomId, data) {\n if (!data.knock_state || !data.knock_state.events) {\n // no new data\n return;\n }\n if (!this.knockRooms[roomId]) {\n this.knockRooms[roomId] = {\n knock_state: data.knock_state\n };\n return;\n }\n // accumulate extra keys\n // clobber based on event type / state key\n // We expect knock_state to be small, so just loop over the events\n var currentData = this.knockRooms[roomId];\n data.knock_state.events.forEach(e => {\n var hasAdded = false;\n for (var i = 0; i < currentData.knock_state.events.length; i++) {\n var current = currentData.knock_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.knock_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.knock_state.events.push(e);\n }\n });\n }\n\n // Accumulate timeline and state events in a room.\n accumulateJoinState(roomId, data) {\n var _ref, _data, _data$ephemeral, _data$state, _data$orgMatrixMsc, _data$timeline;\n var fromDatabase = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n // We expect this function to be called a lot (every /sync) so we want\n // this to be fast. /sync stores events in an array but we often want\n // to clobber based on type/state_key. Rather than convert arrays to\n // maps all the time, just keep private maps which contain\n // the actual current accumulated sync state, and array-ify it when\n // getJSON() is called.\n\n // State resolution:\n // The 'state' key is the delta from the previous sync (or start of time\n // if no token was supplied), to the START of the timeline. To obtain\n // the current state, we need to \"roll forward\" state by reading the\n // timeline. We want to store the current state so we can drop events\n // out the end of the timeline based on opts.maxTimelineEntries.\n //\n // 'state' 'timeline' current state\n // |-------x<======================>x\n // T I M E\n //\n // When getJSON() is called, we 'roll back' the current state by the\n // number of entries in the timeline to work out what 'state' should be.\n\n // Back-pagination:\n // On an initial /sync, the server provides a back-pagination token for\n // the start of the timeline. When /sync deltas come down, they also\n // include back-pagination tokens for the start of the timeline. This\n // means not all events in the timeline have back-pagination tokens, as\n // it is only the ones at the START of the timeline which have them.\n // In order for us to have a valid timeline (and back-pagination token\n // to match), we need to make sure that when we remove old timeline\n // events, that we roll forward to an event which has a back-pagination\n // token. This means we can't keep a strict sliding-window based on\n // opts.maxTimelineEntries, and we may have a few less. We should never\n // have more though, provided that the /sync limit is less than or equal\n // to opts.maxTimelineEntries.\n\n if (!this.joinRooms[roomId]) {\n // Create truly empty objects so event types of 'hasOwnProperty' and co\n // don't cause this code to break.\n this.joinRooms[roomId] = {\n _currentState: Object.create(null),\n _timeline: [],\n _accountData: Object.create(null),\n _unreadNotifications: {},\n _unreadThreadNotifications: {},\n _summary: {},\n _receipts: new ReceiptAccumulator()\n };\n }\n var currentData = this.joinRooms[roomId];\n if (data.account_data && data.account_data.events) {\n // clobber based on type\n data.account_data.events.forEach(e => {\n currentData._accountData[e.type] = e;\n });\n }\n\n // these probably clobber, spec is unclear.\n if (data.unread_notifications) {\n currentData._unreadNotifications = data.unread_notifications;\n }\n currentData._unreadThreadNotifications = (_ref = (_data = data[UNREAD_THREAD_NOTIFICATIONS.stable]) !== null && _data !== void 0 ? _data : data[UNREAD_THREAD_NOTIFICATIONS.unstable]) !== null && _ref !== void 0 ? _ref : undefined;\n if (data.summary) {\n var _sum$HEROES_KEY, _sum$JOINED_COUNT_KEY, _sum$INVITED_COUNT_KE;\n var HEROES_KEY = \"m.heroes\";\n var INVITED_COUNT_KEY = \"m.invited_member_count\";\n var JOINED_COUNT_KEY = \"m.joined_member_count\";\n var acc = currentData._summary;\n var sum = data.summary;\n acc[HEROES_KEY] = (_sum$HEROES_KEY = sum[HEROES_KEY]) !== null && _sum$HEROES_KEY !== void 0 ? _sum$HEROES_KEY : acc[HEROES_KEY];\n acc[JOINED_COUNT_KEY] = (_sum$JOINED_COUNT_KEY = sum[JOINED_COUNT_KEY]) !== null && _sum$JOINED_COUNT_KEY !== void 0 ? _sum$JOINED_COUNT_KEY : acc[JOINED_COUNT_KEY];\n acc[INVITED_COUNT_KEY] = (_sum$INVITED_COUNT_KE = sum[INVITED_COUNT_KEY]) !== null && _sum$INVITED_COUNT_KE !== void 0 ? _sum$INVITED_COUNT_KE : acc[INVITED_COUNT_KEY];\n }\n\n // We purposefully do not persist m.typing events.\n // Technically you could refresh a browser before the timer on a\n // typing event is up, so it'll look like you aren't typing when\n // you really still are. However, the alternative is worse. If\n // we do persist typing events, it will look like people are\n // typing forever until someone really does start typing (which\n // will prompt Synapse to send down an actual m.typing event to\n // clobber the one we persisted).\n\n // Persist the receipts\n currentData._receipts.consumeEphemeralEvents((_data$ephemeral = data.ephemeral) === null || _data$ephemeral === void 0 ? void 0 : _data$ephemeral.events);\n\n // if we got a limited sync, we need to remove all timeline entries or else\n // we will have gaps in the timeline.\n if (data.timeline && data.timeline.limited) {\n currentData._timeline = [];\n }\n\n // Work out the current state. The deltas need to be applied in the order:\n // - existing state which didn't come down /sync.\n // - State events under the 'state' key.\n // - State events under the 'state_after' key OR state events in the 'timeline' if 'state_after' is not present.\n (_data$state = data.state) === null || _data$state === void 0 || (_data$state = _data$state.events) === null || _data$state === void 0 || _data$state.forEach(e => {\n setState(currentData._currentState, e);\n });\n (_data$orgMatrixMsc = data[\"org.matrix.msc4222.state_after\"]) === null || _data$orgMatrixMsc === void 0 || (_data$orgMatrixMsc = _data$orgMatrixMsc.events) === null || _data$orgMatrixMsc === void 0 || _data$orgMatrixMsc.forEach(e => {\n setState(currentData._currentState, e);\n });\n (_data$timeline = data.timeline) === null || _data$timeline === void 0 || (_data$timeline = _data$timeline.events) === null || _data$timeline === void 0 || _data$timeline.forEach((e, index) => {\n var _data$timeline$prev_b;\n if (!data[\"org.matrix.msc4222.state_after\"]) {\n // this nops if 'e' isn't a state event\n setState(currentData._currentState, e);\n }\n // append the event to the timeline. The back-pagination token\n // corresponds to the first event in the timeline\n var transformedEvent;\n if (!fromDatabase) {\n var _e$unsigned;\n transformedEvent = Object.assign({}, e);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n var age = (_e$unsigned = e.unsigned) === null || _e$unsigned === void 0 ? void 0 : _e$unsigned.age;\n if (age !== undefined) transformedEvent._localTs = Date.now() - age;\n } else {\n transformedEvent = e;\n }\n currentData._timeline.push({\n event: transformedEvent,\n token: index === 0 ? (_data$timeline$prev_b = data.timeline.prev_batch) !== null && _data$timeline$prev_b !== void 0 ? _data$timeline$prev_b : null : null\n });\n });\n\n // attempt to prune the timeline by jumping between events which have\n // pagination tokens.\n if (currentData._timeline.length > this.opts.maxTimelineEntries) {\n var startIndex = currentData._timeline.length - this.opts.maxTimelineEntries;\n for (var i = startIndex; i < currentData._timeline.length; i++) {\n if (currentData._timeline[i].token) {\n // keep all events after this, including this one\n currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);\n break;\n }\n }\n }\n }\n\n /**\n * Return everything under the 'rooms' key from a /sync response which\n * represents all room data that should be stored. This should be paired\n * with the sync token which represents the most recent /sync response\n * provided to accumulate().\n * @param forDatabase - True to generate a sync to be saved to storage\n * @returns An object with a \"nextBatch\", \"roomsData\" and \"accountData\"\n * keys.\n * The \"nextBatch\" key is a string which represents at what point in the\n * /sync stream the accumulator reached. This token should be used when\n * restarting a /sync stream at startup. Failure to do so can lead to missing\n * events. The \"roomsData\" key is an Object which represents the entire\n * /sync response from the 'rooms' key onwards. The \"accountData\" key is\n * a list of raw events which represent global account data.\n */\n getJSON() {\n var forDatabase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var data = {\n join: {},\n invite: {},\n knock: {},\n // always empty. This is set by /sync when a room was previously\n // in 'invite' or 'join'. On fresh startup, the client won't know\n // about any previous room being in 'invite' or 'join' so we can\n // just omit mentioning it at all, even if it has previously come\n // down /sync.\n // The notable exception is when a client is kicked or banned:\n // we may want to hold onto that room so the client can clearly see\n // why their room has disappeared. We don't persist it though because\n // it is unclear *when* we can safely remove the room from the DB.\n // Instead, we assume that if you're loading from the DB, you've\n // refreshed the page, which means you've seen the kick/ban already.\n leave: {}\n };\n Object.keys(this.inviteRooms).forEach(roomId => {\n data.invite[roomId] = this.inviteRooms[roomId];\n });\n Object.keys(this.knockRooms).forEach(roomId => {\n data.knock[roomId] = this.knockRooms[roomId];\n });\n Object.keys(this.joinRooms).forEach(roomId => {\n var roomData = this.joinRooms[roomId];\n var roomJson = {\n \"ephemeral\": {\n events: []\n },\n \"account_data\": {\n events: []\n },\n \"state\": {\n events: []\n },\n \"org.matrix.msc4222.state_after\": {\n events: []\n },\n \"timeline\": {\n events: [],\n prev_batch: null\n },\n \"unread_notifications\": roomData._unreadNotifications,\n \"unread_thread_notifications\": roomData._unreadThreadNotifications,\n \"summary\": roomData._summary\n };\n // Add account data\n Object.keys(roomData._accountData).forEach(evType => {\n roomJson.account_data.events.push(roomData._accountData[evType]);\n });\n var receiptEvent = roomData._receipts.buildAccumulatedReceiptEvent(roomId);\n\n // add only if we have some receipt data\n if (receiptEvent) {\n roomJson.ephemeral.events.push(receiptEvent);\n }\n\n // Add timeline data\n roomData._timeline.forEach(msgData => {\n if (!roomJson.timeline.prev_batch) {\n // the first event we add to the timeline MUST match up to\n // the prev_batch token.\n if (!msgData.token) {\n return; // this shouldn't happen as we prune constantly.\n }\n roomJson.timeline.prev_batch = msgData.token;\n }\n var transformedEvent;\n if (!forDatabase && isTaggedEvent(msgData.event)) {\n // This means we have to copy each event, so we can fix it up to\n // set a correct 'age' parameter whilst keeping the local timestamp\n // on our stored event. If this turns out to be a bottleneck, it could\n // be optimised either by doing this in the main process after the data\n // has been structured-cloned to go between the worker & main process,\n // or special-casing data from saved syncs to read the local timestamp\n // directly rather than turning it into age to then immediately be\n // transformed back again into a local timestamp.\n transformedEvent = Object.assign({}, msgData.event);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n delete transformedEvent._localTs;\n transformedEvent.unsigned = transformedEvent.unsigned || {};\n transformedEvent.unsigned.age = Date.now() - msgData.event._localTs;\n } else {\n transformedEvent = msgData.event;\n }\n roomJson.timeline.events.push(transformedEvent);\n });\n\n // Add state data: roll back current state to the start of timeline,\n // by \"reverse clobbering\" from the end of the timeline to the start.\n // Convert maps back into arrays.\n var rollBackState = Object.create(null);\n for (var i = roomJson.timeline.events.length - 1; i >= 0; i--) {\n var timelineEvent = roomJson.timeline.events[i];\n if (timelineEvent.state_key === null || timelineEvent.state_key === undefined) {\n continue; // not a state event\n }\n // since we're going back in time, we need to use the previous\n // state value else we'll break causality. We don't have the\n // complete previous state event, so we need to create one.\n var prevStateEvent = deepCopy(timelineEvent);\n if (prevStateEvent.unsigned) {\n if (prevStateEvent.unsigned.prev_content) {\n prevStateEvent.content = prevStateEvent.unsigned.prev_content;\n }\n if (prevStateEvent.unsigned.prev_sender) {\n prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;\n }\n }\n setState(rollBackState, prevStateEvent);\n }\n Object.keys(roomData._currentState).forEach(evType => {\n Object.keys(roomData._currentState[evType]).forEach(stateKey => {\n var ev = roomData._currentState[evType][stateKey];\n // Push to both fields to provide downgrade compatibility in the sync accumulator db\n // the code will prefer `state_after` if it is present\n roomJson[\"org.matrix.msc4222.state_after\"].events.push(ev);\n // Roll the state back to the value at the start of the timeline if it was changed\n if (rollBackState[evType] && rollBackState[evType][stateKey]) {\n ev = rollBackState[evType][stateKey];\n }\n roomJson.state.events.push(ev);\n });\n });\n data.join[roomId] = roomJson;\n });\n\n // Add account data\n var accData = [];\n Object.keys(this.accountData).forEach(evType => {\n accData.push(this.accountData[evType]);\n });\n return {\n nextBatch: this.nextBatch,\n roomsData: data,\n accountData: accData\n };\n }\n getNextBatchToken() {\n return this.nextBatch;\n }\n}\nfunction setState(eventMap, event) {\n if (event.state_key === null || event.state_key === undefined || !event.type) {\n return;\n }\n if (!eventMap[event.type]) {\n eventMap[event.type] = Object.create(null);\n }\n eventMap[event.type][event.state_key] = event;\n}\n//# sourceMappingURL=sync-accumulator.js.map","/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param indexedDB - The `indexedDB` interface\n * @param dbName - The database name to test for\n * @returns Whether the database exists\n */\nexport function exists(indexedDB, dbName) {\n return new Promise((resolve, reject) => {\n var exists = true;\n var req = indexedDB.open(dbName);\n req.onupgradeneeded = () => {\n // Since we did not provide an explicit version when opening, this event\n // should only fire if the DB did not exist before at any version.\n exists = false;\n };\n req.onblocked = () => reject(req.error);\n req.onsuccess = () => {\n var db = req.result;\n db.close();\n if (!exists) {\n // The DB did not exist before, but has been created as part of this\n // existence check. Delete it now to restore previous state. Delete can\n // actually take a while to complete in some browsers, so don't wait for\n // it. This won't block future open calls that a store might issue next to\n // properly set up the DB.\n indexedDB.deleteDatabase(dbName);\n }\n resolve(exists);\n };\n req.onerror = () => reject(req.error);\n });\n}\n//# sourceMappingURL=indexeddb-helpers.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SyncAccumulator } from \"../sync-accumulator.js\";\nimport { deepCopy, promiseTry } from \"../utils.js\";\nimport { exists as idbExists } from \"../indexeddb-helpers.js\";\nimport { logger } from \"../logger.js\";\nvar DB_MIGRATIONS = [db => {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", {\n keyPath: [\"userId\"]\n });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", {\n keyPath: [\"type\"]\n });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", {\n keyPath: [\"clobber\"]\n });\n}, db => {\n var oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"]\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n}, db => {\n db.createObjectStore(\"client_options\", {\n keyPath: [\"clobber\"]\n });\n}, db => {\n db.createObjectStore(\"to_device_queue\", {\n autoIncrement: true\n });\n}\n// Expand as needed.\n];\nvar VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery(store, keyRange, resultMapper) {\n var query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n var results = [];\n query.onerror = () => {\n var _query$error;\n reject(new Error(\"Query failed: \" + ((_query$error = query.error) === null || _query$error === void 0 ? void 0 : _query$error.name)));\n };\n // collect results\n query.onsuccess = () => {\n var cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\nfunction txnAsPromise(txn) {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function (event) {\n resolve(event);\n };\n txn.onerror = function () {\n reject(txn.error);\n };\n });\n}\nfunction reqAsEventPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = function (event) {\n resolve(event);\n };\n req.onerror = function () {\n reject(req.error);\n };\n });\n}\nfunction reqAsPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req);\n req.onerror = err => reject(err);\n });\n}\nfunction reqAsCursorPromise(req) {\n return reqAsEventPromise(req).then(event => req.result);\n}\nexport class LocalIndexedDBStoreBackend {\n static exists(indexedDB, dbName) {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return idbExists(indexedDB, dbName);\n }\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param indexedDB - The Indexed DB interface e.g\n * `window.indexedDB`\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n constructor(indexedDB) {\n var dbName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"default\";\n this.indexedDB = indexedDB;\n _defineProperty(this, \"dbName\", void 0);\n _defineProperty(this, \"syncAccumulator\", void 0);\n _defineProperty(this, \"db\", void 0);\n _defineProperty(this, \"disconnected\", true);\n _defineProperty(this, \"_isNewlyCreated\", false);\n _defineProperty(this, \"syncToDatabasePromise\", void 0);\n _defineProperty(this, \"pendingUserPresenceData\", []);\n this.dbName = \"matrix-js-sdk:\" + dbName;\n this.syncAccumulator = new SyncAccumulator();\n }\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n connect(onClose) {\n var _this = this;\n if (!this.disconnected) {\n logger.log(\"LocalIndexedDBStoreBackend.connect: already connected or connecting\");\n return Promise.resolve();\n }\n this.disconnected = false;\n logger.log(\"LocalIndexedDBStoreBackend.connect: connecting...\");\n var req = this.indexedDB.open(this.dbName, VERSION);\n req.onupgradeneeded = ev => {\n var db = req.result;\n var oldVersion = ev.oldVersion;\n logger.log(\"LocalIndexedDBStoreBackend.connect: upgrading from \".concat(oldVersion));\n if (oldVersion < 1) {\n // The database did not previously exist\n this._isNewlyCreated = true;\n }\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n };\n req.onblocked = () => {\n logger.log(\"can't yet open LocalIndexedDBStoreBackend because it is open elsewhere\");\n };\n logger.log(\"LocalIndexedDBStoreBackend.connect: awaiting connection...\");\n return reqAsEventPromise(req).then(/*#__PURE__*/_asyncToGenerator(function* () {\n logger.log(\"LocalIndexedDBStoreBackend.connect: connected\");\n _this.db = req.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n _this.db.onversionchange = () => {\n var _this$db;\n (_this$db = _this.db) === null || _this$db === void 0 || _this$db.close(); // this does not call onclose\n _this.disconnected = true;\n _this.db = undefined;\n };\n _this.db.onclose = () => {\n _this.disconnected = true;\n _this.db = undefined;\n onClose === null || onClose === void 0 || onClose();\n };\n yield _this.init();\n }));\n }\n\n /** @returns whether or not the database was newly created in this session. */\n isNewlyCreated() {\n return Promise.resolve(this._isNewlyCreated);\n }\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @returns Promise which resolves on success\n */\n init() {\n return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(_ref2 => {\n var [accountData, syncData] = _ref2;\n logger.log(\"LocalIndexedDBStoreBackend: loaded initial data\");\n this.syncAccumulator.accumulate({\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n account_data: {\n events: accountData\n }\n }, true);\n });\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n getOutOfBandMembers(roomId) {\n return new Promise((resolve, reject) => {\n var tx = this.db.transaction([\"oob_membership_events\"], \"readonly\");\n var store = tx.objectStore(\"oob_membership_events\");\n var roomIndex = store.index(\"room\");\n var range = IDBKeyRange.only(roomId);\n var request = roomIndex.openCursor(range);\n var membershipEvents = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n var oobWritten = false;\n request.onsuccess = () => {\n var cursor = request.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n var record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = err => {\n reject(err);\n };\n }).then(events => {\n logger.log(\"LL: got \".concat(events === null || events === void 0 ? void 0 : events.length, \" membershipEvents from storage for room \").concat(roomId, \" ...\"));\n return events;\n });\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n */\n setOutOfBandMembers(roomId, membershipEvents) {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n logger.log(\"LL: backend about to store \".concat(membershipEvents.length) + \" members for \".concat(roomId));\n var tx = _this2.db.transaction([\"oob_membership_events\"], \"readwrite\");\n var store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach(e => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n var markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0\n };\n store.put(markerObject);\n yield txnAsPromise(tx);\n logger.log(\"LL: backend done storing for \".concat(roomId, \"!\"));\n })();\n }\n clearOutOfBandMembers(roomId) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n var readTx = _this3.db.transaction([\"oob_membership_events\"], \"readonly\");\n var store = readTx.objectStore(\"oob_membership_events\");\n var roomIndex = store.index(\"room\");\n var roomRange = IDBKeyRange.only(roomId);\n var minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n var maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n var [minStateKey, maxStateKey] = yield Promise.all([minStateKeyProm, maxStateKeyProm]);\n var writeTx = _this3.db.transaction([\"oob_membership_events\"], \"readwrite\");\n var writeStore = writeTx.objectStore(\"oob_membership_events\");\n var membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n logger.log(\"LL: Deleting all users + marker in storage for room \".concat(roomId, \", with key range:\"), [roomId, minStateKey], [roomId, maxStateKey]);\n yield reqAsPromise(writeStore.delete(membersKeyRange));\n })();\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts. Closes the database.\n * @returns Resolved when the database is cleared.\n */\n clearDatabase() {\n return new Promise(resolve => {\n var _this$db2;\n logger.log(\"Removing indexeddb instance: \".concat(this.dbName));\n\n // Close the database first to avoid firing unexpected close events\n (_this$db2 = this.db) === null || _this$db2 === void 0 || _this$db2.close();\n var req = this.indexedDB.deleteDatabase(this.dbName);\n req.onblocked = () => {\n logger.log(\"can't yet delete indexeddb \".concat(this.dbName, \" because it is open elsewhere\"));\n };\n req.onerror = () => {\n var _req$error;\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(\"unable to delete js-sdk store indexeddb: \".concat((_req$error = req.error) === null || _req$error === void 0 ? void 0 : _req$error.name));\n resolve();\n };\n req.onsuccess = () => {\n logger.log(\"Removed indexeddb instance: \".concat(this.dbName));\n resolve();\n };\n });\n }\n\n /**\n * @param copy - If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n getSavedSync() {\n var copy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n var data = this.syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n }\n getNextBatchToken() {\n return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n }\n setSyncData(syncData) {\n return Promise.resolve().then(() => {\n this.syncAccumulator.accumulate(syncData);\n });\n }\n\n /**\n * Sync users and all accumulated sync data to the database.\n * If a previous sync is in flight, the new data will be added to the\n * next sync and the current sync's promise will be returned.\n * @param userTuples - The user tuples\n * @returns Promise which resolves if the data was persisted.\n */\n syncToDatabase(userTuples) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n if (_this4.syncToDatabasePromise) {\n logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n _this4.pendingUserPresenceData.push(...userTuples);\n return _this4.syncToDatabasePromise;\n }\n userTuples.unshift(..._this4.pendingUserPresenceData);\n _this4.syncToDatabasePromise = _this4.doSyncToDatabase(userTuples);\n return _this4.syncToDatabasePromise;\n })();\n }\n doSyncToDatabase(userTuples) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n try {\n var syncData = _this5.syncAccumulator.getJSON(true);\n yield Promise.all([_this5.persistUserPresenceEvents(userTuples), _this5.persistAccountData(syncData.accountData), _this5.persistSyncData(syncData.nextBatch, syncData.roomsData)]);\n } finally {\n _this5.syncToDatabasePromise = undefined;\n }\n })();\n }\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param nextBatch - The next_batch /sync value.\n * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n * @returns Promise which resolves if the data was persisted.\n */\n persistSyncData(nextBatch, roomsData) {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return promiseTry(() => {\n var txn = this.db.transaction([\"sync\"], \"readwrite\");\n var store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\",\n // constant key so will always clobber\n nextBatch,\n roomsData\n }); // put == UPSERT\n return txnAsPromise(txn).then(() => {\n logger.log(\"Persisted sync data up to\", nextBatch);\n });\n });\n }\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param accountData - An array of raw user-scoped account data events\n * @returns Promise which resolves if the events were persisted.\n */\n persistAccountData(accountData) {\n return promiseTry(() => {\n var txn = this.db.transaction([\"accountData\"], \"readwrite\");\n var store = txn.objectStore(\"accountData\");\n for (var event of accountData) {\n store.put(event); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param tuples - An array of [userid, event] tuples\n * @returns Promise which resolves if the users were persisted.\n */\n persistUserPresenceEvents(tuples) {\n return promiseTry(() => {\n var txn = this.db.transaction([\"users\"], \"readwrite\");\n var store = txn.objectStore(\"users\");\n for (var tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1]\n }); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @returns A list of presence events in their raw form.\n */\n getUserPresenceEvents() {\n return promiseTry(() => {\n var txn = this.db.transaction([\"users\"], \"readonly\");\n var store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, cursor => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n }\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @returns A list of raw global account events.\n */\n loadAccountData() {\n logger.log(\"LocalIndexedDBStoreBackend: loading account data...\");\n return promiseTry(() => {\n var txn = this.db.transaction([\"accountData\"], \"readonly\");\n var store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, cursor => {\n return cursor.value;\n }).then(result => {\n logger.log(\"LocalIndexedDBStoreBackend: loaded account data\");\n return result;\n });\n });\n }\n\n /**\n * Load the sync data from the database.\n * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n */\n loadSyncData() {\n logger.log(\"LocalIndexedDBStoreBackend: loading sync data...\");\n return promiseTry(() => {\n var txn = this.db.transaction([\"sync\"], \"readonly\");\n var store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, cursor => {\n return cursor.value;\n }).then(results => {\n logger.log(\"LocalIndexedDBStoreBackend: loaded sync data\");\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return results.length > 0 ? results[0] : {};\n });\n });\n }\n getClientOptions() {\n return Promise.resolve().then(() => {\n var txn = this.db.transaction([\"client_options\"], \"readonly\");\n var store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, cursor => {\n var _cursor$value;\n return (_cursor$value = cursor.value) === null || _cursor$value === void 0 ? void 0 : _cursor$value.options;\n }).then(results => results[0]);\n });\n }\n storeClientOptions(options) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n var txn = _this6.db.transaction([\"client_options\"], \"readwrite\");\n var store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\",\n // constant key so will always clobber\n options: options\n }); // put == UPSERT\n yield txnAsPromise(txn);\n })();\n }\n saveToDeviceBatches(batches) {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n var txn = _this7.db.transaction([\"to_device_queue\"], \"readwrite\");\n var store = txn.objectStore(\"to_device_queue\");\n for (var batch of batches) {\n store.add(batch);\n }\n yield txnAsPromise(txn);\n })();\n }\n getOldestToDeviceBatch() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var txn = _this8.db.transaction([\"to_device_queue\"], \"readonly\");\n var store = txn.objectStore(\"to_device_queue\");\n var cursor = yield reqAsCursorPromise(store.openCursor());\n if (!cursor) return null;\n var resultBatch = cursor.value;\n return {\n id: cursor.key,\n txnId: resultBatch.txnId,\n eventType: resultBatch.eventType,\n batch: resultBatch.batch\n };\n })();\n }\n removeToDeviceBatch(id) {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n var txn = _this9.db.transaction([\"to_device_queue\"], \"readwrite\");\n var store = txn.objectStore(\"to_device_queue\");\n store.delete(id);\n yield txnAsPromise(txn);\n })();\n }\n\n /*\n * Close the database\n */\n destroy() {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n var _this0$db;\n (_this0$db = _this0.db) === null || _this0$db === void 0 || _this0$db.close();\n })();\n }\n}\n//# sourceMappingURL=indexeddb-local-backend.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.js\";\nimport { logger } from \"../logger.js\";\n/**\n * This class lives in the webworker and drives a LocalIndexedDBStoreBackend\n * controlled by messages from the main process.\n *\n * @example\n * It should be instantiated by a web worker script provided by the application\n * in a script, for example:\n * ```\n * import {IndexedDBStoreWorker} from 'matrix-js-sdk/lib/indexeddb-worker.js';\n * const remoteWorker = new IndexedDBStoreWorker(postMessage);\n * onmessage = remoteWorker.onMessage;\n * ```\n *\n * Note that it is advisable to import this class by referencing the file directly to\n * avoid a dependency on the whole js-sdk.\n *\n */\nexport class IndexedDBStoreWorker {\n /**\n * @param postMessage - The web worker postMessage function that\n * should be used to communicate back to the main script.\n */\n constructor(postMessage) {\n this.postMessage = postMessage;\n _defineProperty(this, \"backend\", void 0);\n _defineProperty(this, \"onClose\", () => {\n this.postMessage.call(null, {\n command: \"closed\"\n });\n });\n /**\n * Passes a message event from the main script into the class. This method\n * can be directly assigned to the web worker `onmessage` variable.\n *\n * @param ev - The message event\n */\n _defineProperty(this, \"onMessage\", ev => {\n var _this$backend, _this$backend2, _this$backend3, _this$backend4, _this$backend5, _this$backend6, _this$backend7, _this$backend8, _this$backend9, _this$backend0, _this$backend1, _this$backend10, _this$backend11, _this$backend12, _this$backend13, _this$backend14;\n var msg = ev.data;\n var prom;\n switch (msg.command) {\n case \"setupWorker\":\n // this is the 'indexedDB' global (where global != window\n // because it's a web worker and there is no window).\n this.backend = new LocalIndexedDBStoreBackend(indexedDB, msg.args[0]);\n prom = Promise.resolve();\n break;\n case \"connect\":\n prom = (_this$backend = this.backend) === null || _this$backend === void 0 ? void 0 : _this$backend.connect(this.onClose);\n break;\n case \"isNewlyCreated\":\n prom = (_this$backend2 = this.backend) === null || _this$backend2 === void 0 ? void 0 : _this$backend2.isNewlyCreated();\n break;\n case \"clearDatabase\":\n prom = (_this$backend3 = this.backend) === null || _this$backend3 === void 0 ? void 0 : _this$backend3.clearDatabase();\n break;\n case \"getSavedSync\":\n prom = (_this$backend4 = this.backend) === null || _this$backend4 === void 0 ? void 0 : _this$backend4.getSavedSync(false);\n break;\n case \"setSyncData\":\n prom = (_this$backend5 = this.backend) === null || _this$backend5 === void 0 ? void 0 : _this$backend5.setSyncData(msg.args[0]);\n break;\n case \"syncToDatabase\":\n prom = (_this$backend6 = this.backend) === null || _this$backend6 === void 0 ? void 0 : _this$backend6.syncToDatabase(msg.args[0]);\n break;\n case \"getUserPresenceEvents\":\n prom = (_this$backend7 = this.backend) === null || _this$backend7 === void 0 ? void 0 : _this$backend7.getUserPresenceEvents();\n break;\n case \"getNextBatchToken\":\n prom = (_this$backend8 = this.backend) === null || _this$backend8 === void 0 ? void 0 : _this$backend8.getNextBatchToken();\n break;\n case \"getOutOfBandMembers\":\n prom = (_this$backend9 = this.backend) === null || _this$backend9 === void 0 ? void 0 : _this$backend9.getOutOfBandMembers(msg.args[0]);\n break;\n case \"clearOutOfBandMembers\":\n prom = (_this$backend0 = this.backend) === null || _this$backend0 === void 0 ? void 0 : _this$backend0.clearOutOfBandMembers(msg.args[0]);\n break;\n case \"setOutOfBandMembers\":\n prom = (_this$backend1 = this.backend) === null || _this$backend1 === void 0 ? void 0 : _this$backend1.setOutOfBandMembers(msg.args[0], msg.args[1]);\n break;\n case \"getClientOptions\":\n prom = (_this$backend10 = this.backend) === null || _this$backend10 === void 0 ? void 0 : _this$backend10.getClientOptions();\n break;\n case \"storeClientOptions\":\n prom = (_this$backend11 = this.backend) === null || _this$backend11 === void 0 ? void 0 : _this$backend11.storeClientOptions(msg.args[0]);\n break;\n case \"saveToDeviceBatches\":\n prom = (_this$backend12 = this.backend) === null || _this$backend12 === void 0 ? void 0 : _this$backend12.saveToDeviceBatches(msg.args[0]);\n break;\n case \"getOldestToDeviceBatch\":\n prom = (_this$backend13 = this.backend) === null || _this$backend13 === void 0 ? void 0 : _this$backend13.getOldestToDeviceBatch();\n break;\n case \"removeToDeviceBatch\":\n prom = (_this$backend14 = this.backend) === null || _this$backend14 === void 0 ? void 0 : _this$backend14.removeToDeviceBatch(msg.args[0]);\n break;\n }\n if (prom === undefined) {\n this.postMessage({\n command: \"cmd_fail\",\n seq: msg.seq,\n // Can't be an Error because they're not structured cloneable\n error: \"Unrecognised command\"\n });\n return;\n }\n prom.then(ret => {\n this.postMessage.call(null, {\n command: \"cmd_success\",\n seq: msg.seq,\n result: ret\n });\n }, err => {\n logger.error(\"Error running command: \" + msg.command, err);\n this.postMessage.call(null, {\n command: \"cmd_fail\",\n seq: msg.seq,\n // Just send a string because Error objects aren't cloneable\n error: {\n message: err.message,\n name: err.name\n }\n });\n });\n });\n }\n}\n//# sourceMappingURL=indexeddb-store-worker.js.map","/*\nCopyright 2022-2024 New Vector Ltd.\n\nSPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE in the repository root for full details.\n*/\n\nimport { IndexedDBStoreWorker } from \"matrix-js-sdk/lib/indexeddb-worker\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst remoteWorker = new IndexedDBStoreWorker((self as any).postMessage);\n\nself.onmessage = remoteWorker.onMessage;\n"],"names":["_typeof","o","toPrimitive","t","r","i","toPropertyKey","_defineProperty","e","asyncGeneratorStep","n","c","u","_asyncToGenerator","_next","_throw","root","definition","module","this","noop","undefinedType","isIE","logMethods","_loggersByName","defaultLogger","bindMethod","obj","methodName","method","traceForIE","realMethod","replaceLoggingMethods","level","enableLoggingWhenConsoleArrives","defaultMethodFactory","_level","_loggerName","Logger","name","factory","self","inheritedLevel","defaultLevel","userLevel","storageKey","persistLevelIfPossible","levelNum","levelName","getPersistedLevel","storedLevel","cookie","cookieName","location","clearPersistedLevel","normalizeLevel","input","persist","childName","initialLevel","logger","_log","DEFAULT_NAMESPACE","loglevel","logLevel","loggerName","_len","args","_key","supportedByConsole","getPrefixedLogger","prefix","prefixLogger","childPrefix","childLogger","data","require$$0","escapeRegexp","str","REPLACE_RE","replace_fn","match","unhomoglyph","hasRequiredRetry_operation","RetryOperation","timeouts","options","retry_operation","err","currentTime","timeout","timeoutOps","fn","counts","error","count","message","mainErrorCount","mainError","requireRetry_operation","exports","opts","key","a","b","attempt","random","methods","original","op","callback","hasRequiredRetry","hasRequiredPRetry","pRetry","retry","networkErrorMsgs","decorateErrorWithCounts","attemptNumber","retriesLeft","errorMessage","pRetry$1","resolve","reject","operation","isNetworkError","pRetryModule","requirePRetry","NamespacedValue","stable","unstable","names","altName","val","arr","included","ServerControlledNamespacedValue","preferUnstable","UnstableValue","ReceiptType","deepCopy","promiseTry","isSupportedReceiptType","receiptType","processMapToObjectValue","value","recursiveMapToObject","v","map","targetMap","createDefault","UNREAD_THREAD_NOTIFICATIONS","EventType","ReceiptAccumulator","MapWithDefault","userId","receipt","threadId","receiptsForThread","events","eventId","_ref","roomId","receiptEvent","receiptEventContent","receiptData","_userId","_receiptData","Category","isTaggedEvent","event","SyncAccumulator","syncResponse","fromDatabase","category","currentData","hasAdded","current","_data","_data$ephemeral","_data$state","_data$orgMatrixMsc","_data$timeline","_sum$HEROES_KEY","_sum$JOINED_COUNT_KEY","_sum$INVITED_COUNT_KE","HEROES_KEY","INVITED_COUNT_KEY","JOINED_COUNT_KEY","acc","sum","setState","index","_data$timeline$prev_b","transformedEvent","_e$unsigned","age","startIndex","forDatabase","roomJson","roomData","evType","msgData","rollBackState","timelineEvent","prevStateEvent","stateKey","ev","accData","eventMap","exists","indexedDB","dbName","req","db","DB_MIGRATIONS","oobMembersStore","VERSION","selectQuery","store","keyRange","resultMapper","query","_query$error","cursor","results","txnAsPromise","txn","reqAsEventPromise","reqAsPromise","reqAsCursorPromise","onClose","_this","oldVersion","migration","_this$db","_ref2","accountData","syncData","tx","roomIndex","range","request","membershipEvents","oobWritten","record","_this2","markerObject","_this3","readTx","roomRange","minStateKeyProm","maxStateKeyProm","maxStateKey","writeTx","writeStore","membersKeyRange","minStateKey","_this$db2","_req$error","copy","userTuples","_this4","_this5","nextBatch","roomsData","tuples","tuple","result","_cursor$value","_this6","batches","_this7","batch","_this8","resultBatch","id","_this9","_this0$db","_this0","IndexedDBStoreWorker","postMessage","_this$backend","_this$backend2","_this$backend3","_this$backend4","_this$backend5","_this$backend6","_this$backend7","_this$backend8","_this$backend9","_this$backend0","_this$backend1","_this$backend10","_this$backend11","_this$backend12","_this$backend13","_this$backend14","msg","LocalIndexedDBStoreBackend","prom","ret"],"mappings":"yBAAA,SAASA,EAAQC,EAAG,CAClB,0BAEA,OAAOD,EAAwB,OAAO,QAArB,YAA2C,OAAO,OAAO,UAA1B,SAAqC,SAAUC,EAAG,CAChG,OAAO,OAAOA,CACf,EAAG,SAAUA,EAAG,CACf,OAAOA,GAAmB,OAAO,QAArB,YAA+BA,EAAE,cAAgB,QAAUA,IAAM,OAAO,UAAY,SAAW,OAAOA,CACtH,EAAKD,EAAQC,CAAC,CACd,CCPA,SAASC,GAAYC,EAAGC,EAAG,CACzB,GAAgBJ,EAAQG,CAAC,GAArB,UAA0B,CAACA,EAAG,OAAOA,EACzC,IAAI,EAAIA,EAAE,OAAO,WAAW,EAC5B,GAAe,IAAX,OAAc,CAChB,IAAIE,EAAI,EAAE,KAAKF,EAAGC,CAAc,EAChC,GAAgBJ,EAAQK,CAAC,GAArB,SAAwB,OAAOA,EACnC,MAAM,IAAI,UAAU,8CAA8C,CACtE,CACE,OAAqBD,IAAb,SAAiB,OAAS,QAAQD,CAAC,CAC7C,CCRA,SAASG,GAAcH,EAAG,CACxB,IAAIE,EAAIH,GAAYC,EAAG,QAAQ,EAC/B,OAAmBH,EAAQK,CAAC,GAArB,SAAyBA,EAAIA,EAAI,EAC1C,CCJA,SAASE,EAAgBC,EAAGJ,EAAGD,EAAG,CAChC,OAAQC,EAAIE,GAAcF,CAAC,KAAMI,EAAI,OAAO,eAAeA,EAAGJ,EAAG,CAC/D,MAAOD,EACP,WAAY,GACZ,aAAc,GACd,SAAU,EACX,CAAA,EAAIK,EAAEJ,CAAC,EAAID,EAAGK,CACjB,CCRA,SAASC,EAAmBC,EAAG,EAAG,EAAGN,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MAAAA,IAAA,OAAA,OAAAA,EAAA,uBAAA,EACxB,MACA,IAAA,sBACVI,GAAAH,EAAA,KAAA,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,oBAAAC,EAAA,KAAA,CAAA,CAAA,EACU,KACF,CACE,GAAAE,IAAS,OAAU,CAC7B,KAAa,YAAS,CACtB,QAAA,WACU,IAAKF,EAAE,IAET,MAAA,sBACR,CAAA,EACU,MACV,CACUE,EAAA,KAAAC,GAAsB,CAChC,KAAa,YAAS,KAAA,KAAA,CACZ,QAAQ,cACR,IAAAH,EAAA,WACMG,CACR,CAAA,CACR,KAAa,CACHhP,EAAA,MAAmB,0BAAA6O,EAAA,QAAAjN,CAAA,EAC7B,KAAa,YAAS,KAAA,KAAA,CACtB,QAAA,WACU,IAAKiN,EAAE,IAEL,MAAM,CAClB,QAAAjN,EAAA,QACU,KAAAA,EAAA,IACF,CACF,CAAA,CACN,CAAA,CACA,CAAA,ECtIA","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]}
1
+ {"version":3,"file":"IndexedDBWorker-whz4J8_U.js","sources":["../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","../node_modules/loglevel/lib/loglevel.js","../node_modules/matrix-js-sdk/lib/logger.js","../node_modules/unhomoglyph/index.js","../node_modules/retry/lib/retry_operation.js","../node_modules/retry/lib/retry.js","../node_modules/retry/index.js","../node_modules/p-retry/index.js","../node_modules/matrix-js-sdk/lib/NamespacedValue.js","../node_modules/matrix-js-sdk/lib/@types/location.js","../node_modules/matrix-js-sdk/lib/@types/read_receipts.js","../node_modules/matrix-js-sdk/lib/utils.js","../node_modules/matrix-js-sdk/lib/@types/sync.js","../node_modules/matrix-js-sdk/lib/@types/event.js","../node_modules/matrix-js-sdk/lib/receipt-accumulator.js","../node_modules/matrix-js-sdk/lib/sync-accumulator.js","../node_modules/matrix-js-sdk/lib/indexeddb-helpers.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-local-backend.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-store-worker.js","../src/IndexedDBWorker.ts"],"sourcesContent":["function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nexport { _typeof as default };","import _typeof from \"./typeof.js\";\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nexport { toPrimitive as default };","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nexport { _defineProperty as default };","function asyncGeneratorStep(n, t, e, r, o, a, c) {\n try {\n var i = n[a](c),\n u = i.value;\n } catch (n) {\n return void e(n);\n }\n i.done ? t(u) : Promise.resolve(u).then(r, o);\n}\nfunction _asyncToGenerator(n) {\n return function () {\n var t = this,\n e = arguments;\n return new Promise(function (r, o) {\n var a = n.apply(t, e);\n function _next(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n);\n }\n function _throw(n) {\n asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n);\n }\n _next(void 0);\n });\n };\n}\nexport { _asyncToGenerator as default };","/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n var _loggersByName = {};\n var defaultLogger = null;\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods() {\n /*jshint validthis:true */\n var level = this.getLevel();\n\n // Replace the actual methods.\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, this.name);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n\n // Return any important warnings.\n if (typeof console === undefinedType && level < this.levels.SILENT) {\n return \"No console available for logging\";\n }\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, _level, _loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, factory) {\n // Private instance variables.\n var self = this;\n /**\n * The level inherited from a parent logger (or a global default). We\n * cache this here rather than delegating to the parent so that it stays\n * in sync with the actual logging methods that we have installed (the\n * parent could change levels but we might not have rebuilt the loggers\n * in this child yet).\n * @type {number}\n */\n var inheritedLevel;\n /**\n * The default level for this logger, if any. If set, this overrides\n * `inheritedLevel`.\n * @type {number|null}\n */\n var defaultLevel;\n /**\n * A user-specific level for this logger. If set, this overrides\n * `defaultLevel`.\n * @type {number|null}\n */\n var userLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var cookieName = encodeURIComponent(storageKey);\n var location = cookie.indexOf(cookieName + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(\n cookie.slice(location + cookieName.length + 1)\n )[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n function normalizeLevel(input) {\n var level = input;\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n return level;\n } else {\n throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n }\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n if (userLevel != null) {\n return userLevel;\n } else if (defaultLevel != null) {\n return defaultLevel;\n } else {\n return inheritedLevel;\n }\n };\n\n self.setLevel = function (level, persist) {\n userLevel = normalizeLevel(level);\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(userLevel);\n }\n\n // NOTE: in v2, this should call rebuild(), which updates children.\n return replaceLoggingMethods.call(self);\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = normalizeLevel(level);\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n userLevel = null;\n clearPersistedLevel();\n replaceLoggingMethods.call(self);\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n self.rebuild = function () {\n if (defaultLogger !== self) {\n inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n }\n replaceLoggingMethods.call(self);\n\n if (defaultLogger === self) {\n for (var childName in _loggersByName) {\n _loggersByName[childName].rebuild();\n }\n }\n };\n\n // Initialize all the internal levels.\n inheritedLevel = normalizeLevel(\n defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n );\n var initialLevel = getPersistedLevel();\n if (initialLevel != null) {\n userLevel = normalizeLevel(initialLevel);\n }\n replaceLoggingMethods.call(self);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n defaultLogger = new Logger();\n\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name,\n defaultLogger.methodFactory\n );\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2018 André Jaenisch\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\n\n/** Logger interface used within the js-sdk codebase */\n\n/** The basic interface for a logger which doesn't support children */\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nvar DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n var supportedByConsole = methodName === \"error\" || methodName === \"warn\" || methodName === \"trace\" || methodName === \"info\" || methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix) {\n var loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : \"-\".concat(prefix));\n var prefixLogger = loglevel.getLogger(loggerName);\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = childPrefix => {\n // create the new child logger\n var childLogger = getPrefixedLogger((prefix !== null && prefix !== void 0 ? prefix : \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n */\nexport var logger = getPrefixedLogger();\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan {\n constructor(parent, name) {\n this.parent = parent;\n _defineProperty(this, \"name\", void 0);\n this.name = name + \":\";\n }\n trace() {\n for (var _len2 = arguments.length, msg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n msg[_key2] = arguments[_key2];\n }\n this.parent.trace(this.name, ...msg);\n }\n debug() {\n for (var _len3 = arguments.length, msg = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n msg[_key3] = arguments[_key3];\n }\n this.parent.debug(this.name, ...msg);\n }\n info() {\n for (var _len4 = arguments.length, msg = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n msg[_key4] = arguments[_key4];\n }\n this.parent.info(this.name, ...msg);\n }\n warn() {\n for (var _len5 = arguments.length, msg = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n msg[_key5] = arguments[_key5];\n }\n this.parent.warn(this.name, ...msg);\n }\n error() {\n for (var _len6 = arguments.length, msg = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n msg[_key6] = arguments[_key6];\n }\n this.parent.error(this.name, ...msg);\n }\n}\n//# sourceMappingURL=logger.js.map","'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n return data[match];\n}\n\nfunction unhomoglyph(str) {\n return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","module.exports = require('./lib/retry');","'use strict';\nconst retry = require('retry');\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports.default = pRetry;\n\nmodule.exports.AbortError = AbortError;\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nexport class NamespacedValue {\n // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n // Goal is to to have developers explicitly say there is no stable value (if applicable).\n\n constructor(stable, unstable) {\n this.stable = stable;\n this.unstable = unstable;\n if (!this.unstable && !this.stable) {\n throw new Error(\"One of stable or unstable values must be supplied\");\n }\n }\n get name() {\n if (this.stable) {\n return this.stable;\n }\n return this.unstable;\n }\n get altName() {\n if (!this.stable) {\n return null;\n }\n return this.unstable;\n }\n get names() {\n var names = [this.name];\n var altName = this.altName;\n if (altName) names.push(altName);\n return names;\n }\n matches(val) {\n return this.name === val || this.altName === val;\n }\n\n // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.\n findIn(obj) {\n var val = undefined;\n if (this.name) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.name];\n }\n if (!val && this.altName) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.altName];\n }\n return val;\n }\n includedIn(arr) {\n var included = false;\n if (this.name) {\n included = arr.includes(this.name);\n }\n if (!included && this.altName) {\n included = arr.includes(this.altName);\n }\n return included;\n }\n}\nexport class ServerControlledNamespacedValue extends NamespacedValue {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"preferUnstable\", false);\n }\n setPreferUnstable(preferUnstable) {\n this.preferUnstable = preferUnstable;\n }\n get name() {\n if (this.stable && !this.preferUnstable) {\n return this.stable;\n }\n return this.unstable;\n }\n}\n\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\nexport class UnstableValue extends NamespacedValue {\n // Note: Constructor difference is that `unstable` is *required*.\n constructor(stable, unstable) {\n super(stable, unstable);\n if (!this.unstable) {\n throw new Error(\"Unstable value must be supplied\");\n }\n }\n get name() {\n return this.unstable;\n }\n get altName() {\n return this.stable;\n }\n}\n//# sourceMappingURL=NamespacedValue.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types for MSC3488 - m.location: Extending events with location data\n\nimport { UnstableValue } from \"../NamespacedValue.js\";\nexport var LocationAssetType = /*#__PURE__*/function (LocationAssetType) {\n LocationAssetType[\"Self\"] = \"m.self\";\n LocationAssetType[\"Pin\"] = \"m.pin\";\n return LocationAssetType;\n}({});\nexport var M_ASSET = new UnstableValue(\"m.asset\", \"org.matrix.msc3488.asset\");\n\n/**\n * The event definition for an m.asset event (in content)\n */\n\nexport var M_TIMESTAMP = new UnstableValue(\"m.ts\", \"org.matrix.msc3488.ts\");\n/**\n * The event definition for an m.ts event (in content)\n */\n\nexport var M_LOCATION = new UnstableValue(\"m.location\", \"org.matrix.msc3488.location\");\n\n/* From the spec at:\n * https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md\n{\n \"type\": \"m.room.message\",\n \"content\": {\n \"body\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"msgtype\": \"m.location\",\n \"geo_uri\": \"geo:51.5008,0.1247;u=35\",\n \"m.location\": {\n \"uri\": \"geo:51.5008,0.1247;u=35\",\n \"description\": \"Matthew's whereabouts\",\n },\n \"m.asset\": {\n \"type\": \"m.self\"\n },\n \"m.text\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"m.ts\": 1636829458432,\n }\n}\n*/\n\n/**\n * The content for an m.location event\n */\n\n/**\n * Possible content for location events as sent over the wire\n */\n//# sourceMappingURL=location.js.map","/*\nCopyright 2022 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var ReceiptType = /*#__PURE__*/function (ReceiptType) {\n ReceiptType[\"Read\"] = \"m.read\";\n ReceiptType[\"FullyRead\"] = \"m.fully_read\";\n ReceiptType[\"ReadPrivate\"] = \"m.read.private\";\n return ReceiptType;\n}({});\nexport var MAIN_ROOM_TIMELINE = \"main\";\n\n// We will only hold a synthetic receipt if we do not have a real receipt or the synthetic is newer.\n// map: receipt type → user Id → receipt\n//# sourceMappingURL=read_receipts.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\n/*\nCopyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport { M_TIMESTAMP } from \"./@types/location.js\";\nimport { ReceiptType } from \"./@types/read_receipts.js\";\nvar interns = new Map();\n\n/**\n * Internalises a string, reusing a known pointer or storing the pointer\n * if needed for future strings.\n * @param str - The string to internalise.\n * @returns The internalised string.\n */\nexport function internaliseString(str) {\n // Unwrap strings before entering the map, if we somehow got a wrapped\n // string as our input. This should only happen from tests.\n if (str instanceof String) {\n str = str.toString();\n }\n\n // Check the map to see if we can store the value\n if (!interns.has(str)) {\n interns.set(str, str);\n }\n\n // Return any cached string reference\n return interns.get(str);\n}\n\n/**\n * Encode a dictionary of query parameters.\n * Omits any undefined/null values.\n * @param params - A dict of key/values to encode e.g.\n * `{\"foo\": \"bar\", \"baz\": \"taz\"}`\n * @returns The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params, urlSearchParams) {\n var searchParams = urlSearchParams !== null && urlSearchParams !== void 0 ? urlSearchParams : new URLSearchParams();\n var _loop = function _loop(key) {\n if (val !== undefined && val !== null) {\n if (Array.isArray(val)) {\n val.forEach(v => {\n searchParams.append(key, String(v));\n });\n } else {\n searchParams.append(key, String(val));\n }\n }\n };\n for (var [key, val] of Object.entries(params)) {\n _loop(key);\n }\n return searchParams;\n}\n/**\n * Replace a stable parameter with the unstable naming for params\n */\nexport function replaceParam(stable, unstable, dict) {\n var result = _objectSpread(_objectSpread({}, dict), {}, {\n [unstable]: dict[stable]\n });\n delete result[stable];\n return result;\n}\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param query - A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @returns The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query) {\n var o = {};\n var params = new URLSearchParams(query);\n for (var key of params.keys()) {\n var val = params.getAll(key);\n o[key] = val.length === 1 ? val[0] : val;\n }\n return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param pathTemplate - The path with template variables e.g. '/foo/$bar'.\n * @param variables - The key/value pairs to replace the template\n * variables with. E.g. `{ \"$bar\": \"baz\" }`.\n * @returns The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate, variables) {\n for (var key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n var value = variables[key];\n if (value === undefined || value === null) {\n continue;\n }\n pathTemplate = pathTemplate.replace(key, encodeURIComponent(value));\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param array - The array.\n * @param fn - Function to execute on each value in the array, with the\n * function signature `fn(element, index, array)`. Return true to\n * remove this element and break.\n * @param reverse - True to search in reverse order.\n * @returns True if an element was removed.\n */\nexport function removeElement(array, fn, reverse) {\n var i;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param value - The thing to check.\n * @returns True if it is a function.\n */\nexport function isFunction(value) {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param obj - The object to check.\n * @param keys - The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj, keys) {\n for (var key of keys) {\n if (!obj.hasOwnProperty(key)) {\n throw new Error(\"Missing required key: \" + key);\n }\n }\n}\n\n/**\n * Deep copy the given object. The object MUST NOT have circular references and\n * MUST NOT have functions.\n * @param obj - The object to deep copy.\n * @returns A copy of the object without any references to the original.\n */\nexport function deepCopy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Compare two objects for equality. The objects MUST NOT have circular references.\n *\n * @param x - The first object to compare.\n * @param y - The second object to compare.\n *\n * @returns true if the two objects are equal\n */\nexport function deepCompare(x, y) {\n // Inspired by\n // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249\n\n // Compare primitives and functions.\n // Also check if both arguments link to the same object.\n if (x === y) {\n return true;\n }\n if (typeof x !== typeof y) {\n return false;\n }\n\n // special-case NaN (since NaN !== NaN)\n if (typeof x === \"number\" && isNaN(x) && isNaN(y)) {\n return true;\n }\n\n // special-case null (since typeof null == 'object', but null.constructor\n // throws)\n if (x === null || y === null) {\n return x === y;\n }\n\n // everything else is either an unequal primitive, or an object\n if (!(x instanceof Object)) {\n return false;\n }\n\n // check they are the same type of object\n if (x.constructor !== y.constructor || x.prototype !== y.prototype) {\n return false;\n }\n\n // special-casing for some special types of object\n if (x instanceof RegExp || x instanceof Date) {\n return x.toString() === y.toString();\n }\n\n // the object algorithm works for Array, but it's sub-optimal.\n if (Array.isArray(x)) {\n if (x.length !== y.length) {\n return false;\n }\n for (var i = 0; i < x.length; i++) {\n if (!deepCompare(x[i], y[i])) {\n return false;\n }\n }\n } else {\n // check that all of y's direct keys are in x\n for (var p in y) {\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n return false;\n }\n }\n\n // finally, compare each of x's keys with y\n for (var _p in x) {\n if (y.hasOwnProperty(_p) !== x.hasOwnProperty(_p) || !deepCompare(x[_p], y[_p])) {\n return false;\n }\n }\n }\n return true;\n}\n\n// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703\n/**\n * Creates an array of object properties/values (entries) then\n * sorts the result by key, recursively. The input object must\n * ensure it does not have loops. If the input is not an object\n * then it will be returned as-is.\n * @param obj - The object to get entries of\n * @returns The entries, sorted by key.\n */\nexport function deepSortedObjectEntries(obj) {\n if (typeof obj !== \"object\") return obj;\n\n // Apparently these are object types...\n if (obj === null || obj === undefined || Array.isArray(obj)) return obj;\n var pairs = [];\n for (var [k, v] of Object.entries(obj)) {\n pairs.push([k, deepSortedObjectEntries(v)]);\n }\n\n // lexicographicCompare is faster than localeCompare, so let's use that.\n pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));\n return pairs;\n}\n\n/**\n * Returns whether the given value is a finite number without type-coercion\n *\n * @param value - the value to test\n * @returns whether or not value is a finite number without type-coercion\n */\nexport function isNumber(value) {\n return typeof value === \"number\" && isFinite(value);\n}\n\n/**\n * Removes zero width chars, diacritics and whitespace from the string\n * Also applies an unhomoglyph on the string, to prevent similar looking chars\n * @param str - the string to remove hidden characters from\n * @returns a string with the hidden characters removed\n */\nexport function removeHiddenChars(str) {\n if (typeof str === \"string\") {\n return unhomoglyph(str.normalize(\"NFD\").replace(removeHiddenCharsRegex, \"\"));\n }\n return \"\";\n}\n\n/**\n * Removes the direction override characters from a string\n * @returns string with chars removed\n */\nexport function removeDirectionOverrideChars(str) {\n if (typeof str === \"string\") {\n return str.replace(/[\\u202d-\\u202e]/g, \"\");\n }\n return \"\";\n}\nexport function normalize(str) {\n // Note: we have to match the filter with the removeHiddenChars() because the\n // function strips spaces and other characters (M becomes RN for example, in lowercase).\n return removeHiddenChars(str.toLowerCase())\n // Strip all punctuation\n .replace(/[\\\\'!\"#$%&()*+,\\-./:;<=>?@[\\]^_`{|}~\\u2000-\\u206f\\u2e00-\\u2e7f]/g, \"\")\n // We also doubly convert to lowercase to work around oddities of the library.\n .toLowerCase();\n}\n\n// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.\n// Includes:\n// various width spaces U+2000 - U+200D\n// LTR and RTL marks U+200E and U+200F\n// LTR/RTL and other directional formatting marks U+202A - U+202F\n// Arabic Letter RTL mark U+061C\n// Combining characters U+0300 - U+036F\n// Zero width no-break space (BOM) U+FEFF\n// Blank/invisible characters (U2800, U2062-U2063)\n// eslint-disable-next-line no-misleading-character-class\nvar removeHiddenCharsRegex = /[\\u2000-\\u200F\\u202A-\\u202F\\u0300-\\u036F\\uFEFF\\u061C\\u2800\\u2062-\\u2063\\s]/g;\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Converts Matrix glob-style string to a regular expression\n * https://spec.matrix.org/v1.7/appendices/#glob-style-matching\n * @param glob - Matrix glob-style string\n * @returns regular expression\n */\nexport function globToRegexp(glob) {\n return escapeRegExp(glob).replace(/\\\\\\*/g, \".*\").replace(/\\?/g, \".\");\n}\nexport function ensureNoTrailingSlash(url) {\n if (url !== null && url !== void 0 && url.endsWith(\"/\")) {\n return url.slice(0, -1);\n } else {\n return url;\n }\n}\n\n/**\n * Returns a promise which resolves with a given value after the given number of ms\n */\nexport function sleep(ms, value) {\n return new Promise(resolve => {\n setTimeout(resolve, ms, value);\n });\n}\n\n/**\n * Utility to log the duration of a promise.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nexport function logDuration(_x, _x2, _x3) {\n return _logDuration.apply(this, arguments);\n}\n\n/**\n * Utility to log the duration of a synchronous block.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nfunction _logDuration() {\n _logDuration = _asyncToGenerator(function* (logger, name, block) {\n var start = Date.now();\n try {\n return yield block();\n } finally {\n var end = Date.now();\n logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n }\n });\n return _logDuration.apply(this, arguments);\n}\nexport function logDurationSync(logger, name, block) {\n var start = Date.now();\n try {\n return block();\n } finally {\n var end = Date.now();\n logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n }\n}\n\n/**\n * Promise/async version of {@link setImmediate}.\n *\n * Implementation is based on `setTimeout` for wider compatibility.\n * @deprecated Use {@link sleep} instead.\n */\nexport function immediate() {\n return new Promise(resolve => setTimeout(resolve));\n}\nexport function isNullOrUndefined(val) {\n return val === null || val === undefined;\n}\n/**\n * @deprecated use {@link PromiseWithResolvers} instead.\n */\n\n/**\n * Creates a deferred promise. This is a promise that can be resolved or rejected.\n * @deprecated use {@link Promise.withResolvers} instead.\n */\nexport function defer() {\n return Promise.withResolvers();\n}\nexport function promiseMapSeries(_x4, _x5) {\n return _promiseMapSeries.apply(this, arguments);\n}\nfunction _promiseMapSeries() {\n _promiseMapSeries = _asyncToGenerator(function* (promises, fn // if async we don't care about the type as we only await resolution\n ) {\n for (var o of promises) {\n yield fn(yield o);\n }\n });\n return _promiseMapSeries.apply(this, arguments);\n}\nexport function promiseTry(fn) {\n return Promise.resolve(fn());\n}\n\n// Creates and awaits all promises, running no more than `chunkSize` at the same time\nexport function chunkPromises(_x6, _x7) {\n return _chunkPromises.apply(this, arguments);\n}\n\n/**\n * Retries the function until it succeeds or is interrupted. The given function must return\n * a promise which throws/rejects on error, otherwise the retry will assume the request\n * succeeded. The promise chain returned will contain the successful promise. The given function\n * should always return a new promise.\n * @param promiseFn - The function to call to get a fresh promise instance. Takes an\n * attempt count as an argument, for logging/debugging purposes.\n * @returns The promise for the retried operation.\n */\nfunction _chunkPromises() {\n _chunkPromises = _asyncToGenerator(function* (fns, chunkSize) {\n var results = [];\n for (var i = 0; i < fns.length; i += chunkSize) {\n results.push(...(yield Promise.all(fns.slice(i, i + chunkSize).map(fn => fn()))));\n }\n return results;\n });\n return _chunkPromises.apply(this, arguments);\n}\nexport function simpleRetryOperation(promiseFn) {\n return promiseRetry(attempt => {\n return promiseFn(attempt);\n }, {\n forever: true,\n factor: 2,\n minTimeout: 3000,\n // ms\n maxTimeout: 15000 // ms\n });\n}\n\n// String averaging inspired by https://stackoverflow.com/a/2510816\n// Dev note: We make the alphabet a string because it's easier to write syntactically\n// than arrays. Thankfully, strings implement the useful parts of the Array interface\n// anyhow.\n\n/**\n * The default alphabet used by string averaging in this SDK. This matches\n * all usefully printable ASCII characters (0x20-0x7E, inclusive).\n */\nexport var DEFAULT_ALPHABET = (() => {\n var str = \"\";\n for (var c = 0x20; c <= 0x7e; c++) {\n str += String.fromCharCode(c);\n }\n return str;\n})();\n\n/**\n * Pads a string using the given alphabet as a base. The returned string will be\n * padded at the end with the first character in the alphabet.\n *\n * This is intended for use with string averaging.\n * @param s - The string to pad.\n * @param n - The length to pad to.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The padded string.\n */\nexport function alphabetPad(s, n) {\n var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n return s.padEnd(n, alphabet[0]);\n}\n\n/**\n * Converts a baseN number to a string, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param n - The baseN number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number encoded as a string from the alphabet.\n */\nexport function baseToString(n) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n // Developer note: the stringToBase() function offsets the character set by 1 so that repeated\n // characters (ie: \"aaaaaa\" in a..z) don't come out as zero. We have to reverse this here as\n // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun\n // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a\n // sane state. This also means we have to do rollover detection: see below.\n\n var len = BigInt(alphabet.length);\n if (n <= len) {\n var _alphabet;\n return (_alphabet = alphabet[Number(n) - 1]) !== null && _alphabet !== void 0 ? _alphabet : \"\";\n }\n var d = n / len;\n var r = Number(n % len) - 1;\n\n // Rollover detection: if the remainder is negative, it means that the string needs\n // to roll over by 1 character downwards (ie: in a..z, the previous to \"aaa\" would be\n // \"zz\").\n if (r < 0) {\n d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.\n r = Number(len) - 1;\n }\n return baseToString(d, alphabet) + alphabet[r];\n}\n\n/**\n * Converts a string to a baseN number, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param s - The string to convert to a number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number.\n */\nexport function stringToBase(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n var len = BigInt(alphabet.length);\n\n // In our conversion to baseN we do a couple performance optimizations to avoid using\n // excess CPU and such. To create baseN numbers, the input string needs to be reversed\n // so the exponents stack up appropriately, as the last character in the unreversed\n // string has less impact than the first character (in \"abc\" the A is a lot more important\n // for lexicographic sorts). We also do a trick with the character codes to optimize the\n // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know\n // that the alphabet and (theoretically) the input string are constrained on character sets\n // and thus can do simple subtraction to end up with the same result.\n\n // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot\n // rely on Math.pow() (for example) to be capable of handling our insane numbers.\n\n var result = BigInt(0);\n for (var i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {\n var charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);\n\n // We add 1 to the char index to offset the whole numbering scheme. We unpack this in\n // the baseToString() function.\n result += BigInt(1 + charIndex) * len ** j;\n }\n return result;\n}\n\n/**\n * Averages two strings, returning the midpoint between them. This is accomplished by\n * converting both to baseN numbers (where N is the alphabet's length) then averaging\n * those before re-encoding as a string.\n * @param a - The first string.\n * @param b - The second string.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The midpoint between the strings, as a string.\n */\nexport function averageBetweenStrings(a, b) {\n var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n var padN = Math.max(a.length, b.length);\n var baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);\n var baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);\n var avg = (baseA + baseB) / BigInt(2);\n\n // Detect integer division conflicts. This happens when two numbers are divided too close so\n // we lose a .5 precision. We need to add a padding character in these cases.\n if (avg === baseA || avg == baseB) {\n return baseToString(avg, alphabet) + alphabet[0];\n }\n return baseToString(avg, alphabet);\n}\n\n/**\n * Finds the next string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then adding 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which follows the input string.\n */\nexport function nextString(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);\n}\n\n/**\n * Finds the previous string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then subtracting 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which precedes the input string.\n */\nexport function prevString(s) {\n var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);\n}\n\n/**\n * Compares strings lexicographically as a sort-safe function.\n * @param a - The first (reference) string.\n * @param b - The second (compare) string.\n * @returns Negative if the reference string is before the compare string;\n * positive if the reference string is after; and zero if equal.\n */\nexport function lexicographicCompare(a, b) {\n // Dev note: this exists because I'm sad that you can use math operators on strings, so I've\n // hidden the operation in this function.\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n}\n\n/**\n * This function is similar to Object.assign() but it assigns recursively and\n * allows you to ignore nullish values from the source\n *\n * @returns the target object\n */\nexport function recursivelyAssign(target, source) {\n var ignoreNullish = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n for (var [sourceKey, sourceValue] of Object.entries(source)) {\n if (target[sourceKey] instanceof Object && sourceValue) {\n recursivelyAssign(target[sourceKey], sourceValue);\n continue;\n }\n if (sourceValue !== null && sourceValue !== undefined || !ignoreNullish) {\n safeSet(target, sourceKey, sourceValue);\n continue;\n }\n }\n return target;\n}\nfunction getContentTimestampWithFallback(event) {\n var _M_TIMESTAMP$findIn;\n return (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(event.getContent())) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : -1;\n}\n\n/**\n * Sort events by their content m.ts property\n * Latest timestamp first\n */\nexport function sortEventsByLatestContentTimestamp(left, right) {\n return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);\n}\nexport function isSupportedReceiptType(receiptType) {\n return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType);\n}\n\n/**\n * Determines whether two maps are equal.\n * @param eq - The equivalence relation to compare values by. Defaults to strict equality.\n */\nexport function mapsEqual(x, y) {\n var eq = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (v1, v2) => v1 === v2;\n if (x.size !== y.size) return false;\n for (var [k, v1] of x) {\n var v2 = y.get(k);\n if (v2 === undefined || !eq(v1, v2)) return false;\n }\n return true;\n}\nfunction processMapToObjectValue(value) {\n if (value instanceof Map) {\n // Value is a Map. Recursively map it to an object.\n return recursiveMapToObject(value);\n } else if (Array.isArray(value)) {\n // Value is an Array. Recursively map the value (e.g. to cover Array of Arrays).\n return value.map(v => processMapToObjectValue(v));\n } else {\n return value;\n }\n}\n\n/**\n * Recursively converts Maps to plain objects.\n * Also supports sub-lists of Maps.\n */\nexport function recursiveMapToObject(map) {\n var targetMap = new Map();\n for (var [key, value] of map) {\n targetMap.set(key, processMapToObjectValue(value));\n }\n return Object.fromEntries(targetMap.entries());\n}\nexport function unsafeProp(prop) {\n return prop === \"__proto__\" || prop === \"prototype\" || prop === \"constructor\";\n}\nexport function safeSet(obj, prop, value) {\n if (unsafeProp(prop)) {\n throw new Error(\"Trying to modify prototype or constructor\");\n }\n obj[prop] = value;\n}\nexport function noUnsafeEventProps(event) {\n return !(unsafeProp(event.room_id) || unsafeProp(event.sender) || unsafeProp(event.event_id));\n}\nexport class MapWithDefault extends Map {\n constructor(createDefault) {\n super();\n this.createDefault = createDefault;\n }\n\n /**\n * Returns the value if the key already exists.\n * If not, it creates a new value under that key using the ctor callback and returns it.\n */\n getOrCreate(key) {\n if (!this.has(key)) {\n this.set(key, this.createDefault());\n }\n return this.get(key);\n }\n}\n//# sourceMappingURL=utils.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.js\";\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3773\n *\n * @experimental\n */\nexport var UNREAD_THREAD_NOTIFICATIONS = new ServerControlledNamespacedValue(\"unread_thread_notifications\", \"org.matrix.msc3773.unread_thread_notifications\");\n//# sourceMappingURL=sync.js.map","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NamespacedValue, UnstableValue } from \"../NamespacedValue.js\";\nexport var EventType = /*#__PURE__*/function (EventType) {\n // Room state events\n EventType[\"RoomCanonicalAlias\"] = \"m.room.canonical_alias\";\n EventType[\"RoomCreate\"] = \"m.room.create\";\n EventType[\"RoomJoinRules\"] = \"m.room.join_rules\";\n EventType[\"RoomMember\"] = \"m.room.member\";\n EventType[\"RoomThirdPartyInvite\"] = \"m.room.third_party_invite\";\n EventType[\"RoomPowerLevels\"] = \"m.room.power_levels\";\n EventType[\"RoomName\"] = \"m.room.name\";\n EventType[\"RoomTopic\"] = \"m.room.topic\";\n EventType[\"RoomAvatar\"] = \"m.room.avatar\";\n EventType[\"RoomPinnedEvents\"] = \"m.room.pinned_events\";\n EventType[\"RoomEncryption\"] = \"m.room.encryption\";\n EventType[\"RoomHistoryVisibility\"] = \"m.room.history_visibility\";\n EventType[\"RoomGuestAccess\"] = \"m.room.guest_access\";\n EventType[\"RoomServerAcl\"] = \"m.room.server_acl\";\n EventType[\"RoomTombstone\"] = \"m.room.tombstone\";\n EventType[\"RoomPredecessor\"] = \"org.matrix.msc3946.room_predecessor\";\n // Moderation policy lists\n EventType[\"PolicyRuleUser\"] = \"m.policy.rule.user\";\n EventType[\"PolicyRuleRoom\"] = \"m.policy.rule.room\";\n EventType[\"PolicyRuleServer\"] = \"m.policy.rule.server\";\n EventType[\"SpaceChild\"] = \"m.space.child\";\n EventType[\"SpaceParent\"] = \"m.space.parent\";\n // Room timeline events\n EventType[\"RoomRedaction\"] = \"m.room.redaction\";\n EventType[\"RoomMessage\"] = \"m.room.message\";\n EventType[\"RoomMessageEncrypted\"] = \"m.room.encrypted\";\n EventType[\"Sticker\"] = \"m.sticker\";\n EventType[\"CallInvite\"] = \"m.call.invite\";\n EventType[\"CallCandidates\"] = \"m.call.candidates\";\n EventType[\"CallAnswer\"] = \"m.call.answer\";\n EventType[\"CallHangup\"] = \"m.call.hangup\";\n EventType[\"CallReject\"] = \"m.call.reject\";\n EventType[\"CallSelectAnswer\"] = \"m.call.select_answer\";\n EventType[\"CallNegotiate\"] = \"m.call.negotiate\";\n EventType[\"CallSDPStreamMetadataChanged\"] = \"m.call.sdp_stream_metadata_changed\";\n EventType[\"CallSDPStreamMetadataChangedPrefix\"] = \"org.matrix.call.sdp_stream_metadata_changed\";\n EventType[\"CallReplaces\"] = \"m.call.replaces\";\n EventType[\"CallAssertedIdentity\"] = \"m.call.asserted_identity\";\n EventType[\"CallAssertedIdentityPrefix\"] = \"org.matrix.call.asserted_identity\";\n EventType[\"CallEncryptionKeysPrefix\"] = \"io.element.call.encryption_keys\";\n EventType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n EventType[\"KeyVerificationStart\"] = \"m.key.verification.start\";\n EventType[\"KeyVerificationCancel\"] = \"m.key.verification.cancel\";\n EventType[\"KeyVerificationMac\"] = \"m.key.verification.mac\";\n EventType[\"KeyVerificationDone\"] = \"m.key.verification.done\";\n EventType[\"KeyVerificationKey\"] = \"m.key.verification.key\";\n EventType[\"KeyVerificationAccept\"] = \"m.key.verification.accept\";\n // Not used directly - see READY_TYPE in VerificationRequest.\n EventType[\"KeyVerificationReady\"] = \"m.key.verification.ready\";\n // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n EventType[\"RoomMessageFeedback\"] = \"m.room.message.feedback\";\n EventType[\"Reaction\"] = \"m.reaction\";\n EventType[\"PollStart\"] = \"org.matrix.msc3381.poll.start\";\n // Room ephemeral events\n EventType[\"Typing\"] = \"m.typing\";\n EventType[\"Receipt\"] = \"m.receipt\";\n EventType[\"Presence\"] = \"m.presence\";\n // Room account_data events\n EventType[\"FullyRead\"] = \"m.fully_read\";\n EventType[\"Tag\"] = \"m.tag\";\n EventType[\"SpaceOrder\"] = \"org.matrix.msc3230.space_order\";\n // MSC3230\n // User account_data events\n EventType[\"PushRules\"] = \"m.push_rules\";\n EventType[\"Direct\"] = \"m.direct\";\n EventType[\"IgnoredUserList\"] = \"m.ignored_user_list\";\n // to_device events\n EventType[\"RoomKey\"] = \"m.room_key\";\n EventType[\"RoomKeyRequest\"] = \"m.room_key_request\";\n EventType[\"ForwardedRoomKey\"] = \"m.forwarded_room_key\";\n EventType[\"Dummy\"] = \"m.dummy\";\n EventType[\"SecretRequest\"] = \"m.secret.request\";\n EventType[\"SecretSend\"] = \"m.secret.send\";\n // Group call events\n EventType[\"GroupCallPrefix\"] = \"org.matrix.msc3401.call\";\n EventType[\"GroupCallMemberPrefix\"] = \"org.matrix.msc3401.call.member\";\n // MatrixRTC events\n EventType[\"CallNotify\"] = \"org.matrix.msc4075.call.notify\";\n return EventType;\n}({});\nexport var RelationType = /*#__PURE__*/function (RelationType) {\n RelationType[\"Annotation\"] = \"m.annotation\";\n RelationType[\"Replace\"] = \"m.replace\";\n RelationType[\"Reference\"] = \"m.reference\";\n // Don't use this yet: it's only the stable version. The code still assumes we support the unstable prefix and,\n // moreover, our tests currently use the unstable prefix. Use THREAD_RELATION_TYPE.name.\n // Once we support *only* the stable prefix, THREAD_RELATION_TYPE can die and we can switch to this.\n RelationType[\"Thread\"] = \"m.thread\";\n return RelationType;\n}({});\nexport var MsgType = /*#__PURE__*/function (MsgType) {\n MsgType[\"Text\"] = \"m.text\";\n MsgType[\"Emote\"] = \"m.emote\";\n MsgType[\"Notice\"] = \"m.notice\";\n MsgType[\"Image\"] = \"m.image\";\n MsgType[\"File\"] = \"m.file\";\n MsgType[\"Audio\"] = \"m.audio\";\n MsgType[\"Location\"] = \"m.location\";\n MsgType[\"Video\"] = \"m.video\";\n MsgType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n return MsgType;\n}({});\nexport var RoomCreateTypeField = \"type\";\nexport var RoomType = /*#__PURE__*/function (RoomType) {\n RoomType[\"Space\"] = \"m.space\";\n RoomType[\"UnstableCall\"] = \"org.matrix.msc3417.call\";\n RoomType[\"ElementVideo\"] = \"io.element.video\";\n return RoomType;\n}({});\nexport var ToDeviceMessageId = \"org.matrix.msgid\";\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_LEAF = new UnstableValue(\"m.leaf\", \"org.matrix.msc3089.leaf\");\n\n/**\n * Branch (Leaf Reference) type for the index approach in a\n * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is\n * UNSTABLE and subject to breaking changes, including its eventual removal.\n */\nexport var UNSTABLE_MSC3089_BRANCH = new UnstableValue(\"m.branch\", \"org.matrix.msc3089.branch\");\n\n/**\n * Marker event type to point back at imported historical content in a room. See\n * [MSC2716](https://github.com/matrix-org/matrix-spec-proposals/pull/2716).\n * Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC2716_MARKER = new UnstableValue(\"m.room.marker\", \"org.matrix.msc2716.marker\");\n\n/**\n * Name of the request property for relation based redactions.\n * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}\n */\nexport var MSC3912_RELATION_BASED_REDACTIONS_PROP = new UnstableValue(\"with_rel_types\", \"org.matrix.msc3912.with_relations\");\n\n/**\n * Functional members type for declaring a purpose of room members (e.g. helpful bots).\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n *\n * Schema (TypeScript):\n * ```\n * {\n * service_members?: string[]\n * }\n * ```\n *\n * @example\n * ```\n * {\n * \"service_members\": [\n * \"@helperbot:localhost\",\n * \"@reminderbot:alice.tdl\"\n * ]\n * }\n * ```\n */\nexport var UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new UnstableValue(\"io.element.functional_members\", \"io.element.functional_members\");\n\n/**\n * A type of message that affects visibility of a message,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * @experimental\n */\nexport var EVENT_VISIBILITY_CHANGE_TYPE = new UnstableValue(\"m.visibility\", \"org.matrix.msc3531.visibility\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_ENABLED = new UnstableValue(\"enabled\", \"org.matrix.msc3881.enabled\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_DEVICE_ID = new UnstableValue(\"device_id\", \"org.matrix.msc3881.device_id\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3890\n *\n * @experimental\n */\nexport var LOCAL_NOTIFICATION_SETTINGS_PREFIX = new UnstableValue(\"m.local_notification_settings\", \"org.matrix.msc3890.local_notification_settings\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/4023\n *\n * @experimental\n */\nexport var UNSIGNED_THREAD_ID_FIELD = new UnstableValue(\"thread_id\", \"org.matrix.msc4023.thread_id\");\n\n/**\n * https://github.com/matrix-org/matrix-spec-proposals/pull/4115\n *\n * @experimental\n */\nexport var UNSIGNED_MEMBERSHIP_FIELD = new NamespacedValue(\"membership\", \"io.element.msc4115.membership\");\n\n/**\n * Mapped type from event type to content type for all specified non-state room events.\n */\n\n/**\n * Mapped type from event type to content type for all specified room state events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global account_data events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global events encrypted by secret storage.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\n//# sourceMappingURL=event.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"./@types/event.js\";\nimport { isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils.js\";\n/**\n * Summarises the read receipts within a room. Used by the sync accumulator.\n *\n * Given receipts for users, picks the most recently-received one and provides\n * the results in a new fake receipt event returned from\n * buildAccumulatedReceiptEvent().\n *\n * Handles unthreaded receipts and receipts in each thread separately, so the\n * returned event contains the most recently received unthreaded receipt, and\n * the most recently received receipt in each thread.\n */\nexport class ReceiptAccumulator {\n constructor() {\n /** user_id -\\> most-recently-received unthreaded receipt */\n _defineProperty(this, \"unthreadedReadReceipts\", new Map());\n /** thread_id -\\> user_id -\\> most-recently-received receipt for this thread */\n _defineProperty(this, \"threadedReadReceipts\", new MapWithDefault(() => new Map()));\n }\n /**\n * Provide an unthreaded receipt for this user. Overwrites any other\n * unthreaded receipt we have for this user.\n */\n setUnthreaded(userId, receipt) {\n this.unthreadedReadReceipts.set(userId, receipt);\n }\n\n /**\n * Provide a receipt for this user in this thread. Overwrites any other\n * receipt we have for this user in this thread.\n */\n setThreaded(threadId, userId, receipt) {\n this.threadedReadReceipts.getOrCreate(threadId).set(userId, receipt);\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received unthreaded receipts for each user.\n */\n allUnthreaded() {\n return this.unthreadedReadReceipts.entries();\n }\n\n /**\n * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n * most recently-received threaded receipts for each user, in all\n * threads.\n */\n *allThreaded() {\n for (var receiptsForThread of this.threadedReadReceipts.values()) {\n for (var e of receiptsForThread.entries()) {\n yield e;\n }\n }\n }\n\n /**\n * Given a list of ephemeral events, find the receipts and store the\n * relevant ones to be returned later from buildAccumulatedReceiptEvent().\n */\n consumeEphemeralEvents(events) {\n events === null || events === void 0 || events.forEach(e => {\n if (e.type !== EventType.Receipt || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach(eventId => {\n Object.entries(e.content[eventId]).forEach(_ref => {\n var [key, value] = _ref;\n if (!isSupportedReceiptType(key)) return;\n for (var userId of Object.keys(value)) {\n var data = e.content[eventId][key][userId];\n var receipt = {\n data: e.content[eventId][key][userId],\n type: key,\n eventId\n };\n\n // In a world that supports threads, read receipts normally have\n // a `thread_id` which is either the thread they belong in or\n // `MAIN_ROOM_TIMELINE`, so we normally use `setThreaded(...)`\n // here. The `MAIN_ROOM_TIMELINE` is just treated as another\n // thread.\n //\n // We still encounter read receipts that are \"unthreaded\"\n // (missing the `thread_id` property). These come from clients\n // that don't support threads, and from threaded clients that\n // are doing a \"Mark room as read\" operation. Unthreaded\n // receipts mark everything \"before\" them as read, in all\n // threads, where \"before\" means in Sync Order i.e. the order\n // the events were received from the homeserver in a sync.\n // [Note: we have some bugs where we use timestamp order instead\n // of Sync Order, because we don't correctly remember the Sync\n // Order. See #3325.]\n //\n // Calling the wrong method will cause incorrect behavior like\n // messages re-appearing as \"new\" when you already read them\n // previously.\n if (!data.thread_id) {\n this.setUnthreaded(userId, receipt);\n } else {\n this.setThreaded(data.thread_id, userId, receipt);\n }\n }\n });\n });\n });\n }\n\n /**\n * Build a receipt event that contains all relevant information for this\n * room, taking the most recently received receipt for each user in an\n * unthreaded context, and in each thread.\n */\n buildAccumulatedReceiptEvent(roomId) {\n var receiptEvent = {\n type: EventType.Receipt,\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n }\n };\n var receiptEventContent = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n for (var [userId, receiptData] of this.allUnthreaded()) {\n receiptEventContent.getOrCreate(receiptData.eventId).getOrCreate(receiptData.type).set(userId, receiptData.data);\n }\n for (var [_userId, _receiptData] of this.allThreaded()) {\n receiptEventContent.getOrCreate(_receiptData.eventId).getOrCreate(_receiptData.type).set(_userId, _receiptData.data);\n }\n receiptEvent.content = recursiveMapToObject(receiptEventContent);\n return receiptEventContent.size > 0 ? receiptEvent : null;\n }\n}\n//# sourceMappingURL=receipt-accumulator.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n */\n\nimport { logger } from \"./logger.js\";\nimport { deepCopy } from \"./utils.js\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.js\";\nimport { ReceiptAccumulator } from \"./receipt-accumulator.js\";\n\n/* eslint-disable camelcase */\n\n/* eslint-enable camelcase */\n\nexport var Category = /*#__PURE__*/function (Category) {\n Category[\"Invite\"] = \"invite\";\n Category[\"Leave\"] = \"leave\";\n Category[\"Join\"] = \"join\";\n Category[\"Knock\"] = \"knock\";\n return Category;\n}({});\nfunction isTaggedEvent(event) {\n return \"_localTs\" in event && event[\"_localTs\"] !== undefined;\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n constructor() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.opts = opts;\n _defineProperty(this, \"accountData\", {});\n // $event_type: Object\n _defineProperty(this, \"inviteRooms\", {});\n // $roomId: { ... sync 'invite' json data ... }\n _defineProperty(this, \"knockRooms\", {});\n // $roomId: { ... sync 'knock' json data ... }\n _defineProperty(this, \"joinRooms\", {});\n // the /sync token which corresponds to the last time rooms were\n // accumulated. We remember this so that any caller can obtain a\n // coherent /sync response and know at what point they should be\n // streaming from without losing events.\n _defineProperty(this, \"nextBatch\", null);\n this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;\n }\n accumulate(syncResponse) {\n var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n this.accumulateRooms(syncResponse, fromDatabase);\n this.accumulateAccountData(syncResponse);\n this.nextBatch = syncResponse.next_batch;\n }\n accumulateAccountData(syncResponse) {\n if (!syncResponse.account_data || !syncResponse.account_data.events) {\n return;\n }\n // Clobbers based on event type.\n syncResponse.account_data.events.forEach(e => {\n this.accountData[e.type] = e;\n });\n }\n\n /**\n * Accumulate incremental /sync room data.\n * @param syncResponse - the complete /sync JSON\n * @param fromDatabase - True if the sync response is one saved to the database\n */\n accumulateRooms(syncResponse) {\n var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (!syncResponse.rooms) {\n return;\n }\n if (syncResponse.rooms.invite) {\n Object.keys(syncResponse.rooms.invite).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.join) {\n Object.keys(syncResponse.rooms.join).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.leave) {\n Object.keys(syncResponse.rooms.leave).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.knock) {\n Object.keys(syncResponse.rooms.knock).forEach(roomId => {\n this.accumulateRoom(roomId, Category.Knock, syncResponse.rooms.knock[roomId], fromDatabase);\n });\n }\n }\n accumulateRoom(roomId, category, data) {\n var fromDatabase = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n // Valid /sync state transitions\n // +--------+ <======+ 1: Accept an invite\n // +== | INVITE | | (5) 2: Leave a room\n // | +--------+ =====+ | 3: Join a public room previously\n // |(1) (4) | | left (handle as if new room)\n // V (2) V | 4: Reject an invite\n // +------+ ========> +--------+ 5: Invite to a room previously\n // | JOIN | (3) | LEAVE* | left (handle as if new room)\n // +------+ <======== +--------+\n //\n // * equivalent to \"no state\"\n switch (category) {\n case Category.Invite:\n // (5)\n if (this.knockRooms[roomId]) {\n // was previously knock, now invite, need to delete knock state\n delete this.knockRooms[roomId];\n }\n this.accumulateInviteState(roomId, data);\n break;\n case Category.Knock:\n this.accumulateKnockState(roomId, data);\n break;\n case Category.Join:\n if (this.inviteRooms[roomId]) {\n // (1)\n // was previously invite, now join. We expect /sync to give\n // the entire state and timeline on 'join', so delete previous\n // invite state\n delete this.inviteRooms[roomId];\n }\n // (3)\n this.accumulateJoinState(roomId, data, fromDatabase);\n break;\n case Category.Leave:\n if (this.knockRooms[roomId]) {\n // delete knock state on leave\n delete this.knockRooms[roomId];\n } else if (this.inviteRooms[roomId]) {\n // (4)\n delete this.inviteRooms[roomId];\n } else {\n // (2)\n delete this.joinRooms[roomId];\n }\n break;\n default:\n logger.error(\"Unknown cateogory: \", category);\n }\n }\n accumulateInviteState(roomId, data) {\n if (!data.invite_state || !data.invite_state.events) {\n // no new data\n return;\n }\n if (!this.inviteRooms[roomId]) {\n this.inviteRooms[roomId] = {\n invite_state: data.invite_state\n };\n return;\n }\n // accumulate extra keys for invite->invite transitions\n // clobber based on event type / state key\n // We expect invite_state to be small, so just loop over the events\n var currentData = this.inviteRooms[roomId];\n data.invite_state.events.forEach(e => {\n var hasAdded = false;\n for (var i = 0; i < currentData.invite_state.events.length; i++) {\n var current = currentData.invite_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.invite_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.invite_state.events.push(e);\n }\n });\n }\n accumulateKnockState(roomId, data) {\n if (!data.knock_state || !data.knock_state.events) {\n // no new data\n return;\n }\n if (!this.knockRooms[roomId]) {\n this.knockRooms[roomId] = {\n knock_state: data.knock_state\n };\n return;\n }\n // accumulate extra keys\n // clobber based on event type / state key\n // We expect knock_state to be small, so just loop over the events\n var currentData = this.knockRooms[roomId];\n data.knock_state.events.forEach(e => {\n var hasAdded = false;\n for (var i = 0; i < currentData.knock_state.events.length; i++) {\n var current = currentData.knock_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.knock_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.knock_state.events.push(e);\n }\n });\n }\n\n // Accumulate timeline and state events in a room.\n accumulateJoinState(roomId, data) {\n var _ref, _data, _data$ephemeral, _data$state, _data$orgMatrixMsc, _data$timeline;\n var fromDatabase = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n // We expect this function to be called a lot (every /sync) so we want\n // this to be fast. /sync stores events in an array but we often want\n // to clobber based on type/state_key. Rather than convert arrays to\n // maps all the time, just keep private maps which contain\n // the actual current accumulated sync state, and array-ify it when\n // getJSON() is called.\n\n // State resolution:\n // The 'state' key is the delta from the previous sync (or start of time\n // if no token was supplied), to the START of the timeline. To obtain\n // the current state, we need to \"roll forward\" state by reading the\n // timeline. We want to store the current state so we can drop events\n // out the end of the timeline based on opts.maxTimelineEntries.\n //\n // 'state' 'timeline' current state\n // |-------x<======================>x\n // T I M E\n //\n // When getJSON() is called, we 'roll back' the current state by the\n // number of entries in the timeline to work out what 'state' should be.\n\n // Back-pagination:\n // On an initial /sync, the server provides a back-pagination token for\n // the start of the timeline. When /sync deltas come down, they also\n // include back-pagination tokens for the start of the timeline. This\n // means not all events in the timeline have back-pagination tokens, as\n // it is only the ones at the START of the timeline which have them.\n // In order for us to have a valid timeline (and back-pagination token\n // to match), we need to make sure that when we remove old timeline\n // events, that we roll forward to an event which has a back-pagination\n // token. This means we can't keep a strict sliding-window based on\n // opts.maxTimelineEntries, and we may have a few less. We should never\n // have more though, provided that the /sync limit is less than or equal\n // to opts.maxTimelineEntries.\n\n if (!this.joinRooms[roomId]) {\n // Create truly empty objects so event types of 'hasOwnProperty' and co\n // don't cause this code to break.\n this.joinRooms[roomId] = {\n _currentState: Object.create(null),\n _timeline: [],\n _accountData: Object.create(null),\n _unreadNotifications: {},\n _unreadThreadNotifications: {},\n _summary: {},\n _receipts: new ReceiptAccumulator()\n };\n }\n var currentData = this.joinRooms[roomId];\n if (data.account_data && data.account_data.events) {\n // clobber based on type\n data.account_data.events.forEach(e => {\n currentData._accountData[e.type] = e;\n });\n }\n\n // these probably clobber, spec is unclear.\n if (data.unread_notifications) {\n currentData._unreadNotifications = data.unread_notifications;\n }\n currentData._unreadThreadNotifications = (_ref = (_data = data[UNREAD_THREAD_NOTIFICATIONS.stable]) !== null && _data !== void 0 ? _data : data[UNREAD_THREAD_NOTIFICATIONS.unstable]) !== null && _ref !== void 0 ? _ref : undefined;\n if (data.summary) {\n var _sum$HEROES_KEY, _sum$JOINED_COUNT_KEY, _sum$INVITED_COUNT_KE;\n var HEROES_KEY = \"m.heroes\";\n var INVITED_COUNT_KEY = \"m.invited_member_count\";\n var JOINED_COUNT_KEY = \"m.joined_member_count\";\n var acc = currentData._summary;\n var sum = data.summary;\n acc[HEROES_KEY] = (_sum$HEROES_KEY = sum[HEROES_KEY]) !== null && _sum$HEROES_KEY !== void 0 ? _sum$HEROES_KEY : acc[HEROES_KEY];\n acc[JOINED_COUNT_KEY] = (_sum$JOINED_COUNT_KEY = sum[JOINED_COUNT_KEY]) !== null && _sum$JOINED_COUNT_KEY !== void 0 ? _sum$JOINED_COUNT_KEY : acc[JOINED_COUNT_KEY];\n acc[INVITED_COUNT_KEY] = (_sum$INVITED_COUNT_KE = sum[INVITED_COUNT_KEY]) !== null && _sum$INVITED_COUNT_KE !== void 0 ? _sum$INVITED_COUNT_KE : acc[INVITED_COUNT_KEY];\n }\n\n // We purposefully do not persist m.typing events.\n // Technically you could refresh a browser before the timer on a\n // typing event is up, so it'll look like you aren't typing when\n // you really still are. However, the alternative is worse. If\n // we do persist typing events, it will look like people are\n // typing forever until someone really does start typing (which\n // will prompt Synapse to send down an actual m.typing event to\n // clobber the one we persisted).\n\n // Persist the receipts\n currentData._receipts.consumeEphemeralEvents((_data$ephemeral = data.ephemeral) === null || _data$ephemeral === void 0 ? void 0 : _data$ephemeral.events);\n\n // if we got a limited sync, we need to remove all timeline entries or else\n // we will have gaps in the timeline.\n if (data.timeline && data.timeline.limited) {\n currentData._timeline = [];\n }\n\n // Work out the current state. The deltas need to be applied in the order:\n // - existing state which didn't come down /sync.\n // - State events under the 'state' key.\n // - State events under the 'state_after' key OR state events in the 'timeline' if 'state_after' is not present.\n (_data$state = data.state) === null || _data$state === void 0 || (_data$state = _data$state.events) === null || _data$state === void 0 || _data$state.forEach(e => {\n setState(currentData._currentState, e);\n });\n (_data$orgMatrixMsc = data[\"org.matrix.msc4222.state_after\"]) === null || _data$orgMatrixMsc === void 0 || (_data$orgMatrixMsc = _data$orgMatrixMsc.events) === null || _data$orgMatrixMsc === void 0 || _data$orgMatrixMsc.forEach(e => {\n setState(currentData._currentState, e);\n });\n (_data$timeline = data.timeline) === null || _data$timeline === void 0 || (_data$timeline = _data$timeline.events) === null || _data$timeline === void 0 || _data$timeline.forEach((e, index) => {\n var _data$timeline$prev_b;\n if (!data[\"org.matrix.msc4222.state_after\"]) {\n // this nops if 'e' isn't a state event\n setState(currentData._currentState, e);\n }\n // append the event to the timeline. The back-pagination token\n // corresponds to the first event in the timeline\n var transformedEvent;\n if (!fromDatabase) {\n var _e$unsigned;\n transformedEvent = Object.assign({}, e);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n var age = (_e$unsigned = e.unsigned) === null || _e$unsigned === void 0 ? void 0 : _e$unsigned.age;\n if (age !== undefined) transformedEvent._localTs = Date.now() - age;\n } else {\n transformedEvent = e;\n }\n currentData._timeline.push({\n event: transformedEvent,\n token: index === 0 ? (_data$timeline$prev_b = data.timeline.prev_batch) !== null && _data$timeline$prev_b !== void 0 ? _data$timeline$prev_b : null : null\n });\n });\n\n // attempt to prune the timeline by jumping between events which have\n // pagination tokens.\n if (currentData._timeline.length > this.opts.maxTimelineEntries) {\n var startIndex = currentData._timeline.length - this.opts.maxTimelineEntries;\n for (var i = startIndex; i < currentData._timeline.length; i++) {\n if (currentData._timeline[i].token) {\n // keep all events after this, including this one\n currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);\n break;\n }\n }\n }\n }\n\n /**\n * Return everything under the 'rooms' key from a /sync response which\n * represents all room data that should be stored. This should be paired\n * with the sync token which represents the most recent /sync response\n * provided to accumulate().\n * @param forDatabase - True to generate a sync to be saved to storage\n * @returns An object with a \"nextBatch\", \"roomsData\" and \"accountData\"\n * keys.\n * The \"nextBatch\" key is a string which represents at what point in the\n * /sync stream the accumulator reached. This token should be used when\n * restarting a /sync stream at startup. Failure to do so can lead to missing\n * events. The \"roomsData\" key is an Object which represents the entire\n * /sync response from the 'rooms' key onwards. The \"accountData\" key is\n * a list of raw events which represent global account data.\n */\n getJSON() {\n var forDatabase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var data = {\n join: {},\n invite: {},\n knock: {},\n // always empty. This is set by /sync when a room was previously\n // in 'invite' or 'join'. On fresh startup, the client won't know\n // about any previous room being in 'invite' or 'join' so we can\n // just omit mentioning it at all, even if it has previously come\n // down /sync.\n // The notable exception is when a client is kicked or banned:\n // we may want to hold onto that room so the client can clearly see\n // why their room has disappeared. We don't persist it though because\n // it is unclear *when* we can safely remove the room from the DB.\n // Instead, we assume that if you're loading from the DB, you've\n // refreshed the page, which means you've seen the kick/ban already.\n leave: {}\n };\n Object.keys(this.inviteRooms).forEach(roomId => {\n data.invite[roomId] = this.inviteRooms[roomId];\n });\n Object.keys(this.knockRooms).forEach(roomId => {\n data.knock[roomId] = this.knockRooms[roomId];\n });\n Object.keys(this.joinRooms).forEach(roomId => {\n var roomData = this.joinRooms[roomId];\n var roomJson = {\n \"ephemeral\": {\n events: []\n },\n \"account_data\": {\n events: []\n },\n \"state\": {\n events: []\n },\n \"org.matrix.msc4222.state_after\": {\n events: []\n },\n \"timeline\": {\n events: [],\n prev_batch: null\n },\n \"unread_notifications\": roomData._unreadNotifications,\n \"unread_thread_notifications\": roomData._unreadThreadNotifications,\n \"summary\": roomData._summary\n };\n // Add account data\n Object.keys(roomData._accountData).forEach(evType => {\n roomJson.account_data.events.push(roomData._accountData[evType]);\n });\n var receiptEvent = roomData._receipts.buildAccumulatedReceiptEvent(roomId);\n\n // add only if we have some receipt data\n if (receiptEvent) {\n roomJson.ephemeral.events.push(receiptEvent);\n }\n\n // Add timeline data\n roomData._timeline.forEach(msgData => {\n if (!roomJson.timeline.prev_batch) {\n // the first event we add to the timeline MUST match up to\n // the prev_batch token.\n if (!msgData.token) {\n return; // this shouldn't happen as we prune constantly.\n }\n roomJson.timeline.prev_batch = msgData.token;\n }\n var transformedEvent;\n if (!forDatabase && isTaggedEvent(msgData.event)) {\n // This means we have to copy each event, so we can fix it up to\n // set a correct 'age' parameter whilst keeping the local timestamp\n // on our stored event. If this turns out to be a bottleneck, it could\n // be optimised either by doing this in the main process after the data\n // has been structured-cloned to go between the worker & main process,\n // or special-casing data from saved syncs to read the local timestamp\n // directly rather than turning it into age to then immediately be\n // transformed back again into a local timestamp.\n transformedEvent = Object.assign({}, msgData.event);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n delete transformedEvent._localTs;\n transformedEvent.unsigned = transformedEvent.unsigned || {};\n transformedEvent.unsigned.age = Date.now() - msgData.event._localTs;\n } else {\n transformedEvent = msgData.event;\n }\n roomJson.timeline.events.push(transformedEvent);\n });\n\n // Add state data: roll back current state to the start of timeline,\n // by \"reverse clobbering\" from the end of the timeline to the start.\n // Convert maps back into arrays.\n var rollBackState = Object.create(null);\n for (var i = roomJson.timeline.events.length - 1; i >= 0; i--) {\n var timelineEvent = roomJson.timeline.events[i];\n if (timelineEvent.state_key === null || timelineEvent.state_key === undefined) {\n continue; // not a state event\n }\n // since we're going back in time, we need to use the previous\n // state value else we'll break causality. We don't have the\n // complete previous state event, so we need to create one.\n var prevStateEvent = deepCopy(timelineEvent);\n if (prevStateEvent.unsigned) {\n if (prevStateEvent.unsigned.prev_content) {\n prevStateEvent.content = prevStateEvent.unsigned.prev_content;\n }\n if (prevStateEvent.unsigned.prev_sender) {\n prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;\n }\n }\n setState(rollBackState, prevStateEvent);\n }\n Object.keys(roomData._currentState).forEach(evType => {\n Object.keys(roomData._currentState[evType]).forEach(stateKey => {\n var ev = roomData._currentState[evType][stateKey];\n // Push to both fields to provide downgrade compatibility in the sync accumulator db\n // the code will prefer `state_after` if it is present\n roomJson[\"org.matrix.msc4222.state_after\"].events.push(ev);\n // Roll the state back to the value at the start of the timeline if it was changed\n if (rollBackState[evType] && rollBackState[evType][stateKey]) {\n ev = rollBackState[evType][stateKey];\n }\n roomJson.state.events.push(ev);\n });\n });\n data.join[roomId] = roomJson;\n });\n\n // Add account data\n var accData = [];\n Object.keys(this.accountData).forEach(evType => {\n accData.push(this.accountData[evType]);\n });\n return {\n nextBatch: this.nextBatch,\n roomsData: data,\n accountData: accData\n };\n }\n getNextBatchToken() {\n return this.nextBatch;\n }\n}\nfunction setState(eventMap, event) {\n if (event.state_key === null || event.state_key === undefined || !event.type) {\n return;\n }\n if (!eventMap[event.type]) {\n eventMap[event.type] = Object.create(null);\n }\n eventMap[event.type][event.state_key] = event;\n}\n//# sourceMappingURL=sync-accumulator.js.map","/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param indexedDB - The `indexedDB` interface\n * @param dbName - The database name to test for\n * @returns Whether the database exists\n */\nexport function exists(indexedDB, dbName) {\n return new Promise((resolve, reject) => {\n var exists = true;\n var req = indexedDB.open(dbName);\n req.onupgradeneeded = () => {\n // Since we did not provide an explicit version when opening, this event\n // should only fire if the DB did not exist before at any version.\n exists = false;\n };\n req.onblocked = () => reject(req.error);\n req.onsuccess = () => {\n var db = req.result;\n db.close();\n if (!exists) {\n // The DB did not exist before, but has been created as part of this\n // existence check. Delete it now to restore previous state. Delete can\n // actually take a while to complete in some browsers, so don't wait for\n // it. This won't block future open calls that a store might issue next to\n // properly set up the DB.\n indexedDB.deleteDatabase(dbName);\n }\n resolve(exists);\n };\n req.onerror = () => reject(req.error);\n });\n}\n//# sourceMappingURL=indexeddb-helpers.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SyncAccumulator } from \"../sync-accumulator.js\";\nimport { deepCopy, promiseTry } from \"../utils.js\";\nimport { exists as idbExists } from \"../indexeddb-helpers.js\";\nimport { logger } from \"../logger.js\";\nvar DB_MIGRATIONS = [db => {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", {\n keyPath: [\"userId\"]\n });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", {\n keyPath: [\"type\"]\n });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", {\n keyPath: [\"clobber\"]\n });\n}, db => {\n var oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"]\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n}, db => {\n db.createObjectStore(\"client_options\", {\n keyPath: [\"clobber\"]\n });\n}, db => {\n db.createObjectStore(\"to_device_queue\", {\n autoIncrement: true\n });\n}\n// Expand as needed.\n];\nvar VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery(store, keyRange, resultMapper) {\n var query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n var results = [];\n query.onerror = () => {\n var _query$error;\n reject(new Error(\"Query failed: \" + ((_query$error = query.error) === null || _query$error === void 0 ? void 0 : _query$error.name)));\n };\n // collect results\n query.onsuccess = () => {\n var cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\nfunction txnAsPromise(txn) {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function (event) {\n resolve(event);\n };\n txn.onerror = function () {\n reject(txn.error);\n };\n });\n}\nfunction reqAsEventPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = function (event) {\n resolve(event);\n };\n req.onerror = function () {\n reject(req.error);\n };\n });\n}\nfunction reqAsPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req);\n req.onerror = err => reject(err);\n });\n}\nfunction reqAsCursorPromise(req) {\n return reqAsEventPromise(req).then(event => req.result);\n}\nexport class LocalIndexedDBStoreBackend {\n static exists(indexedDB, dbName) {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return idbExists(indexedDB, dbName);\n }\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param indexedDB - The Indexed DB interface e.g\n * `window.indexedDB`\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n constructor(indexedDB) {\n var dbName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"default\";\n this.indexedDB = indexedDB;\n _defineProperty(this, \"dbName\", void 0);\n _defineProperty(this, \"syncAccumulator\", void 0);\n _defineProperty(this, \"db\", void 0);\n _defineProperty(this, \"disconnected\", true);\n _defineProperty(this, \"_isNewlyCreated\", false);\n _defineProperty(this, \"syncToDatabasePromise\", void 0);\n _defineProperty(this, \"pendingUserPresenceData\", []);\n this.dbName = \"matrix-js-sdk:\" + dbName;\n this.syncAccumulator = new SyncAccumulator();\n }\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n connect(onClose) {\n var _this = this;\n if (!this.disconnected) {\n logger.log(\"LocalIndexedDBStoreBackend.connect: already connected or connecting\");\n return Promise.resolve();\n }\n this.disconnected = false;\n logger.log(\"LocalIndexedDBStoreBackend.connect: connecting...\");\n var req = this.indexedDB.open(this.dbName, VERSION);\n req.onupgradeneeded = ev => {\n var db = req.result;\n var oldVersion = ev.oldVersion;\n logger.log(\"LocalIndexedDBStoreBackend.connect: upgrading from \".concat(oldVersion));\n if (oldVersion < 1) {\n // The database did not previously exist\n this._isNewlyCreated = true;\n }\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n };\n req.onblocked = () => {\n logger.log(\"can't yet open LocalIndexedDBStoreBackend because it is open elsewhere\");\n };\n logger.log(\"LocalIndexedDBStoreBackend.connect: awaiting connection...\");\n return reqAsEventPromise(req).then(/*#__PURE__*/_asyncToGenerator(function* () {\n logger.log(\"LocalIndexedDBStoreBackend.connect: connected\");\n _this.db = req.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n _this.db.onversionchange = () => {\n var _this$db;\n (_this$db = _this.db) === null || _this$db === void 0 || _this$db.close(); // this does not call onclose\n _this.disconnected = true;\n _this.db = undefined;\n };\n _this.db.onclose = () => {\n _this.disconnected = true;\n _this.db = undefined;\n onClose === null || onClose === void 0 || onClose();\n };\n yield _this.init();\n }));\n }\n\n /** @returns whether or not the database was newly created in this session. */\n isNewlyCreated() {\n return Promise.resolve(this._isNewlyCreated);\n }\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @returns Promise which resolves on success\n */\n init() {\n return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(_ref2 => {\n var [accountData, syncData] = _ref2;\n logger.log(\"LocalIndexedDBStoreBackend: loaded initial data\");\n this.syncAccumulator.accumulate({\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n account_data: {\n events: accountData\n }\n }, true);\n });\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n getOutOfBandMembers(roomId) {\n return new Promise((resolve, reject) => {\n var tx = this.db.transaction([\"oob_membership_events\"], \"readonly\");\n var store = tx.objectStore(\"oob_membership_events\");\n var roomIndex = store.index(\"room\");\n var range = IDBKeyRange.only(roomId);\n var request = roomIndex.openCursor(range);\n var membershipEvents = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n var oobWritten = false;\n request.onsuccess = () => {\n var cursor = request.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n var record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = err => {\n reject(err);\n };\n }).then(events => {\n logger.log(\"LL: got \".concat(events === null || events === void 0 ? void 0 : events.length, \" membershipEvents from storage for room \").concat(roomId, \" ...\"));\n return events;\n });\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n */\n setOutOfBandMembers(roomId, membershipEvents) {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n logger.log(\"LL: backend about to store \".concat(membershipEvents.length) + \" members for \".concat(roomId));\n var tx = _this2.db.transaction([\"oob_membership_events\"], \"readwrite\");\n var store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach(e => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n var markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0\n };\n store.put(markerObject);\n yield txnAsPromise(tx);\n logger.log(\"LL: backend done storing for \".concat(roomId, \"!\"));\n })();\n }\n clearOutOfBandMembers(roomId) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n var readTx = _this3.db.transaction([\"oob_membership_events\"], \"readonly\");\n var store = readTx.objectStore(\"oob_membership_events\");\n var roomIndex = store.index(\"room\");\n var roomRange = IDBKeyRange.only(roomId);\n var minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n var maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n var [minStateKey, maxStateKey] = yield Promise.all([minStateKeyProm, maxStateKeyProm]);\n var writeTx = _this3.db.transaction([\"oob_membership_events\"], \"readwrite\");\n var writeStore = writeTx.objectStore(\"oob_membership_events\");\n var membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n logger.log(\"LL: Deleting all users + marker in storage for room \".concat(roomId, \", with key range:\"), [roomId, minStateKey], [roomId, maxStateKey]);\n yield reqAsPromise(writeStore.delete(membersKeyRange));\n })();\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts. Closes the database.\n * @returns Resolved when the database is cleared.\n */\n clearDatabase() {\n return new Promise(resolve => {\n var _this$db2;\n logger.log(\"Removing indexeddb instance: \".concat(this.dbName));\n\n // Close the database first to avoid firing unexpected close events\n (_this$db2 = this.db) === null || _this$db2 === void 0 || _this$db2.close();\n var req = this.indexedDB.deleteDatabase(this.dbName);\n req.onblocked = () => {\n logger.log(\"can't yet delete indexeddb \".concat(this.dbName, \" because it is open elsewhere\"));\n };\n req.onerror = () => {\n var _req$error;\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(\"unable to delete js-sdk store indexeddb: \".concat((_req$error = req.error) === null || _req$error === void 0 ? void 0 : _req$error.name));\n resolve();\n };\n req.onsuccess = () => {\n logger.log(\"Removed indexeddb instance: \".concat(this.dbName));\n resolve();\n };\n });\n }\n\n /**\n * @param copy - If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n getSavedSync() {\n var copy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n var data = this.syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n }\n getNextBatchToken() {\n return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n }\n setSyncData(syncData) {\n return Promise.resolve().then(() => {\n this.syncAccumulator.accumulate(syncData);\n });\n }\n\n /**\n * Sync users and all accumulated sync data to the database.\n * If a previous sync is in flight, the new data will be added to the\n * next sync and the current sync's promise will be returned.\n * @param userTuples - The user tuples\n * @returns Promise which resolves if the data was persisted.\n */\n syncToDatabase(userTuples) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n if (_this4.syncToDatabasePromise) {\n logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n _this4.pendingUserPresenceData.push(...userTuples);\n return _this4.syncToDatabasePromise;\n }\n userTuples.unshift(..._this4.pendingUserPresenceData);\n _this4.syncToDatabasePromise = _this4.doSyncToDatabase(userTuples);\n return _this4.syncToDatabasePromise;\n })();\n }\n doSyncToDatabase(userTuples) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n try {\n var syncData = _this5.syncAccumulator.getJSON(true);\n yield Promise.all([_this5.persistUserPresenceEvents(userTuples), _this5.persistAccountData(syncData.accountData), _this5.persistSyncData(syncData.nextBatch, syncData.roomsData)]);\n } finally {\n _this5.syncToDatabasePromise = undefined;\n }\n })();\n }\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param nextBatch - The next_batch /sync value.\n * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n * @returns Promise which resolves if the data was persisted.\n */\n persistSyncData(nextBatch, roomsData) {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return promiseTry(() => {\n var txn = this.db.transaction([\"sync\"], \"readwrite\");\n var store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\",\n // constant key so will always clobber\n nextBatch,\n roomsData\n }); // put == UPSERT\n return txnAsPromise(txn).then(() => {\n logger.log(\"Persisted sync data up to\", nextBatch);\n });\n });\n }\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param accountData - An array of raw user-scoped account data events\n * @returns Promise which resolves if the events were persisted.\n */\n persistAccountData(accountData) {\n return promiseTry(() => {\n var txn = this.db.transaction([\"accountData\"], \"readwrite\");\n var store = txn.objectStore(\"accountData\");\n for (var event of accountData) {\n store.put(event); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param tuples - An array of [userid, event] tuples\n * @returns Promise which resolves if the users were persisted.\n */\n persistUserPresenceEvents(tuples) {\n return promiseTry(() => {\n var txn = this.db.transaction([\"users\"], \"readwrite\");\n var store = txn.objectStore(\"users\");\n for (var tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1]\n }); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @returns A list of presence events in their raw form.\n */\n getUserPresenceEvents() {\n return promiseTry(() => {\n var txn = this.db.transaction([\"users\"], \"readonly\");\n var store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, cursor => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n }\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @returns A list of raw global account events.\n */\n loadAccountData() {\n logger.log(\"LocalIndexedDBStoreBackend: loading account data...\");\n return promiseTry(() => {\n var txn = this.db.transaction([\"accountData\"], \"readonly\");\n var store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, cursor => {\n return cursor.value;\n }).then(result => {\n logger.log(\"LocalIndexedDBStoreBackend: loaded account data\");\n return result;\n });\n });\n }\n\n /**\n * Load the sync data from the database.\n * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n */\n loadSyncData() {\n logger.log(\"LocalIndexedDBStoreBackend: loading sync data...\");\n return promiseTry(() => {\n var txn = this.db.transaction([\"sync\"], \"readonly\");\n var store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, cursor => {\n return cursor.value;\n }).then(results => {\n logger.log(\"LocalIndexedDBStoreBackend: loaded sync data\");\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return results.length > 0 ? results[0] : {};\n });\n });\n }\n getClientOptions() {\n return Promise.resolve().then(() => {\n var txn = this.db.transaction([\"client_options\"], \"readonly\");\n var store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, cursor => {\n var _cursor$value;\n return (_cursor$value = cursor.value) === null || _cursor$value === void 0 ? void 0 : _cursor$value.options;\n }).then(results => results[0]);\n });\n }\n storeClientOptions(options) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n var txn = _this6.db.transaction([\"client_options\"], \"readwrite\");\n var store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\",\n // constant key so will always clobber\n options: options\n }); // put == UPSERT\n yield txnAsPromise(txn);\n })();\n }\n saveToDeviceBatches(batches) {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n var txn = _this7.db.transaction([\"to_device_queue\"], \"readwrite\");\n var store = txn.objectStore(\"to_device_queue\");\n for (var batch of batches) {\n store.add(batch);\n }\n yield txnAsPromise(txn);\n })();\n }\n getOldestToDeviceBatch() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var txn = _this8.db.transaction([\"to_device_queue\"], \"readonly\");\n var store = txn.objectStore(\"to_device_queue\");\n var cursor = yield reqAsCursorPromise(store.openCursor());\n if (!cursor) return null;\n var resultBatch = cursor.value;\n return {\n id: cursor.key,\n txnId: resultBatch.txnId,\n eventType: resultBatch.eventType,\n batch: resultBatch.batch\n };\n })();\n }\n removeToDeviceBatch(id) {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n var txn = _this9.db.transaction([\"to_device_queue\"], \"readwrite\");\n var store = txn.objectStore(\"to_device_queue\");\n store.delete(id);\n yield txnAsPromise(txn);\n })();\n }\n\n /*\n * Close the database\n */\n destroy() {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n var _this0$db;\n (_this0$db = _this0.db) === null || _this0$db === void 0 || _this0$db.close();\n })();\n }\n}\n//# sourceMappingURL=indexeddb-local-backend.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.js\";\nimport { logger } from \"../logger.js\";\n/**\n * This class lives in the webworker and drives a LocalIndexedDBStoreBackend\n * controlled by messages from the main process.\n *\n * @example\n * It should be instantiated by a web worker script provided by the application\n * in a script, for example:\n * ```\n * import {IndexedDBStoreWorker} from 'matrix-js-sdk/lib/indexeddb-worker.js';\n * const remoteWorker = new IndexedDBStoreWorker(postMessage);\n * onmessage = remoteWorker.onMessage;\n * ```\n *\n * Note that it is advisable to import this class by referencing the file directly to\n * avoid a dependency on the whole js-sdk.\n *\n */\nexport class IndexedDBStoreWorker {\n /**\n * @param postMessage - The web worker postMessage function that\n * should be used to communicate back to the main script.\n */\n constructor(postMessage) {\n this.postMessage = postMessage;\n _defineProperty(this, \"backend\", void 0);\n _defineProperty(this, \"onClose\", () => {\n this.postMessage.call(null, {\n command: \"closed\"\n });\n });\n /**\n * Passes a message event from the main script into the class. This method\n * can be directly assigned to the web worker `onmessage` variable.\n *\n * @param ev - The message event\n */\n _defineProperty(this, \"onMessage\", ev => {\n var _this$backend, _this$backend2, _this$backend3, _this$backend4, _this$backend5, _this$backend6, _this$backend7, _this$backend8, _this$backend9, _this$backend0, _this$backend1, _this$backend10, _this$backend11, _this$backend12, _this$backend13, _this$backend14;\n var msg = ev.data;\n var prom;\n switch (msg.command) {\n case \"setupWorker\":\n // this is the 'indexedDB' global (where global != window\n // because it's a web worker and there is no window).\n this.backend = new LocalIndexedDBStoreBackend(indexedDB, msg.args[0]);\n prom = Promise.resolve();\n break;\n case \"connect\":\n prom = (_this$backend = this.backend) === null || _this$backend === void 0 ? void 0 : _this$backend.connect(this.onClose);\n break;\n case \"isNewlyCreated\":\n prom = (_this$backend2 = this.backend) === null || _this$backend2 === void 0 ? void 0 : _this$backend2.isNewlyCreated();\n break;\n case \"clearDatabase\":\n prom = (_this$backend3 = this.backend) === null || _this$backend3 === void 0 ? void 0 : _this$backend3.clearDatabase();\n break;\n case \"getSavedSync\":\n prom = (_this$backend4 = this.backend) === null || _this$backend4 === void 0 ? void 0 : _this$backend4.getSavedSync(false);\n break;\n case \"setSyncData\":\n prom = (_this$backend5 = this.backend) === null || _this$backend5 === void 0 ? void 0 : _this$backend5.setSyncData(msg.args[0]);\n break;\n case \"syncToDatabase\":\n prom = (_this$backend6 = this.backend) === null || _this$backend6 === void 0 ? void 0 : _this$backend6.syncToDatabase(msg.args[0]);\n break;\n case \"getUserPresenceEvents\":\n prom = (_this$backend7 = this.backend) === null || _this$backend7 === void 0 ? void 0 : _this$backend7.getUserPresenceEvents();\n break;\n case \"getNextBatchToken\":\n prom = (_this$backend8 = this.backend) === null || _this$backend8 === void 0 ? void 0 : _this$backend8.getNextBatchToken();\n break;\n case \"getOutOfBandMembers\":\n prom = (_this$backend9 = this.backend) === null || _this$backend9 === void 0 ? void 0 : _this$backend9.getOutOfBandMembers(msg.args[0]);\n break;\n case \"clearOutOfBandMembers\":\n prom = (_this$backend0 = this.backend) === null || _this$backend0 === void 0 ? void 0 : _this$backend0.clearOutOfBandMembers(msg.args[0]);\n break;\n case \"setOutOfBandMembers\":\n prom = (_this$backend1 = this.backend) === null || _this$backend1 === void 0 ? void 0 : _this$backend1.setOutOfBandMembers(msg.args[0], msg.args[1]);\n break;\n case \"getClientOptions\":\n prom = (_this$backend10 = this.backend) === null || _this$backend10 === void 0 ? void 0 : _this$backend10.getClientOptions();\n break;\n case \"storeClientOptions\":\n prom = (_this$backend11 = this.backend) === null || _this$backend11 === void 0 ? void 0 : _this$backend11.storeClientOptions(msg.args[0]);\n break;\n case \"saveToDeviceBatches\":\n prom = (_this$backend12 = this.backend) === null || _this$backend12 === void 0 ? void 0 : _this$backend12.saveToDeviceBatches(msg.args[0]);\n break;\n case \"getOldestToDeviceBatch\":\n prom = (_this$backend13 = this.backend) === null || _this$backend13 === void 0 ? void 0 : _this$backend13.getOldestToDeviceBatch();\n break;\n case \"removeToDeviceBatch\":\n prom = (_this$backend14 = this.backend) === null || _this$backend14 === void 0 ? void 0 : _this$backend14.removeToDeviceBatch(msg.args[0]);\n break;\n }\n if (prom === undefined) {\n this.postMessage({\n command: \"cmd_fail\",\n seq: msg.seq,\n // Can't be an Error because they're not structured cloneable\n error: \"Unrecognised command\"\n });\n return;\n }\n prom.then(ret => {\n this.postMessage.call(null, {\n command: \"cmd_success\",\n seq: msg.seq,\n result: ret\n });\n }, err => {\n logger.error(\"Error running command: \" + msg.command, err);\n this.postMessage.call(null, {\n command: \"cmd_fail\",\n seq: msg.seq,\n // Just send a string because Error objects aren't cloneable\n error: {\n message: err.message,\n name: err.name\n }\n });\n });\n });\n }\n}\n//# sourceMappingURL=indexeddb-store-worker.js.map","/*\nCopyright 2022-2024 New Vector Ltd.\n\nSPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE in the repository root for full details.\n*/\n\nimport { IndexedDBStoreWorker } from \"matrix-js-sdk/lib/indexeddb-worker\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst remoteWorker = new IndexedDBStoreWorker((self as any).postMessage);\n\nself.onmessage = remoteWorker.onMessage;\n"],"names":["_typeof","o","toPrimitive","t","r","i","toPropertyKey","_defineProperty","e","asyncGeneratorStep","n","c","u","_asyncToGenerator","_next","_throw","root","definition","module","this","noop","undefinedType","isIE","logMethods","_loggersByName","defaultLogger","bindMethod","obj","methodName","method","traceForIE","realMethod","replaceLoggingMethods","level","enableLoggingWhenConsoleArrives","defaultMethodFactory","_level","_loggerName","Logger","name","factory","self","inheritedLevel","defaultLevel","userLevel","storageKey","persistLevelIfPossible","levelNum","levelName","getPersistedLevel","storedLevel","cookie","cookieName","location","clearPersistedLevel","normalizeLevel","input","persist","childName","initialLevel","logger","_log","DEFAULT_NAMESPACE","loglevel","logLevel","loggerName","_len","args","_key","supportedByConsole","getPrefixedLogger","prefix","prefixLogger","childPrefix","childLogger","data","require$$0","escapeRegexp","str","REPLACE_RE","replace_fn","match","unhomoglyph","hasRequiredRetry_operation","RetryOperation","timeouts","options","retry_operation","err","currentTime","timeout","timeoutOps","fn","counts","error","count","message","mainErrorCount","mainError","requireRetry_operation","exports","opts","key","a","b","attempt","random","methods","original","op","callback","hasRequiredRetry","hasRequiredPRetry","pRetry","retry","networkErrorMsgs","decorateErrorWithCounts","attemptNumber","retriesLeft","errorMessage","pRetry$1","resolve","reject","operation","isNetworkError","pRetryModule","requirePRetry","NamespacedValue","stable","unstable","names","altName","val","arr","included","ServerControlledNamespacedValue","preferUnstable","UnstableValue","ReceiptType","deepCopy","promiseTry","isSupportedReceiptType","receiptType","processMapToObjectValue","value","recursiveMapToObject","v","map","targetMap","createDefault","UNREAD_THREAD_NOTIFICATIONS","EventType","ReceiptAccumulator","MapWithDefault","userId","receipt","threadId","receiptsForThread","events","eventId","_ref","roomId","receiptEvent","receiptEventContent","receiptData","_userId","_receiptData","Category","isTaggedEvent","event","SyncAccumulator","syncResponse","fromDatabase","category","currentData","hasAdded","current","_data","_data$ephemeral","_data$state","_data$orgMatrixMsc","_data$timeline","_sum$HEROES_KEY","_sum$JOINED_COUNT_KEY","_sum$INVITED_COUNT_KE","HEROES_KEY","INVITED_COUNT_KEY","JOINED_COUNT_KEY","acc","sum","setState","index","_data$timeline$prev_b","transformedEvent","_e$unsigned","age","startIndex","forDatabase","roomJson","roomData","evType","msgData","rollBackState","timelineEvent","prevStateEvent","stateKey","ev","accData","eventMap","exists","indexedDB","dbName","req","db","DB_MIGRATIONS","oobMembersStore","VERSION","selectQuery","store","keyRange","resultMapper","query","_query$error","cursor","results","txnAsPromise","txn","reqAsEventPromise","reqAsPromise","reqAsCursorPromise","onClose","_this","oldVersion","migration","_this$db","_ref2","accountData","syncData","tx","roomIndex","range","request","membershipEvents","oobWritten","record","_this2","markerObject","_this3","readTx","roomRange","minStateKeyProm","maxStateKeyProm","maxStateKey","writeTx","writeStore","membersKeyRange","minStateKey","_this$db2","_req$error","copy","userTuples","_this4","_this5","nextBatch","roomsData","tuples","tuple","result","_cursor$value","_this6","batches","_this7","batch","_this8","resultBatch","id","_this9","_this0$db","_this0","IndexedDBStoreWorker","postMessage","_this$backend","_this$backend2","_this$backend3","_this$backend4","_this$backend5","_this$backend6","_this$backend7","_this$backend8","_this$backend9","_this$backend0","_this$backend1","_this$backend10","_this$backend11","_this$backend12","_this$backend13","_this$backend14","msg","LocalIndexedDBStoreBackend","prom","ret"],"mappings":"yBAAA,SAASA,EAAQC,EAAG,CAClB,0BAEA,OAAOD,EAAwB,OAAO,QAArB,YAA2C,OAAO,OAAO,UAA1B,SAAqC,SAAUC,EAAG,CAChG,OAAO,OAAOA,CACf,EAAG,SAAUA,EAAG,CACf,OAAOA,GAAmB,OAAO,QAArB,YAA+BA,EAAE,cAAgB,QAAUA,IAAM,OAAO,UAAY,SAAW,OAAOA,CACtH,EAAKD,EAAQC,CAAC,CACd,CCPA,SAASC,GAAYC,EAAGC,EAAG,CACzB,GAAgBJ,EAAQG,CAAC,GAArB,UAA0B,CAACA,EAAG,OAAOA,EACzC,IAAI,EAAIA,EAAE,OAAO,WAAW,EAC5B,GAAe,IAAX,OAAc,CAChB,IAAIE,EAAI,EAAE,KAAKF,EAAGC,CAAc,EAChC,GAAgBJ,EAAQK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