openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
42,170 lines • 1.58 MB
JavaScript
import { o as __toESM, t as __commonJSMin } from "./chunk-DORXReHP.js";
import { t as require_content_type } from "./content-type-DRlQpE2g.js";
import { EventEmitter as EventEmitter$1 } from "events";
import { v4 } from "uuid";
//#region node_modules/@babel/runtime/helpers/asyncToGenerator.js
var require_asyncToGenerator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c), u = i.value;
} catch (n) {
e(n);
return;
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function() {
var t = this, e = arguments;
return new Promise(function(r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/typeof.js
var require_typeof = /* @__PURE__ */ __commonJSMin(((exports, module) => {
function _typeof(o) {
"@babel/helpers - typeof";
return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
return typeof o;
} : function(o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/toPrimitive.js
var require_toPrimitive = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var _typeof = require_typeof()["default"];
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/toPropertyKey.js
var require_toPropertyKey = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var _typeof = require_typeof()["default"];
var toPrimitive = require_toPrimitive();
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/defineProperty.js
var require_defineProperty = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var toPropertyKey = require_toPropertyKey();
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/unhomoglyph/data.json
var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = {
"0": "O",
"1": "l",
"֭": "֖",
"֮": "֘",
"֨": "֙",
"֤": "֚",
"᪴": "ۛ",
"⃛": "ۛ",
"ؙ": "̓",
"ࣳ": "̓",
"̓": "̓",
"̕": "̓",
"ُ": "̓",
"ٝ": "̔",
"֜": "́",
"֝": "́",
"ؘ": "́",
"݇": "́",
"́": "́",
"॔": "́",
"َ": "́",
"̀": "̀",
"॓": "̀",
"̌": "̆",
"꙼": "̆",
"٘": "̆",
"ٚ": "̆",
"ͮ": "̆",
"ۨ": "̆̇",
"̐": "̆̇",
"ँ": "̆̇",
"ঁ": "̆̇",
"ઁ": "̆̇",
"ଁ": "̆̇",
"ఀ": "̆̇",
"ಁ": "̆̇",
"ഁ": "̆̇",
"𑒿": "̆̇",
"᳐": "̂",
"̑": "̂",
"ٛ": "̂",
"߮": "̂",
"꛰": "̂",
"֯": "̊",
"۟": "̊",
"៓": "̊",
"゚": "̊",
"ْ": "̊",
"ஂ": "̊",
"ံ": "̊",
"ំ": "̊",
"𑌀": "̊",
"ํ": "̊",
"ໍ": "̊",
"ͦ": "̊",
"ⷪ": "̊",
"࣫": "̈",
"߳": "̈",
"ً": "̋",
"ࣰ": "̋",
"͂": "̃",
"ٓ": "̃",
"ׄ": "̇",
"۬": "̇",
"݀": "̇",
"࣪": "̇",
"݁": "̇",
"͘": "̇",
"ֹ": "̇",
"ֺ": "̇",
"ׂ": "̇",
"ׁ": "̇",
"߭": "̇",
"ं": "̇",
"ਂ": "̇",
"ં": "̇",
"்": "̇",
"̷": "̸",
"᪷": "̨",
"̢": "̨",
"ͅ": "̨",
"᳒": "̄",
"̅": "̄",
"ٙ": "̄",
"߫": "̄",
"꛱": "̄",
"᳚": "̎",
"ٗ": "̒",
"͗": "͐",
"ࣿ": "͐",
"ࣸ": "͐",
"ऀ": "͒",
"᳭": "̖",
"᳜": "̩",
"ٖ": "̩",
"᳕": "̫",
"͇": "̳",
"ࣹ": "͔",
"ࣺ": "͕",
"゛": "゙",
"゜": "゚",
"̶": "̵",
"〬": "̉",
"ׅ": "̣",
"࣭": "̣",
"᳝": "̣",
"ִ": "̣",
"ٜ": "̣",
"़": "̣",
"়": "̣",
"਼": "̣",
"઼": "̣",
"଼": "̣",
"𑇊": "̣",
"𑓃": "̣",
"𐨺": "̣",
"࣮": "̤",
"᳞": "̤",
"༷": "̥",
"〭": "̥",
"̧": "̦",
"̡": "̦",
"̹": "̦",
"᳙": "̭",
"᳘": "̮",
"॒": "̱",
"̠": "̱",
"ࣱ": "ٌ",
"ࣨ": "ٌ",
"ࣥ": "ٌ",
"ﱞ": "ﹲّ",
"ࣲ": "ٍ",
"ﱟ": "ﹴّ",
"ﳲ": "ﹷّ",
"ﱠ": "ﹶّ",
"ﳳ": "ﹹّ",
"ﱡ": "ﹸّ",
"ؚ": "ِ",
"̗": "ِ",
"ﳴ": "ﹻّ",
"ﱢ": "ﹺّ",
"ﱣ": "ﹼٰ",
"ٟ": "ٕ",
"̍": "ٰ",
"݂": "ܼ",
"ਃ": "ঃ",
"ః": "ঃ",
"ಃ": "ঃ",
"ഃ": "ঃ",
"ඃ": "ঃ",
"း": "ঃ",
"𑓁": "ঃ",
"់": "่",
"່": "่",
"້": "้",
"໊": "๊",
"໋": "๋",
"꙯": "⃩",
"\u2028": " ",
"\u2029": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
" ": " ",
"\xA0": " ",
" ": " ",
" ": " ",
"ߺ": "_",
"﹍": "_",
"﹎": "_",
"﹏": "_",
"‐": "-",
"‑": "-",
"‒": "-",
"–": "-",
"﹘": "-",
"۔": "-",
"⁃": "-",
"˗": "-",
"−": "-",
"➖": "-",
"Ⲻ": "-",
"⨩": "-̓",
"⸚": "-̈",
"﬩": "-̇",
"∸": "-̇",
"⨪": "-̣",
"꓾": "-.",
"~": "〜",
"؍": ",",
"٫": ",",
"‚": ",",
"¸": ",",
"ꓹ": ",",
"⸲": "،",
"٬": "،",
";": ";",
"⸵": "؛",
"ः": ":",
"ઃ": ":",
":": ":",
"։": ":",
"܃": ":",
"܄": ":",
"᛬": ":",
"︰": ":",
"᠃": ":",
"᠉": ":",
"⁚": ":",
"׃": ":",
"˸": ":",
"꞉": ":",
"∶": ":",
"ː": ":",
"ꓽ": ":",
"⩴": "::=",
"⧴": ":→",
"!": "!",
"ǃ": "!",
"ⵑ": "!",
"‼": "!!",
"⁉": "!?",
"ʔ": "?",
"Ɂ": "?",
"ॽ": "?",
"Ꭾ": "?",
"ꛫ": "?",
"⁈": "?!",
"⁇": "??",
"⸮": "؟",
"𝅭": ".",
"․": ".",
"܁": ".",
"܂": ".",
"꘎": ".",
"𐩐": ".",
"٠": ".",
"۰": ".",
"ꓸ": ".",
"ꓻ": ".,",
"‥": "..",
"ꓺ": "..",
"…": "...",
"꛴": "꛳꛳",
"・": "·",
"・": "·",
"᛫": "·",
"·": "·",
"⸱": "·",
"𐄁": "·",
"•": "·",
"‧": "·",
"∙": "·",
"⋅": "·",
"ꞏ": "·",
"ᐧ": "·",
"⋯": "···",
"ⵈ": "···",
"ᑄ": "·<",
"⋗": "·>",
"ᐷ": "·>",
"ᑀ": "·>",
"ᔯ": "·4",
"ᑾ": "·b",
"ᒀ": "·ḃ",
"ᑺ": "·d",
"ᒘ": "·J",
"ᒶ": "·L",
"ᑶ": "·P",
"ᑗ": "·U",
"ᐺ": "·V",
"ᐼ": "·Ʌ",
"ᒮ": "·Γ",
"ᐎ": "·Δ",
"ᑙ": "·Ո",
"ᐌ": "·ᐁ",
"ᐐ": "·ᐄ",
"ᐒ": "·ᐅ",
"ᐔ": "·ᐆ",
"ᐗ": "·ᐊ",
"ᐙ": "·ᐋ",
"ᐾ": "·ᐲ",
"ᑂ": "·ᐴ",
"ᑆ": "·ᐹ",
"ᑛ": "·ᑏ",
"ᑔ": "·ᑐ",
"ᑝ": "·ᑐ",
"ᑟ": "·ᑑ",
"ᑡ": "·ᑕ",
"ᑣ": "·ᑖ",
"ᑴ": "·ᑫ",
"ᑸ": "·ᑮ",
"ᑼ": "·ᑰ",
"ᒒ": "·ᒉ",
"ᒔ": "·ᒋ",
"ᒖ": "·ᒌ",
"ᒚ": "·ᒎ",
"ᒜ": "·ᒐ",
"ᒞ": "·ᒑ",
"ᒬ": "·ᒣ",
"ᒰ": "·ᒦ",
"ᒲ": "·ᒧ",
"ᒴ": "·ᒨ",
"ᒸ": "·ᒫ",
"ᓉ": "·ᓀ",
"ᣆ": "·ᓂ",
"ᣈ": "·ᓃ",
"ᣊ": "·ᓄ",
"ᣌ": "·ᓅ",
"ᓋ": "·ᓇ",
"ᓍ": "·ᓈ",
"ᓜ": "·ᓓ",
"ᓞ": "·ᓕ",
"ᓠ": "·ᓖ",
"ᓢ": "·ᓗ",
"ᓤ": "·ᓘ",
"ᓦ": "·ᓚ",
"ᓨ": "·ᓛ",
"ᓶ": "·ᓭ",
"ᓸ": "·ᓯ",
"ᓺ": "·ᓰ",
"ᓼ": "·ᓱ",
"ᓾ": "·ᓲ",
"ᔀ": "·ᓴ",
"ᔂ": "·ᓵ",
"ᔗ": "·ᔐ",
"ᔙ": "·ᔑ",
"ᔛ": "·ᔒ",
"ᔝ": "·ᔓ",
"ᔟ": "·ᔔ",
"ᔡ": "·ᔕ",
"ᔣ": "·ᔖ",
"ᔱ": "·ᔨ",
"ᔳ": "·ᔩ",
"ᔵ": "·ᔪ",
"ᔷ": "·ᔫ",
"ᔹ": "·ᔭ",
"ᔻ": "·ᔮ",
"ᣎ": "·ᕃ",
"ᣏ": "·ᕆ",
"ᣐ": "·ᕇ",
"ᣑ": "·ᕈ",
"ᣒ": "·ᕉ",
"ᣓ": "·ᕋ",
"ᕎ": "·ᕌ",
"ᕛ": "·ᕚ",
"ᕨ": "·ᕧ",
"ᢳ": "·ᢱ",
"ᢶ": "·ᢴ",
"ᢹ": "·ᢸ",
"ᣂ": "·ᣀ",
"꠰": "।",
"॥": "।।",
"᰼": "᰻᰻",
"။": "၊၊",
"᪩": "᪨᪨",
"᪫": "᪪᪨",
"᭟": "᭞᭞",
"𐩗": "𐩖𐩖",
"𑑌": "𑑋𑑋",
"𑙂": "𑙁𑙁",
"𑱂": "𑱁𑱁",
"᱿": "᱾᱾",
"՝": "'",
"'": "'",
"‘": "'",
"’": "'",
"‛": "'",
"′": "'",
"‵": "'",
"՚": "'",
"׳": "'",
"`": "'",
"`": "'",
"`": "'",
"´": "'",
"΄": "'",
"´": "'",
"᾽": "'",
"᾿": "'",
"῾": "'",
"ʹ": "'",
"ʹ": "'",
"ˈ": "'",
"ˊ": "'",
"ˋ": "'",
"˴": "'",
"ʻ": "'",
"ʽ": "'",
"ʼ": "'",
"ʾ": "'",
"ꞌ": "'",
"י": "'",
"ߴ": "'",
"ߵ": "'",
"ᑊ": "'",
"ᛌ": "'",
"𖽑": "'",
"𖽒": "'",
"᳓": "''",
"\"": "''",
""": "''",
"“": "''",
"”": "''",
"‟": "''",
"″": "''",
"‶": "''",
"〃": "''",
"״": "''",
"˝": "''",
"ʺ": "''",
"˶": "''",
"ˮ": "''",
"ײ": "''",
"‴": "'''",
"‷": "'''",
"⁗": "''''",
"Ɓ": "'B",
"Ɗ": "'D",
"ʼn": "'n",
"Ƥ": "'P",
"Ƭ": "'T",
"Ƴ": "'Y",
"[": "(",
"❨": "(",
"❲": "(",
"〔": "(",
"﴾": "(",
"⸨": "((",
"㈠": "(ー)",
"⑵": "(2)",
"⒇": "(2O)",
"⑶": "(3)",
"⑷": "(4)",
"⑸": "(5)",
"⑹": "(6)",
"⑺": "(7)",
"⑻": "(8)",
"⑼": "(9)",
"⒜": "(a)",
"🄐": "(A)",
"⒝": "(b)",
"🄑": "(B)",
"⒞": "(c)",
"🄒": "(C)",
"⒟": "(d)",
"🄓": "(D)",
"⒠": "(e)",
"🄔": "(E)",
"⒡": "(f)",
"🄕": "(F)",
"⒢": "(g)",
"🄖": "(G)",
"⒣": "(h)",
"🄗": "(H)",
"⒤": "(i)",
"⒥": "(j)",
"🄙": "(J)",
"⒦": "(k)",
"🄚": "(K)",
"⑴": "(l)",
"🄘": "(l)",
"⒧": "(l)",
"🄛": "(L)",
"⑿": "(l2)",
"⒀": "(l3)",
"⒁": "(l4)",
"⒂": "(l5)",
"⒃": "(l6)",
"⒄": "(l7)",
"⒅": "(l8)",
"⒆": "(l9)",
"⑾": "(ll)",
"⑽": "(lO)",
"🄜": "(M)",
"⒩": "(n)",
"🄝": "(N)",
"⒪": "(o)",
"🄞": "(O)",
"⒫": "(p)",
"🄟": "(P)",
"⒬": "(q)",
"🄠": "(Q)",
"⒭": "(r)",
"🄡": "(R)",
"⒨": "(rn)",
"⒮": "(s)",
"🄢": "(S)",
"🄪": "(S)",
"⒯": "(t)",
"🄣": "(T)",
"⒰": "(u)",
"🄤": "(U)",
"⒱": "(v)",
"🄥": "(V)",
"⒲": "(w)",
"🄦": "(W)",
"⒳": "(x)",
"🄧": "(X)",
"⒴": "(y)",
"🄨": "(Y)",
"⒵": "(z)",
"🄩": "(Z)",
"㈀": "(ᄀ)",
"㈎": "(가)",
"㈁": "(ᄂ)",
"㈏": "(나)",
"㈂": "(ᄃ)",
"㈐": "(다)",
"㈃": "(ᄅ)",
"㈑": "(라)",
"㈄": "(ᄆ)",
"㈒": "(마)",
"㈅": "(ᄇ)",
"㈓": "(바)",
"㈆": "(ᄉ)",
"㈔": "(사)",
"㈇": "(ᄋ)",
"㈕": "(아)",
"㈝": "(오전)",
"㈞": "(오후)",
"㈈": "(ᄌ)",
"㈖": "(자)",
"㈜": "(주)",
"㈉": "(ᄎ)",
"㈗": "(차)",
"㈊": "(ᄏ)",
"㈘": "(카)",
"㈋": "(ᄐ)",
"㈙": "(타)",
"㈌": "(ᄑ)",
"㈚": "(파)",
"㈍": "(ᄒ)",
"㈛": "(하)",
"㈦": "(七)",
"㈢": "(三)",
"🉁": "(三)",
"㈨": "(九)",
"㈡": "(二)",
"🉂": "(二)",
"㈤": "(五)",
"㈹": "(代)",
"㈽": "(企)",
"㉁": "(休)",
"㈧": "(八)",
"㈥": "(六)",
"㈸": "(労)",
"🉇": "(勝)",
"㈩": "(十)",
"㈿": "(協)",
"㈴": "(名)",
"㈺": "(呼)",
"㈣": "(四)",
"㈯": "(土)",
"㈻": "(学)",
"🉃": "(安)",
"🉅": "(打)",
"🉈": "(敗)",
"㈰": "(日)",
"㈪": "(月)",
"㈲": "(有)",
"㈭": "(木)",
"🉀": "(本)",
"㈱": "(株)",
"㈬": "(水)",
"㈫": "(火)",
"🉄": "(点)",
"㈵": "(特)",
"🉆": "(盗)",
"㈼": "(監)",
"㈳": "(社)",
"㈷": "(祝)",
"㉀": "(祭)",
"㉂": "(自)",
"㉃": "(至)",
"㈶": "(財)",
"㈾": "(資)",
"㈮": "(金)",
"]": ")",
"❩": ")",
"❳": ")",
"〕": ")",
"﴿": ")",
"⸩": "))",
"❴": "{",
"𝄔": "{",
"❵": "}",
"〚": "⟦",
"〛": "⟧",
"⟨": "❬",
"〈": "❬",
"〈": "❬",
"㇛": "❬",
"く": "❬",
"𡿨": "❬",
"⟩": "❭",
"〉": "❭",
"〉": "❭",
"^": "︿",
"⸿": "¶",
"⁎": "*",
"٭": "*",
"∗": "*",
"𐌟": "*",
"᜵": "/",
"⁁": "/",
"∕": "/",
"⁄": "/",
"╱": "/",
"⟋": "/",
"⧸": "/",
"𝈺": "/",
"㇓": "/",
"〳": "/",
"Ⳇ": "/",
"ノ": "/",
"丿": "/",
"⼃": "/",
"⧶": "/̄",
"⫽": "//",
"⫻": "///",
"\": "\\",
"﹨": "\\",
"∖": "\\",
"⟍": "\\",
"⧵": "\\",
"⧹": "\\",
"𝈏": "\\",
"𝈻": "\\",
"㇔": "\\",
"丶": "\\",
"⼂": "\\",
"⳹": "\\\\",
"⑊": "\\\\",
"⟈": "\\ᑕ",
"ꝸ": "&",
"૰": "॰",
"𑂻": "॰",
"𑇇": "॰",
"⚬": "॰",
"𑇛": "꣼",
"៙": "๏",
"៕": "๚",
"៚": "๛",
"༌": "་",
"༎": "།།",
"˄": "^",
"ˆ": "^",
"꙾": "ˇ",
"˘": "ˇ",
"‾": "ˉ",
"﹉": "ˉ",
"﹊": "ˉ",
"﹋": "ˉ",
"﹌": "ˉ",
"¯": "ˉ",
" ̄": "ˉ",
"▔": "ˉ",
"ъ": "ˉb",
"ꙑ": "ˉbi",
"͵": "ˏ",
"˻": "˪",
"꜖": "˪",
"꜔": "˫",
"。": "˳",
"⸰": "°",
"˚": "°",
"∘": "°",
"○": "°",
"◦": "°",
"⍜": "°̲",
"⍤": "°̈",
"℃": "°C",
"℉": "°F",
"௵": "௳",
"༛": "༚༚",
"༟": "༚༝",
"࿎": "༝༚",
"༞": "༝༝",
"Ⓒ": "©",
"Ⓡ": "®",
"Ⓟ": "℗",
"𝈛": "⅄",
"⯬": "↞",
"⯭": "↟",
"⯮": "↠",
"⯯": "↡",
"↵": "↲",
"⥥": "⇃⇂",
"⥯": "⇃ᛚ",
"𝛛": "∂",
"𝜕": "∂",
"𝝏": "∂",
"𝞉": "∂",
"𝟃": "∂",
"𞣌": "∂",
"𞣍": "∂̵",
"ð": "∂̵",
"⌀": "∅",
"𝛁": "∇",
"𝛻": "∇",
"𝜵": "∇",
"𝝯": "∇",
"𝞩": "∇",
"𑢨": "∇",
"⍢": "∇̈",
"⍫": "∇̴",
"█": "∎",
"■": "∎",
"⨿": "∐",
"᛭": "+",
"➕": "+",
"𐊛": "+",
"⨣": "+̂",
"⨢": "+̊",
"⨤": "+̃",
"∔": "+̇",
"⨥": "+̣",
"⨦": "+̰",
"⨧": "+₂",
"➗": "÷",
"‹": "<",
"❮": "<",
"˂": "<",
"𝈶": "<",
"ᐸ": "<",
"ᚲ": "<",
"⋖": "<·",
"Ⲵ": "<·",
"ᑅ": "<·",
"≪": "<<",
"⋘": "<<<",
"᐀": "=",
"⹀": "=",
"゠": "=",
"꓿": "=",
"≚": "=̆",
"≙": "=̂",
"≗": "=̊",
"≐": "=̇",
"≑": "=̣̇",
"⩮": "=⃰",
"⩵": "==",
"⩶": "===",
"≞": "=ͫ",
"›": ">",
"❯": ">",
"˃": ">",
"𝈷": ">",
"ᐳ": ">",
"𖼿": ">",
"ᑁ": ">·",
"⪥": "><",
"≫": ">>",
"⨠": ">>",
"⋙": ">>>",
"⁓": "~",
"˜": "~",
"῀": "~",
"∼": "~",
"⍨": "~̈",
"⸞": "~̇",
"⩪": "~̇",
"⸟": "~̣",
"𞣈": "∠",
"⋀": "∧",
"∯": "∮∮",
"∰": "∮∮∮",
"⸫": "∴",
"⸪": "∵",
"⸬": "∷",
"𑇞": "≈",
"♎": "≏",
"🝞": "≏",
"≣": "≡",
"⨃": "⊍",
"⨄": "⊎",
"𝈸": "⊏",
"𝈹": "⊐",
"⨅": "⊓",
"⨆": "⊔",
"⨂": "⊗",
"⍟": "⊛",
"🝱": "⊠",
"🝕": "⊡",
"◁": "⊲",
"▷": "⊳",
"⍣": "⋆̈",
"︴": "⌇",
"◠": "⌒",
"⨽": "⌙",
"⌥": "⌤",
"⧇": "⌻",
"◎": "⌾",
"⦾": "⌾",
"⧅": "⍂",
"⦰": "⍉",
"⏃": "⍋",
"⏂": "⍎",
"⏁": "⍕",
"⏆": "⍭",
"☸": "⎈",
"︵": "⏜",
"︶": "⏝",
"︷": "⏞",
"︸": "⏟",
"︹": "⏠",
"︺": "⏡",
"▱": "⏥",
"⏼": "⏻",
"︱": "│",
"|": "│",
"┃": "│",
"┏": "┌",
"┣": "├",
"▐": "▌",
"▗": "▖",
"▝": "▘",
"☐": "□",
"■": "▪",
"▸": "▶",
"►": "▶",
"⳩": "☧",
"🜊": "☩",
"🌒": "☽",
"🌙": "☽",
"⏾": "☾",
"🌘": "☾",
"⧙": "⦚",
"🜺": "⧟",
"⨾": "⨟",
"𐆠": "⳨",
"♩": "𝅘𝅥",
"♪": "𝅘𝅥𝅮",
"⓪": "🄍",
"↺": "🄎",
"˙": "ॱ",
"ൎ": "ॱ",
"-": "ー",
"—": "ー",
"―": "ー",
"─": "ー",
"━": "ー",
"㇐": "ー",
"ꟷ": "ー",
"ᅳ": "ー",
"ㅡ": "ー",
"一": "ー",
"⼀": "ー",
"ᆖ": "ーー",
"ힹ": "ーᅡ",
"ힺ": "ーᅥ",
"ힻ": "ーᅥ丨",
"ힼ": "ーᅩ",
"ᆕ": "ーᅮ",
"ᅴ": "ー丨",
"ㅢ": "ー丨",
"ᆗ": "ー丨ᅮ",
"🄏": "$⃠",
"₤": "£",
"〒": "₸",
"〶": "₸",
"᭜": "᭐",
"꧆": "꧐",
"𑓑": "১",
"೧": "౧",
"ၥ": "၁",
"①": "➀",
"⑩": "➉",
"⏨": "₁₀",
"𝟐": "2",
"𝟚": "2",
"𝟤": "2",
"𝟮": "2",
"𝟸": "2",
"🯲": "2",
"Ꝛ": "2",
"Ƨ": "2",
"Ϩ": "2",
"Ꙅ": "2",
"ᒿ": "2",
"ꛯ": "2",
"ꧏ": "٢",
"۲": "٢",
"૨": "२",
"𑓒": "২",
"೨": "౨",
"②": "➁",
"ƻ": "2̵",
"🄃": "2,",
"⒉": "2.",
"㏵": "22日",
"㍮": "22点",
"㏶": "23日",
"㍯": "23点",
"㏷": "24日",
"㍰": "24点",
"㏸": "25日",
"㏹": "26日",
"㏺": "27日",
"㏻": "28日",
"㏼": "29日",
"㏴": "2l日",
"㍭": "2l点",
"⒛": "2O.",
"㏳": "2O日",
"㍬": "2O点",
"෩": "෨ා",
"෯": "෨ී",
"㏡": "2日",
"㋁": "2月",
"㍚": "2点",
"𝈆": "3",
"𝟑": "3",
"𝟛": "3",
"𝟥": "3",
"𝟯": "3",
"𝟹": "3",
"🯳": "3",
"Ɜ": "3",
"Ȝ": "3",
"Ʒ": "3",
"Ꝫ": "3",
"Ⳍ": "3",
"З": "3",
"Ӡ": "3",
"𖼻": "3",
"𑣊": "3",
"۳": "٣",
"𞣉": "٣",
"૩": "३",
"③": "➂",
"Ҙ": "3̦",
"🄄": "3,",
"⒊": "3.",
"㏾": "3l日",
"㏽": "3O日",
"㏢": "3日",
"㋂": "3月",
"㍛": "3点",
"𝟒": "4",
"𝟜": "4",
"𝟦": "4",
"𝟰": "4",
"𝟺": "4",
"🯴": "4",
"Ꮞ": "4",
"𑢯": "4",
"۴": "٤",
"૪": "४",
"④": "➃",
"🄅": "4,",
"⒋": "4.",
"ᔰ": "4·",
"㏣": "4日",
"㋃": "4月",
"㍜": "4点",
"𝟓": "5",
"𝟝": "5",
"𝟧": "5",
"𝟱": "5",
"𝟻": "5",
"🯵": "5",
"Ƽ": "5",
"𑢻": "5",
"⑤": "➄",
"🄆": "5,",
"⒌": "5.",
"㏤": "5日",
"㋄": "5月",
"㍝": "5点",
"𝟔": "6",
"𝟞": "6",
"𝟨": "6",
"𝟲": "6",
"𝟼": "6",
"🯶": "6",
"Ⳓ": "6",
"б": "6",
"Ꮾ": "6",
"𑣕": "6",
"۶": "٦",
"𑓖": "৬",
"⑥": "➅",
"🄇": "6,",
"⒍": "6.",
"㏥": "6日",
"㋅": "6月",
"㍞": "6点",
"𝈒": "7",
"𝟕": "7",
"𝟟": "7",
"𝟩": "7",
"𝟳": "7",
"𝟽": "7",
"🯷": "7",
"𐓒": "7",
"𑣆": "7",
"⑦": "➆",
"🄈": "7,",
"⒎": "7.",
"㏦": "7日",
"㋆": "7月",
"㍟": "7点",
"ଃ": "8",
"৪": "8",
"੪": "8",
"𞣋": "8",
"𝟖": "8",
"𝟠": "8",
"𝟪": "8",
"𝟴": "8",
"𝟾": "8",
"🯸": "8",
"ȣ": "8",
"Ȣ": "8",
"𐌚": "8",
"૮": "८",
"⑧": "➇",
"🄉": "8,",
"⒏": "8.",
"㏧": "8日",
"㋇": "8月",
"㍠": "8点",
"੧": "9",
"୨": "9",
"৭": "9",
"൭": "9",
"𝟗": "9",
"𝟡": "9",
"𝟫": "9",
"𝟵": "9",
"𝟿": "9",
"🯹": "9",
"Ꝯ": "9",
"Ⳋ": "9",
"𑣌": "9",
"𑢬": "9",
"𑣖": "9",
"१": "٩",
"𑣤": "٩",
"۹": "٩",
"೯": "౯",
"⑨": "➈",
"🄊": "9,",
"⒐": "9.",
"㏨": "9日",
"㋈": "9月",
"㍡": "9点",
"⍺": "a",
"a": "a",
"𝐚": "a",
"𝑎": "a",
"𝒂": "a",
"𝒶": "a",
"𝓪": "a",
"𝔞": "a",
"𝕒": "a",
"𝖆": "a",
"𝖺": "a",
"𝗮": "a",
"𝘢": "a",
"𝙖": "a",
"𝚊": "a",
"ɑ": "a",
"α": "a",
"𝛂": "a",
"𝛼": "a",
"𝜶": "a",
"𝝰": "a",
"𝞪": "a",
"а": "a",
"ⷶ": "ͣ",
"A": "A",
"𝐀": "A",
"𝐴": "A",
"𝑨": "A",
"𝒜": "A",
"𝓐": "A",
"𝔄": "A",
"𝔸": "A",
"𝕬": "A",
"𝖠": "A",
"𝗔": "A",
"𝘈": "A",
"𝘼": "A",
"𝙰": "A",
"Α": "A",
"𝚨": "A",
"𝛢": "A",
"𝜜": "A",
"𝝖": "A",
"𝞐": "A",
"А": "A",
"Ꭺ": "A",
"ᗅ": "A",
"ꓮ": "A",
"𖽀": "A",
"𐊠": "A",
"⍶": "a̲",
"ǎ": "ă",
"Ǎ": "Ă",
"ȧ": "å",
"Ȧ": "Å",
"ẚ": "ả",
"℀": "a/c",
"℁": "a/s",
"ꜳ": "aa",
"Ꜳ": "AA",
"æ": "ae",
"ӕ": "ae",
"Æ": "AE",
"Ӕ": "AE",
"ꜵ": "ao",
"Ꜵ": "AO",
"🜇": "AR",
"ꜷ": "au",
"Ꜷ": "AU",
"ꜹ": "av",
"ꜻ": "av",
"Ꜹ": "AV",
"Ꜻ": "AV",
"ꜽ": "ay",
"Ꜽ": "AY",
"ꭺ": "ᴀ",
"∀": "Ɐ",
"𝈗": "Ɐ",
"ᗄ": "Ɐ",
"ꓯ": "Ɐ",
"𐐟": "Ɒ",
"𝐛": "b",
"𝑏": "b",
"𝒃": "b",
"𝒷": "b",
"𝓫": "b",
"𝔟": "b",
"𝕓": "b",
"𝖇": "b",
"𝖻": "b",
"𝗯": "b",
"𝘣": "b",
"𝙗": "b",
"𝚋": "b",
"Ƅ": "b",
"Ь": "b",
"Ꮟ": "b",
"ᑲ": "b",
"ᖯ": "b",
"B": "B",
"ℬ": "B",
"𝐁": "B",
"𝐵": "B",
"𝑩": "B",
"𝓑": "B",
"𝔅": "B",
"𝔹": "B",
"𝕭": "B",
"𝖡": "B",
"𝗕": "B",
"𝘉": "B",
"𝘽": "B",
"𝙱": "B",
"Ꞵ": "B",
"Β": "B",
"𝚩": "B",
"𝛣": "B",
"𝜝": "B",
"𝝗": "B",
"𝞑": "B",
"В": "B",
"Ᏼ": "B",
"ᗷ": "B",
"ꓐ": "B",
"𐊂": "B",
"𐊡": "B",
"𐌁": "B",
"ɓ": "b̔",
"ᑳ": "ḃ",
"ƃ": "b̄",
"Ƃ": "b̄",
"Б": "b̄",
"ƀ": "b̵",
"ҍ": "b̵",
"Ҍ": "b̵",
"ѣ": "b̵",
"Ѣ": "b̵",
"ᑿ": "b·",
"ᒁ": "ḃ·",
"ᒈ": "b'",
"Ы": "bl",
"в": "ʙ",
"ᏼ": "ʙ",
"c": "c",
"ⅽ": "c",
"𝐜": "c",
"𝑐": "c",
"𝒄": "c",
"𝒸": "c",
"𝓬": "c",
"𝔠": "c",
"𝕔": "c",
"𝖈": "c",
"𝖼": "c",
"𝗰": "c",
"𝘤": "c",
"𝙘": "c",
"𝚌": "c",
"ᴄ": "c",
"ϲ": "c",
"ⲥ": "c",
"с": "c",
"ꮯ": "c",
"𐐽": "c",
"ⷭ": "ͨ",
"🝌": "C",
"𑣲": "C",
"𑣩": "C",
"C": "C",
"Ⅽ": "C",
"ℂ": "C",
"ℭ": "C",
"𝐂": "C",
"𝐶": "C",
"𝑪": "C",
"𝒞": "C",
"𝓒": "C",
"𝕮": "C",
"𝖢": "C",
"𝗖": "C",
"𝘊": "C",
"𝘾": "C",
"𝙲": "C",
"Ϲ": "C",
"Ⲥ": "C",
"С": "C",
"Ꮯ": "C",
"ꓚ": "C",
"𐊢": "C",
"𐌂": "C",
"𐐕": "C",
"𐔜": "C",
"¢": "c̸",
"ȼ": "c̸",
"₡": "C⃫",
"🅮": "C⃠",
"ç": "c̦",
"ҫ": "c̦",
"Ç": "C̦",
"Ҫ": "C̦",
"Ƈ": "C'",
"℅": "c/o",
"℆": "c/u",
"🅭": "㏄ ⃝",
"⋴": "ꞓ",
"ɛ": "ꞓ",
"ε": "ꞓ",
"ϵ": "ꞓ",
"𝛆": "ꞓ",
"𝛜": "ꞓ",
"𝜀": "ꞓ",
"𝜖": "ꞓ",
"𝜺": "ꞓ",
"𝝐": "ꞓ",
"𝝴": "ꞓ",
"𝞊": "ꞓ",
"𝞮": "ꞓ",
"𝟄": "ꞓ",
"ⲉ": "ꞓ",
"є": "ꞓ",
"ԑ": "ꞓ",
"ꮛ": "ꞓ",
"𑣎": "ꞓ",
"𐐩": "ꞓ",
"€": "Ꞓ",
"Ⲉ": "Ꞓ",
"Є": "Ꞓ",
"⍷": "ꞓ̲",
"ͽ": "ꜿ",
"Ͽ": "Ꜿ",
"ⅾ": "d",
"ⅆ": "d",
"𝐝": "d",
"𝑑": "d",
"𝒅": "d",
"𝒹": "d",
"𝓭": "d",
"𝔡": "d",
"𝕕": "d",
"𝖉": "d",
"𝖽": "d",
"𝗱": "d",
"𝘥": "d",
"𝙙": "d",
"𝚍": "d",
"ԁ": "d",
"Ꮷ": "d",
"ᑯ": "d",
"ꓒ": "d",
"Ⅾ": "D",
"ⅅ": "D",
"𝐃": "D",
"𝐷": "D",
"𝑫": "D",
"𝒟": "D",
"𝓓": "D",
"𝔇": "D",
"𝔻": "D",
"𝕯": "D",
"𝖣": "D",
"𝗗": "D",
"𝘋": "D",
"𝘿": "D",
"𝙳": "D",
"Ꭰ": "D",
"ᗞ": "D",
"ᗪ": "D",
"ꓓ": "D",
"ɗ": "d̔",
"ɖ": "d̨",
"ƌ": "d̄",
"đ": "d̵",
"Đ": "D̵",
"Ð": "D̵",
"Ɖ": "D̵",
"₫": "ḏ̵",
"ꝺ": "Ꝺ",
"ᑻ": "d·",
"ᒇ": "d'",
"ʤ": "dȝ",
"dz": "dz",
"ʣ": "dz",
"Dz": "Dz",
"DZ": "DZ",
"dž": "dž",
"Dž": "Dž",
"DŽ": "DŽ",
"ʥ": "dʑ",
"ꭰ": "ᴅ",
"⸹": "ẟ",
"δ": "ẟ",
"𝛅": "ẟ",
"𝛿": "ẟ",
"𝜹": "ẟ",
"𝝳": "ẟ",
"𝞭": "ẟ",
"ծ": "ẟ",
"ᕷ": "ẟ",
"℮": "e",
"e": "e",
"ℯ": "e",
"ⅇ": "e",
"𝐞": "e",
"𝑒": "e",
"𝒆": "e",
"𝓮": "e",
"𝔢": "e",
"𝕖": "e",
"𝖊": "e",
"𝖾": "e",
"𝗲": "e",
"𝘦": "e",
"𝙚": "e",
"𝚎": "e",
"ꬲ": "e",
"е": "e",
"ҽ": "e",
"ⷷ": "ͤ",
"⋿": "E",
"E": "E",
"ℰ": "E",
"𝐄": "E",
"𝐸": "E",
"𝑬": "E",
"𝓔": "E",
"𝔈": "E",
"𝔼": "E",
"𝕰": "E",
"𝖤": "E",
"𝗘": "E",
"𝘌": "E",
"𝙀": "E",
"𝙴": "E",
"Ε": "E",
"𝚬": "E",
"𝛦": "E",
"𝜠": "E",
"𝝚": "E",
"𝞔": "E",
"Е": "E",
"ⴹ": "E",
"Ꭼ": "E",
"ꓰ": "E",
"𑢦": "E",
"𑢮": "E",
"𐊆": "E",
"ě": "ĕ",
"Ě": "Ĕ",
"ɇ": "e̸",
"Ɇ": "E̸",
"ҿ": "ę",
"ꭼ": "ᴇ",
"ə": "ǝ",
"ә": "ǝ",
"∃": "Ǝ",
"ⴺ": "Ǝ",
"ꓱ": "Ǝ",
"ɚ": "ǝ˞",
"ᴔ": "ǝo",
"ꭁ": "ǝo̸",
"ꭂ": "ǝo̵",
"Ә": "Ə",
"𝈡": "Ɛ",
"ℇ": "Ɛ",
"Ԑ": "Ɛ",
"Ꮛ": "Ɛ",
"𖼭": "Ɛ",
"𐐁": "Ɛ",
"ᶟ": "ᵋ",
"ᴈ": "ɜ",
"з": "ɜ",
"ҙ": "ɜ̦",
"𐑂": "ɞ",
"ꞝ": "ʚ",
"𐐪": "ʚ",
"𝐟": "f",
"𝑓": "f",
"𝒇": "f",
"𝒻": "f",
"𝓯": "f",
"𝔣": "f",
"𝕗": "f",
"𝖋": "f",
"𝖿": "f",
"𝗳": "f",
"𝘧": "f",
"𝙛": "f",
"𝚏": "f",
"ꬵ": "f",
"ꞙ": "f",
"ſ": "f",
"ẝ": "f",
"ք": "f",
"𝈓": "F",
"ℱ": "F",
"𝐅": "F",
"𝐹": "F",
"𝑭": "F",
"𝓕": "F",
"𝔉": "F",
"𝔽": "F",
"𝕱": "F",
"𝖥": "F",
"𝗙": "F",
"𝘍": "F",
"𝙁": "F",
"𝙵": "F",
"Ꞙ": "F",
"Ϝ": "F",
"𝟊": "F",
"ᖴ": "F",
"ꓝ": "F",
"𑣂": "F",
"𑢢": "F",
"𐊇": "F",
"𐊥": "F",
"𐔥": "F",
"ƒ": "f̦",
"Ƒ": "F̦",
"ᵮ": "f̴",
"℻": "FAX",
"ff": "ff",
"ffi": "ffi",
"ffl": "ffl",
"fi": "fi",
"fl": "fl",
"ʩ": "fŋ",
"ᖵ": "Ⅎ",
"ꓞ": "Ⅎ",
"𝈰": "ꟻ",
"ᖷ": "ꟻ",
"g": "g",
"ℊ": "g",
"𝐠": "g",
"𝑔": "g",
"𝒈": "g",
"𝓰": "g",
"𝔤": "g",
"𝕘": "g",
"𝖌": "g",
"𝗀": "g",
"𝗴": "g",
"𝘨": "g",
"𝙜": "g",
"𝚐": "g",
"ɡ": "g",
"ᶃ": "g",
"ƍ": "g",
"ց": "g",
"𝐆": "G",
"𝐺": "G",
"𝑮": "G",
"𝒢": "G",
"𝓖": "G",
"𝔊": "G",
"𝔾": "G",
"𝕲": "G",
"𝖦": "G",
"𝗚": "G",
"𝘎": "G",
"𝙂": "G",
"𝙶": "G",
"Ԍ": "G",
"Ꮐ": "G",
"Ᏻ": "G",
"ꓖ": "G",
"ᶢ": "ᵍ",
"ɠ": "g̔",
"ǧ": "ğ",
"Ǧ": "Ğ",
"ǵ": "ģ",
"ǥ": "g̵",
"Ǥ": "G̵",
"Ɠ": "G'",
"ԍ": "ɢ",
"ꮐ": "ɢ",
"ᏻ": "ɢ",
"h": "h",
"ℎ": "h",
"𝐡": "h",
"𝒉": "h",
"𝒽": "h",
"𝓱": "h",
"𝔥": "h",
"𝕙": "h",
"𝖍": "h",
"𝗁": "h",
"𝗵": "h",
"𝘩": "h",
"𝙝": "h",
"𝚑": "h",
"һ": "h",
"հ": "h",
"Ꮒ": "h",
"H": "H",
"ℋ": "H",
"ℌ": "H",
"ℍ": "H",
"𝐇": "H",
"𝐻": "H",
"𝑯": "H",
"𝓗": "H",
"𝕳": "H",
"𝖧": "H",
"𝗛": "H",
"𝘏": "H",
"𝙃": "H",
"𝙷": "H",
"Η": "H",
"𝚮": "H",
"𝛨": "H",
"𝜢": "H",
"𝝜": "H",
"𝞖": "H",
"Ⲏ": "H",
"Н": "H",
"Ꮋ": "H",
"ᕼ": "H",
"ꓧ": "H",
"𐋏": "H",
"ᵸ": "ᴴ",
"ɦ": "h̔",
"ꚕ": "h̔",
"Ᏺ": "h̔",
"Ⱨ": "H̩",
"Ң": "H̩",
"ħ": "h̵",
"ℏ": "h̵",
"ћ": "h̵",
"Ħ": "H̵",
"Ӊ": "H̦",
"Ӈ": "H̦",
"н": "ʜ",
"ꮋ": "ʜ",
"ң": "ʜ̩",
"ӊ": "ʜ̦",
"ӈ": "ʜ̦",
"Ԋ": "Ƕ",
"ꮀ": "ⱶ",
"Ͱ": "Ⱶ",
"Ꭸ": "Ⱶ",
"Ꮀ": "Ⱶ",
"ꚱ": "Ⱶ",
"ꞕ": "ꜧ",
"˛": "i",
"⍳": "i",
"i": "i",
"ⅰ": "i",
"ℹ": "i",
"ⅈ": "i",
"𝐢": "i",
"𝑖": "i",
"𝒊": "i",
"𝒾": "i",
"𝓲": "i",
"𝔦": "i",
"𝕚": "i",
"𝖎": "i",
"𝗂": "i",
"𝗶": "i",
"𝘪": "i",
"𝙞": "i",
"𝚒": "i",
"ı": "i",
"𝚤": "i",
"ɪ": "i",
"ɩ": "i",
"ι": "i",
"ι": "i",
"ͺ": "i",
"𝛊": "i",
"𝜄": "i",
"𝜾": "i",
"𝝸": "i",
"𝞲": "i",
"і": "i",
"ꙇ": "i",
"ӏ": "i",
"ꭵ": "i",
"Ꭵ": "i",
"𑣃": "i",
"ⓛ": "Ⓘ",
"⍸": "i̲",
"ǐ": "ĭ",
"Ǐ": "Ĭ",
"ɨ": "i̵",
"ᵻ": "i̵",
"ᵼ": "i̵",
"ⅱ": "ii",
"ⅲ": "iii",
"ij": "ij",
"ⅳ": "iv",
"ⅸ": "ix",
"j": "j",
"ⅉ": "j",
"𝐣": "j",
"𝑗": "j",
"𝒋": "j",
"𝒿": "j",
"𝓳": "j",
"𝔧": "j",
"𝕛": "j",
"𝖏": "j",
"𝗃": "j",
"𝗷": "j",
"𝘫": "j",
"𝙟": "j",
"𝚓": "j",
"ϳ": "j",
"ј": "j",
"J": "J",
"𝐉": "J",
"𝐽": "J",
"𝑱": "J",
"𝒥": "J",
"𝓙": "J",
"𝔍": "J",
"𝕁": "J",
"𝕵": "J",
"𝖩": "J",
"𝗝": "J",
"𝘑": "J",
"𝙅": "J",
"𝙹": "J",
"Ʝ": "J",
"Ϳ": "J",
"Ј": "J",
"Ꭻ": "J",
"ᒍ": "J",
"ꓙ": "J",
"ɉ": "j̵",
"Ɉ": "J̵",
"ᒙ": "J·",
"𝚥": "ȷ",
"յ": "ȷ",
"ꭻ": "ᴊ",
"𝐤": "k",
"𝑘": "k",
"𝒌": "k",
"𝓀": "k",
"𝓴": "k",
"𝔨": "k",
"𝕜": "k",
"𝖐": "k",
"𝗄": "k",
"𝗸": "k",
"𝘬": "k",
"𝙠": "k",
"𝚔": "k",
"K": "K",
"K": "K",
"𝐊": "K",
"𝐾": "K",
"𝑲": "K",
"𝒦": "K",
"𝓚": "K",
"𝔎": "K",
"𝕂": "K",
"𝕶": "K",
"𝖪": "K",
"𝗞": "K",
"𝘒": "K",
"𝙆": "K",
"𝙺": "K",
"Κ": "K",
"𝚱": "K",
"𝛫": "K",
"𝜥": "K",
"𝝟": "K",
"𝞙": "K",
"Ⲕ": "K",
"К": "K",
"Ꮶ": "K",
"ᛕ": "K",
"ꓗ": "K",
"𐔘": "K",
"ƙ": "k̔",
"Ⱪ": "K̩",
"Қ": "K̩",
"₭": "K̵",
"Ꝁ": "K̵",
"Ҟ": "K̵",
"Ƙ": "K'",
"׀": "l",
"|": "l",
"∣": "l",
"⏽": "l",
"│": "l",
"١": "l",
"۱": "l",
"𐌠": "l",
"𞣇": "l",
"𝟏": "l",
"𝟙": "l",
"𝟣": "l",
"𝟭": "l",
"𝟷": "l",
"🯱": "l",
"I": "l",
"I": "l",
"Ⅰ": "l",
"ℐ": "l",
"ℑ": "l",
"𝐈": "l",
"𝐼": "l",
"𝑰": "l",
"𝓘": "l",
"𝕀": "l",
"𝕴": "l",
"𝖨": "l",
"𝗜": "l",
"𝘐": "l",
"𝙄": "l",
"𝙸": "l",
"Ɩ": "l",
"l": "l",
"ⅼ": "l",
"ℓ": "l",
"𝐥": "l",
"𝑙": "l",
"𝒍": "l",
"𝓁": "l",
"𝓵": "l",
"𝔩": "l",
"𝕝": "l",
"𝖑": "l",
"𝗅": "l",
"𝗹": "l",
"𝘭": "l",
"𝙡": "l",
"𝚕": "l",
"ǀ": "l",
"Ι": "l",
"𝚰": "l",
"𝛪": "l",
"𝜤": "l",
"𝝞": "l",
"𝞘": "l",
"Ⲓ": "l",
"І": "l",
"Ӏ": "l",
"ו": "l",
"ן": "l",
"ا": "l",
"𞸀": "l",
"𞺀": "l",
"ﺎ": "l",
"ﺍ": "l",
"ߊ": "l",
"ⵏ": "l",
"ᛁ": "l",
"ꓲ": "l",
"𖼨": "l",
"𐊊": "l",
"𐌉": "l",
"𝈪": "L",
"Ⅼ": "L",
"ℒ": "L",
"𝐋": "L",
"𝐿": "L",
"𝑳": "L",
"𝓛": "L",
"𝔏": "L",
"𝕃": "L",
"𝕷": "L",
"𝖫": "L",
"𝗟": "L",
"𝘓": "L",
"𝙇": "L",
"𝙻": "L",
"Ⳑ": "L",
"Ꮮ": "L",
"ᒪ": "L",
"ꓡ": "L",
"𖼖": "L",
"𑢣": "L",
"𑢲": "L",
"𐐛": "L",
"𐔦": "L",
"ﴼ": "l̋",
"ﴽ": "l̋",
"ł": "l̸",
"Ł": "L̸",
"ɭ": "l̨",
"Ɨ": "l̵",
"ƚ": "l̵",
"ɫ": "l̴",
"إ": "lٕ",
"ﺈ": "lٕ",
"ﺇ": "lٕ",
"ٳ": "lٕ",
"ŀ": "l·",
"Ŀ": "l·",
"ᒷ": "l·",
"🄂": "l,",
"⒈": "l.",
"ױ": "l'",
"⒓": "l2.",
"㏫": "l2日",
"㋋": "l2月",
"㍤": "l2点",
"⒔": "l3.",
"㏬": "l3日",
"㍥": "l3点",
"⒕": "l4.",
"㏭": "l4日",
"㍦": "l4点",
"⒖": "l5.",
"㏮": "l5日",
"㍧": "l5点",
"⒗": "l6.",
"㏯": "l6日",
"㍨": "l6点",
"⒘": "l7.",
"㏰": "l7日",
"㍩": "l7点",
"⒙": "l8.",
"㏱": "l8日",
"㍪": "l8点",
"⒚": "l9.",
"㏲": "l9日",
"㍫": "l9点",
"lj": "lj",
"IJ": "lJ",
"Lj": "Lj",
"LJ": "LJ",
"‖": "ll",
"∥": "ll",
"Ⅱ": "ll",
"ǁ": "ll",
"װ": "ll",
"𐆙": "l̵l̵",
"⒒": "ll.",
"Ⅲ": "lll",
"𐆘": "l̵l̵S̵",
"㏪": "ll日",
"㋊": "ll月",
"㍣": "ll点",
"Ю": "lO",
"⒑": "lO.",
"㏩": "lO日",
"㋉": "lO月",
"㍢": "lO点",
"ʪ": "ls",
"₶": "lt",
"Ⅳ": "lV",
"Ⅸ": "lX",
"ɮ": "lȝ",
"ʫ": "lz",
"أ": "lٴ",
"ﺄ": "lٴ",
"ﺃ": "lٴ",
"ٲ": "lٴ",
"ٵ": "lٴ",
"ﷳ": "lكبر",
"ﷲ": "lللّٰo",
"㏠": "l日",
"㋀": "l月",
"㍙": "l点",
"ⳑ": "ʟ",
"ꮮ": "ʟ",
"𐑃": "ʟ",
"M": "M",
"Ⅿ": "M",
"ℳ": "M",
"𝐌": "M",
"𝑀": "M",
"𝑴": "M",
"𝓜": "M",
"𝔐": "M",
"𝕄": "M",
"𝕸": "M",
"𝖬": "M",
"𝗠": "M",
"𝘔": "M",
"𝙈": "M",
"𝙼": "M",
"Μ": "M",
"𝚳": "M",
"𝛭": "M",
"𝜧": "M",
"𝝡": "M",
"𝞛": "M",
"Ϻ": "M",
"Ⲙ": "M",
"М": "M",
"Ꮇ": "M",
"ᗰ": "M",
"ᛖ": "M",
"ꓟ": "M",
"𐊰": "M",
"𐌑": "M",
"Ӎ": "M̦",
"🝫": "MB",
"ⷨ": "ᷟ",
"𝐧": "n",
"𝑛": "n",
"𝒏": "n",
"𝓃": "n",
"𝓷": "n",
"𝔫": "n",
"𝕟": "n",
"𝖓": "n",
"𝗇": "n",
"𝗻": "n",
"𝘯": "n",
"𝙣": "n",
"𝚗": "n",
"ո": "n",
"ռ": "n",
"N": "N",
"ℕ": "N",
"𝐍": "N",
"𝑁": "N",
"𝑵": "N",
"𝒩": "N",
"𝓝": "N",
"𝔑": "N",
"𝕹": "N",
"𝖭": "N",
"𝗡": "N",
"𝘕": "N",
"𝙉": "N",
"𝙽": "N",
"Ν": "N",
"𝚴": "N",
"𝛮": "N",
"𝜨": "N",
"𝝢": "N",
"𝞜": "N",
"Ⲛ": "N",
"ꓠ": "N",
"𐔓": "N",
"𐆎": "N̊",
"ɳ": "n̨",
"ƞ": "n̩",
"η": "n̩",
"𝛈": "n̩",
"𝜂": "n̩",
"𝜼": "n̩",
"𝝶": "n̩",
"𝞰": "n̩",
"Ɲ": "N̦",
"ᵰ": "n̴",
"nj": "nj",
"Nj": "Nj",
"NJ": "NJ",
"№": "No",
"ͷ": "ᴎ",
"и": "ᴎ",
"𐑍": "ᴎ",
"ņ": "ɲ",
"ం": "o",
"ಂ": "o",
"ം": "o",
"ං": "o",
"०": "o",
"੦": "o",
"૦": "o",
"௦": "o",
"౦": "o",
"೦": "o",
"൦": "o",
"๐": "o",
"໐": "o",
"၀": "o",
"٥": "o",
"۵": "o",
"o": "o",
"ℴ": "o",
"𝐨": "o",
"𝑜": "o",
"𝒐": "o",
"𝓸": "o",
"𝔬": "o",
"𝕠": "o",
"𝖔": "o",
"𝗈": "o",
"𝗼": "o",
"𝘰": "o",
"𝙤": "o",
"𝚘": "o",
"ᴏ": "o",
"ᴑ": "o",
"ꬽ": "o",
"ο": "o",
"𝛐": "o",
"𝜊": "o",
"𝝄": "o",
"𝝾": "o",
"𝞸": "o",
"σ": "o",
"𝛔": "o",
"𝜎": "o",
"𝝈": "o",
"𝞂": "o",
"𝞼": "o",
"ⲟ": "o",
"о": "o",
"ჿ": "o",
"օ": "o",
"ס": "o",
"ه": "o",
"𞸤": "o",
"𞹤": "o",
"𞺄": "o",
"ﻫ": "o",
"ﻬ": "o",
"ﻪ": "o",
"ﻩ": "o",
"ھ": "o",
"ﮬ": "o",
"ﮭ": "o",
"ﮫ": "o",
"ﮪ": "o",
"ہ": "o",
"ﮨ": "o",
"ﮩ": "o",
"ﮧ": "o",
"ﮦ": "o",
"ە": "o",
"ഠ": "o",
"ဝ": "o",
"𐓪": "o",
"𑣈": "o",
"𑣗": "o",
"𐐬": "o",
"߀": "O",
"০": "O",
"୦": "O",
"〇": "O",
"𑓐": "O",
"𑣠": "O",
"𝟎": "O",
"𝟘": "O",
"𝟢": "O",
"𝟬": "O",
"𝟶": "O",
"🯰": "O",
"O": "O",
"𝐎": "O",
"𝑂": "O",
"𝑶": "O",
"𝒪": "O",
"𝓞": "O",
"𝔒": "O",
"𝕆": "O",
"𝕺": "O",
"𝖮": "O",
"𝗢": "O",
"𝘖": "O",
"𝙊": "O",
"𝙾": "O",
"Ο": "O",
"𝚶": "O",
"𝛰": "O",
"𝜪": "O",
"𝝤": "O",
"𝞞": "O",
"Ⲟ": "O",
"О": "O",
"Օ": "O",
"ⵔ": "O",
"ዐ": "O",
"ଠ": "O",
"𐓂": "O",
"ꓳ": "O",
"𑢵": "O",
"𐊒": "O",
"𐊫": "O",
"𐐄": "O",
"𐔖": "O",
"⁰": "º",
"ᵒ": "º",
"ǒ": "ŏ",
"Ǒ": "Ŏ",
"ۿ": "ô",
"Ő": "Ö",
"ø": "o̸",
"ꬾ": "o̸",
"Ø": "O̸",
"ⵁ": "O̸",
"Ǿ": "Ó̸",
"ɵ": "o̵",
"ꝋ": "o̵",
"ө": "o̵",
"ѳ": "o̵",
"ꮎ": "o̵",
"ꮻ": "o̵",
"⊖": "O̵",
"⊝": "O̵",
"⍬": "O̵",
"𝈚": "O̵",
"🜔": "O̵",
"Ɵ": "O̵",
"Ꝋ": "O̵",
"θ": "O̵",
"ϑ": "O̵",
"𝛉": "O̵",
"𝛝": "O̵",
"𝜃": "O̵",
"𝜗": "O̵",
"𝜽": "O̵",
"𝝑": "O̵",
"𝝷": "O̵",
"𝞋": "O̵",
"𝞱": "O̵",
"𝟅": "O̵",
"Θ": "O̵",
"ϴ": "O̵",
"𝚯": "O̵",
"𝚹": "O̵",
"𝛩": "O̵",
"𝛳": "O̵",
"𝜣": "O̵",
"𝜭": "O̵",
"𝝝": "O̵",
"𝝧": "O̵",
"𝞗": "O̵",
"𝞡": "O̵",
"Ө": "O̵",
"Ѳ": "O̵",
"ⴱ": "O̵",
"Ꮎ": "O̵",
"Ꮻ": "O̵",
"ꭴ": "ơ",
"ﳙ": "oٰ",
"🄁": "O,",
"🄀": "O.",
"ơ": "o'",
"Ơ": "O'",
"Ꭴ": "O'",
"%": "º/₀",
"٪": "º/₀",
"⁒": "º/₀",
"‰": "º/₀₀",
"؉": "º/₀₀",
"‱": "º/₀₀₀",
"؊": "º/₀₀₀",
"œ": "oe",
"Œ": "OE",
"ɶ": "oᴇ",
"∞": "oo",
"ꝏ": "oo",
"ꚙ": "oo",
"Ꝏ": "OO",
"Ꚙ": "OO",
"ﳗ": "oج",
"ﱑ": "oج",
"ﳘ": "oم",
"ﱒ": "oم",
"ﶓ": "oمج",
"ﶔ": "oمم",
"ﱓ": "oى",
"ﱔ": "oى",
"ൟ": "oരo",
"တ": "oာ",
"㍘": "O点",
"ↄ": "ɔ",
"ᴐ": "ɔ",
"ͻ": "ɔ",
"𐑋": "ɔ",
"Ↄ": "Ɔ",
"Ͻ": "Ɔ",
"ꓛ": "Ɔ",
"𐐣": "Ɔ",
"ꬿ": "ɔ̸",
"ꭢ": "ɔe",
"𐐿": "ɷ",
"⍴": "p",
"p": "p",
"𝐩": "p",
"𝑝": "p",
"𝒑": "p",
"𝓅": "p",
"𝓹": "p",
"𝔭": "p",
"𝕡": "p",
"𝖕": "p",
"𝗉": "p",
"𝗽": "p",
"𝘱": "p",
"𝙥": "p",
"𝚙": "p",
"ρ": "p",
"ϱ": "p",
"𝛒": "p",
"𝛠": "p",
"𝜌": "p",
"𝜚": "p",
"𝝆": "p",
"𝝔": "p",
"𝞀": "p",
"𝞎": "p",
"𝞺": "p",
"𝟈": "p",
"ⲣ": "p",
"р": "p",
"P": "P",
"ℙ": "P",
"𝐏": "P",
"𝑃": "P",
"𝑷": "P",
"𝒫": "P",
"𝓟": "P",
"𝔓": "P",
"𝕻": "P",
"𝖯": "P",
"𝗣": "P",
"𝘗": "P",
"𝙋": "P",
"𝙿": "P",
"Ρ": "P",
"𝚸": "P",
"𝛲": "P",
"𝜬": "P",
"𝝦": "P",
"𝞠": "P",
"Ⲣ": "P",
"Р": "P",
"Ꮲ": "P",
"ᑭ": "P",
"ꓑ": "P",
"𐊕": "P",
"ƥ": "p̔",
"ᵽ": "p̵",
"ᑷ": "p·",
"ᒆ": "P'",
"ᴩ": "ᴘ",
"ꮲ": "ᴘ",
"φ": "ɸ",
"ϕ": "ɸ",
"𝛗": "ɸ",
"𝛟": "ɸ",
"𝜑": "ɸ",
"𝜙": "ɸ",
"𝝋": "ɸ",
"𝝓": "ɸ",
"𝞅": "ɸ",
"𝞍": "ɸ",
"𝞿": "ɸ",
"𝟇": "ɸ",
"ⲫ": "ɸ",
"ф": "ɸ",
"𝐪": "q",
"𝑞": "q",
"𝒒": "q",
"𝓆": "q",
"𝓺": "q",
"𝔮": "q",
"𝕢": "q",
"𝖖": "q",
"𝗊": "q",
"𝗾": "q",
"𝘲": "q",
"𝙦": "q",
"𝚚": "q",
"ԛ": "q",
"գ": "q",
"զ": "q",
"ℚ": "Q",
"𝐐": "Q",
"𝑄": "Q",
"𝑸": "Q",
"𝒬": "Q",
"𝓠": "Q",
"𝔔": "Q",
"𝕼": "Q",
"𝖰": "Q",
"𝗤": "Q",
"𝘘": "Q",
"𝙌": "Q",
"𝚀": "Q",
"ⵕ": "Q",
"ʠ": "q̔",
"🜀": "QE",
"ᶐ": "ɋ",
"ᴋ": "ĸ",
"κ": "ĸ",
"ϰ": "ĸ",
"𝛋": "ĸ",
"𝛞": "ĸ",
"𝜅": "ĸ",
"𝜘": "ĸ",
"𝜿": "ĸ",
"𝝒": "ĸ",
"𝝹": "ĸ",
"𝞌": "ĸ",
"𝞳": "ĸ",
"𝟆": "ĸ",
"ⲕ": "ĸ",
"к": "ĸ",
"ꮶ": "ĸ",
"қ": "ĸ̩",
"ҟ": "ĸ̵",
"𝐫": "r",
"𝑟": "r",
"𝒓": "r",
"𝓇": "r",
"𝓻": "r",
"𝔯": "r",
"𝕣": "r",
"𝖗": "r",
"𝗋": "r",
"𝗿": "r",
"𝘳": "r",
"𝙧": "r",
"𝚛": "r",
"ꭇ": "r",
"ꭈ": "r",
"ᴦ": "r",
"ⲅ": "r",
"г": "r",
"ꮁ": "r",
"𝈖": "R",
"ℛ": "R",
"ℜ": "R",
"ℝ": "R",
"𝐑": "R",
"𝑅": "R",
"𝑹": "R",
"𝓡": "R",
"𝕽": "R",
"𝖱": "R",
"𝗥": "R",
"𝘙": "R",
"𝙍": "R",
"𝚁": "R",
"Ʀ": "R",
"Ꭱ": "R",
"Ꮢ": "R",
"𐒴": "R",
"ᖇ": "R",
"ꓣ": "R",
"𖼵": "R",
"ɽ": "r̨",
"ɼ": "r̩",
"ɍ": "r̵",
"ғ": "r̵",
"ᵲ": "r̴",
"ґ": "r'",
"𑣣": "rn",
"m": "rn",
"ⅿ": "rn",
"𝐦": "rn",
"𝑚": "rn",
"𝒎": "rn",
"𝓂": "rn",
"𝓶": "rn",
"𝔪": "rn",
"𝕞": "rn",
"𝖒": "rn",
"𝗆": "rn",
"𝗺": "rn",
"𝘮": "rn",
"𝙢": "rn",
"𝚖": "rn",
"𑜀": "rn",
"₥": "rn̸",
"ɱ": "rn̦",
"ᵯ": "rn̴",
"₨": "Rs",
"ꭱ": "ʀ",
"ꮢ": "ʀ",
"я": "ᴙ",
"ᵳ": "ɾ̴",
"℩": "ɿ",
"s": "s",
"𝐬": "s",
"𝑠": "s",
"𝒔": "s",
"𝓈": "s",
"𝓼": "s",
"𝔰": "s",
"𝕤": "s",
"𝖘": "s",
"𝗌": "s",
"𝘀": "s",
"𝘴": "s",
"𝙨": "s",
"𝚜": "s",
"ꜱ": "s",
"ƽ": "s",
"ѕ": "s",
"ꮪ": "s",
"𑣁": "s",
"𐑈": "s",
"S": "S",
"𝐒": "S",
"𝑆": "S",
"𝑺": "S",
"𝒮": "S",
"𝓢": "S",
"𝔖": "S",
"𝕊": "S",
"𝕾": "S",
"𝖲": "S",
"𝗦": "S",
"𝘚": "S",
"𝙎": "S",
"𝚂": "S",
"Ѕ": "S",
"Տ": "S",
"Ꮥ": "S",
"Ꮪ": "S",
"ꓢ": "S",
"𖼺": "S",
"𐊖": "S",
"𐐠": "S",
"ʂ": "s̨",
"ᵴ": "s̴",
"ꞵ": "ß",
"β": "ß",
"ϐ": "ß",
"𝛃": "ß",
"𝛽": "ß",
"𝜷": "ß",
"𝝱": "ß",
"𝞫": "ß",
"Ᏸ": "ß",
"🝜": "sss",
"st": "st",
"∫": "ʃ",
"ꭍ": "ʃ",
"∑": "Ʃ",
"⅀": "Ʃ",
"Σ": "Ʃ",
"𝚺": "Ʃ",
"𝛴": "Ʃ",
"𝜮": "Ʃ",
"𝝨": "Ʃ",
"𝞢": "Ʃ",
"ⵉ": "Ʃ",
"∬": "ʃʃ",
"∭": "ʃʃʃ",
"⨌": "ʃʃʃʃ",
"𝐭": "t",
"𝑡": "t",
"𝒕": "t",
"𝓉": "t",
"𝓽": "t",
"𝔱": "t",
"𝕥": "t",
"𝖙": "t",
"𝗍": "t",
"𝘁": "t",
"𝘵": "t",
"𝙩": "t",
"𝚝": "t",
"⊤": "T",
"⟙": "T",
"🝨": "T",
"T": "T",
"𝐓": "T",
"𝑇": "T",
"𝑻": "T",
"𝒯": "T",
"𝓣": "T",
"𝔗": "T",
"𝕋": "T",
"𝕿": "T",
"𝖳": "T",
"𝗧": "T",
"𝘛": "T",
"𝙏": "T",
"𝚃": "T",
"Τ": "T",
"𝚻": "T",
"𝛵": "T",
"𝜯": "T",
"𝝩": "T",
"𝞣": "T",
"Ⲧ": "T",
"Т": "T",
"Ꭲ": "T",
"ꓔ": "T",
"𖼊": "T",
"𑢼": "T",
"𐊗": "T",
"𐊱": "T",
"𐌕": "T",
"ƭ": "t̔",
"⍡": "T̈",
"Ⱦ": "T̸",
"Ț": "Ţ",
"Ʈ": "T̨",
"Ҭ": "T̩",
"₮": "T⃫",
"ŧ": "t̵",
"Ŧ": "T̵",
"ᵵ": "t̴",
"Ⴀ": "Ꞇ",
"Ꜩ": "T3",
"ʨ": "tɕ",
"℡": "TEL",
"ꝷ": "tf",
"ʦ": "ts",
"ʧ": "tʃ",
"ꜩ": "tȝ",
"τ": "ᴛ",
"𝛕": "ᴛ",
"𝜏": "ᴛ",
"𝝉": "ᴛ",
"𝞃": "ᴛ",
"𝞽": "ᴛ",
"т": "ᴛ",
"ꭲ": "ᴛ",
"ҭ": "ᴛ̩",
"ţ": "ƫ",
"ț": "ƫ",
"Ꮏ": "ƫ",
"𝐮": "u",
"𝑢": "u",
"𝒖": "u",
"𝓊": "u",
"𝓾": "u",
"𝔲": "u",
"𝕦": "u",
"𝖚": "u",
"𝗎": "u",
"𝘂": "u",
"𝘶": "u",
"𝙪": "u",
"𝚞": "u",
"ꞟ": "u",
"ᴜ": "u",
"ꭎ": "u",
"ꭒ": "u",
"ʋ": "u",
"υ": "u",
"𝛖": "u",
"𝜐": "u",
"𝝊": "u",
"𝞄": "u",
"𝞾": "u",
"ս": "u",
"𐓶": "u",
"𑣘": "u",
"∪": "U",
"⋃": "U",
"𝐔": "U",
"𝑈": "U",
"𝑼": "U",
"𝒰": "U",
"𝓤": "U",
"𝔘": "U",
"𝕌": "U",
"𝖀": "U",
"𝖴": "U",
"𝗨": "U",
"𝘜": "U",
"𝙐": "U",
"𝚄": "U",
"Ս": "U",
"ሀ": "U",
"𐓎": "U",
"ᑌ": "U",
"ꓴ": "U",
"𖽂": "U",
"𑢸": "U",
"ǔ": "ŭ",
"Ǔ": "Ŭ",
"ᵾ": "u̵",
"ꮜ": "u̵",
"Ʉ": "U̵",
"Ꮜ": "U̵",
"ᑘ": "U·",
"ᑧ": "U'",
"ᵫ": "ue",
"ꭣ": "uo",
"ṃ": "ꭑ",
"պ": "ɰ",
"ሣ": "ɰ",
"℧": "Ʊ",
"ᘮ": "Ʊ",
"ᘴ": "Ʊ",
"ᵿ": "ʊ̵",
"∨": "v",
"⋁": "v",
"v": "v",
"ⅴ": "v",
"𝐯": "v",
"𝑣": "v",
"𝒗": "v",
"𝓋": "v",
"𝓿": "v",
"𝔳": "v",
"𝕧": "v",
"𝖛": "v",
"𝗏": "v",
"𝘃": "v",
"𝘷": "v",
"𝙫": "v",
"𝚟": "v",
"ᴠ": "v",
"ν": "v",
"𝛎": "v",
"𝜈": "v",
"𝝂": "v",
"𝝼": "v",
"𝞶": "v",
"ѵ": "v",
"ט": "v",
"𑜆": "v",
"ꮩ": "v",
"𑣀": "v",
"𝈍": "V",
"٧": "V",
"۷": "V",
"Ⅴ": "V",
"𝐕": "V",
"𝑉": "V",
"𝑽": "V",
"𝒱": "V",
"𝓥": "V",
"𝔙": "V",
"𝕍": "V",
"𝖁": "V",
"𝖵": "V",
"𝗩": "V",
"𝘝": "V",
"𝙑": "V",
"𝚅": "V",
"Ѵ": "V",
"ⴸ": "V",
"Ꮩ": "V",
"ᐯ": "V",
"ꛟ": "V",
"ꓦ": "V",
"𖼈": "V",
"𑢠": "V",
"𐔝": "V",
"𐆗": "V̵",
"ᐻ": "V·",
"🝬": "VB",
"ⅵ": "vi",
"ⅶ": "vii",
"ⅷ": "viii",
"Ⅵ": "Vl",
"Ⅶ": "Vll",
"Ⅷ": "Vlll",
"🜈": "Vᷤ",
"ᴧ": "ʌ",
"𐓘": "ʌ",
"٨": "Ʌ",
"۸": "Ʌ",
"Λ": "Ʌ",
"𝚲": "Ʌ",
"𝛬": "Ʌ",
"𝜦": "Ʌ",
"𝝠": "Ʌ",
"𝞚": "Ʌ",
"Л": "Ʌ",
"ⴷ": "Ʌ",
"𐒰": "Ʌ",
"ᐱ": "Ʌ",
"ꛎ": "Ʌ",
"ꓥ": "Ʌ",
"𖼽": "Ʌ",
"𐊍": "Ʌ",
"Ӆ": "Ʌ̦",
"ᐽ": "Ʌ·",
"ɯ": "w",
"𝐰": "w",
"𝑤": "w",
"𝒘": "w",
"𝓌": "w",
"𝔀": "w",
"𝔴": "w",
"𝕨": "w",
"𝖜": "w",
"𝗐": "w",
"𝘄": "w",
"𝘸": "w",
"𝙬": "w",
"𝚠": "w",
"ᴡ": "w",
"ѡ": "w",
"ԝ": "w",
"ա": "w",
"𑜊": "w",
"𑜎": "w",
"𑜏": "w",
"ꮃ": "w",
"𑣯": "W",
"𑣦": "W",
"𝐖": "W",
"𝑊": "W",
"𝑾": "W",
"𝒲": "W",
"𝓦": "W",
"𝔚": "W",
"𝕎": "W",
"𝖂": "W",
"𝖶": "W",
"𝗪": "W",
"𝘞": "W",
"𝙒": "W",
"𝚆": "W",
"Ԝ": "W",
"Ꮃ": "W",
"Ꮤ": "W",
"ꓪ": "W",
"ѽ": "w҆҇",
"𑓅": "ẇ",
"₩": "W̵",
"ꝡ": "w̦",
"ᴍ": "ʍ",
"м": "ʍ",
"ꮇ": "ʍ",
"ӎ": "ʍ̦",
"᙮": "x",
"×": "x",
"⤫": "x",
"⤬": "x",
"⨯": "x",
"x": "x",
"ⅹ": "x",
"𝐱": "x",
"𝑥": "x",
"𝒙": "x",
"𝓍": "x",
"𝔁": "x",
"𝔵": "x",
"𝕩": "x",
"𝖝": "x",
"𝗑": "x",
"𝘅": "x",
"𝘹": "x",
"𝙭": "x",
"𝚡": "x",
"х": "x",
"ᕁ": "x",
"ᕽ": "x",
"ⷯ": "ͯ",
"᙭": "X",
"╳": "X",
"𐌢": "X",
"𑣬": "X",
"X": "X",
"Ⅹ": "X",
"𝐗": "X",
"𝑋": "X",
"𝑿": "X",
"𝒳": "X",
"𝓧": "X",
"𝔛": "X",
"𝕏": "X",
"𝖃": "X",
"𝖷": "X",
"𝗫": "X",
"𝘟": "X",
"𝙓": "X",
"𝚇": "X",
"Ꭓ": "X",
"Χ": "X",
"𝚾": "X",
"𝛸": "X",
"𝜲": "X",
"𝝬": "X",
"𝞦": "X",
"Ⲭ": "X",
"Х": "X",
"ⵝ": "X",
"ᚷ": "X",
"ꓫ": "X",
"𐊐": "X",
"𐊴": "X",
"𐌗": "X",
"𐔧": "X",
"⨰": "ẋ",
"Ҳ": "X̩",
"𐆖": "X̵",
"ⅺ": "xi",
"ⅻ": "xii",
"Ⅺ": "Xl",
"Ⅻ": "Xll",
"ɣ": "y",
"ᶌ": "y",
"y": "y",
"𝐲": "y",
"𝑦": "y",
"𝒚": "y",
"𝓎": "y",
"𝔂": "y",
"𝔶": "y",
"𝕪": "y",
"𝖞": "y",
"𝗒": "y",
"𝘆": "y",
"𝘺": "y",
"𝙮": "y",
"𝚢": "y",
"ʏ": "y",
"ỿ": "y",
"ꭚ": "y",
"γ": "y",
"ℽ": "y",
"𝛄": "y",
"𝛾": "y",
"𝜸": "y",
"𝝲": "y",
"𝞬": "y",
"у": "y",
"ү": "y",
"ყ": "y",
"𑣜": "y",
"Y": "Y",
"𝐘": "Y",
"𝑌": "Y",
"𝒀": "Y",
"𝒴": "Y",
"𝓨": "Y",
"𝔜": "Y",
"𝕐": "Y",
"𝖄": "Y",
"𝖸": "Y",
"𝗬": "Y",
"𝘠": "Y",
"𝙔": "Y",
"𝚈": "Y",
"Υ": "Y",
"ϒ": "Y",
"𝚼": "Y",
"𝛶": "Y",
"𝜰": "Y",
"𝝪": "Y",
"𝞤": "Y",
"Ⲩ": "Y",
"У": "Y",
"Ү": "Y",
"Ꭹ": "Y",
"Ꮍ": "Y",
"ꓬ": "Y",
"𖽃": "Y",
"𑢤": "Y",
"𐊲": "Y",
"ƴ": "y̔",
"ɏ": "y̵",
"ұ": "y̵",
"¥": "Y̵",
"Ɏ": "Y̵",
"Ұ": "Y̵",
"ʒ": "ȝ",
"ꝫ": "ȝ",
"ⳍ": "ȝ",
"ӡ": "ȝ",
"ჳ": "ȝ",
"𝐳": "z",
"𝑧": "z",
"𝒛": "z",
"𝓏": "z",
"𝔃": "z",
"𝔷": "z",
"𝕫": "z",
"𝖟": "z",
"𝗓": "z",
"𝘇": "z",
"𝘻": "z",
"𝙯": "z",
"𝚣": "z",
"ᴢ": "z",
"ꮓ": "z",
"𑣄": "z",
"𐋵": "Z",
"𑣥": "Z",
"Z": "Z",
"ℤ": "Z",
"ℨ": "Z",
"𝐙": "Z",
"𝑍": "Z",
"𝒁": "Z",
"𝒵": "Z",
"𝓩": "Z",
"𝖅": "Z",
"𝖹": "Z",
"𝗭": "Z",
"𝘡": "Z",
"𝙕": "Z",
"𝚉": "Z",
"Ζ": "Z",
"𝚭": "Z",
"𝛧": "Z",
"𝜡": "Z",
"𝝛": "Z",
"𝞕": "Z",
"Ꮓ": "Z",
"ꓜ": "Z",
"𑢩": "Z",
"ʐ": "z̨",
"ƶ": "z̵",
"Ƶ": "Z̵",
"ȥ": "z̦",
"Ȥ": "Z̦",
"ᵶ": "z̴",
"ƿ": "þ",
"ϸ": "þ",
"Ϸ": "Þ",
"𐓄": "Þ",
"⁹": "ꝰ",
"ᴤ": "ƨ",
"ϩ": "ƨ",
"ꙅ": "ƨ",
"ь": "ƅ",
"ꮟ": "ƅ",
"ы": "ƅi",
"ꭾ": "ɂ",
"ˤ": "ˁ",
"ꛍ": "ʡ",
"⊙": "ʘ",
"☉": "ʘ",
"⨀": "ʘ",
"Ꙩ": "ʘ",
"ⵙ": "ʘ",
"𐓃": "ʘ",
"ℾ": "Γ",
"𝚪": "Γ",
"𝛤": "Γ",
"𝜞": "Γ",
"𝝘": "Γ",
"𝞒": "Γ",
"Ⲅ": "Γ",
"Г": "Γ",
"Ꮁ": "Γ",
"ᒥ": "Γ",
"𖼇": "Γ",
"Ғ": "Γ̵",
"ᒯ": "Γ·",
"Ґ": "Γ'",
"∆": "Δ",
"△": "Δ",
"🜂": "Δ",
"𝚫": "Δ",
"𝛥": "Δ",
"𝜟": "Δ",
"𝝙": "Δ",
"𝞓": "Δ",
"Ⲇ": "Δ",
"ⵠ": "Δ",
"ᐃ": "Δ",
"𖼚": "Δ",
"𐊅": "Δ",
"𐊣": "Δ",
"⍙": "Δ̲",
"ᐏ": "Δ·",
"ᐬ": "Δᐠ",
"𝟋": "ϝ",
"𝛇": "ζ",
"𝜁": "ζ",
"𝜻": "ζ",
"𝝵": "ζ",
"𝞯": "ζ",
"ⳤ": "ϗ",
"𝛌": "λ",
"𝜆": "λ",
"𝝀": "λ",
"𝝺": "λ",
"𝞴": "λ",
"Ⲗ": "λ",
"𐓛": "λ",
"µ": "μ",
"𝛍": "μ",
"𝜇": "μ",
"𝝁": "μ",
"𝝻": "μ",
"𝞵": "μ",
"𝛏": "ξ",
"𝜉": "ξ",
"𝝃": "ξ",
"𝝽": "ξ",
"𝞷": "ξ",
"𝚵": "Ξ",
"𝛯": "Ξ",
"𝜩": "Ξ",
"𝝣": "Ξ",
"𝞝": "Ξ",
"ϖ": "π",
"ℼ": "π",
"𝛑": "π",
"𝛡": "π",
"𝜋": "π",
"𝜛": "π",
"𝝅": "π",
"𝝕": "π",
"𝝿": "π",
"𝞏": "π",
"𝞹": "π",
"𝟉": "π",
"ᴨ": "π",
"п": "π",
"∏": "Π",
"ℿ": "Π",
"𝚷": "Π",
"𝛱": "Π",
"𝜫": "Π",
"𝝥": "Π",
"𝞟": "Π",
"Ⲡ": "Π",
"П": "Π",
"ꛛ": "Π",
"𐊭": "Ϙ",
"𐌒": "Ϙ",
"ϛ": "ς",
"𝛓": "ς",
"𝜍": "ς",
"𝝇": "ς",
"𝞁": "ς",
"𝞻": "ς",
"𝚽": "Φ",
"𝛷": "Φ",
"𝜱": "Φ",
"𝝫": "Φ",
"𝞥": "Φ",
"Ⲫ": "Φ",
"Ф": "Φ",
"Փ": "Φ",
"ቀ": "Φ",
"ᛰ": "Φ",
"𐊳": "Φ",
"ꭓ": "χ",
"ꭕ": "χ",
"𝛘": "χ",
"𝜒": "χ",
"𝝌": "χ",
"𝞆": "χ",
"𝟀": "χ",
"ⲭ": "χ",
"𝛙": "ψ",
"𝜓": "ψ",
"𝝍": "ψ",
"𝞇": "ψ",
"𝟁": "ψ",
"ѱ": "ψ",
"𐓹": "ψ",
"𝚿": "Ψ",
"𝛹": "Ψ",
"𝜳": "Ψ",
"𝝭": "Ψ",
"𝞧": "Ψ",
"Ⲯ": "Ψ",
"Ѱ": "Ψ",
"𐓑": "Ψ",
"ᛘ": "Ψ",
"𐊵": "Ψ",
"⍵": "ω",
"ꞷ": "ω",
"𝛚": "ω",
"𝜔": "ω",
"𝝎": "ω",
"𝞈": "ω",
"𝟂": "ω",
"ⲱ": "ω",
"ꙍ": "ω",
"Ω": "Ω",
"𝛀": "Ω",
"𝛺": "Ω",
"𝜴": "Ω",
"𝝮": "Ω",
"𝞨": "Ω",
"ᘯ": "Ω",
"ᘵ": "Ω",
"𐊶": "Ω",
"⍹": "ω̲",
"ώ": "ῴ",
"☰": "Ⲷ",
"Ⳝ": "Ϭ",
"җ": "ж̩",
"Җ": "Ж̩",
"𝈋": "И",
"Ͷ": "И",
"ꚡ": "И",
"𐐥": "И",
"Й": "Ѝ",
"Ҋ": "Ѝ̦",
"ѝ": "й",
"ҋ": "й̦",
"𐒼": "Ӄ",
"ᴫ": "л",
"ӆ": "л̦",
"ꭠ": "љ",
"𐓫": "ꙩ",
"ᷮ": "ⷬ",
"𐓍": "Ћ",
"𝈂": "Ӿ",
"𝈢": "Ѡ",
"Ꮗ": "Ѡ",
"ᗯ": "Ѡ",
"Ѽ": "Ѡ҆҇",
"ᣭ": "Ѡ·",
"Ꞷ": "Ꙍ",
"ӌ": "ҷ",
"Ӌ": "Ҷ",
"Ҿ": "Ҽ̨",
"ⲽ": "ш",
"Ⲽ": "Ш",
"Ꙑ": "Ъl",
"℈": "Э",
"🜁": "Ꙙ",
"𖼜": "Ꙙ",
"ꦒ": "ⰿ",
"և": "եւ",
"ኔ": "ձ",
"ﬔ": "մե",
"ﬕ": "մի",
"ﬗ": "մխ",
"ﬓ": "մն",
"∩": "Ո",
"⋂": "Ո",
"𝉅": "Ո",
"በ": "Ո",
"ᑎ": "Ո",
"ꓵ": "Ո",
"ᑚ": "Ո·",
"ᑨ": "Ո'",
"ﬖ": "վն",
"₽": "Ք",
"˓": "ՙ",
"ʿ": "ՙ",
"ℵ": "א",
"ﬡ": "א",
"אָ": "אַ",
"אּ": "אַ",
"ﭏ": "אל",
"ℶ": "ב",
"ℷ": "ג",
"ℸ": "ד",
"ﬢ": "ד",
"ﬣ": "ה",
"יּ": "יִ",
"ﬤ": "כ",
"ﬥ": "ל",
"ﬦ": "ם",
"ﬠ": "ע",
"ﬧ": "ר",
"שׂ": "שׁ",
"שּ": "שׁ",
"שּׂ": "שּׁ",
"ﬨ": "ת",
"ﺀ": "ء",
"۽": "ء͈",
"ﺂ": "آ",
"ﺁ": "آ",
"ﭑ": "ٱ",
"ﭐ": "ٱ",
"𞸁": "ب",
"𞸡": "ب",
"𞹡": "ب",
"𞺁": "ب",
"𞺡": "ب",
"ﺑ": "ب",
"ﺒ": "ب",
"ﺐ": "ب",
"ﺏ": "ب",
"ݑ": "بۛ",
"ࢶ": "بۢ",
"ࢡ": "بٔ",
"ﲠ": "بo",
"ﳢ": "بo",
"ﲜ": "بج",
"ﰅ": "بج",
"ﲝ": "بح",
"ﰆ": "بح",
"ﷂ": "بحى",
"ﲞ": "بخ",
"ﰇ": "بخ",
"ﳒ": "بخ",
"ﱋ": "بخ",
"ﶞ": "بخى",
"ﱪ": "بر",
"ﱫ": "بز",
"ﲟ": "بم",
"ﳡ": "بم",
"ﱬ": "بم",
"ﰈ": "بم",
"ﱭ": "بن",
"ﱮ": "بى",
"ﰉ": "بى",
"ﱯ": "بى",
"ﰊ": "بى",
"ﭔ": "ٻ",
"ﭕ": "ٻ",
"ﭓ": "ٻ",
"ﭒ": "ٻ",
"ې": "ٻ",
"ﯦ": "ٻ",
"ﯧ": "ٻ",
"ﯥ": "ٻ",
"ﯤ": "ٻ",
"ﭜ": "ڀ",
"ﭝ": "ڀ",
"ﭛ": "ڀ",
"ﭚ": "ڀ",
"ࢩ": "ݔ",
"ݧ": "ݔ",
"⍥": "ة",
"ö": "ة",
"ﺔ": "ة",
"ﺓ": "ة",
"ۃ": "ة",
"𞸕": "ت",
"𞸵": "ت",
"𞹵": "ت",
"𞺕": "ت",
"𞺵": "ت",
"ﺗ": "ت",
"ﺘ": "ت",
"ﺖ": "ت",
"ﺕ": "ت",
"ﲥ": "تo",
"ﳤ": "تo",
"ﲡ": "تج",
"ﰋ": "تج",
"ﵐ": "تجم",
"ﶠ": "تجى",
"ﶟ": "تجى",
"ﲢ": "تح",
"ﰌ": "تح",
"ﵒ": "تحج",
"ﵑ": "تحج",
"ﵓ": "تحم",
"ﲣ": "تخ",
"ﰍ": "تخ",
"ﵔ": "تخم",
"ﶢ": "تخى",
"ﶡ": "تخى",
"ﱰ": "تر",
"ﱱ": "تز",
"ﲤ": "تم",
"ﳣ": "تم",
"ﱲ": "تم",
"ﰎ": "تم",
"ﵕ": "تمج",
"ﵖ": "تمح",
"ﵗ": "تمخ",
"ﶤ": "تمى",
"ﶣ": "تمى",
"ﱳ": "تن",
"ﱴ": "تى",
"ﰏ": "تى",
"ﱵ": "تى",
"ﰐ": "تى",
"ﭠ": "ٺ",
"ﭡ": "ٺ",
"ﭟ": "ٺ",
"ﭞ": "ٺ",
"ﭤ": "ٿ",
"ﭥ": "ٿ",
"ﭣ": "ٿ",
"ﭢ": "ٿ",
"𞸂": "ج",
"𞸢": "ج",
"𞹂": "ج",
"𞹢": "ج",
"𞺂": "ج",
"𞺢": "ج",
"ﺟ": "ج",
"ﺠ": "ج",
"ﺞ": "ج",
"ﺝ": "ج",
"ﲧ": "جح",
"ﰕ": "جح",
"ﶦ": "جحى",
"ﶾ": "جحى",
"ﷻ": "جل جلlلo",
"ﲨ": "جم",
"ﰖ": "جم",
"ﵙ": "جمح",
"ﵘ": "جمح",
"ﶧ": "جمى",
"ﶥ": "جمى",
"ﴝ": "جى",
"ﴁ": "جى",
"ﴞ": "جى",
"ﴂ": "جى",
"ﭸ": "ڃ",
"ﭹ": "ڃ",
"ﭷ": "ڃ",
"ﭶ": "ڃ",
"ﭴ": "ڄ",
"ﭵ": "ڄ",
"ﭳ": "ڄ",
"ﭲ": "ڄ",
"ﭼ": "چ",
"ﭽ": "چ",
"ﭻ": "چ",
"ﭺ": "چ",
"ﮀ": "ڇ",
"ﮁ": "ڇ",
"ﭿ": "ڇ",
"ﭾ": "ڇ",
"𞸇": "ح",
"𞸧": "ح",
"𞹇": "ح",
"𞹧": "ح",
"𞺇": "ح",
"𞺧": "ح",
"ﺣ": "ح",
"ﺤ": "ح",
"ﺢ": "ح",
"ﺡ": "ح",
"څ": "حۛ",
"ځ": "حٔ",
"ݲ": "حٔ",
"ﲩ": "حج",
"ﰗ": "حج",
"ﶿ": "حجى",
"ﲪ": "حم",
"ﰘ": "حم",
"ﵛ": "حمى",
"ﵚ": "حمى",
"ﴛ": "حى",
"ﳿ": "حى",
"ﴜ": "حى",
"ﴀ": "حى",
"𞸗": "خ",
"𞸷": "خ",
"𞹗": "خ",
"𞹷": "خ",
"𞺗": "خ",
"𞺷": "خ",
"ﺧ": "خ",
"ﺨ": "خ",
"ﺦ": "خ",
"ﺥ": "خ",
"ﲫ": "خج",
"ﰙ": "خج",
"ﰚ": "خح",
"ﲬ": "خم",
"ﰛ": "خم",
"ﴟ": "خى",
"ﴃ": "خى",
"ﴠ": "خى",
"ﴄ": "خى",
"𐋡": "د",
"𞸃": "د",
"𞺃": "د",
"𞺣": "د",
"ﺪ": "د",
"ﺩ": "د",
"ڈ": "دؕ",
"ﮉ": "دؕ",
"ﮈ": "دؕ",
"ڎ": "دۛ",
"ﮇ": "دۛ",
"ﮆ": "دۛ",
"ۮ": "د̂",
"ࢮ": "د̤̣",
"𞸘": "ذ",
"𞺘": "ذ",
"𞺸": "ذ",
"ﺬ": "ذ",
"ﺫ": "ذ",
"ﱛ": "ذٰ",
"ڋ": "ڊؕ",
"ﮅ": "ڌ",
"ﮄ": "ڌ",
"ﮃ": "ڍ",
"ﮂ": "ڍ",
"𞸓": "ر",
"𞺓": "ر",
"𞺳": "ر",
"ﺮ": "ر",
"ﺭ": "ر",
"ڑ": "رؕ",
"ﮍ": "رؕ",
"ﮌ": "رؕ",
"ژ": "رۛ",
"ﮋ": "رۛ",
"ﮊ": "رۛ",
"ڒ": "ر̆",
"ࢹ": "ر̆̇",
"ۯ": "ر̂",
"ݬ": "رٔ",
"ﱜ": "رٰ",
"ﷶ": "رسول",
"﷼": "رىlل",
"𞸆": "ز",
"𞺆": "ز",
"𞺦": "ز",
"ﺰ": "ز",
"ﺯ": "ز",
"ࢲ": "ز̂",
"ݱ": "ڗؕ",
"𞸎": "س",
"𞸮": "س",
"𞹎": "س",
"𞹮": "س",
"𞺎": "س",
"𞺮": "س",
"ﺳ": "س",
"ﺴ": "س",
"ﺲ": "س",
"ﺱ": "س",
"ش": "سۛ",
"𞸔": "سۛ",
"𞸴": "سۛ",
"𞹔": "سۛ",
"𞹴": "سۛ",
"𞺔": "سۛ",
"𞺴": "سۛ",
"ﺷ": "سۛ",
"ﺸ": "سۛ",
"ﺶ": "سۛ",
"ﺵ": "سۛ",
"ݾ": "س̂",
"ﴱ": "سo",
"ﳨ": "سo",
"ﴲ": "سۛo",
"ﳪ": "سۛo",
"ﲭ": "سج",
"ﴴ": "سج",
"ﰜ": "سج",
"ﴭ": "سۛج",
"ﴷ": "سۛج",
"ﴥ": "سۛج",
"ﴉ": "سۛج",
"ﵝ": "سجح",
"ﵞ": "سجى",
"ﵩ": "سۛجى",
"ﲮ": "سح",
"ﴵ": "سح",
"ﰝ": "سح",
"ﴮ": "سۛح",
"ﴸ": "سۛح",
"ﴦ": "سۛح",
"ﴊ": "سۛح",
"ﵜ": "سحج",
"ﵨ": "سۛحم",
"ﵧ": "سۛحم",
"ﶪ": "سۛحى",
"ﲯ": "سخ",
"ﴶ": "سخ",
"ﰞ": "سخ",
"ﴯ": "سۛخ",
"ﴹ": "سۛخ",
"ﴧ": "سۛخ",
"ﴋ": "سۛخ",
"ﶨ": "سخى",
"ﷆ": "سخى",
"ﴪ": "سر",
"ﴎ": "سر",
"ﴩ": "سۛر",
"ﴍ": "سۛر",
"ﲰ": "سم",
"ﳧ": "سم",
"ﰟ": "سم",
"ﴰ": "سۛم",
"ﳩ": "سۛم",
"ﴨ": "سۛم",
"ﴌ": "سۛم",
"ﵡ": "سمج",
"ﵠ": "سمح",
"ﵟ": "سمح",
"ﵫ": "سۛمخ",
"ﵪ": "سۛمخ",
"ﵣ": "سمم",
"ﵢ": "سمم",
"ﵭ": "سۛمم",
"ﵬ": "سۛمم",
"ﴗ": "سى",
"ﳻ": "سى",
"ﴘ": "سى",
"ﳼ": "سى",
"ﴙ": "سۛى",
"ﳽ": "سۛى",
"ﴚ": "سۛى",
"ﳾ": "سۛى",
"𐋲": "ص",
"𞸑": "ص",
"𞸱": "ص",
"𞹑": "ص",
"𞹱": "ص",
"𞺑": "ص",
"𞺱": "ص",
"ﺻ": "ص",
"ﺼ": "ص",
"ﺺ": "ص",
"ﺹ": "ص",
"ڞ": "صۛ",
"ࢯ": "ص̤̣",
"ﲱ": "صح",
"ﰠ": "صح",
"ﵥ": "صحح",
"ﵤ": "صحح",
"ﶩ": "صحى",
"ﲲ": "صخ",
"ﴫ": "صر",
"ﴏ": "صر",
"ﷵ": "صلعم",
"ﷹ": "صلى",
"ﷰ": "صلى",
"ﷺ": "صلى lللo علىo وسلم",
"ﲳ": "صم",
"ﰡ": "صم",
"ﷅ": "صمم",
"ﵦ": "صمم",
"ﴡ": "صى",
"ﴅ": "صى",
"ﴢ": "صى",
"ﴆ": "صى",
"𞸙": "ض",
"𞸹": "ض",
"𞹙": "ض",
"𞹹": "ض",
"𞺙": "ض",
"𞺹": "ض",
"ﺿ": "ض",
"ﻀ": "ض",
"ﺾ": "ض",
"ﺽ": "ض",
"ﲴ": "ضج",
"ﰢ": "ضج",
"ﲵ": "ضح",
"ﰣ": "ضح",
"ﵮ": "ضحى",
"ﶫ": "ضحى",
"ﲶ": "ضخ",
"ﰤ": "ضخ",
"ﵰ": "ضخم",
"ﵯ": "ضخم",
"ﴬ": "ضر",
"ﴐ": "ضر",
"ﲷ": "ضم",
"ﰥ": "ضم",
"ﴣ": "ضى",
"ﴇ": "ضى",
"ﴤ": "ضى",
"ﴈ": "ضى",
"𐋨": "ط",
"𞸈": "ط",
"𞹨": "ط",
"𞺈": "ط",
"𞺨": "ط",
"ﻃ": "ط",
"ﻄ": "ط",
"ﻂ": "ط",
"ﻁ": "ط",
"ڟ": "طۛ",
"ﲸ": "طح",
"ﰦ": "طح",
"ﴳ": "طم",
"ﴺ": "طم",
"ﰧ": "طم",
"ﵲ": "طمح",
"ﵱ": "طمح",
"ﵳ": "طمم",
"ﵴ": "طمى",
"ﴑ": "طى",
"ﳵ": "طى",
"ﴒ": "طى",
"ﳶ": "طى",
"𞸚": "ظ",
"𞹺": "ظ",
"𞺚": "ظ",
"𞺺": "ظ",
"ﻇ": "ظ",
"ﻈ": "ظ",
"ﻆ": "ظ",
"ﻅ": "ظ",
"ﲹ": "ظم",
"ﴻ": "ظم",
"ﰨ": "ظم",
"؏": "ع",
"𞸏": "ع",
"𞸯": "ع",
"𞹏": "ع",
"𞹯": "ع",
"𞺏": "ع",
"𞺯": "ع",
"ﻋ": "ع",
"ﻌ": "ع",
"ﻊ": "ع",
"ﻉ": "ع",
"ﲺ": "عج",
"ﰩ": "عج",
"ﷄ": "عجم",
"ﵵ": "عجم",
"ﷷ": "علىo",
"ﲻ": "عم",
"ﰪ": "عم",
"ﵷ": "عمم",
"ﵶ": "عمم",
"ﵸ": "عمى",
"ﶶ": "عمى",
"ﴓ": "عى",
"ﳷ": "عى",
"ﴔ": "عى",
"ﳸ": "عى",
"𞸛": "غ",
"𞸻": "غ",
"𞹛": "غ",
"𞹻": "غ",
"𞺛": "غ",
"𞺻": "غ",
"ﻏ": "غ",
"ﻐ": "غ",
"ﻎ": "غ",
"ﻍ": "غ",
"ﲼ": "غج",
"ﰫ": "غج",
"ﲽ": "غم",
"ﰬ": "غم",
"ﵹ": "غمم",
"ﵻ": "غمى",
"ﵺ": "غمى",
"ﴕ": "غى",
"ﳹ": "غى",
"ﴖ": "غى",
"ﳺ": "غى",
"𞸐": "ف",
"𞸰": "ف",
"𞹰": "ف",
"𞺐": "ف",
"𞺰": "ف",
"ﻓ": "ف",
"ﻔ": "ف",
"ﻒ": "ف",
"ﻑ": "ف",
"ڧ": "ف",
"ﲾ": "فج",
"ﰭ": "فج",
"ﲿ": "فح",
"ﰮ": "فح",
"ﳀ": "فخ",
"ﰯ": "فخ",
"ﵽ": "فخم",
"ﵼ": "فخم",
"ﳁ": "فم",
"ﰰ": "فم",
"ﷁ": "فمى",
"ﱼ": "فى",
"ﰱ": "فى",
"ﱽ": "فى",
"ﰲ": "فى",
"𞸞": "ڡ",
"𞹾": "ڡ",
"ࢻ": "ڡ",
"ٯ": "ڡ",
"𞸟": "ڡ",
"𞹟": "ڡ",
"ࢼ": "ڡ",
"ڤ": "ڡۛ",
"ﭬ": "ڡۛ",
"ﭭ": "ڡۛ",
"ﭫ": "ڡۛ",
"ﭪ": "ڡۛ",
"ڨ": "ڡۛ",
"ࢤ": "ڢۛ",
"ﭰ": "ڦ",
"ﭱ": "ڦ",
"ﭯ": "ڦ",
"ﭮ": "ڦ",
"𞸒": "ق",
"𞸲": "ق",
"𞹒": "ق",
"𞹲": "ق",
"𞺒": "ق",
"𞺲": "ق",
"ﻗ": "ق",
"ﻘ": "ق",
"ﻖ": "ق",
"ﻕ": "ق",
"ﳂ": "قح",
"ﰳ": "قح",
"ﷱ": "قلى",
"ﳃ": "قم",
"ﰴ": "قم",
"ﶴ": "قمح",
"ﵾ": "قمح",
"ﵿ": "قمم",
"ﶲ": "قمى",
"ﱾ": "قى",
"ﰵ": "قى",
"ﱿ": "قى",
"ﰶ": "قى",
"𞸊": "ك",
"𞸪": "ك",
"𞹪": "ك",
"ﻛ": "ك",
"ﻜ": "ك",
"ﻚ": "ك",
"ﻙ": "ك",
"ک": "ك",
"ﮐ": "ك",
"ﮑ": "ك",
"ﮏ": "ك",
"ﮎ": "ك",
"ڪ": "ك",
"ڭ": "كۛ",
"ﯕ": "كۛ",
"ﯖ": "كۛ",
"ﯔ": "كۛ",
"ﯓ": "كۛ",
"ݣ": "كۛ",
"ﲀ": "كl",
"ﰷ": "كl",
"ﳄ": "كج",
"ﰸ": "كج",
"ﳅ": "كح",
"ﰹ": "كح",
"ﳆ": "كخ",
"ﰺ": "كخ",
"ﳇ": "كل",
"ﳫ": "كل",
"ﲁ": "كل",
"ﰻ": "كل",
"ﳈ": "كم",
"ﳬ": "كم",
"ﲂ": "كم",
"ﰼ": "كم",
"ﷃ": "كمم",
"ﶻ": "كمم",
"ﶷ": "كمى",
"ﲃ": "كى",
"ﰽ": "كى",
"ﲄ": "كى",
"ﰾ": "كى",
"ݢ": "ڬ",
"ﮔ": "گ",
"ﮕ": "گ",
"ﮓ": "گ",
"ﮒ": "گ",
"ࢰ": "گ",
"ڴ": "گۛ",
"ﮜ": "ڱ",
"ﮝ": "ڱ",
"ﮛ": "ڱ",
"ﮚ": "ڱ",
"ﮘ": "ڳ",
"ﮙ": "ڳ",
"ﮗ": "ڳ",
"ﮖ": "ڳ",
"𞸋": "ل",
"𞸫": "ل",
"𞹋": "ل",
"𞺋": "ل",
"𞺫": "ل",
"ﻟ": "ل",
"ﻠ": "ل",
"ﻞ": "ل",
"ﻝ": "ل",
"ڷ": "لۛ",
"ڵ": "ل̆",
"ﻼ": "لl",
"ﻻ": "لl",
"ﻺ": "لlٕ",
"ﻹ": "لlٕ",
"ﻸ": "لlٴ",
"ﻷ": "لlٴ",
"ﳍ": "لo",
"ﻶ": "لآ",
"ﻵ": "لآ",
"ﳉ": "لج",
"ﰿ": "لج",
"ﶃ": "لجج",
"ﶄ": "لجج",
"ﶺ": "لجم",
"ﶼ": "لجم",
"ﶬ": "لجى",
"ﳊ": "لح",
"ﱀ": "لح",
"ﶵ": "لحم",
"ﶀ": "لحم",
"ﶂ": "لحى",
"ﶁ": "لحى",
"ﳋ": "لخ",
"ﱁ": "لخ",
"ﶆ": "لخم",
"ﶅ": "لخم",
"ﳌ": "لم",
"ﳭ": "لم",
"ﲅ": "لم",
"ﱂ": "لم",
"ﶈ": "لمح",
"ﶇ": "لمح",
"ﶭ": "لمى",
"ﲆ": "لى",
"ﱃ": "لى",
"ﲇ": "لى",
"ﱄ": "لى",
"𞸌": "م",
"𞸬": "م",
"𞹬": "م",
"𞺌": "م",
"𞺬": "م",
"ﻣ": "م",
"ﻤ": "م",
"ﻢ": "م",
"ﻡ": "م",
"ࢧ": "مۛ",
"۾": "م͈",
"ﲈ": "مl",
"ﳎ": "مج",
"ﱅ": "مج",
"ﶌ": "مجح",
"ﶒ": "مجخ",
"ﶍ": "مجم",
"ﷀ": "مجى",
"ﳏ": "مح",
"ﱆ": "مح",
"ﶉ": "محج",
"ﶊ": "محم",
"ﷴ": "محمد",
"ﶋ": "محى",
"ﳐ": "مخ",
"ﱇ": "مخ",
"ﶎ": "مخج",
"ﶏ": "مخم",
"ﶹ": "مخى",
"ﳑ": "مم",
"ﲉ": "مم",
"ﱈ": "مم",
"ﶱ": "ممى",
"ﱉ": "مى",
"ﱊ": "مى",
"𞸍": "ن",
"𞸭": "ن",
"𞹍": "ن",
"𞹭": "ن",
"𞺍": "ن",
"𞺭": "ن",
"ﻧ": "ن",
"ﻨ": "ن",
"ﻦ": "ن",
"ﻥ": "ن",
"ݨ": "نؕ",
"ݩ": "ن̆",
"ﳖ": "نo",
"ﳯ": "نo",
"ﶸ": "نجح",
"ﶽ": "نجح",
"ﶘ": "نجم",
"ﶗ": "نجم",
"ﶙ": "نجى",
"ﷇ": "نجى",
"ﳓ": "نح",
"ﱌ": "نح",
"ﶕ": "نحم",
"ﶖ": "نحى",
"ﶳ": "نحى",
"ﳔ": "نخ",
"ﱍ": "نخ",
"ﲊ": "نر",
"ﲋ": "نز",
"ﳕ": "نم",
"ﳮ": "نم",
"ﲌ": "نم",
"ﱎ": "نم",
"ﶛ": "نمى",
"ﶚ": "نمى",
"ﲍ": "نن",
"ﲎ": "نى",
"ﱏ": "نى",
"ﲏ": "نى",
"ﱐ": "نى",
"ۂ": "ۀ",
"ﮥ": "ۀ",
"ﮤ": "ۀ",
"𐋤": "و",
"𞸅": "و",
"𞺅": "و",
"𞺥": "و",
"ﻮ": "و",
"ﻭ": "و",
"ࢱ": "و",
"ۋ": "وۛ",
"ﯟ": "وۛ",
"ﯞ": "وۛ",
"ۇ": "و̓",
"ﯘ": "و̓",
"ﯗ": "و̓",
"ۆ": "و̆",
"ﯚ": "و̆",
"ﯙ": "و̆",
"ۉ": "و̂",
"ﯣ": "و̂",
"ﯢ": "و̂",
"ۈ": "وٰ",
"ﯜ": "وٰ",
"ﯛ": "وٰ",
"ؤ": "وٴ",
"ﺆ": "وٴ",
"ﺅ": "وٴ",
"ٶ": "وٴ",
"ٷ": "و̓ٴ",
"ﯝ": "و̓ٴ",
"ﷸ": "وسلم",
"ﯡ": "ۅ",
"ﯠ": "ۅ",
"ٮ": "ى",
"𞸜": "ى",
"𞹼": "ى",
"ں": "ى",
"𞸝": "ى",
"𞹝": "ى",
"ﮟ": "ى",
"ﮞ": "ى",
"ࢽ": "ى",
"ﯨ": "ى",
"ﯩ": "ى",
"ﻰ": "ى",
"ﻯ": "ى",
"ي": "ى",
"𞸉": "ى",
"𞸩": "ى",
"𞹉": "ى",
"𞹩": "ى",
"𞺉": "ى",
"𞺩": "ى",
"ﻳ": "ى",
"ﻴ": "ى",
"ﻲ": "ى",
"ﻱ": "ى",
"ی": "ى",
"ﯾ": "ى",
"ﯿ": "ى",
"ﯽ": "ى",
"ﯼ": "ى",
"ے": "ى",
"ﮯ": "ى",
"ﮮ": "ى",
"ٹ": "ىؕ",
"ﭨ": "ىؕ",
"ﭩ": "ىؕ",
"ﭧ": "ىؕ",
"ﭦ": "ىؕ",
"ڻ": "ىؕ",
"ﮢ": "ىؕ",
"ﮣ": "ىؕ",
"ﮡ": "ىؕ",
"ﮠ": "ىؕ",
"پ": "ىۛ",
"ﭘ": "ىۛ",
"ﭙ": "ىۛ",
"ﭗ": "ىۛ",
"ﭖ": "ىۛ",
"ث": "ىۛ",
"𞸖": "ىۛ",
"𞸶": "ىۛ",
"𞹶": "ىۛ",
"𞺖": "ىۛ",
"𞺶": "ىۛ",
"ﺛ": "ىۛ",
"ﺜ": "ىۛ",
"ﺚ": "ىۛ",
"ﺙ": "ىۛ",
"ڽ": "ىۛ",
"ۑ": "ىۛ",
"ؿ": "ىۛ",
"ࢷ": "ىۛۢ",
"ݖ": "ى̆",
"ێ": "ى̆",
"ࢺ": "ى̆̇",
"ؽ": "ى̂",
"ࢨ": "ىٔ",
"ﲐ": "ىٰ",
"ﱝ": "ىٰ",
"ﳞ": "ىo",
"ﳱ": "ىo",
"ﳦ": "ىۛo",
"ئ": "ىٴ",
"ﺋ": "ىٴ",
"ﺌ": "ىٴ",
"ﺊ": "ىٴ",
"ﺉ": "ىٴ",
"ٸ": "ىٴ",
"ﯫ": "ىٴl",
"ﯪ": "ىٴl",
"ﲛ": "ىٴo",
"ﳠ": "ىٴo",
"ﯭ": "ىٴo",
"ﯬ": "ىٴo",
"ﯸ": "ىٴٻ",
"ﯷ": "ىٴٻ",
"ﯶ": "ىٴٻ",
"ﲗ": "ىٴج",
"ﰀ": "ىٴج",
"ﲘ": "ىٴح",
"ﰁ": "ىٴح",
"ﲙ": "ىٴخ",
"ﱤ": "ىٴر",
"ﱥ": "ىٴز",
"ﲚ": "ىٴم",
"ﳟ": "ىٴم",
"ﱦ": "ىٴم",
"ﰂ": "ىٴم",
"ﱧ": "ىٴن",
"ﯯ": "ىٴو",
"ﯮ": "ىٴو",
"ﯱ": "ىٴو̓",
"ﯰ": "ىٴو̓",
"ﯳ": "ىٴو̆",
"ﯲ": "ىٴو̆",
"ﯵ": "ىٴوٰ",
"ﯴ": "ىٴوٰ",
"ﯻ": "ىٴى",
"ﯺ": "ىٴى",
"ﱨ": "ىٴى",
"ﯹ": "ىٴى",
"ﰃ": "ىٴى",
"ﱩ": "ىٴى",
"ﰄ": "ىٴى",
"ﳚ": "ىج",
"ﱕ": "ىج",
"ﰑ": "ىۛج",
"ﶯ": "ىجى",
"ﳛ": "ىح",
"ﱖ": "ىح",
"ﶮ": "ىحى",
"ﳜ": "ىخ",
"ﱗ": "ىخ",
"ﲑ": "ىر",
"ﱶ": "ىۛر",
"ﲒ": "ىز",
"ﱷ": "ىۛز",
"ﳝ": "ىم",
"ﳰ": "ىم",
"ﲓ": "ىم",
"ﱘ": "ىم",
"ﲦ": "ىۛم",
"ﳥ": "ىۛم",
"ﱸ": "ىۛم",
"ﰒ": "ىۛم",
"ﶝ": "ىمم",
"ﶜ": "ىمم",
"ﶰ": "ىمى",
"ﲔ": "ىن",
"ﱹ": "ىۛن",
"ﲕ": "ىى",
"ﱙ": "ىى",
"ﲖ": "ىى",
"ﱚ": "ىى",
"ﱺ": "ىۛى",
"ﰓ": "ىۛى",
"ﱻ": "ىۛى",
"ﰔ": "ىۛى",
"ﮱ": "ۓ",
"ﮰ": "ۓ",
"𐊸": "ⵀ",
"⁞": "ⵂ",
"⸽": "ⵂ",
"⦙": "ⵂ",
"︙": "ⵗ",
"⁝": "ⵗ",
"⋮": "ⵗ",
"Մ": "ሆ",
"Ռ": "ቡ",
"Ի": "ኮ",
"Պ": "ጣ",
"आ": "अा",
"ऒ": "अाॆ",
"ओ": "अाे",
"औ": "अाै",
"ऄ": "अॆ",
"ऑ": "अॉ",
"ऍ": "एॅ",
"ऎ": "एॆ",
"ऐ": "एे",
"ई": "र्इ",
"ઽ": "ऽ",
"𑇜": "ꣻ",
"𑇋": "ऺ",
"ુ": "ु",
"ૂ": "ू",
"ੋ": "ॆ",
"੍": "्",
"્": "्",
"আ": "অা",
"ৠ": "ঋৃ",
"ৡ": "ঋৃ",
"𑒒": "ঘ",
"𑒔": "চ",
"𑒖": "জ",
"𑒘": "ঞ",
"𑒙": "ট",
"𑒛": "ড",
"𑒪": "ণ",
"𑒞": "ত",
"𑒟": "থ",
"𑒠": "দ",
"𑒡": "ধ",
"𑒢": "ন",
"𑒣": "প",
"𑒩": "ব",
"𑒧": "ম",
"𑒨": "য",
"𑒫": "র",
"𑒝": "ল",
"𑒭": "ষ",
"𑒮": "স",
"𑓄": "ঽ",
"𑒰": "া",
"𑒱": "ি",
"𑒹": "ে",
"𑒼": "ো",
"𑒾": "ৌ",
"𑓂": "্",
"𑒽": "ৗ",
"ਉ": "ੳੁ",
"ਊ": "ੳੂ",
"ਆ": "ਅਾ",
"ਐ": "ਅੈ",
"ਔ": "ਅੌ",
"ਇ": "ੲਿ",
"ਈ": "ੲੀ",
"ਏ": "ੲੇ",
"આ": "અા",
"ઑ": "અાૅ",
"ઓ": "અાે",
"ઔ": "અાૈ",
"ઍ": "અૅ",
"એ": "અે",
"ઐ": "અૈ",
"ଆ": "ଅା",
"௮": "அ",
"ர": "ஈ",
"ா": "ஈ",
"௫": "ஈு",
"௨": "உ",
"ഉ": "உ",
"ஊ": "உள",
"ഊ": "உൗ",
"௭": "எ",
"௷": "எவ",
"ஜ": "ஐ",
"ജ": "ஐ",
"௧": "க",
"௪": "ச",
"௬": "சு",
"௲": "சூ",
"ഺ": "டி",
"ണ": "ண",
"௺": "நீ",
"௴": "மீ",
"௰": "ய",
"ഴ": "ழ",
"ௗ": "ள",
"ை": "ன",
"ശ": "ஶ",
"௸": "ஷ",
"ി": "ி",
"ീ": "ி",
"ொ": "ெஈ",
"ௌ": "ெள",
"ோ": "ேஈ",
"ಅ": "అ",
"ಆ": "ఆ",
"ಇ": "ఇ",
"ౠ": "ఋా",
"ౡ": "ఌా",
"ಒ": "ఒ",
"ఔ": "ఒౌ",
"ಔ": "ఒౌ",
"ఓ": "ఒౕ",
"ಓ": "ఒౕ",
"ಜ": "జ",
"ಞ": "ఞ",
"ఢ": "డ̣",
"ಣ": "ణ",
"థ": "ధּ",
"భ": "బ̣",
"ಯ": "య",
"ఠ": "రּ",
"ಱ": "ఱ",
"ಲ": "ల",
"ష": "వ̣",
"హ": "వా",
"మ": "వు",
"ూ": "ుా",
"ౄ": "ృా",
"ೡ": "ಌಾ",
"ഈ": "ഇൗ",
"ഐ": "എെ",
"ഓ": "ഒാ",
"ഔ": "ഒൗ",
"ൡ": "ഞ",
"൫": "ദ്ര",
"൹": "നു",
"ഌ": "നു",
"ങ": "നു",
"൯": "ന്",
"ൻ": "ന്",
"൬": "ന്ന",
"൚": "ന്മ",
"റ": "ര",
"൪": "ര്",
"ർ": "ര്",
"൮": "വ്ര",
"൶": "ഹ്മ",
"ൂ": "ു",
"ൃ": "ു",
"ൈ": "െെ",
"෪": "ජ",
"෫": "ද",
"𑐓": "𑐴𑑂𑐒",
"𑐙": "𑐴𑑂𑐘",
"𑐤": "𑐴𑑂𑐣",
"𑐪": "𑐴𑑂𑐩",
"𑐭": "𑐴𑑂𑐬",
"𑐯": "𑐴𑑂𑐮",
"𑗘": "𑖂",
"𑗙": "𑖂",
"𑗚": "𑖃",
"𑗛": "𑖄",
"𑗜": "𑖲",
"𑗝": "𑖳",
"ฃ": "ข",
"ด": "ค",
"ต": "ค",
"ม": "ฆ",
"ຈ": "จ",
"ซ": "ช",
"ฏ": "ฎ",
"ท": "ฑ",
"ບ": "บ",
"ປ": "ป",
"ຝ": "ฝ",
"ພ": "พ",
"ຟ": "ฟ",
"ฦ": "ภ",
"ຍ": "ย",
"។": "ฯ",
"ๅ": "า",
"ำ": "̊า",
"ិ": "ิ",
"ី": "ี",
"ឹ": "ึ",
"ឺ": "ื",
"ຸ": "ุ",
"ູ": "ู",
"แ": "เเ",
"ໜ": "ຫນ",
"ໝ": "ຫມ",
"ຳ": "̊າ",
"༂": "འུྂཿ",
"༃": "འུྂ༔",
"ཪ": "ར",
"ༀ": "ཨོཾ",
"ཷ": "ྲཱྀ",
"ཹ": "ླཱྀ",
"𑲲": "𑲪",
"ႁ": "ဂှ",
"က": "ဂာ",
"ၰ": "ဃှ",
"ၦ": "ပှ",
"ဟ": "ပာ",
"ၯ": "ပာှ",
"ၾ": "ၽှ",
"ဩ": "သြ",
"ဪ": "သြော်",
"႞": "ႃ̊",
"ឣ": "អ",
"᧐": "ᦞ",
"᧑": "ᦱ",
"᪀": "ᩅ",
"᪐": "ᩅ",
"꩓": "ꨁ",
"꩖": "ꨣ",
"᭒": "ᬍ",
"᭓": "ᬑ",
"᭘": "ᬨ",
"ꦣ": "ꦝ",
"ᢖ": "ᡜ",
"ᡕ": "ᠵ",
"ῶ": "Ꮿ",
"ᐍ": "ᐁ·",
"ᐫ": "ᐁᐠ",
"ᐑ": "ᐄ·",
"ᐓ": "ᐅ·",
"ᐭ": "ᐅᐠ",
"ᐕ": "ᐆ·",
"ᐘ": "ᐊ·",
"ᐮ": "ᐊᐠ",
"ᐚ": "ᐋ·",
"ᣝ": "ᐞᣟ",
"ᓑ": "ᐡ",
"ᕀ": "ᐩ",
"ᐿ": "ᐲ·",
"ᑃ": "ᐴ·",
"⍩": "ᐵ",
"ᑇ": "ᐹ·",
"ᑜ": "ᑏ·",
"⸧": "ᑐ",
"⊃": "ᑐ",
"ᑞ": "ᑐ·",
"ᑩ": "ᑐ'",
"⟉": "ᑐ/",
"⫗": "ᑐᑕ",
"ᑠ": "ᑑ·",
"⸦": "ᑕ",
"⊂": "ᑕ",
"ᑢ": "ᑕ·",
"ᑪ": "ᑕ'",
"ᑤ": "ᑖ·",
"ᑵ": "ᑫ·",
"ᒅ": "ᑫ'",
"ᑹ": "ᑮ·",
"ᑽ": "ᑰ·",
"ᘃ": "ᒉ",
"ᒓ": "ᒉ·",
"ᒕ": "ᒋ·",
"ᒗ": "ᒌ·",
"ᒛ": "ᒎ·",
"ᘂ": "ᒐ",
"ᒝ": "ᒐ·",
"ᒟ": "ᒑ·",
"ᒭ": "ᒣ·",
"ᒱ": "ᒦ·",
"ᒳ": "ᒧ·",
"ᒵ": "ᒨ·",
"ᒹ": "ᒫ·",
"ᓊ": "ᓀ·",
"ᣇ": "ᓂ·",
"ᣉ": "ᓃ·",
"ᣋ": "ᓄ·",
"ᣍ": "ᓅ·",
"ᓌ": "ᓇ·",
"ᓎ": "ᓈ·",
"ᘄ": "ᓓ",
"ᓝ": "ᓓ·",
"ᓟ": "ᓕ·",
"ᓡ": "ᓖ·",
"ᓣ": "ᓗ·",
"ᓥ": "ᓘ·",
"ᘇ": "ᓚ",
"ᓧ": "ᓚ·",
"ᓩ": "ᓛ·",
"ᓷ": "ᓭ·",
"ᓹ": "ᓯ·",
"ᓻ": "ᓰ·",
"ᓽ": "ᓱ·",
"ᓿ": "ᓲ·",
"ᔁ": "ᓴ·",
"ᔃ": "ᓵ·",
"ᔌ": "ᔋ<",
"ᔎ": "ᔋb",
"ᔍ": "ᔋᑕ",
"ᔏ": "ᔋᒐ",
"ᔘ": "ᔐ·",
"ᔚ": "ᔑ·",
"ᔜ": "ᔒ·",
"ᔞ": "ᔓ·",
"ᔠ": "ᔔ·",
"ᔢ": "ᔕ·",
"ᔤ": "ᔖ·",
"ᔲ": "ᔨ·",
"ᔴ": "ᔩ·",
"ᔶ": "ᔪ·",
"ᔸ": "ᔫ·",
"ᔺ": "ᔭ·",
"ᔼ": "ᔮ·",
"ᘢ": "ᕃ",
"ᣠ": "ᕃ·",
"ᘣ": "ᕆ",
"ᘤ": "ᕊ",
"ᕏ": "ᕌ·",
"ᖃ": "ᕐb",
"ᖄ": "ᕐḃ",
"ᖁ": "ᕐd",
"ᕿ": "ᕐP",
"ᙯ": "ᕐᑫ",
"ᕾ": "ᕐᑬ",
"ᖀ": "ᕐᑮ",
"ᖂ": "ᕐᑰ",
"ᖅ": "ᕐᒃ",
"ᕜ": "ᕚ·",
"ᣣ": "ᕞ·",
"ᣤ": "ᕦ·",
"ᕩ": "ᕧ·",
"ᣥ": "ᕫ·",
"ᣨ": "ᖆ·",
"ᖑ": "ᖕJ",
"ᙰ": "ᖕᒉ",
"ᖎ": "ᖕᒊ",
"ᖏ": "ᖕᒋ",
"ᖐ": "ᖕᒌ",
"ᖒ": "ᖕᒎ",
"ᖓ": "ᖕᒐ",
"ᖔ": "ᖕᒑ",
"ᙳ": "ᖖJ",
"ᙱ": "ᖖᒋ",
"ᙲ": "ᖖᒌ",
"ᙴ": "ᖖᒎ",
"ᙵ": "ᖖᒐ",
"ᙶ": "ᖖᒑ",
"ᣪ": "ᖗ·",
"ᙷ": "ᖧ·",
"ᙸ": "ᖨ·",
"ᙹ": "ᖩ·",
"ᙺ": "ᖪ·",
"ᙻ": "ᖫ·",
"ᙼ": "ᖬ·",
"ᙽ": "ᖭ·",
"⪫": "ᗒ",
"⪪": "ᗕ",
"ꓷ": "ᗡ",
"ᣰ": "ᗴ·",
"ᣲ": "ᘛ·",
"ᶻ": "ᙆ",
"ꓭ": "ᙠ",
"ᶺ": "ᣔ",
"ᴾ": "ᣖ",
"ᣜ": "ᣟᐞ",
"ˡ": "ᣳ",
"ʳ": "ᣴ",
"ˢ": "ᣵ",
"ᣛ": "ᣵ",
"ꚰ": "ᚹ",
"ᛡ": "ᚼ",
"⍿": "ᚽ",
"ᛂ": "ᚽ",
"𝈿": "ᛋ",
"↑": "ᛏ",
"↿": "ᛐ",
"⥮": "ᛐ⇂",
"⥣": "ᛐᛚ",
"ⵣ": "ᛯ",
"↾": "ᛚ",
"⨡": "ᛚ",
"⋄": "ᛜ",
"◇": "ᛜ",
"◊": "ᛜ",
"♢": "ᛜ",
"🝔": "ᛜ",
"𑢷": "ᛜ",
"𐊔": "ᛜ",
"⍚": "ᛜ̲",
"⋈": "ᛞ",
"⨝": "ᛞ",
"𐓐": "ᛦ",
"↕": "ᛨ",
"𐳼": "𐲂",
"𐳺": "𐲥",
"ㄱ": "ᄀ",
"ᆨ": "ᄀ",
"ᄁ": "ᄀᄀ",
"ㄲ": "ᄀᄀ",
"ᆩ": "ᄀᄀ",
"ᇺ": "ᄀᄂ",
"ᅚ": "ᄀᄃ",
"ᇃ": "ᄀᄅ",
"ᇻ": "ᄀᄇ",
"ᆪ": "ᄀᄉ",
"ㄳ": "ᄀᄉ",
"ᇄ": "ᄀᄉᄀ",
"ᇼ": "ᄀᄎ",
"ᇽ": "ᄀᄏ",
"ᇾ": "ᄀᄒ",
"ㄴ": "ᄂ",
"ᆫ": "ᄂ",
"ᄓ": "ᄂᄀ",
"ᇅ": "ᄂᄀ",
"ᄔ": "ᄂᄂ",
"ㅥ": "ᄂᄂ",
"ᇿ": "ᄂᄂ",
"ᄕ": "ᄂᄃ",
"ㅦ": "ᄂᄃ",
"ᇆ": "ᄂᄃ",
"ퟋ": "ᄂᄅ",
"ᄖ": "ᄂᄇ",
"ᅛ": "ᄂᄉ",
"ᇇ": "ᄂᄉ",
"ㅧ": "ᄂᄉ",
"ᅜ": "ᄂᄌ",
"ᆬ": "ᄂᄌ",
"ㄵ": "ᄂᄌ",
"ퟌ": "ᄂᄎ",
"ᇉ": "ᄂᄐ",
"ᅝ": "ᄂᄒ",
"ᆭ": "ᄂᄒ",
"ㄶ": "ᄂᄒ",
"ᇈ": "ᄂᅀ",
"ㅨ": "ᄂᅀ",
"ㄷ": "ᄃ",
"ᆮ": "ᄃ",
"ᄗ": "ᄃᄀ",
"ᇊ": "ᄃᄀ",
"ᄄ": "ᄃᄃ",
"ㄸ": "ᄃᄃ",
"ퟍ": "ᄃᄃ",
"ퟎ": "ᄃᄃᄇ",
"ᅞ": "ᄃᄅ",
"ᇋ": "ᄃᄅ",
"ꥠ": "ᄃᄆ",
"ꥡ": "ᄃᄇ",
"ퟏ": "ᄃᄇ",
"ꥢ": "ᄃᄉ",
"ퟐ": "ᄃᄉ",
"ퟑ": "ᄃᄉᄀ",
"ꥣ": "ᄃᄌ",
"ퟒ": "ᄃᄌ",
"ퟓ": "ᄃᄎ",
"ퟔ": "ᄃᄐ",
"ㄹ": "ᄅ",
"ᆯ": "ᄅ",
"ꥤ": "ᄅᄀ",
"ᆰ": "ᄅᄀ",
"ㄺ": "ᄅᄀ",
"ꥥ": "ᄅᄀᄀ",
"ퟕ": "ᄅᄀᄀ",
"ᇌ": "ᄅᄀᄉ",
"ㅩ": "ᄅᄀᄉ",
"ퟖ": "ᄅᄀᄒ",
"ᄘ": "ᄅᄂ",
"ᇍ": "ᄅᄂ",
"ꥦ": "ᄅᄃ",
"ᇎ": "ᄅᄃ",
"ㅪ": "ᄅᄃ",
"ꥧ": "ᄅᄃᄃ",
"ᇏ": "ᄅᄃᄒ",
"ᄙ": "ᄅᄅ",
"ᇐ": "ᄅᄅ",
"ퟗ": "ᄅᄅᄏ",
"ꥨ": "ᄅᄆ",
"ᆱ": "ᄅᄆ",
"ㄻ": "ᄅᄆ",
"ᇑ": "ᄅᄆᄀ",
"ᇒ": "ᄅᄆᄉ",
"ퟘ": "ᄅᄆᄒ",
"ꥩ": "ᄅᄇ",
"ᆲ": "ᄅᄇ",
"ㄼ": "ᄅᄇ",
"ퟙ": "ᄅᄇᄃ",
"ꥪ": "ᄅᄇᄇ",
"ᇓ": "ᄅᄇᄉ",
"ㅫ": "ᄅᄇᄉ",
"ꥫ": "ᄅᄇᄋ",
"ᇕ": "ᄅᄇᄋ",
"ퟚ": "ᄅᄇᄑ",
"ᇔ": "ᄅᄇᄒ",
"ꥬ": "ᄅᄉ",
"ᆳ": "ᄅᄉ",
"ㄽ": "ᄅᄉ",
"ᇖ": "ᄅᄉᄉ",
"ᄛ": "ᄅᄋ",
"ퟝ": "ᄅᄋ",
"ꥭ": "ᄅᄌ",
"ꥮ": "ᄅᄏ",
"ᇘ": "ᄅᄏ",
"ᆴ": "ᄅᄐ",
"ㄾ": "ᄅᄐ",
"ᆵ": "ᄅᄑ",
"ㄿ": "ᄅᄑ",
"ᄚ": "ᄅᄒ",
"ㅀ": "ᄅᄒ",
"ᄻ": "ᄅᄒ",
"ᆶ": "ᄅᄒ",
"ퟲ": "ᄅᄒ",
"ᇗ": "ᄅᅀ",
"ㅬ": "ᄅᅀ",
"ퟛ": "ᄅᅌ",
"ᇙ": "ᄅᅙ",
"ㅭ": "ᄅᅙ",
"ퟜ": "ᄅᅙᄒ",
"ㅁ": "ᄆ",
"ᆷ": "ᄆ",
"ꥯ": "ᄆᄀ",
"ᇚ": "ᄆᄀ",
"ퟞ": "ᄆᄂ",
"ퟟ": "ᄆᄂᄂ",
"ꥰ": "ᄆᄃ",
"ᇛ": "ᄆᄅ",
"ퟠ": "ᄆᄆ",
"ᄜ": "ᄆᄇ",
"ㅮ": "ᄆᄇ",
"ᇜ": "ᄆᄇ",
"ퟡ": "ᄆᄇᄉ",
"ꥱ": "ᄆᄉ",
"ᇝ": "ᄆᄉ",
"ㅯ": "ᄆᄉ",
"ᇞ": "ᄆᄉᄉ",
"ᄝ": "ᄆᄋ",
"ㅱ": "ᄆᄋ",
"ᇢ": "ᄆᄋ",
"ퟢ": "ᄆᄌ",
"ᇠ": "ᄆᄎ",
"ᇡ": "ᄆᄒ",
"ᇟ": "ᄆᅀ",
"ㅰ": "ᄆᅀ",
"ㅂ": "ᄇ",
"ᆸ": "ᄇ",
"ᄞ": "ᄇᄀ",
"ㅲ": "ᄇᄀ",
"ᄟ": "ᄇᄂ",
"ᄠ": "ᄇᄃ",
"ㅳ": "ᄇᄃ",
"ퟣ": "ᄇᄃ",
"ᇣ": "ᄇᄅ",
"ퟤ": "ᄇᄅᄑ",
"ퟥ": "ᄇᄆ",
"ᄈ": "ᄇᄇ",
"ㅃ": "ᄇᄇ",
"ퟦ": "ᄇᄇ",
"ᄬ": "ᄇᄇᄋ",
"ㅹ": "ᄇᄇᄋ",
"ᄡ": "ᄇᄉ",
"ㅄ": "ᄇᄉ",
"ᆹ": "ᄇᄉ",
"ᄢ": "ᄇᄉᄀ",
"ㅴ": "ᄇᄉᄀ",
"ᄣ": "ᄇᄉᄃ",
"ㅵ": "ᄇᄉᄃ",
"ퟧ": "ᄇᄉᄃ",
"ᄤ": "ᄇᄉᄇ",
"ᄥ": "ᄇᄉᄉ",
"ᄦ": "ᄇᄉᄌ",
"ꥲ": "ᄇᄉᄐ",
"ᄫ": "ᄇᄋ",
"ㅸ": "ᄇᄋ",
"ᇦ": "ᄇᄋ",
"ᄧ": "ᄇᄌ",
"ㅶ": "ᄇᄌ",
"ퟨ": "ᄇᄌ",
"ᄨ": "ᄇᄎ",
"ퟩ": "ᄇᄎ",
"ꥳ": "ᄇᄏ",
"ᄩ": "ᄇᄐ",
"ㅷ": "ᄇᄐ",
"ᄪ": "ᄇᄑ",
"ᇤ": "ᄇᄑ",
"ꥴ": "ᄇᄒ",
"ᇥ": "ᄇᄒ",
"ㅅ": "ᄉ",
"ᆺ": "ᄉ",
"ᄭ": "ᄉᄀ",
"ㅺ": "ᄉᄀ",
"ᇧ": "ᄉᄀ",
"ᄮ": "ᄉᄂ",
"ㅻ": "ᄉᄂ",
"ᄯ": "ᄉᄃ",
"ㅼ": "ᄉᄃ",
"ᇨ": "ᄉᄃ",
"ᄰ": "ᄉᄅ",
"ᇩ": "ᄉᄅ",
"ᄱ": "ᄉᄆ",
"ퟪ": "ᄉᄆ",
"ᄲ": "ᄉᄇ",
"ㅽ": "ᄉᄇ",
"ᇪ": "ᄉᄇ",
"ᄳ": "ᄉᄇᄀ",
"ퟫ": "ᄉᄇᄋ",
"ᄊ": "ᄉᄉ",
"ㅆ": "ᄉᄉ",
"ᆻ": "ᄉᄉ",
"ퟬ": "ᄉᄉᄀ",
"ퟭ": "ᄉᄉᄃ",
"ꥵ": "ᄉᄉᄇ",
"ᄴ": "ᄉᄉᄉ",
"ᄵ": "ᄉᄋ",
"ᄶ": "ᄉᄌ",
"ㅾ": "ᄉᄌ",
"ퟯ": "ᄉᄌ",
"ᄷ": "ᄉᄎ",
"ퟰ": "ᄉᄎ",
"ᄸ": "ᄉᄏ",
"ᄹ": "ᄉᄐ",
"ퟱ": "ᄉᄐ",
"ᄺ": "ᄉᄑ",
"ퟮ": "ᄉᅀ",
"ㅇ": "ᄋ",
"ᆼ": "ᄋ",
"ᅁ": "ᄋᄀ",
"ᇬ": "ᄋᄀ",
"ᇭ": "ᄋᄀᄀ",
"ᅂ": "ᄋᄃ",
"ꥶ": "ᄋᄅ",
"ᅃ": "ᄋᄆ",
"ᅄ": "ᄋᄇ",
"ᅅ": "ᄋᄉ",
"ᇱ": "ᄋᄉ",
"ㆂ": "ᄋᄉ",
"ᅇ": "ᄋᄋ",
"ㆀ": "ᄋᄋ",
"ᇮ": "ᄋᄋ",
"ᅈ": "ᄋᄌ",
"ᅉ": "ᄋᄎ",
"ᇯ": "ᄋᄏ",
"ᅊ": "ᄋᄐ",
"ᅋ": "ᄋᄑ",
"ꥷ": "ᄋᄒ",
"ᅆ": "ᄋᅀ",
"ᇲ": "ᄋᅀ",
"ㆃ": "ᄋᅀ",
"ㅈ": "ᄌ",
"ᆽ": "ᄌ",
"ퟷ": "ᄌᄇ",
"ퟸ": "ᄌᄇᄇ",
"ᅍ": "ᄌᄋ",
"ᄍ": "ᄌᄌ",
"ㅉ": "ᄌᄌ",
"ퟹ": "ᄌᄌ",
"ꥸ": "ᄌᄌᄒ",
"ㅊ": "ᄎ",
"ᆾ": "ᄎ",
"ᅒ": "ᄎᄏ",
"ᅓ": "ᄎᄒ",
"ㅋ": "ᄏ",
"ᆿ": "ᄏ",
"ㅌ": "ᄐ",
"ᇀ": "ᄐ",
"ꥹ": "ᄐᄐ",
"ㅍ": "ᄑ",
"ᇁ": "ᄑ",
"ᅖ": "ᄑᄇ",
"ᇳ": "ᄑᄇ",
"ퟺ": "ᄑᄉ",
"ᅗ": "ᄑᄋ",
"ㆄ": "ᄑᄋ",
"ᇴ": "ᄑᄋ",
"ퟻ": "ᄑᄐ",
"ꥺ": "ᄑᄒ",
"ㅎ": "ᄒ",
"ᇂ": "ᄒ",
"ᇵ": "ᄒᄂ",
"ᇶ": "ᄒᄅ",
"ᇷ": "ᄒᄆ",
"ᇸ": "ᄒᄇ",
"ꥻ": "ᄒᄉ",
"ᅘ": "ᄒᄒ",
"ㆅ": "ᄒᄒ",
"ᄽ": "ᄼᄼ",
"ᄿ": "ᄾᄾ",
"ㅿ": "ᅀ",
"ᇫ": "ᅀ",
"ퟳ": "ᅀᄇ",
"ퟴ": "ᅀᄇᄋ",
"ㆁ": "ᅌ",
"ᇰ": "ᅌ",
"ퟵ": "ᅌᄆ",
"ퟶ": "ᅌᄒ",
"ᅏ": "ᅎᅎ",
"ᅑ": "ᅐᅐ",
"ㆆ": "ᅙ",
"ᇹ": "ᅙ",
"ꥼ": "ᅙᅙ",
"ㅤ": "ᅠ",
"ㅏ": "ᅡ",
"ᆣ": "ᅡー",
"ᅶ": "ᅡᅩ",
"ᅷ": "ᅡᅮ",
"ᅢ": "ᅡ丨",
"ㅐ": "ᅡ丨",
"ㅑ": "ᅣ",
"ᅸ": "ᅣᅩ",
"ᅹ": "ᅣᅭ",
"ᆤ": "ᅣᅮ",
"ᅤ": "ᅣ丨",
"ㅒ": "ᅣ丨",
"ㅓ": "ᅥ",
"ᅼ": "ᅥー",
"ᅺ": "ᅥᅩ",
"ᅻ": "ᅥᅮ",
"ᅦ": "ᅥ丨",
"ㅔ": "ᅥ丨",
"ㅕ": "ᅧ",
"ᆥ": "ᅧᅣ",
"ᅽ": "ᅧᅩ",
"ᅾ": "ᅧᅮ",
"ᅨ": "ᅧ丨",
"ㅖ": "ᅧ丨",
"ㅗ": "ᅩ",
"ᅪ": "ᅩᅡ",
"ㅘ": "ᅩᅡ",
"ᅫ": "ᅩᅡ丨",
"ㅙ": "ᅩᅡ丨",
"ᆦ": "ᅩᅣ",
"ᆧ": "ᅩᅣ丨",
"ᅿ": "ᅩᅥ",
"ᆀ": "ᅩᅥ丨",
"ힰ": "ᅩᅧ",
"ᆁ": "ᅩᅧ丨",
"ᆂ": "ᅩᅩ",
"ힱ": "ᅩᅩ丨",
"ᆃ": "ᅩᅮ",
"ᅬ": "ᅩ丨",
"ㅚ": "ᅩ丨",
"ㅛ": "ᅭ",
"ힲ": "ᅭᅡ",
"ힳ": "ᅭᅡ丨",
"ᆄ": "ᅭᅣ",
"ㆇ": "ᅭᅣ",
"ᆆ": "ᅭᅣ",
"ᆅ": "ᅭᅣ丨",
"ㆈ": "ᅭᅣ丨",
"ힴ": "ᅭᅥ",
"ᆇ": "ᅭᅩ",
"ᆈ": "ᅭ丨",
"ㆉ": "ᅭ丨",
"ㅜ": "ᅮ",
"ᆉ": "ᅮᅡ",
"ᆊ": "ᅮᅡ丨",
"ᅯ": "ᅮᅥ",
"ㅝ": "ᅮᅥ",
"ᆋ": "ᅮᅥー",
"ᅰ": "ᅮᅥ丨",
"ㅞ": "ᅮᅥ丨",
"ힵ": "ᅮᅧ",
"ᆌ": "ᅮᅧ丨",
"ᆍ": "ᅮᅮ",
"ᅱ": "ᅮ丨",
"ㅟ": "ᅮ丨",
"ힶ": "ᅮ丨丨",
"ㅠ": "ᅲ",
"ᆎ": "ᅲᅡ",
"ힷ": "ᅲᅡ丨",
"ᆏ": "ᅲᅥ",
"ᆐ": "ᅲᅥ丨",
"ᆑ": "ᅲᅧ",
"ㆊ": "ᅲᅧ",
"ᆒ": "ᅲᅧ丨",
"ㆋ": "ᅲᅧ丨",
"ힸ": "ᅲᅩ",
"ᆓ": "ᅲᅮ",
"ᆔ": "ᅲ丨",
"ㆌ": "ᅲ丨",
"ㆍ": "ᆞ",
"ퟅ": "ᆞᅡ",
"ᆟ": "ᆞᅥ",
"ퟆ": "ᆞᅥ丨",
"ᆠ": "ᆞᅮ",
"ᆢ": "ᆞᆞ",
"ᆡ": "ᆞ丨",
"ㆎ": "ᆞ丨",
"ヘ": "へ",
"⍁": "〼",
"⧄": "〼",
"꒞": "ꁊ",
"꒬": "ꁐ",
"꒜": "ꃀ",
"꒨": "ꄲ",
"꒿": "ꉙ",
"꒾": "ꊱ",
"꒔": "ꋍ",
"꓀": "ꎫ",
"꓂": "ꎵ",
"꒺": "ꎿ",
"꒰": "ꏂ",
"꒧": "ꑘ",
"⊥": "ꓕ",
"⟂": "ꓕ",
"𝈜": "ꓕ",
"Ʇ": "ꓕ",
"Ꞟ": "ꓤ",
"⅁": "ꓨ",
"⅂": "ꓶ",
"𝈕": "ꓶ",
"𝈫": "ꓶ",
"𖼦": "ꓶ",
"𐐑": "ꓶ",
"⅃": "𖼀",
"𑫦": "𑫥𑫯",
"𑫨": "𑫥𑫥",
"𑫩": "𑫥𑫥𑫯",
"𑫪": "𑫥𑫥𑫰",
"𑫧": "𑫥𑫰",
"𑫴": "𑫳𑫯",
"𑫶": "𑫳𑫳",
"𑫷": "𑫳𑫳𑫯",
"𑫸": "𑫳𑫳𑫰",
"𑫵": "𑫳𑫰",
"𑫬": "𑫫𑫯",
"𑫭": "𑫫𑫫",
"𑫮": "𑫫𑫫𑫯",
"⊕": "𐊨",
"⨁": "𐊨",
"🜨": "𐊨",
"Ꚛ": "𐊨",
"▽": "𐊼",
"𝈔": "𐊼",
"🜄": "𐊼",
"⧖": "𐋀",
"ꞛ": "𐐺",
"Ꞛ": "𐐒",
"𐒠": "𐒆",
"𐏑": "𐎂",
"𐏓": "𐎓",
"𒀸": "𐎚",
"☥": "𐦞",
"𓋹": "𐦞",
"〹": "卄",
"不": "不",
"丽": "丽",
"並": "並",
"⎜": "丨",
"⎟": "丨",
"⎢": "丨",
"⎥": "丨",
"⎪": "丨",
"⎮": "丨",
"㇑": "丨",
"ᅵ": "丨",
"ㅣ": "丨",
"⼁": "丨",
"ᆜ": "丨ー",
"ᆘ": "丨ᅡ",
"ᆙ": "丨ᅣ",
"ힽ": "丨ᅣᅩ",
"ힾ": "丨ᅣ丨",
"ힿ": "丨ᅧ",
"ퟀ": "丨ᅧ丨",
"ᆚ": "丨ᅩ",
"ퟁ": "丨ᅩ丨",
"ퟂ": "丨ᅭ",
"ᆛ": "丨ᅮ",
"ퟃ": "丨ᅲ",
"ᆝ": "丨ᆞ",
"ퟄ": "丨丨",
"串": "串",
"丸": "丸",
"丹": "丹",
"乁": "乁",
"㇠": "乙",
"⼄": "乙",
"㇟": "乚",
"⺃": "乚",
"㇖": "乛",
"⺂": "乛",
"⻲": "亀",
"亂": "亂",
"㇚": "亅",
"⼅": "亅",
"了": "了",
"ニ": "二",
"⼆": "二",
"𠄢": "𠄢",
"⼇": "亠",
"亮": "亮",
"⼈": "人",
"イ": "亻",
"⺅": "亻",
"什": "什",
"仌": "仌",
"令": "令",
"你": "你",
"倂": "併",
"倂": "併",
"侀": "侀",
"來": "來",
"例": "例",
"侮": "侮",
"侮": "侮",
"侻": "侻",
"便": "便",
"值": "値",
"倫": "倫",
"偺": "偺",
"備": "備",
"像": "像",
"僚": "僚",
"僧": "僧",
"僧": "僧",
"㒞": "㒞",
"⼉": "儿",
"兀": "兀",
"⺎": "兀",
"充": "充",
"免": "免",
"免": "免",
"兔": "兔",
"兤": "兤",
"⼊": "入",
"內": "內",
"全": "全",
"兩": "兩",
"ハ": "八",
"⼋": "八",
"六": "六",
"具": "具",
"𠔜": "𠔜",
"𠔥": "𠔥",
"冀": "冀",
"㒹": "㒹",
"⼌": "冂",
"再": "再",
"𠕋": "𠕋",
"冒": "冒",
"冕": "冕",
"㒻": "㒻",
"最": "最",
"⼍": "冖",
"冗": "冗",
"冤": "冤",
"⼎": "冫",
"冬": "冬",
"况": "况",
"况": "况",
"冷": "冷",
"凉": "凉",
"凌": "凌",
"凜": "凜",
"凞": "凞",
"⼏": "几",
"𠘺": "𠘺",
"凵": "凵",
"⼐": "凵",
"⼑": "刀",
"⺉": "刂",
"刃": "刃",
"切": "切",
"切": "切",
"列": "列",
"利": "利",
"㓟": "㓟",
"刺": "刺",
"刻": "刻",
"剆": "剆",
"割": "割",
"剷": "剷",
"劉": "劉",
"𠠄": "𠠄",
"カ": "力",
"力": "力",
"⼒": "力",
"劣": "劣",
"㔕": "㔕",
"劳": "劳",
"勇": "勇",
"勇": "勇",
"勉": "勉",
"勉": "勉",
"勒": "勒",
"勞": "勞",
"勤": "勤",
"勤": "勤",
"勵": "勵",
"⼓": "勹",
"勺": "勺",
"勺": "勺",
"包": "包",
"匆": "匆",
"𠣞": "𠣞",
"⼔": "匕",
"北": "北",
"北": "北",
"⼕": "匚",
"⼖": "匸",
"匿": "匿",
"⼗": "十",
"〸": "十",
"〺": "卅",
"卉": "卉",
"࿖": "卍",
"࿕": "卐",
"卑": "卑",
"卑": "卑",
"博": "博",
"ト": "卜",
"⼘": "卜",
"⼙": "卩",
"⺋": "㔾",
"即": "即",
"卵": "卵",
"卽": "卽",
"卿": "卿",
"卿": "卿",
"卿": "卿",
"⼚": "厂",
"𠨬": "𠨬",
"⼛": "厶",
"參": "參",
"⼜": "又",
"及": "及",
"叟": "叟",
"𠭣": "𠭣",
"ロ": "口",
"⼝": "口",
"囗": "口",
"⼞": "口",
"句": "句",
"叫": "叫",
"叱": "叱",
"吆": "吆",
"吏": "吏",
"吝": "吝",
"吸": "吸",
"呂": "呂",
"呈": "呈",
"周": "周",
"咞": "咞",
"咢": "咢",
"咽": "咽",
"䎛": "㖈",
"哶": "哶",
"唐": "唐",
"啓": "啓",
"啟": "啓",
"啕": "啕",
"啣": "啣",
"善": "善",
"善": "善",
"喇": "喇",
"喙": "喙",
"喙": "喙",
"喝": "喝",
"喝": "喝",
"喫": "喫",
"喳": "喳",
"嗀": "嗀",
"嗂": "嗂",
"嗢": "嗢",
"嘆": "嘆",
"嘆": "嘆",
"噑": "噑",
"噴": "噴",
"器": "器",
"囹": "囹",
"圖": "圖",
"圗": "圗",
"⼟": "土",
"士": "土",
"⼠": "土",
"型": "型",
"城": "城",
"㦳": "㘽",
"埴": "埴",
"堍": "堍",
"報": "報",
"堲": "堲",
"塀": "塀",
"塚": "塚",
"塚": "塚",
"塞": "塞",
"填": "塡",
"壿": "墫",
"墬": "墬",
"墳": "墳",
"壘": "壘",
"壟": "壟",
"𡓤": "𡓤",
"壮": "壮",
"売": "売",
"壷": "壷",
"⼡": "夂",
"夆": "夆",
"⼢": "夊",
"タ": "夕",
"⼣": "夕",
"多": "多",
"夢": "夢",
"⼤": "大",
"奄": "奄",
"奈": "奈",
"契": "契",
"奔": "奔",
"奢": "奢",
"女": "女",
"⼥": "女",
"𡚨": "𡚨",
"𡛪": "𡛪",
"姘": "姘",
"姬": "姬",
"娛": "娛",
"娧": "娧",
"婢": "婢",
"婦": "婦",
"嬀": "媯",
"㛮": "㛮",
"㛼": "㛼",
"媵": "媵",
"嬈": "嬈",
"嬨": "嬨",
"嬾": "嬾",
"嬾": "嬾",
"⼦": "子",
"⼧": "宀",
"宅": "宅",
"𡧈": "𡧈",
"寃": "寃",
"寘": "寘",
"寧": "寧",
"寧": "寧",
"寧": "寧",
"寮": "寮",
"寳": "寳",
"𡬘": "𡬘",
"⼨": "寸",
"寿": "寿",
"将": "将",
"⼩": "小",
"尢": "尢",
"⺐": "尢",
"⼪": "尢",
"⺏": "尣",
"㞁": "㞁",
"⼫": "尸",
"尿": "尿",
"屠": "屠",
"屢": "屢",
"層": "層",
"履": "履",
"屮": "屮",
"屮": "屮",
"⼬": "屮",
"𡴋": "𡴋",
"⼭": "山",
"峀": "峀",
"岍": "岍",
"𡷤": "𡷤",
"𡷦": "𡷦",
"崙": "崙",
"嵃": "嵃",
"嵐": "嵐",
"嵫": "嵫",
"嵮": "嵮",
"嵼": "嵼",
"嶲": "嶲",
"嶺": "嶺",
"⼮": "巛",
"巢": "巢",
"エ": "工",
"⼯": "工",
"⼰": "己",
"⺒": "巳",
"㠯": "㠯",
"巽": "巽",
"⼱": "巾",
"帲": "帡",
"帨": "帨",
"帽": "帽",
"幩": "幩",
"㡢": "㡢",
"𢆃": "𢆃",
"⼲": "干",
"年": "年",
"𢆟": "𢆟",
"⺓": "幺",
"⼳": "幺",
"⼴": "广",
"度": "度",
"㡼": "㡼",
"庰": "庰",
"庳": "庳",
"庶": "庶",
"廊": "廊",
"廊": "廊",
"廉": "廉",
"廒": "廒",
"廓": "廓",
"廙": "廙",
"廬": "廬",
"⼵": "廴",
"廾": "廾",
"⼶": "廾",
"𢌱": "𢌱",
"𢌱": "𢌱",
"弄": "弄",
"⼷": "弋",
"⼸": "弓",
"弢": "弢",
"弢": "弢",
"⼹": "彐",
"⺔": "彑",
"当": "当",
"㣇": "㣇",
"⼺": "彡",
"形": "形",
"彩": "彩",
"彫": "彫",
"⼻": "彳",
"律": "律",
"㣣": "㣣",
"徚": "徚",
"復": "復",
"徭": "徭",
"⼼": "心",
"⺖": "忄",
"⺗": "㣺",
"忍": "忍",
"志": "志",
"念": "念",
"忹": "忹",
"怒": "怒",
"怜": "怜",
"恵": "恵",
"㤜": "㤜",
"㤺": "㤺",
"悁": "悁",
"悔": "悔",
"悔": "悔",
"惇": "惇",
"惘": "惘",
"惡": "惡",
"𢛔": "𢛔",
"愈": "愈",
"慨": "慨",
"慄": "慄",
"慈": "慈",
"慌": "慌",
"慌": "慌",
"慎": "慎",
"慎": "慎",
"慠": "慠",
"慺": "慺",
"憎": "憎",
"憎": "憎",
"憎": "憎",
"憐": "憐",
"憤": "憤",
"憯": "憯",
"憲": "憲",
"𢡄": "𢡄",
"𢡊": "𢡊",
"懞": "懞",
"懲": "懲",
"懲": "懲",
"懲": "懲",
"懶": "懶",
"懶": "懶",
"戀": "戀",
"⼽": "戈",
"成": "成",
"戛": "戛",
"戮": "戮",
"戴": "戴",
"⼾": "戶",
"戸": "戶",
"⼿": "手",
"⺘": "扌",
"扝": "扝",
"抱": "抱",
"拉": "拉",
"拏": "拏",
"拓": "拓",
"拔": "拔",
"拼": "拼",
"拾": "拾",
"𢬌": "𢬌",
"挽": "挽",
"捐": "捐",
"捨": "捨",
"捻": "捻",
"掃": "掃",
"掠": "掠",
"掩": "掩",
"揄": "揄",
"揤": "揤",
"摒": "摒",
"𢯱": "𢯱",
"搜": "搜",
"搢": "搢",
"揅": "揅",
"摩": "摩",
"摷": "摷",
"摾": "摾",
"㨮": "㨮",
"搉": "㩁",
"撚": "撚",
"撝": "撝",
"擄": "擄",
"㩬": "㩬",
"⽀": "支",
"⽁": "攴",
"⺙": "攵",
"敏": "敏",
"敏": "敏",
"敖": "敖",
"敬": "敬",
"數": "數",
"𣀊": "𣀊",
"⽂": "文",
"⻫": "斉",
"⽃": "斗",
"料": "料",
"⽄": "斤",
"⽅": "方",
"旅": "旅",
"⽆": "无",
"⺛": "旡",
"既": "既",
"旣": "旣",
"⽇": "日",
"易": "易",
"曶": "㫚",
"㫤": "㫤",
"晉": "晉",
"晩": "晚",
"晴": "晴",
"晴": "晴",
"暑": "暑",
"暑": "暑",
"暈": "暈",
"㬈": "㬈",
"暜": "暜",
"暴": "暴",
"曆": "曆",
"㬙": "㬙",
"𣊸": "𣊸",
"⽈": "曰",
"更": "更",
"書": "書",
"⽉": "月",
"𣍟": "𣍟",
"肦": "朌",
"胐": "朏",
"胊": "朐",
"脁": "朓",
"胶": "㬵",
"朗": "朗",
"朗": "朗",
"朗": "朗",
"脧": "朘",
"望": "望",
"望": "望",
"幐": "㬺",
"䐠": "㬻",
"𣎓": "𣎓",
"膧": "朣",
"𣎜": "𣎜",
"⽊": "木",
"李": "李",
"杓": "杓",
"杖": "杖",
"杞": "杞",
"𣏃": "𣏃",
"柿": "杮",
"杻": "杻",
"枅": "枅",
"林": "林",
"㭉": "㭉",
"𣏕": "𣏕",
"柳": "柳",
"柺": "柺",
"栗": "栗",
"栟": "栟",
"桒": "桒",
"𣑭": "𣑭",
"梁": "梁",
"梅": "梅",
"梅": "梅",
"梎": "梎",
"梨": "梨",
"椔": "椔",
"楂": "楂",
"㮝": "㮝",
"㮝": "㮝",
"槩": "㮣",
"樧": "榝",
"榣": "榣",
"槪": "槪",
"樂": "樂",
"樂": "樂",
"樂": "樂",
"樓": "樓",
"𣚣": "𣚣",
"檨": "檨",
"櫓": "櫓",
"櫛": "櫛",
"欄": "欄",
"㰘": "㰘",
"⽋": "欠",
"次": "次",
"𣢧": "𣢧",
"歔": "歔",
"㱎": "㱎",
"⽌": "止",
"⻭": "歯",
"歲": "歲",
"歷": "歷",
"歹": "歹",
"⽍": "歹",
"⺞": "歺",
"殟": "殟",
"殮": "殮",
"⽎": "殳",
"殺": "殺",
"殺": "殺",
"殺": "殺",
"殻": "殻",
"𣪍": "𣪍",
"⽏": "毋",
"⺟": "母",
"𣫺": "𣫺",
"⽐": "比",
"⽑": "毛",
"⽒": "氏",
"⺠": "民",
"⽓": "气",
"⽔": "水",
"⺡": "氵",
"⺢": "氺",
"汎": "汎",
"汧": "汧",
"沈": "沈",
"沿": "沿",
"泌": "泌",
"泍": "泍",
"泥": "泥",
"𣲼": "𣲼",
"洛": "洛",
"洞": "洞",
"洴": "洴",
"派": "派",
"流": "流",
"流": "流",
"流": "流",
"洖": "洖",
"浩": "浩",
"浪": "浪",
"海": "海",
"海": "海",
"浸": "浸",
"涅": "涅",
"𣴞": "𣴞",
"淋": "淋",
"淚": "淚",
"淪": "淪",
"淹": "淹",
"渚": "渚",
"港": "港",
"湮": "湮",
"潙": "溈",
"滋": "滋",
"滋": "滋",
"溜": "溜",
"溺": "溺",
"滇": "滇",
"滑": "滑",
"滛": "滛",
"㴳": "㴳",
"漏": "漏",
"漢": "漢",
"漢": "漢",
"漣": "漣",
"𣻑": "𣻑",
"潮": "潮",
"𣽞": "𣽞",
"𣾎": "𣾎",
"濆": "濆",
"濫": "濫",
"濾": "濾",
"瀛": "瀛",
"瀞": "瀞",
"瀞": "瀞",
"瀹": "瀹",
"灊": "灊",
"㶖": "㶖",
"⽕": "火",
"⺣": "灬",
"灰": "灰",
"灷": "灷",
"災": "災",
"炙": "炙",
"炭": "炭",
"烈": "烈",
"烙": "烙",
"煮": "煮",
"煮": "煮",
"𤉣": "𤉣",
"煅": "煅",
"煉": "煉",
"𤋮": "𤋮",
"熜": "熜",
"燎": "燎",
"燐": "燐",
"𤎫": "𤎫",
"爐": "爐",
"爛": "爛",
"爨": "爨",
"⽖": "爪",
"爫": "爫",
"⺤": "爫",
"爵": "爵",
"爵": "爵",
"⽗": "父",
"⽘": "爻",
"⺦": "丬",
"⽙": "爿",
"⽚": "片",
"牐": "牐",
"⽛": "牙",
"𤘈": "𤘈",
"⽜": "牛",
"牢": "牢",
"犀": "犀",
"犕": "犕",
"⽝": "犬",
"⺨": "犭",
"犯": "犯",
"狀": "狀",
"𤜵": "𤜵",
"狼": "狼",
"猪": "猪",
"猪": "猪",
"𤠔": "𤠔",
"獵": "獵",
"獺": "獺",
"⽞": "玄",
"率": "率",
"率": "率",
"⽟": "玉",
"王": "王",
"㺬": "㺬",
"玥": "玥",
"玲": "玲",
"㺸": "㺸",
"㺸": "㺸",
"珞": "珞",
"琉": "琉",
"理": "理",
"琢": "琢",
"瑇": "瑇",
"瑜": "瑜",
"瑩": "瑩",
"瑱": "瑱",
"瑱": "瑱",
"璅": "璅",
"璉": "璉",
"璘": "璘",
"瓊": "瓊",
"⽠": "瓜",
"⽡": "瓦",
"㼛": "㼛",
"甆": "甆",
"⽢": "甘",
"⽣": "生",
"甤": "甤",
"⽤": "用",
"⽥": "田",
"画": "画",
"甾": "甾",
"𤰶": "𤰶",
"留": "留",
"略": "略",
"異": "異",
"異": "異",
"𤲒": "𤲒",
"⽦": "疋",
"⽧": "疒",
"痢": "痢",
"瘐": "瘐",
"瘟": "瘟",
"瘝": "瘝",
"療": "療",
"癩": "癩",
"⽨": "癶",
"⽩": "白",
"𤾡": "𤾡",
"𤾸": "𤾸",
"⽪": "皮",
"⽫": "皿",
"𥁄": "𥁄",
"㿼": "㿼",
"益": "益",
"益": "益",
"盛": "盛",
"盧": "盧",
"䀈": "䀈",
"⽬": "目",
"直": "直",
"直": "直",
"𥃲": "𥃲",
"𥃳": "𥃳",
"省": "省",
"䀘": "䀘",
"𥄙": "𥄙",
"眞": "眞",
"真": "真",
"真": "真",
"𥄳": "𥄳",
"着": "着",
"睊": "睊",
"睊": "睊",
"鿃": "䀹",
"䀹": "䀹",
"䀹": "䀹",
"晣": "䀿",
"䁆": "䁆",
"瞋": "瞋",
"𥉉": "𥉉",
"瞧": "瞧",
"⽭": "矛",
"⽮": "矢",
"⽯": "石",
"䂖": "䂖",
"𥐝": "𥐝",
"硏": "研",
"硎": "硎",
"硫": "硫",
"碌": "碌",
"碌": "碌",
"碑": "碑",
"磊": "磊",
"磌": "磌",
"磌": "磌",
"磻": "磻",
"䃣": "䃣",
"礪": "礪",
"⽰": "示",
"⺭": "礻",
"礼": "礼",
"社": "社",
"祈": "祈",
"祉": "祉",
"𥘦": "𥘦",
"祐": "祐",
"祖": "祖",
"祖": "祖",
"祝": "祝",
"神": "神",
"祥": "祥",
"視": "視",
"視": "視",
"祿": "祿",
"𥚚": "𥚚",
"禍": "禍",
"禎": "禎",
"福": "福",
"福": "福",
"𥛅": "𥛅",
"禮": "禮",
"⽱": "禸",
"⽲": "禾",
"秊": "秊",
"䄯": "䄯",
"秫": "秫",
"稜": "稜",
"穊": "穊",
"穀": "穀",
"穀": "穀",
"穏": "穏",
"⽳": "穴",
"突": "突",
"𥥼": "𥥼",
"窱": "窱",
"立": "立",
"⽴": "立",
"⻯": "竜",
"𥪧": "𥪧",
"𥪧": "𥪧",
"竮": "竮",
"⽵": "竹",
"笠": "笠",
"節": "節",
"節": "節",
"䈂": "䈂",
"𥮫": "𥮫",
"篆": "篆",
"䈧": "䈧",
"築": "築",
"𥲀": "𥲀",
"𥳐": "𥳐",
"簾": "簾",
"籠": "籠",
"⽶": "米",
"类": "类",
"粒": "粒",
"精": "精",
"糒": "糒",
"糖": "糖",
"糨": "糨",
"䊠": "䊠",
"糣": "糣",
"糧": "糧",
"⽷": "糸",
"⺯": "糹",
"𥾆": "𥾆",
"紀": "紀",
"紐": "紐",
"索": "索",
"累": "累",
"絶": "絕",
"絣": "絣",
"絛": "絛",
"綠": "綠",
"綾": "綾",
"緇": "緇",
"練": "練",
"練": "練",
"練": "練",
"縂": "縂",
"䌁": "䌁",
"縉": "縉",
"縷": "縷",
"繁": "繁",
"繅": "繅",
"𦇚": "𦇚",
"䌴": "䌴",
"⽸": "缶",
"𦈨": "𦈨",
"缾": "缾",
"𦉇": "𦉇",
"⽹": "网",
"⺫": "罒",
"⺲": "罒",
"⺱": "罓",
"䍙": "䍙",
"署": "署",
"𦋙": "𦋙",
"罹": "罹",
"罺": "罺",
"羅": "羅",
"𦌾": "𦌾",
"⽺": "羊",
"羕": "羕",
"羚": "羚",
"羽": "羽",
"⽻": "羽",
"翺": "翺",
"老": "老",
"⽼": "老",
"⺹": "耂",
"者": "者",
"者": "者",
"者": "者",
"⽽": "而",
"𦓚": "𦓚",
"⽾": "耒",
"𦔣": "𦔣",
"⽿": "耳",
"聆": "聆",
"聠": "聠",
"𦖨": "𦖨",
"聯": "聯",
"聰": "聰",
"聾": "聾",
"⾀": "聿",
"⺺": "肀",
"⾁": "肉",
"肋": "肋",
"肭": "肭",
"育": "育",
"䏕": "䏕",
"䏙": "䏙",
"腁": "胼",
"脃": "脃",
"脾": "脾",
"䐋": "䐋",
"朡": "朡",
"𦞧": "𦞧",
"𦞵": "𦞵",
"朦": "䑃",
"臘": "臘",
"⾂": "臣",
"臨": "臨",
"⾃": "自",
"臭": "臭",
"⾄": "至",
"⾅": "臼",
"舁": "舁",
"舁": "舁",
"舄": "舄",
"⾆": "舌",
"舘": "舘",
"⾇": "舛",
"⾈": "舟",
"䑫": "䑫",
"⾉": "艮",
"良": "良",
"⾊": "色",
"⾋": "艸",
"艹": "艹",
"艹": "艹",
"⺾": "艹",
"⺿": "艹",
"⻀": "艹",
"芋": "芋",
"芑": "芑",
"芝": "芝",
"花": "花",
"芳": "芳",
"芽": "芽",
"若": "若",
"若": "若",
"苦": "苦",
"𦬼": "𦬼",
"茶": "茶",
"荒": "荒",
"荣": "荣",
"茝": "茝",
"茣": "茣",
"莽": "莽",
"荓": "荓",
"菉": "菉",
"菊": "菊",
"菌": "菌",
"菜": "菜",
"菧": "菧",
"華": "華",
"菱": "菱",
"著": "著",
"著": "著",
"𦰶": "𦰶",
"莭": "莭",
"落": "落",
"葉": "葉",
"蔿": "蒍",
"𦳕": "𦳕",
"𦵫": "𦵫",
"蓮": "蓮",
"蓱": "蓱",
"蓳": "蓳",
"蓼": "蓼",
"蔖": "蔖",
"䔫": "䔫",
"蕤": "蕤",
"𦼬": "𦼬",
"藍": "藍",
"䕝": "䕝",
"𦾱": "𦾱",
"䕡": "䕡",
"藺": "藺",
"蘆": "蘆",
"䕫": "䕫",
"蘒": "蘒",
"蘭": "蘭",
"𧃒": "𧃒",
"虁": "蘷",
"蘿": "蘿",
"⾌": "虍",
"⻁": "虎",
"虐": "虐",
"虜": "虜",
"虜": "虜",
"虧": "虧",
"虩": "虩",
"⾍": "虫",
"蚩": "蚩",
"蚈": "蚈",
"蛢": "蛢",
"蜎": "蜎",
"蜨": "蜨",
"蝫": "蝫",
"蟡": "蟡",
"蝹": "蝹",
"蝹": "蝹",
"螆": "螆",
"䗗": "䗗",
"𧏊": "𧏊",
"螺": "螺",
"蠁": "蠁",
"䗹": "䗹",
"蠟": "蠟",
"⾎": "血",
"行": "行",
"⾏": "行",
"衠": "衠",
"衣": "衣",
"⾐": "衣",
"⻂": "衤",
"裂": "裂",
"𧙧": "𧙧",
"裏": "裏",
"裗": "裗",
"裞": "裞",
"裡": "裡",
"裸": "裸",
"裺": "裺",
"䘵": "䘵",
"褐": "褐",
"襁": "襁",
"襤": "襤",
"⾑": "襾",
"⻄": "西",
"⻃": "覀",
"覆": "覆",
"見": "見",
"⾒": "見",
"𧢮": "𧢮",
"⻅": "见",
"⾓": "角",
"⾔": "言",
"𧥦": "𧥦",
"詽": "訮",
"訞": "䚶",
"䚾": "䚾",
"䛇": "䛇",
"誠": "誠",
"說": "說",
"說": "說",
"調": "調",
"請": "請",
"諒": "諒",
"論": "論",
"諭": "諭",
"諭": "諭",
"諸": "諸",
"諸": "諸",
"諾": "諾",
"諾": "諾",
"謁": "謁",
"謁": "謁",
"謹": "謹",
"謹": "謹",
"識": "識",
"讀": "讀",
"讏": "讆",
"變": "變",
"變": "變",
"⻈": "讠",
"⾕": "谷",
"⾖": "豆",
"豈": "豈",
"豕": "豕",
"⾗": "豕",
"豣": "豜",
"⾘": "豸",
"𧲨": "𧲨",
"⾙": "貝",
"貫": "貫",
"賁": "賁",
"賂": "賂",
"賈": "賈",
"賓": "賓",
"贈": "贈",
"贈": "贈",
"贛": "贛",
"⻉": "贝",
"⾚": "赤",
"⾛": "走",
"起": "起",
"趆": "赿",
"𧻓": "𧻓",
"𧼯": "𧼯",
"⾜": "足",
"跋": "跋",
"趼": "趼",
"跺": "跥",
"路": "路",
"跰": "跰",
"躛": "躗",
"⾝": "身",
"車": "車",
"⾞": "車",
"軔": "軔",
"輧": "軿",
"輦": "輦",
"輪": "輪",
"輸": "輸",
"輸": "輸",
"輻": "輻",
"轢": "轢",
"⻋": "车",
"⾟": "辛",
"辞": "辞",
"辰": "辰",
"⾠": "辰",
"⾡": "辵",
"辶": "辶",
"⻌": "辶",
"⻍": "辶",
"巡": "巡",
"連": "連",
"逸": "逸",
"逸": "逸",
"遲": "遲",
"遼": "遼",
"𨗒": "𨗒",
"𨗭": "𨗭",
"邏": "邏",
"⾢": "邑",
"邔": "邔",
"郎": "郎",
"郞": "郎",
"郞": "郎",
"郱": "郱",
"都": "都",
"𨜮": "𨜮",
"鄑": "鄑",
"鄛": "鄛",
"⾣": "酉",
"酪": "酪",
"醙": "醙",
"醴": "醴",
"⾤": "釆",
"里": "里",
"⾥": "里",
"量": "量",
"金": "金",
"⾦": "金",
"鈴": "鈴",
"鈸": "鈸",
"鉶": "鉶",
"鋗": "鋗",
"鋘": "鋘",
"鉼": "鉼",
"錄": "錄",
"鍊": "鍊",
"鎮": "鎭",
"鏹": "鏹",
"鐕": "鐕",
"𨯺": "𨯺",
"⻐": "钅",
"⻑": "長",
"⾧": "長",
"⻒": "镸",
"⻓": "长",
"⾨": "門",
"開": "開",
"䦕": "䦕",
"閭": "閭",
"閷": "閷",
"𨵷": "𨵷",
"⻔": "门",
"⾩": "阜",
"⻏": "阝",
"⻖": "阝",
"阮": "阮",
"陋": "陋",
"降": "降",
"陵": "陵",
"陸": "陸",
"陼": "陼",
"隆": "隆",
"隣": "隣",
"䧦": "䧦",
"⾪": "隶",
"隷": "隷",
"隸": "隷",
"隸": "隷",
"⾫": "隹",
"雃": "雃",
"離": "離",
"難": "難",
"難": "難",
"⾬": "雨",
"零": "零",
"雷": "雷",
"霣": "霣",
"𩅅": "𩅅",
"露": "露",
"靈": "靈",
"⾭": "靑",
"⻘": "青",
"靖": "靖",
"靖": "靖",
"𩇟": "𩇟",
"⾮": "非",
"⾯": "面",
"𩈚": "𩈚",
"⾰": "革",
"䩮": "䩮",
"䩶": "䩶",
"⾱": "韋",
"韛": "韛",
"韠": "韠",
"⻙": "韦",
"⾲": "韭",
"𩐊": "𩐊",
"⾳": "音",
"響": "響",
"響": "響",
"⾴": "頁",
"䪲": "䪲",
"頋": "頋",
"頋": "頋",
"頋": "頋",
"領": "領",
"頩": "頩",
"𩒖": "𩒖",
"頻": "頻",
"頻": "頻",
"類": "類",
"⻚": "页",
"⾵": "風",
"𩖶": "𩖶",
"⻛": "风",
"⾶": "飛",
"⻜": "飞",
"⻝": "食",
"⾷": "食",
"⻟": "飠",
"飢": "飢",
"飯": "飯",
"飼": "飼",
"䬳": "䬳",
"館": "館",
"餩": "餩",
"⻠": "饣",
"⾸": "首",
"⾹": "香",
"馧": "馧",
"⾺": "馬",
"駂": "駂",
"駱": "駱",
"駾": "駾",
"驪": "驪",
"⻢": "马",
"⾻": "骨",
"䯎": "䯎",
"⾼": "高",
"⾽": "髟",
"𩬰": "𩬰",
"鬒": "鬒",
"鬒": "鬒",
"⾾": "鬥",
"⾿": "鬯",
"⿀": "鬲",
"⿁": "鬼",
"⻤": "鬼",
"⿂": "魚",
"魯": "魯",
"鱀": "鱀",
"鱗": "鱗",
"⻥": "鱼",
"⿃": "鳥",
"鳽": "鳽",
"䳎": "䳎",
"鵧": "鵧",
"䳭": "䳭",
"𪃎": "𪃎",
"鶴": "鶴",
"𪄅": "𪄅",
"䳸": "䳸",
"鷺": "鷺",
"𪈎": "𪈎",
"鸞": "鸞",
"鹃": "鹂",
"⿄": "鹵",
"鹿": "鹿",
"⿅": "鹿",
"𪊑": "𪊑",
"麗": "麗",
"麟": "麟",
"⿆": "麥",
"⻨": "麦",
"麻": "麻",
"⿇": "麻",
"𪎒": "𪎒",
"⿈": "黃",
"⻩": "黄",
"⿉": "黍",
"黎": "黎",
"䵖": "䵖",
"⿊": "黑",
"黒": "黑",
"墨": "墨",
"黹": "黹",
"⿋": "黹",
"⿌": "黽",
"鼅": "鼅",
"黾": "黾",
"⿍": "鼎",
"鼏": "鼏",
"⿎": "鼓",
"鼖": "鼖",
"⿏": "鼠",
"鼻": "鼻",
"⿐": "鼻",
"齃": "齃",
"⿑": "齊",
"⻬": "齐",
"⿒": "齒",
"𪘀": "𪘀",
"⻮": "齿",
"龍": "龍",
"⿓": "龍",
"龎": "龎",
"⻰": "龙",
"龜": "龜",
"龜": "龜",
"龜": "龜",
"⿔": "龜",
"⻳": "龟",
"⿕": "龠"
};
}));
//#endregion
//#region node_modules/unhomoglyph/index.js
var require_unhomoglyph = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var data = require_data();
function escapeRegexp(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
var REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join("|"), "g");
function replace_fn(match) {
return data[match];
}
function unhomoglyph(str) {
return str.replace(REPLACE_RE, replace_fn);
}
module.exports = unhomoglyph;
}));
//#endregion
//#region node_modules/is-network-error/index.js
const objectToString = Object.prototype.toString;
const isError = (value) => objectToString.call(value) === "[object Error]";
const errorMessages = new Set([
"network error",
"NetworkError when attempting to fetch resource.",
"The Internet connection appears to be offline.",
"Network request failed",
"fetch failed",
"terminated",
" A network error occurred.",
"Network connection lost"
]);
function isNetworkError(error) {
if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false;
const { message, stack } = error;
if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error;
if (message.startsWith("error sending request for url")) return true;
if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) return true;
return errorMessages.has(message);
}
//#endregion
//#region node_modules/matrix-js-sdk/node_modules/p-retry/index.js
function validateRetries(retries) {
if (typeof retries === "number") {
if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number.");
if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
} else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity.");
}
function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
if (value === void 0) return;
if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`);
if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
}
var AbortError = class extends Error {
constructor(message) {
super();
if (message instanceof Error) {
this.originalError = message;
({message} = message);
} else {
this.originalError = new Error(message);
this.originalError.stack = this.stack;
}
this.name = "AbortError";
this.message = message;
}
};
function calculateDelay(retriesConsumed, options) {
const attempt = Math.max(1, retriesConsumed + 1);
const random = options.randomize ? Math.random() + 1 : 1;
let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
timeout = Math.min(timeout, options.maxTimeout);
return timeout;
}
function calculateRemainingTime(start, max) {
if (!Number.isFinite(max)) return max;
return max - (performance.now() - start);
}
async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
if (normalizedError instanceof AbortError) throw normalizedError.originalError;
const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
const context = Object.freeze({
error: normalizedError,
attemptNumber,
retriesLeft,
retriesConsumed
});
await options.onFailedAttempt(context);
if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError;
const consumeRetry = await options.shouldConsumeRetry(context);
const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError;
if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {
if (consumeRetry) throw normalizedError;
options.signal?.throwIfAborted();
return false;
}
if (!await options.shouldRetry(context)) throw normalizedError;
if (!consumeRetry) {
options.signal?.throwIfAborted();
return false;
}
const delayTime = calculateDelay(retriesConsumed, options);
const finalDelay = Math.min(delayTime, remainingTime);
options.signal?.throwIfAborted();
if (finalDelay > 0) await new Promise((resolve, reject) => {
const onAbort = () => {
clearTimeout(timeoutToken);
options.signal?.removeEventListener("abort", onAbort);
reject(options.signal.reason);
};
const timeoutToken = setTimeout(() => {
options.signal?.removeEventListener("abort", onAbort);
resolve();
}, finalDelay);
if (options.unref) timeoutToken.unref?.();
options.signal?.addEventListener("abort", onAbort, { once: true });
});
options.signal?.throwIfAborted();
return true;
}
async function pRetry(input, options = {}) {
options = { ...options };
validateRetries(options.retries);
if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
options.retries ??= 10;
options.factor ??= 2;
options.minTimeout ??= 1e3;
options.maxTimeout ??= Number.POSITIVE_INFINITY;
options.maxRetryTime ??= Number.POSITIVE_INFINITY;
options.randomize ??= false;
options.onFailedAttempt ??= () => {};
options.shouldRetry ??= () => true;
options.shouldConsumeRetry ??= () => true;
validateNumberOption("factor", options.factor, {
min: 0,
allowInfinity: false
});
validateNumberOption("minTimeout", options.minTimeout, {
min: 0,
allowInfinity: false
});
validateNumberOption("maxTimeout", options.maxTimeout, {
min: 0,
allowInfinity: true
});
validateNumberOption("maxRetryTime", options.maxRetryTime, {
min: 0,
allowInfinity: true
});
if (!(options.factor > 0)) options.factor = 1;
options.signal?.throwIfAborted();
let attemptNumber = 0;
let retriesConsumed = 0;
const startTime = performance.now();
while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
attemptNumber++;
try {
options.signal?.throwIfAborted();
const result = await input(attemptNumber);
options.signal?.throwIfAborted();
return result;
} catch (error) {
if (await onAttemptFailure({
error,
attemptNumber,
retriesConsumed,
startTime,
options
})) retriesConsumed++;
}
}
throw new Error("Retry attempts exhausted without throwing an error.");
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/NamespacedValue.js
var import_defineProperty = /* @__PURE__ */ __toESM(require_defineProperty(), 1);
/**
* Represents a simple Matrix namespaced value. This will assume that if a stable prefix
* is provided that the stable prefix should be used when representing the identifier.
*/
var NamespacedValue$1 = class {
constructor(stable, unstable) {
this.stable = stable;
this.unstable = unstable;
if (!this.unstable && !this.stable) throw new Error("One of stable or unstable values must be supplied");
}
get name() {
if (this.stable) return this.stable;
return this.unstable;
}
get altName() {
if (!this.stable) return null;
return this.unstable;
}
get names() {
var names = [this.name];
var altName = this.altName;
if (altName) names.push(altName);
return names;
}
matches(val) {
return this.name === val || this.altName === val;
}
findIn(obj) {
var val = void 0;
if (this.name) val = obj === null || obj === void 0 ? void 0 : obj[this.name];
if (!val && this.altName) val = obj === null || obj === void 0 ? void 0 : obj[this.altName];
return val;
}
includedIn(arr) {
var included = false;
if (this.name) included = arr.includes(this.name);
if (!included && this.altName) included = arr.includes(this.altName);
return included;
}
};
var ServerControlledNamespacedValue = class extends NamespacedValue$1 {
constructor() {
super(...arguments);
(0, import_defineProperty.default)(this, "preferUnstable", false);
}
setPreferUnstable(preferUnstable) {
this.preferUnstable = preferUnstable;
}
get name() {
if (this.stable && !this.preferUnstable) return this.stable;
return this.unstable;
}
};
/**
* Represents a namespaced value which prioritizes the unstable value over the stable
* value.
*/
var UnstableValue$3 = class extends NamespacedValue$1 {
constructor(stable, unstable) {
super(stable, unstable);
if (!this.unstable) throw new Error("Unstable value must be supplied");
}
get name() {
return this.unstable;
}
get altName() {
return this.stable;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/location.js
var M_ASSET = new UnstableValue$3("m.asset", "org.matrix.msc3488.asset");
/**
* The event definition for an m.asset event (in content)
*/
var M_TIMESTAMP = new UnstableValue$3("m.ts", "org.matrix.msc3488.ts");
/**
* The event definition for an m.ts event (in content)
*/
var M_LOCATION = new UnstableValue$3("m.location", "org.matrix.msc3488.location");
/**
* The content for an m.location event
*/
/**
* Possible content for location events as sent over the wire
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/read_receipts.js
var ReceiptType = /* @__PURE__ */ function(ReceiptType) {
ReceiptType["Read"] = "m.read";
ReceiptType["FullyRead"] = "m.fully_read";
ReceiptType["ReadPrivate"] = "m.read.private";
return ReceiptType;
}({});
var MAIN_ROOM_TIMELINE = "main";
//#endregion
//#region node_modules/matrix-js-sdk/lib/utils.js
var import_asyncToGenerator = /* @__PURE__ */ __toESM(require_asyncToGenerator(), 1);
var import_unhomoglyph = /* @__PURE__ */ __toESM(require_unhomoglyph(), 1);
function ownKeys$19(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;
}
function _objectSpread$19(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$19(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$19(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var interns = /* @__PURE__ */ new Map();
/**
* Internalises a string, reusing a known pointer or storing the pointer
* if needed for future strings.
* @param str - The string to internalise.
* @returns The internalised string.
*/
function internaliseString(str) {
if (str instanceof String) str = str.toString();
if (!interns.has(str)) interns.set(str, str);
return interns.get(str);
}
/**
* Encode a dictionary of query parameters.
* Omits any undefined/null values.
* @param params - A dict of key/values to encode e.g.
* `{"foo": "bar", "baz": "taz"}`
* @returns The encoded string e.g. foo=bar&baz=taz
*/
function encodeParams(params, urlSearchParams) {
var searchParams = urlSearchParams !== null && urlSearchParams !== void 0 ? urlSearchParams : new URLSearchParams();
var _loop = function _loop(key) {
if (val !== void 0 && val !== null) if (Array.isArray(val)) val.forEach((v) => {
searchParams.append(key, String(v));
});
else searchParams.append(key, String(val));
};
for (var [key, val] of Object.entries(params)) _loop(key);
return searchParams;
}
/**
* Replace a stable parameter with the unstable naming for params
*/
function replaceParam(stable, unstable, dict) {
var result = _objectSpread$19(_objectSpread$19({}, dict), {}, { [unstable]: dict[stable] });
delete result[stable];
return result;
}
/**
* Encodes a URI according to a set of template variables. Variables will be
* passed through encodeURIComponent.
* @param pathTemplate - The path with template variables e.g. '/foo/$bar'.
* @param variables - The key/value pairs to replace the template
* variables with. E.g. `{ "$bar": "baz" }`.
* @returns The result of replacing all template variables e.g. '/foo/baz'.
*/
function encodeUri(pathTemplate, variables) {
for (var key in variables) {
if (!variables.hasOwnProperty(key)) continue;
var value = variables[key];
if (value === void 0 || value === null) continue;
pathTemplate = pathTemplate.replace(key, encodeURIComponent(value));
}
return pathTemplate;
}
/**
* The removeElement() method removes the first element in the array that
* satisfies (returns true) the provided testing function.
* @param array - The array.
* @param fn - Function to execute on each value in the array, with the
* function signature `fn(element, index, array)`. Return true to
* remove this element and break.
* @param reverse - True to search in reverse order.
* @returns True if an element was removed.
*/
function removeElement(array, fn, reverse) {
var i;
if (reverse) {
for (i = array.length - 1; i >= 0; i--) if (fn(array[i], i, array)) {
array.splice(i, 1);
return true;
}
} else for (i = 0; i < array.length; i++) if (fn(array[i], i, array)) {
array.splice(i, 1);
return true;
}
return false;
}
/**
* Checks that the given object has the specified keys.
* @param obj - The object to check.
* @param keys - The list of keys that 'obj' must have.
* @throws If the object is missing keys.
*/
function checkObjectHasKeys(obj, keys) {
for (var key of keys) if (!obj.hasOwnProperty(key)) throw new Error("Missing required key: " + key);
}
/**
* Deep copy the given object. The object MUST NOT have circular references and
* MUST NOT have functions.
* @param obj - The object to deep copy.
* @returns A copy of the object without any references to the original.
*/
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* Compare two objects for equality. The objects MUST NOT have circular references.
*
* @param x - The first object to compare.
* @param y - The second object to compare.
*
* @returns true if the two objects are equal
*/
function deepCompare(x, y) {
if (x === y) return true;
if (typeof x !== typeof y) return false;
if (typeof x === "number" && isNaN(x) && isNaN(y)) return true;
if (x === null || y === null) return x === y;
if (x.constructor.name !== "Object" && x.constructor.name !== "RegExp" && x.constructor.name !== "Date" && x.constructor.name !== "Array") return false;
if (x.prototype !== y.prototype) return false;
if (x instanceof RegExp || x instanceof Date) return x.toString() === y.toString();
if (Array.isArray(x)) {
if (x.length !== y.length) return false;
for (var i = 0; i < x.length; i++) if (!deepCompare(x[i], y[i])) return false;
} else {
for (var p in y) if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) return false;
for (var _p in x) if (y.hasOwnProperty(_p) !== x.hasOwnProperty(_p) || !deepCompare(x[_p], y[_p])) return false;
}
return true;
}
/**
* Creates an array of object properties/values (entries) then
* sorts the result by key, recursively. The input object must
* ensure it does not have loops. If the input is not an object
* then it will be returned as-is.
* @param obj - The object to get entries of
* @returns The entries, sorted by key.
*/
function deepSortedObjectEntries(obj) {
if (typeof obj !== "object") return obj;
if (obj === null || obj === void 0 || Array.isArray(obj)) return obj;
var pairs = [];
for (var [k, v] of Object.entries(obj)) pairs.push([k, deepSortedObjectEntries(v)]);
pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));
return pairs;
}
/**
* Returns whether the given value is a finite number without type-coercion
*
* @param value - the value to test
* @returns whether or not value is a finite number without type-coercion
*/
function isNumber(value) {
return typeof value === "number" && isFinite(value);
}
/**
* Removes zero width chars, diacritics and whitespace from the string
* Also applies an unhomoglyph on the string, to prevent similar looking chars
* @param str - the string to remove hidden characters from
* @returns a string with the hidden characters removed
*/
function removeHiddenChars(str) {
if (typeof str === "string") return (0, import_unhomoglyph.default)(str.normalize("NFD").replace(removeHiddenCharsRegex, ""));
return "";
}
/**
* Removes the direction override characters from a string
* @returns string with chars removed
*/
function removeDirectionOverrideChars(str) {
if (typeof str === "string") return str.replace(/[\u202d-\u202e]/g, "");
return "";
}
function normalize(str) {
return removeHiddenChars(str.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g, "").toLowerCase();
}
var removeHiddenCharsRegex = /[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Converts Matrix glob-style string to a regular expression
* https://spec.matrix.org/v1.7/appendices/#glob-style-matching
* @param glob - Matrix glob-style string
* @returns regular expression
*/
function globToRegexp(glob) {
return escapeRegExp(glob).replace(/\\\*/g, ".*").replace(/\?/g, ".");
}
function ensureNoTrailingSlash(url) {
if (url !== null && url !== void 0 && url.endsWith("/")) return url.slice(0, -1);
else return url;
}
/**
* Returns a promise which resolves with a given value after the given number of ms
*/
function sleep(ms, value) {
return new Promise((resolve) => {
setTimeout(resolve, ms, value);
});
}
/**
* Utility to log the duration of a promise.
*
* @param logger - The logger to log to.
* @param name - The name of the operation.
* @param block - The block to execute.
*/
function logDuration(_x, _x2, _x3) {
return _logDuration.apply(this, arguments);
}
/**
* Utility to log the duration of a synchronous block.
*
* @param logger - The logger to log to.
* @param name - The name of the operation.
* @param block - The block to execute.
*/
function _logDuration() {
_logDuration = (0, import_asyncToGenerator.default)(function* (logger, name, block) {
var start = Date.now();
try {
return yield block();
} finally {
var end = Date.now();
logger.debug("[Perf]: ".concat(name, " took ").concat(end - start, "ms"));
}
});
return _logDuration.apply(this, arguments);
}
function logDurationSync(logger, name, block) {
var start = Date.now();
try {
return block();
} finally {
var end = Date.now();
logger.debug("[Perf]: ".concat(name, " took ").concat(end - start, "ms"));
}
}
function isNullOrUndefined(val) {
return val === null || val === void 0;
}
function promiseMapSeries(_x4, _x5) {
return _promiseMapSeries.apply(this, arguments);
}
function _promiseMapSeries() {
_promiseMapSeries = (0, import_asyncToGenerator.default)(function* (promises, fn) {
for (var o of promises) yield fn(yield o);
});
return _promiseMapSeries.apply(this, arguments);
}
function simpleRetryOperation(promiseFn, shouldRetry) {
return pRetry((attempt) => {
return promiseFn(attempt);
}, {
retries: Infinity,
shouldRetry: shouldRetry ? (_ref) => {
var { error } = _ref;
return shouldRetry(error);
} : void 0,
factor: 2,
minTimeout: 3e3,
maxTimeout: 15e3
});
}
/**
* The default alphabet used by string averaging in this SDK. This matches
* all usefully printable ASCII characters (0x20-0x7E, inclusive).
*/
var DEFAULT_ALPHABET = (() => {
var str = "";
for (var c = 32; c <= 126; c++) str += String.fromCharCode(c);
return str;
})();
/**
* Pads a string using the given alphabet as a base. The returned string will be
* padded at the end with the first character in the alphabet.
*
* This is intended for use with string averaging.
* @param s - The string to pad.
* @param n - The length to pad to.
* @param alphabet - The alphabet to use as a single string.
* @returns The padded string.
*/
function alphabetPad(s, n) {
var alphabet = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : DEFAULT_ALPHABET;
return s.padEnd(n, alphabet[0]);
}
/**
* Converts a baseN number to a string, where N is the alphabet's length.
*
* This is intended for use with string averaging.
* @param n - The baseN number.
* @param alphabet - The alphabet to use as a single string.
* @returns The baseN number encoded as a string from the alphabet.
*/
function baseToString(n) {
var alphabet = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_ALPHABET;
var len = BigInt(alphabet.length);
if (n <= len) {
var _alphabet;
return (_alphabet = alphabet[Number(n) - 1]) !== null && _alphabet !== void 0 ? _alphabet : "";
}
var d = n / len;
var r = Number(n % len) - 1;
if (r < 0) {
d -= BigInt(Math.abs(r));
r = Number(len) - 1;
}
return baseToString(d, alphabet) + alphabet[r];
}
/**
* Converts a string to a baseN number, where N is the alphabet's length.
*
* This is intended for use with string averaging.
* @param s - The string to convert to a number.
* @param alphabet - The alphabet to use as a single string.
* @returns The baseN number.
*/
function stringToBase(s) {
var alphabet = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_ALPHABET;
var len = BigInt(alphabet.length);
var result = BigInt(0);
for (var i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {
var charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);
result += BigInt(1 + charIndex) * len ** j;
}
return result;
}
/**
* Averages two strings, returning the midpoint between them. This is accomplished by
* converting both to baseN numbers (where N is the alphabet's length) then averaging
* those before re-encoding as a string.
* @param a - The first string.
* @param b - The second string.
* @param alphabet - The alphabet to use as a single string.
* @returns The midpoint between the strings, as a string.
*/
function averageBetweenStrings(a, b) {
var alphabet = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : DEFAULT_ALPHABET;
var padN = Math.max(a.length, b.length);
var baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);
var baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);
var avg = (baseA + baseB) / BigInt(2);
if (avg === baseA || avg == baseB) return baseToString(avg, alphabet) + alphabet[0];
return baseToString(avg, alphabet);
}
/**
* Finds the next string using the alphabet provided. This is done by converting the
* string to a baseN number, where N is the alphabet's length, then adding 1 before
* converting back to a string.
* @param s - The string to start at.
* @param alphabet - The alphabet to use as a single string.
* @returns The string which follows the input string.
*/
function nextString(s) {
var alphabet = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_ALPHABET;
return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);
}
/**
* Finds the previous string using the alphabet provided. This is done by converting the
* string to a baseN number, where N is the alphabet's length, then subtracting 1 before
* converting back to a string.
* @param s - The string to start at.
* @param alphabet - The alphabet to use as a single string.
* @returns The string which precedes the input string.
*/
function prevString(s) {
var alphabet = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_ALPHABET;
return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);
}
/**
* Compares strings lexicographically as a sort-safe function.
* @param a - The first (reference) string.
* @param b - The second (compare) string.
* @returns Negative if the reference string is before the compare string;
* positive if the reference string is after; and zero if equal.
*/
function lexicographicCompare(a, b) {
if (a < b) return -1;
else if (a > b) return 1;
else return 0;
}
/**
* This function is similar to Object.assign() but it assigns recursively and
* allows you to ignore nullish values from the source
*
* @returns the target object
*/
function recursivelyAssign(target, source) {
var ignoreNullish = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
for (var [sourceKey, sourceValue] of Object.entries(source)) {
if (target[sourceKey] instanceof Object && sourceValue) {
recursivelyAssign(target[sourceKey], sourceValue);
continue;
}
if (sourceValue !== null && sourceValue !== void 0 || !ignoreNullish) {
safeSet(target, sourceKey, sourceValue);
continue;
}
}
return target;
}
function getContentTimestampWithFallback(event) {
var _M_TIMESTAMP$findIn;
return (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(event.getContent())) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : -1;
}
/**
* Sort events by their content m.ts property
* Latest timestamp first
*/
function sortEventsByLatestContentTimestamp(left, right) {
return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);
}
function isSupportedReceiptType(receiptType) {
return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType);
}
/**
* Determines whether two maps are equal.
* @param eq - The equivalence relation to compare values by. Defaults to strict equality.
*/
function mapsEqual(x, y) {
var eq = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : (v1, v2) => v1 === v2;
if (x.size !== y.size) return false;
for (var [k, v1] of x) {
var v2 = y.get(k);
if (v2 === void 0 || !eq(v1, v2)) return false;
}
return true;
}
function processMapToObjectValue(value) {
if (value instanceof Map) return recursiveMapToObject(value);
else if (Array.isArray(value)) return value.map((v) => processMapToObjectValue(v));
else return value;
}
/**
* Recursively converts Maps to plain objects.
* Also supports sub-lists of Maps.
*/
function recursiveMapToObject(map) {
var targetMap = /* @__PURE__ */ new Map();
for (var [key, value] of map) targetMap.set(key, processMapToObjectValue(value));
return Object.fromEntries(targetMap.entries());
}
function unsafeProp(prop) {
return prop === "__proto__" || prop === "prototype" || prop === "constructor";
}
function safeSet(obj, prop, value) {
if (unsafeProp(prop)) throw new Error("Trying to modify prototype or constructor");
obj[prop] = value;
}
function noUnsafeEventProps(event) {
return !(unsafeProp(event.room_id) || unsafeProp(event.sender) || unsafeProp(event.event_id));
}
var MapWithDefault = class extends Map {
constructor(createDefault) {
super();
this.createDefault = createDefault;
}
/**
* Returns the value if the key already exists.
* If not, it creates a new value under that key using the ctor callback and returns it.
*/
getOrCreate(key) {
if (!this.has(key)) this.set(key, this.createDefault());
return this.get(key);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto/store/base.js
/**
* Internal module. Definitions for storage for the crypto module
*/
/**
* Abstraction of things that can store data required for end-to-end encryption
*/
/** Data on a Megolm session */
/** Extended data on a Megolm session */
/** Data on an Olm session */
/**
* Represents an outgoing room key request
*/
/**
* Keys for the `account` object store to store the migration state.
* Values are defined in `MigrationState`.
* @internal
*/
var ACCOUNT_OBJECT_KEY_MIGRATION_STATE = "migrationState";
/**
* A record of which steps have been completed in the libolm to Rust Crypto migration.
*
* Used by {@link CryptoStore#getMigrationState} and {@link CryptoStore#setMigrationState}.
*
* @internal
*/
var MigrationState = /* @__PURE__ */ function(MigrationState) {
/** No migration steps have yet been completed. */
MigrationState[MigrationState["NOT_STARTED"] = 0] = "NOT_STARTED";
/** We have migrated the account data, cross-signing keys, etc. */
MigrationState[MigrationState["INITIAL_DATA_MIGRATED"] = 1] = "INITIAL_DATA_MIGRATED";
/** INITIAL_DATA_MIGRATED, and in addition, we have migrated all the Olm sessions. */
MigrationState[MigrationState["OLM_SESSIONS_MIGRATED"] = 2] = "OLM_SESSIONS_MIGRATED";
/** OLM_SESSIONS_MIGRATED, and in addition, we have migrated all the Megolm sessions. */
MigrationState[MigrationState["MEGOLM_SESSIONS_MIGRATED"] = 3] = "MEGOLM_SESSIONS_MIGRATED";
/** MEGOLM_SESSIONS_MIGRATED, and in addition, we have migrated all the room settings. */
MigrationState[MigrationState["ROOM_SETTINGS_MIGRATED"] = 4] = "ROOM_SETTINGS_MIGRATED";
/** ROOM_SETTINGS_MIGRATED, and in addition, we have done the first own keys query in order to
* load the public part of the keys that have been migrated */
MigrationState[MigrationState["INITIAL_OWN_KEY_QUERY_DONE"] = 5] = "INITIAL_OWN_KEY_QUERY_DONE";
return MigrationState;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto/store/memory-crypto-store.js
function ownKeys$18(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;
}
function _objectSpread$18(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$18(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$18(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function encodeSessionKey(senderCurve25519Key, sessionId) {
return encodeURIComponent(senderCurve25519Key) + "/" + encodeURIComponent(sessionId);
}
function decodeSessionKey(key) {
var keyParts = key.split("/");
return {
senderKey: decodeURIComponent(keyParts[0]),
sessionId: decodeURIComponent(keyParts[1])
};
}
/**
* Internal module. in-memory storage for e2e.
*/
var MemoryCryptoStore = class {
constructor() {
(0, import_defineProperty.default)(this, "migrationState", MigrationState.NOT_STARTED);
(0, import_defineProperty.default)(this, "account", null);
(0, import_defineProperty.default)(this, "crossSigningKeys", null);
(0, import_defineProperty.default)(this, "privateKeys", {});
(0, import_defineProperty.default)(this, "sessions", {});
(0, import_defineProperty.default)(this, "inboundGroupSessions", {});
(0, import_defineProperty.default)(this, "inboundGroupSessionsWithheld", {});
(0, import_defineProperty.default)(this, "rooms", {});
(0, import_defineProperty.default)(this, "sessionsNeedingBackup", {});
}
/**
* Returns true if this CryptoStore has ever been initialised (ie, it might contain data).
*
* Implementation of {@link CryptoStore.containsData}.
*
* @internal
*/
containsData() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this.account !== null;
})();
}
/**
* Ensure the database exists and is up-to-date.
*
* This must be called before the store can be used.
*
* @returns resolves to the store.
*/
startup() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this2;
})();
}
/**
* Delete all data from this store.
*
* @returns Promise which resolves when the store has been cleared.
*/
deleteAllData() {
return Promise.resolve();
}
/**
* Get data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.getMigrationState}.
*
* @internal
*/
getMigrationState() {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this3.migrationState;
})();
}
/**
* Set data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.setMigrationState}.
*
* @internal
*/
setMigrationState(migrationState) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
_this4.migrationState = migrationState;
})();
}
getAccount(txn, func) {
func(this.account);
}
storeAccount(txn, accountPickle) {
this.account = accountPickle;
}
getCrossSigningKeys(txn, func) {
func(this.crossSigningKeys);
}
getSecretStorePrivateKey(txn, func, type) {
var result = this.privateKeys[type];
func(result || null);
}
storeSecretStorePrivateKey(txn, type, key) {
this.privateKeys[type] = key;
}
countEndToEndSessions(txn, func) {
var count = 0;
for (var deviceSessions of Object.values(this.sessions)) count += Object.keys(deviceSessions).length;
func(count);
}
getEndToEndSession(deviceKey, sessionId, txn, func) {
func((this.sessions[deviceKey] || {})[sessionId] || null);
}
getEndToEndSessions(deviceKey, txn, func) {
func(this.sessions[deviceKey] || {});
}
storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
var deviceSessions = this.sessions[deviceKey];
if (deviceSessions === void 0) {
deviceSessions = {};
this.sessions[deviceKey] = deviceSessions;
}
safeSet(deviceSessions, sessionId, sessionInfo);
}
/**
* Fetch a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.
*
* @internal
*/
getEndToEndSessionsBatch() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = [];
for (var deviceSessions of Object.values(_this5.sessions)) for (var session of Object.values(deviceSessions)) {
result.push(session);
if (result.length >= 50) return result;
}
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.
*
* @internal
*/
deleteEndToEndSessionsBatch(sessions) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var { deviceKey, sessionId } of sessions) {
var deviceSessions = _this6.sessions[deviceKey] || {};
delete deviceSessions[sessionId];
if (Object.keys(deviceSessions).length === 0) delete _this6.sessions[deviceKey];
}
})();
}
getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
var k = encodeSessionKey(senderCurve25519Key, sessionId);
func(this.inboundGroupSessions[k] || null, this.inboundGroupSessionsWithheld[k] || null);
}
storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
var k = encodeSessionKey(senderCurve25519Key, sessionId);
this.inboundGroupSessions[k] = sessionData;
}
/**
* Count the number of Megolm sessions in the database.
*
* Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.
*
* @internal
*/
countEndToEndInboundGroupSessions() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
return Object.keys(_this7.inboundGroupSessions).length;
})();
}
/**
* Fetch a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
getEndToEndInboundGroupSessionsBatch() {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = [];
for (var [key, session] of Object.entries(_this8.inboundGroupSessions)) {
result.push(_objectSpread$18(_objectSpread$18({}, decodeSessionKey(key)), {}, {
sessionData: session,
needsBackup: key in _this8.sessionsNeedingBackup
}));
if (result.length >= 50) return result;
}
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
deleteEndToEndInboundGroupSessionsBatch(sessions) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var { senderKey, sessionId } of sessions) {
var k = encodeSessionKey(senderKey, sessionId);
delete _this9.inboundGroupSessions[k];
}
})();
}
getEndToEndRooms(txn, func) {
func(this.rooms);
}
markSessionsNeedingBackup(sessions) {
for (var session of sessions) {
var sessionKey = encodeSessionKey(session.senderKey, session.sessionId);
this.sessionsNeedingBackup[sessionKey] = true;
}
return Promise.resolve();
}
doTxn(mode, stores, func) {
return Promise.resolve(func(null));
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/content-repo.js
var serverNameRegex = /^(?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:\[[\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\d\-.]{1,255}))(?::\d{1,5})?$/;
function validateServerName(serverName) {
var matches = serverNameRegex.exec(serverName);
return (matches === null || matches === void 0 ? void 0 : matches[0]) === serverName;
}
var mediaIdRegex = /^[\w-]+$/;
function validateMediaId(mediaId) {
var matches = mediaIdRegex.exec(mediaId);
return (matches === null || matches === void 0 ? void 0 : matches[0]) === mediaId;
}
/**
* Get the HTTP URL for an MXC URI.
* @param baseUrl - The base homeserver url which has a content repo.
* @param mxc - The mxc:// URI.
* @param width - The desired width of the thumbnail.
* @param height - The desired height of the thumbnail.
* @param resizeMethod - The thumbnail resize method to use, either
* "crop" or "scale".
* @param allowDirectLinks - If true, return any non-mxc URLs
* directly. Fetching such URLs will leak information about the user to
* anyone they share a room with. If false, will return the emptry string
* for such URLs.
* @param allowRedirects - If true, the caller supports the URL being 307 or
* 308 redirected to another resource upon request. If false, redirects
* are not expected. Implied `true` when `useAuthentication` is `true`.
* @param useAuthentication - If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support
* for authenticated media will *not* be checked - it is the caller's responsibility
* to do so before calling this function. Note also that `useAuthentication`
* implies `allowRedirects`. Defaults to false (unauthenticated endpoints).
* @param animated - Whether the desired thumbnail should be animated.
* @returns The complete URL to the content, may be an empty string if the provided mxc is not valid.
*/
function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {
var allowDirectLinks = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false;
var allowRedirects = arguments.length > 6 ? arguments[6] : void 0;
var useAuthentication = arguments.length > 7 ? arguments[7] : void 0;
var animated = arguments.length > 8 ? arguments[8] : void 0;
if (typeof mxc !== "string" || !mxc) return "";
if (!mxc.startsWith("mxc://")) if (allowDirectLinks) return mxc;
else return "";
var [serverName, mediaId, ...rest] = mxc.slice(6).split("/");
if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) return "";
if (useAuthentication) allowRedirects = true;
var prefix;
var verb = !!width || !!height || !!resizeMethod ? "thumbnail" : "download";
if (useAuthentication) prefix = "/_matrix/client/v1/media/".concat(verb);
else prefix = "/_matrix/media/v3/".concat(verb);
var url = new URL("".concat(prefix, "/").concat(serverName, "/").concat(mediaId), baseUrl);
if (width) url.searchParams.set("width", Math.round(width).toString());
if (height) url.searchParams.set("height", Math.round(height).toString());
if (resizeMethod) url.searchParams.set("method", resizeMethod);
if (animated !== void 0) url.searchParams.set("animated", String(animated));
if (typeof allowRedirects === "boolean") url.searchParams.set("allow_redirect", JSON.stringify(allowRedirects));
return url.href;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/logger.js
var import_loglevel = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
(function(root, definition) {
"use strict";
if (typeof define === "function" && define.amd) define(definition);
else if (typeof module === "object" && module.exports) module.exports = definition();
else root.log = definition();
})(exports, function() {
"use strict";
var noop = function() {};
var undefinedType = "undefined";
var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
var _loggersByName = {};
var defaultLogger = null;
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === "function") return method.bind(obj);
else try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
function traceForIE() {
if (console.log) if (console.log.apply) console.log.apply(console, arguments);
else Function.prototype.apply.apply(console.log, [console, arguments]);
if (console.trace) console.trace();
}
function realMethod(methodName) {
if (methodName === "debug") methodName = "log";
if (typeof console === undefinedType) return false;
else if (methodName === "trace" && isIE) return traceForIE;
else if (console[methodName] !== void 0) return bindMethod(console, methodName);
else if (console.log !== void 0) return bindMethod(console, "log");
else return noop;
}
function replaceLoggingMethods() {
var level = this.getLevel();
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
}
this.log = this.debug;
if (typeof console === undefinedType && level < this.levels.SILENT) return "No console available for logging";
}
function enableLoggingWhenConsoleArrives(methodName) {
return function() {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this);
this[methodName].apply(this, arguments);
}
};
}
function defaultMethodFactory(methodName, _level, _loggerName) {
return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
}
function Logger(name, factory) {
var self = this;
/**
* The level inherited from a parent logger (or a global default). We
* cache this here rather than delegating to the parent so that it stays
* in sync with the actual logging methods that we have installed (the
* parent could change levels but we might not have rebuilt the loggers
* in this child yet).
* @type {number}
*/
var inheritedLevel;
/**
* The default level for this logger, if any. If set, this overrides
* `inheritedLevel`.
* @type {number|null}
*/
var defaultLevel;
/**
* A user-specific level for this logger. If set, this overrides
* `defaultLevel`.
* @type {number|null}
*/
var userLevel;
var storageKey = "loglevel";
if (typeof name === "string") storageKey += ":" + name;
else if (typeof name === "symbol") storageKey = void 0;
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || "silent").toUpperCase();
if (typeof window === undefinedType || !storageKey) return;
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
try {
window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
if (typeof window === undefinedType || !storageKey) return;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
if (typeof storedLevel === undefinedType) try {
var cookie = window.document.cookie;
var cookieName = encodeURIComponent(storageKey);
var location = cookie.indexOf(cookieName + "=");
if (location !== -1) storedLevel = /^([^;]+)/.exec(cookie.slice(location + cookieName.length + 1))[1];
} catch (ignore) {}
if (self.levels[storedLevel] === void 0) storedLevel = void 0;
return storedLevel;
}
function clearPersistedLevel() {
if (typeof window === undefinedType || !storageKey) return;
try {
window.localStorage.removeItem(storageKey);
} catch (ignore) {}
try {
window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
} catch (ignore) {}
}
function normalizeLevel(input) {
var level = input;
if (typeof level === "string" && self.levels[level.toUpperCase()] !== void 0) level = self.levels[level.toUpperCase()];
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) return level;
else throw new TypeError("log.setLevel() called with invalid level: " + input);
}
self.name = name;
self.levels = {
"TRACE": 0,
"DEBUG": 1,
"INFO": 2,
"WARN": 3,
"ERROR": 4,
"SILENT": 5
};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function() {
if (userLevel != null) return userLevel;
else if (defaultLevel != null) return defaultLevel;
else return inheritedLevel;
};
self.setLevel = function(level, persist) {
userLevel = normalizeLevel(level);
if (persist !== false) persistLevelIfPossible(userLevel);
return replaceLoggingMethods.call(self);
};
self.setDefaultLevel = function(level) {
defaultLevel = normalizeLevel(level);
if (!getPersistedLevel()) self.setLevel(level, false);
};
self.resetLevel = function() {
userLevel = null;
clearPersistedLevel();
replaceLoggingMethods.call(self);
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
self.rebuild = function() {
if (defaultLogger !== self) inheritedLevel = normalizeLevel(defaultLogger.getLevel());
replaceLoggingMethods.call(self);
if (defaultLogger === self) for (var childName in _loggersByName) _loggersByName[childName].rebuild();
};
inheritedLevel = normalizeLevel(defaultLogger ? defaultLogger.getLevel() : "WARN");
var initialLevel = getPersistedLevel();
if (initialLevel != null) userLevel = normalizeLevel(initialLevel);
replaceLoggingMethods.call(self);
}
defaultLogger = new Logger();
defaultLogger.getLogger = function getLogger(name) {
if (typeof name !== "symbol" && typeof name !== "string" || name === "") throw new TypeError("You must supply a name when creating a logger.");
var logger = _loggersByName[name];
if (!logger) logger = _loggersByName[name] = new Logger(name, defaultLogger.methodFactory);
return logger;
};
var _log = typeof window !== undefinedType ? window.log : void 0;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType && window.log === defaultLogger) window.log = _log;
return defaultLogger;
};
defaultLogger.getLoggers = function getLoggers() {
return _loggersByName;
};
defaultLogger["default"] = defaultLogger;
return defaultLogger;
});
})))(), 1);
/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */
/** Logger interface used within the js-sdk codebase */
/** The basic interface for a logger which doesn't support children */
var DEFAULT_NAMESPACE = "matrix";
import_loglevel.default.methodFactory = function(methodName, logLevel, loggerName) {
return function() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
if (this.prefix) args.unshift(this.prefix);
if (methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info" || methodName === "debug") return console[methodName](...args);
else return console.log(...args);
};
};
/**
* Implementation of {@link Logger} based on `loglevel`.
*/
/**
* Internal utility function: gets a {@link Logger} based on `loglevel`.
*
* Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.
*
* @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.
*/
function getPrefixedLogger(prefix) {
var loggerName = DEFAULT_NAMESPACE + (prefix === void 0 ? "" : "-".concat(prefix));
var prefixLogger = import_loglevel.default.getLogger(loggerName);
if (prefixLogger.getChild === void 0) {
prefixLogger.prefix = prefix;
prefixLogger.getChild = (childPrefix) => {
var childLogger = getPrefixedLogger((prefix !== null && prefix !== void 0 ? prefix : "") + childPrefix);
childLogger.methodFactory = prefixLogger.methodFactory;
childLogger.rebuild();
return childLogger;
};
prefixLogger.setLevel(import_loglevel.default.levels.DEBUG, false);
}
return prefixLogger;
}
/**
* Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.
* Can be tailored down to specific use cases if needed.
*
* @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger
* associated with `MatrixClient`.
*/
var logger$2 = getPrefixedLogger();
/**
* A "span" for grouping related log lines together.
*
* The current implementation just adds the name at the start of each log line.
*
* This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,
* it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,
* no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course
* of an application's life and just drop references to them when the job is done.
*/
var LogSpan = class {
constructor(parent, name) {
this.parent = parent;
(0, import_defineProperty.default)(this, "name", void 0);
this.name = name + ":";
}
trace() {
for (var _len2 = arguments.length, msg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) msg[_key2] = arguments[_key2];
this.parent.trace(this.name, ...msg);
}
debug() {
for (var _len3 = arguments.length, msg = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) msg[_key3] = arguments[_key3];
this.parent.debug(this.name, ...msg);
}
info() {
for (var _len4 = arguments.length, msg = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) msg[_key4] = arguments[_key4];
this.parent.info(this.name, ...msg);
}
warn() {
for (var _len5 = arguments.length, msg = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) msg[_key5] = arguments[_key5];
this.parent.warn(this.name, ...msg);
}
error() {
for (var _len6 = arguments.length, msg = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) msg[_key6] = arguments[_key6];
this.parent.error(this.name, ...msg);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/typed-event-emitter.js
/** Events emitted by EventEmitter itself */
var EventEmitterEvents = /* @__PURE__ */ function(EventEmitterEvents) {
EventEmitterEvents["NewListener"] = "newListener";
EventEmitterEvents["RemoveListener"] = "removeListener";
EventEmitterEvents["Error"] = "error";
return EventEmitterEvents;
}({});
/** Base class for types mapping from event name to the type of listeners to that event */
/**
* The expected type of a listener function for a particular event.
*
* Type parameters:
* * `E` - List of all events emitted by the `TypedEventEmitter`. Normally an enum type.
* * `A` - A type providing mappings from event names to listener types.
* * `T` - The name of the actual event that this listener is for. Normally one of the types in `E` or
* {@link EventEmitterEvents}.
*/
/**
* Typed Event Emitter class which can act as a Base Model for all our model
* and communication events.
* This makes it much easier for us to distinguish between events, as we now need
* to properly type this, so that our events are not stringly-based and prone
* to silly typos.
*
* Type parameters:
* * `Events` - List of all events emitted by this `TypedEventEmitter`. Normally an enum type.
* * `Arguments` - A {@link ListenerMap} type providing mappings from event names to listener types.
* * `SuperclassArguments` - TODO: not really sure. Alternative listener mappings, I think? But only honoured for `.emit`?
*/
var TypedEventEmitter = class extends EventEmitter$1 {
/**
* Alias for {@link on}.
*/
addListener(event, listener) {
return super.addListener(event, listener);
}
/**
* Synchronously calls each of the listeners registered for the event named
* `event`, in the order they were registered, passing the supplied arguments
* to each.
*
* @param event - The name of the event to emit
* @param args - Arguments to pass to the listener
* @returns `true` if the event had listeners, `false` otherwise.
*/
emit(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key];
return super.emit(event, ...args);
}
/**
* Similar to `emit` but calls all listeners within a `Promise.all` and returns the promise chain
* @param event - The name of the event to emit
* @param args - Arguments to pass to the listener
* @returns `true` if the event had listeners, `false` otherwise.
*/
emitPromised(event) {
var _arguments = arguments, _this = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var _len2 = _arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) args[_key2 - 1] = _arguments[_key2];
var listeners = _this.listeners(event);
return Promise.allSettled(listeners.map((l) => l(...args))).then(() => {
return listeners.length > 0;
});
})();
}
/**
* Returns the number of listeners listening to the event named `event`.
*
* @param event - The name of the event being listened for
*/
listenerCount(event) {
return super.listenerCount(event);
}
/**
* Returns a copy of the array of listeners for the event named `event`.
*/
listeners(event) {
return super.listeners(event);
}
/**
* Alias for {@link removeListener}
*/
off(event, listener) {
return super.off(event, listener);
}
/**
* Adds the `listener` function to the end of the listeners array for the
* event named `event`.
*
* No checks are made to see if the `listener` has already been added. Multiple calls
* passing the same combination of `event` and `listener` will result in the `listener`
* being added, and called, multiple times.
*
* By default, event listeners are invoked in the order they are added. The
* {@link prependListener} method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* @param event - The name of the event.
* @param listener - The callback function
*
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
on(event, listener) {
return super.on(event, listener);
}
/**
* Adds a **one-time** `listener` function for the event named `event`. The
* next time `event` is triggered, this listener is removed and then invoked.
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
*
* By default, event listeners are invoked in the order they are added.
* The {@link prependOnceListener} method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* @param event - The name of the event.
* @param listener - The callback function
*
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
once(event, listener) {
return super.once(event, listener);
}
/**
* Adds the `listener` function to the _beginning_ of the listeners array for the
* event named `event`.
*
* No checks are made to see if the `listener` has already been added. Multiple calls
* passing the same combination of `event` and `listener` will result in the `listener`
* being added, and called, multiple times.
*
* @param event - The name of the event.
* @param listener - The callback function
*
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
prependListener(event, listener) {
return super.prependListener(event, listener);
}
/**
* Adds a **one-time**`listener` function for the event named `event` to the _beginning_ of the listeners array.
* The next time `event` is triggered, this listener is removed, and then invoked.
*
* @param event - The name of the event.
* @param listener - The callback function
*
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
prependOnceListener(event, listener) {
return super.prependOnceListener(event, listener);
}
/**
* Removes all listeners, or those of the specified `event`.
*
* It is bad practice to remove listeners added elsewhere in the code,
* particularly when the `EventEmitter` instance was created by some other
* component or module (e.g. sockets or file streams).
*
* @param event - The name of the event. If undefined, all listeners everywhere are removed.
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
removeAllListeners(event) {
if (event === void 0) return super.removeAllListeners();
return super.removeAllListeners(event);
}
/**
* Removes the specified `listener` from the listener array for the event named `event`.
*
* @returns a reference to the `EventEmitter`, so that calls can be chained.
*/
removeListener(event, listener) {
return super.removeListener(event, listener);
}
/**
* Returns a copy of the array of listeners for the event named `eventName`,
* including any wrappers (such as those created by `.once()`).
*/
rawListeners(event) {
return super.rawListeners(event);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/event.js
var EventType = /* @__PURE__ */ function(EventType) {
EventType["RoomCanonicalAlias"] = "m.room.canonical_alias";
EventType["RoomCreate"] = "m.room.create";
EventType["RoomJoinRules"] = "m.room.join_rules";
EventType["RoomMember"] = "m.room.member";
EventType["RoomThirdPartyInvite"] = "m.room.third_party_invite";
EventType["RoomPowerLevels"] = "m.room.power_levels";
EventType["RoomName"] = "m.room.name";
EventType["RoomTopic"] = "m.room.topic";
EventType["RoomAvatar"] = "m.room.avatar";
EventType["RoomPinnedEvents"] = "m.room.pinned_events";
EventType["RoomEncryption"] = "m.room.encryption";
EventType["RoomHistoryVisibility"] = "m.room.history_visibility";
EventType["RoomGuestAccess"] = "m.room.guest_access";
EventType["RoomServerAcl"] = "m.room.server_acl";
EventType["RoomTombstone"] = "m.room.tombstone";
EventType["RoomPredecessor"] = "org.matrix.msc3946.room_predecessor";
EventType["PolicyRuleUser"] = "m.policy.rule.user";
EventType["PolicyRuleRoom"] = "m.policy.rule.room";
EventType["PolicyRuleServer"] = "m.policy.rule.server";
EventType["SpaceChild"] = "m.space.child";
EventType["SpaceParent"] = "m.space.parent";
EventType["RoomRedaction"] = "m.room.redaction";
EventType["RoomMessage"] = "m.room.message";
EventType["RoomMessageEncrypted"] = "m.room.encrypted";
EventType["Sticker"] = "m.sticker";
EventType["CallInvite"] = "m.call.invite";
EventType["CallCandidates"] = "m.call.candidates";
EventType["CallAnswer"] = "m.call.answer";
EventType["CallHangup"] = "m.call.hangup";
EventType["CallReject"] = "m.call.reject";
EventType["CallSelectAnswer"] = "m.call.select_answer";
EventType["CallNegotiate"] = "m.call.negotiate";
EventType["CallSDPStreamMetadataChanged"] = "m.call.sdp_stream_metadata_changed";
EventType["CallSDPStreamMetadataChangedPrefix"] = "org.matrix.call.sdp_stream_metadata_changed";
EventType["CallReplaces"] = "m.call.replaces";
EventType["CallAssertedIdentity"] = "m.call.asserted_identity";
EventType["CallAssertedIdentityPrefix"] = "org.matrix.call.asserted_identity";
EventType["CallEncryptionKeysPrefix"] = "io.element.call.encryption_keys";
EventType["KeyVerificationRequest"] = "m.key.verification.request";
EventType["KeyVerificationStart"] = "m.key.verification.start";
EventType["KeyVerificationCancel"] = "m.key.verification.cancel";
EventType["KeyVerificationMac"] = "m.key.verification.mac";
EventType["KeyVerificationDone"] = "m.key.verification.done";
EventType["KeyVerificationKey"] = "m.key.verification.key";
EventType["KeyVerificationAccept"] = "m.key.verification.accept";
EventType["KeyVerificationReady"] = "m.key.verification.ready";
EventType["RoomMessageFeedback"] = "m.room.message.feedback";
EventType["Reaction"] = "m.reaction";
EventType["PollStart"] = "org.matrix.msc3381.poll.start";
EventType["Typing"] = "m.typing";
EventType["Receipt"] = "m.receipt";
EventType["Presence"] = "m.presence";
EventType["FullyRead"] = "m.fully_read";
EventType["Tag"] = "m.tag";
EventType["SpaceOrder"] = "org.matrix.msc3230.space_order";
EventType["MarkedUnread"] = "m.marked_unread";
EventType["PushRules"] = "m.push_rules";
EventType["Direct"] = "m.direct";
EventType["IgnoredUserList"] = "m.ignored_user_list";
EventType["InvitePermissionConfig"] = "m.invite_permission_config";
EventType["RoomKey"] = "m.room_key";
EventType["RoomKeyRequest"] = "m.room_key_request";
EventType["ForwardedRoomKey"] = "m.forwarded_room_key";
EventType["Dummy"] = "m.dummy";
EventType["SecretRequest"] = "m.secret.request";
EventType["SecretSend"] = "m.secret.send";
EventType["GroupCallPrefix"] = "org.matrix.msc3401.call";
EventType["GroupCallMemberPrefix"] = "org.matrix.msc3401.call.member";
EventType["RTCMembership"] = "org.matrix.msc4143.rtc.member";
EventType["CallNotify"] = "org.matrix.msc4075.call.notify";
EventType["RTCNotification"] = "org.matrix.msc4075.rtc.notification";
EventType["RTCDecline"] = "org.matrix.msc4310.rtc.decline";
EventType["RoomPolicy"] = "org.matrix.msc4284.policy";
return EventType;
}({});
var RelationType = /* @__PURE__ */ function(RelationType) {
RelationType["Annotation"] = "m.annotation";
RelationType["Replace"] = "m.replace";
RelationType["Reference"] = "m.reference";
RelationType["Thread"] = "m.thread";
return RelationType;
}({});
var MsgType = /* @__PURE__ */ function(MsgType) {
MsgType["Text"] = "m.text";
MsgType["Emote"] = "m.emote";
MsgType["Notice"] = "m.notice";
MsgType["Image"] = "m.image";
MsgType["File"] = "m.file";
MsgType["Audio"] = "m.audio";
MsgType["Location"] = "m.location";
MsgType["Video"] = "m.video";
MsgType["KeyVerificationRequest"] = "m.key.verification.request";
return MsgType;
}({});
var RoomCreateTypeField = "type";
var RoomType = /* @__PURE__ */ function(RoomType) {
RoomType["Space"] = "m.space";
RoomType["UnstableCall"] = "org.matrix.msc3417.call";
RoomType["ElementVideo"] = "io.element.video";
return RoomType;
}({});
var ToDeviceMessageId = "org.matrix.msgid";
/**
* Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)
* room purpose. Note that this reference is UNSTABLE and subject to breaking changes,
* including its eventual removal.
*/
var UNSTABLE_MSC3088_PURPOSE = new UnstableValue$3("m.room.purpose", "org.matrix.msc3088.purpose");
/**
* Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)
* room purpose. Note that this reference is UNSTABLE and subject to breaking changes,
* including its eventual removal.
*/
var UNSTABLE_MSC3088_ENABLED = new UnstableValue$3("m.enabled", "org.matrix.msc3088.enabled");
/**
* Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.
* Note that this reference is UNSTABLE and subject to breaking changes, including its
* eventual removal.
*/
var UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue$3("m.data_tree", "org.matrix.msc3089.data_tree");
/**
* Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.
* Note that this reference is UNSTABLE and subject to breaking changes, including its
* eventual removal.
*/
var UNSTABLE_MSC3089_LEAF = new UnstableValue$3("m.leaf", "org.matrix.msc3089.leaf");
/**
* Branch (Leaf Reference) type for the index approach in a
* [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is
* UNSTABLE and subject to breaking changes, including its eventual removal.
*/
var UNSTABLE_MSC3089_BRANCH = new UnstableValue$3("m.branch", "org.matrix.msc3089.branch");
/**
* Marker event type to point back at imported historical content in a room. See
* [MSC2716](https://github.com/matrix-org/matrix-spec-proposals/pull/2716).
* Note that this reference is UNSTABLE and subject to breaking changes,
* including its eventual removal.
*/
var UNSTABLE_MSC2716_MARKER = new UnstableValue$3("m.room.marker", "org.matrix.msc2716.marker");
/**
* Name of the request property for relation based redactions.
* {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}
*/
var MSC3912_RELATION_BASED_REDACTIONS_PROP = new UnstableValue$3("with_rel_types", "org.matrix.msc3912.with_relations");
/**
* Functional members type for declaring a purpose of room members (e.g. helpful bots).
* Note that this reference is UNSTABLE and subject to breaking changes, including its
* eventual removal.
*
* Schema (TypeScript):
* ```
* {
* service_members?: string[]
* }
* ```
*
* @example
* ```
* {
* "service_members": [
* "@helperbot:localhost",
* "@reminderbot:alice.tdl"
* ]
* }
* ```
*/
var UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new UnstableValue$3("io.element.functional_members", "io.element.functional_members");
/**
* A type of message that affects visibility of a message,
* as per https://github.com/matrix-org/matrix-doc/pull/3531
*
* @experimental
*/
var EVENT_VISIBILITY_CHANGE_TYPE = new UnstableValue$3("m.visibility", "org.matrix.msc3531.visibility");
/**
* https://github.com/matrix-org/matrix-doc/pull/3881
*
* @experimental
*/
var PUSHER_ENABLED = new UnstableValue$3("enabled", "org.matrix.msc3881.enabled");
new UnstableValue$3("device_id", "org.matrix.msc3881.device_id");
/**
* https://github.com/matrix-org/matrix-doc/pull/3890
*
* @experimental
*/
var LOCAL_NOTIFICATION_SETTINGS_PREFIX = new UnstableValue$3("m.local_notification_settings", "org.matrix.msc3890.local_notification_settings");
/**
* https://github.com/matrix-org/matrix-doc/pull/4023
*
* @experimental
*/
var UNSIGNED_THREAD_ID_FIELD = new UnstableValue$3("thread_id", "org.matrix.msc4023.thread_id");
/**
* https://github.com/matrix-org/matrix-spec-proposals/pull/4115
*
* @experimental
*/
var UNSIGNED_MEMBERSHIP_FIELD = new NamespacedValue$1("membership", "io.element.msc4115.membership");
/**
* Mapped type from event type to content type for all specified non-state room events.
*/
/**
* Mapped type from event type to content type for all specified room state events.
*/
/**
* Mapped type from event type to content type for all specified room-specific account_data events.
*/
/**
* Mapped type from event type to content type for all specified global account_data events.
*/
/**
* Subset of AccountDataEvents, excluding events specified in https://spec.matrix.org/v1.17/client-server-api/#server-behaviour-12
*/
/**
* Mapped type from event type to content type for all specified global events encrypted by secret storage.
*
* See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/membership.js
/**
* Well-known values (from the spec or MSCs) that are allowed in the
* {@link Membership} type.
*/
var KnownMembership = /* @__PURE__ */ function(KnownMembership) {
/**
* The user has been banned from the room, and is no longer allowed to join
* it until they are un-banned from the room (by having their membership
* state set to a value other than ban).
*/
KnownMembership["Ban"] = "ban";
/**
* The user has been invited to join a room, but has not yet joined it.
* They may not participate in the room until they join.
* */
KnownMembership["Invite"] = "invite";
/**
* The user has joined the room (possibly after accepting an invite), and
* may participate in it.
*/
KnownMembership["Join"] = "join";
/**
* The user has knocked on the room, requesting permission to participate.
* They may not participate in the room until they join.
*/
KnownMembership["Knock"] = "knock";
/**
* The user was once joined to the room, but has since left (possibly by
* choice, or possibly by being kicked).
*/
KnownMembership["Leave"] = "leave";
return KnownMembership;
}({});
/**
* The membership state for a user in a room [1]. A value from
* {@link KnownMembership} should be used where available, but all string values
* are allowed to provide flexibility for upcoming spec changes or proposals.
*
* [1] https://spec.matrix.org/latest/client-server-api/#mroommember
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room-member.js
var RoomMemberEvent = /* @__PURE__ */ function(RoomMemberEvent) {
RoomMemberEvent["Membership"] = "RoomMember.membership";
RoomMemberEvent["Name"] = "RoomMember.name";
RoomMemberEvent["PowerLevel"] = "RoomMember.powerLevel";
RoomMemberEvent["Typing"] = "RoomMember.typing";
return RoomMemberEvent;
}({});
var RoomMember = class extends TypedEventEmitter {
/**
* Construct a new room member.
*
* @param roomId - The room ID of the member.
* @param userId - The user ID of the member.
*/
constructor(roomId, userId) {
super();
this.roomId = roomId;
this.userId = userId;
(0, import_defineProperty.default)(this, "_isOutOfBand", false);
(0, import_defineProperty.default)(this, "modified", -1);
(0, import_defineProperty.default)(this, "requestedProfileInfo", false);
/**
* True if the room member is currently typing.
*/
(0, import_defineProperty.default)(this, "typing", false);
/**
* The human-readable name for this room member. Similar to {@link rawDisplayName}, but
* disambiguated with a suffix of " (\@user_id:matrix.org)" if another member shares the
* same displayname.
*/
(0, import_defineProperty.default)(this, "name", void 0);
/**
* The ambiguous displayname of this room member, with some preprocessing:
*
* * Direction override characters (RTO and LRO) are removed.
* * If the displayname is empty, or contains only blank, non-printing, or diacritcic characters, it is
* replaced with the user ID.
*/
(0, import_defineProperty.default)(this, "rawDisplayName", void 0);
/**
* The power level for this room member.
*/
(0, import_defineProperty.default)(this, "powerLevel", 0);
/**
* The User object for this room member, if one exists.
*/
(0, import_defineProperty.default)(this, "user", void 0);
/**
* The membership state for this room member e.g. 'join'.
*/
(0, import_defineProperty.default)(this, "membership", void 0);
/**
* True if the member's name is disambiguated.
*/
(0, import_defineProperty.default)(this, "disambiguate", false);
/**
* The events describing this RoomMember.
*/
(0, import_defineProperty.default)(this, "events", {});
this.name = userId;
this.rawDisplayName = userId;
this.updateModifiedTime();
}
/**
* Mark the member as coming from a channel that is not sync
*/
markOutOfBand() {
this._isOutOfBand = true;
}
/**
* @returns does the member come from a channel that is not sync?
* This is used to store the member seperately
* from the sync state so it available across browser sessions.
*/
isOutOfBand() {
return this._isOutOfBand;
}
/**
* Update this room member's membership event. May fire "RoomMember.name" if
* this event updates this member's name.
* @param event - The `m.room.member` event
* @param roomState - Optional. The room state to take into account
* when calculating (e.g. for disambiguating users with the same name).
*
* @remarks
* Fires {@link RoomMemberEvent.Name}
* Fires {@link RoomMemberEvent.Membership}
*/
setMembershipEvent(event, roomState) {
var _event$getDirectional, _event$getDirectional2;
var displayName = (_event$getDirectional = event.getDirectionalContent().displayname) !== null && _event$getDirectional !== void 0 ? _event$getDirectional : "";
if (event.getType() !== EventType.RoomMember) return;
this._isOutOfBand = false;
this.events.member = event;
var oldMembership = this.membership;
this.membership = event.getDirectionalContent().membership;
if (this.membership === void 0) logger$2.trace("membership event with membership undefined (forwardLooking: ".concat(event.forwardLooking, ")!"), event.getContent(), "prevcontent is ", event.getPrevContent());
this.disambiguate = shouldDisambiguate(this.userId, displayName, roomState);
var oldName = this.name;
this.name = calculateDisplayName(this.userId, displayName, this.disambiguate);
this.rawDisplayName = removeDirectionOverrideChars((_event$getDirectional2 = event.getDirectionalContent().displayname) !== null && _event$getDirectional2 !== void 0 ? _event$getDirectional2 : "");
if (!this.rawDisplayName || !removeHiddenChars(this.rawDisplayName)) this.rawDisplayName = this.userId;
if (oldMembership !== this.membership) {
this.updateModifiedTime();
this.emit(RoomMemberEvent.Membership, event, this, oldMembership);
}
if (oldName !== this.name) {
this.updateModifiedTime();
this.emit(RoomMemberEvent.Name, event, this, oldName);
}
}
/**
* Recalculate the disambiguation flag for this member based on current room state.
* This should be called when another member's display name changes and may affect
* whether this member needs disambiguation.
*
* @param roomState - The current room state to use for disambiguation check
* @returns true if the member's name changed as a result of the disambiguation update
*
* @remarks
* Fires {@link RoomMemberEvent.Name}
*/
recalculateDisambiguatedName(roomState) {
var _this$events$member$g;
if (!this.events.member) return false;
var displayName = (_this$events$member$g = this.events.member.getDirectionalContent().displayname) !== null && _this$events$member$g !== void 0 ? _this$events$member$g : "";
var newDisambiguate = shouldDisambiguate(this.userId, displayName, roomState);
if (newDisambiguate === this.disambiguate) return false;
this.disambiguate = newDisambiguate;
var oldName = this.name;
this.name = calculateDisplayName(this.userId, displayName, this.disambiguate);
if (oldName !== this.name) {
this.updateModifiedTime();
this.emit(RoomMemberEvent.Name, this.events.member, this, oldName);
return true;
}
return false;
}
/**
* Update this room member's power level event. Will fire
* "RoomMember.powerLevel" if the new power level is different
* @param powerLevel - The power level of the room member.
*
* @remarks
* Fires {@link RoomMemberEvent.PowerLevel}
*/
setPowerLevel(powerLevel, powerLevelEvent) {
var oldPowerLevel = this.powerLevel;
this.powerLevel = powerLevel;
if (oldPowerLevel !== this.powerLevel) {
this.updateModifiedTime();
this.emit(RoomMemberEvent.PowerLevel, powerLevelEvent, this);
}
}
/**
* Update this room member's typing event. May fire "RoomMember.typing" if
* this event changes this member's typing state.
* @param event - The typing event
*
* @remarks
* Fires {@link RoomMemberEvent.Typing}
*/
setTypingEvent(event) {
if (event.getType() !== "m.typing") return;
var oldTyping = this.typing;
this.typing = false;
var typingList = event.getContent().user_ids;
if (!Array.isArray(typingList)) return;
if (typingList.indexOf(this.userId) !== -1) this.typing = true;
if (oldTyping !== this.typing) {
this.updateModifiedTime();
this.emit(RoomMemberEvent.Typing, event, this);
}
}
/**
* Update the last modified time to the current time.
*/
updateModifiedTime() {
this.modified = Date.now();
}
/**
* Get the timestamp when this RoomMember was last updated. This timestamp is
* updated when properties on this RoomMember are updated.
* It is updated <i>before</i> firing events.
* @returns The timestamp
*/
getLastModifiedTime() {
return this.modified;
}
isKicked() {
return this.membership === KnownMembership.Leave && this.events.member !== void 0 && this.events.member.getSender() !== this.events.member.getStateKey();
}
/**
* If this member was invited with the is_direct flag set, return
* the user that invited this member
* @returns user id of the inviter
*/
getDMInviter() {
if (this.events.member) {
var memberEvent = this.events.member;
var memberContent = memberEvent.getContent();
var inviteSender = memberEvent.getSender();
if (memberContent.membership === KnownMembership.Join) {
memberContent = memberEvent.getPrevContent();
inviteSender = memberEvent.getUnsigned().prev_sender;
}
if (memberContent.membership === KnownMembership.Invite && memberContent.is_direct) return inviteSender;
}
}
/**
* Get the avatar URL for a room member.
* @param baseUrl - The base homeserver URL See
* {@link MatrixClient#getHomeserverUrl}.
* @param width - The desired width of the thumbnail.
* @param height - The desired height of the thumbnail.
* @param resizeMethod - The thumbnail resize method to use, either
* "crop" or "scale".
* @param allowDefault - (optional) Passing false causes this method to
* return null if the user has no avatar image. Otherwise, a default image URL
* will be returned. Default: true. (Deprecated)
* @param allowDirectLinks - (optional) If true, the avatar URL will be
* returned even if it is a direct hyperlink rather than a matrix content URL.
* If false, any non-matrix content URLs will be ignored. Setting this option to
* true will expose URLs that, if fetched, will leak information about the user
* to anyone who they share a room with.
* @param useAuthentication - (optional) If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support for
* authenticated media will not be checked - it is the caller's responsibility
* to do so before calling this function. Note also that useAuthentication
* implies allowRedirects. Defaults to false (unauthenticated endpoints).
* @returns the avatar URL or null.
*/
getAvatarUrl(baseUrl, width, height, resizeMethod) {
var allowDefault = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
var allowDirectLinks = arguments.length > 5 ? arguments[5] : void 0;
var useAuthentication = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : false;
var rawUrl = this.getMxcAvatarUrl();
if (!rawUrl && !allowDefault) return null;
var httpUrl = getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks, void 0, useAuthentication);
if (httpUrl) return httpUrl;
return null;
}
/**
* get the mxc avatar url, either from a state event, or from a lazily loaded member
* @returns the mxc avatar url
*/
getMxcAvatarUrl() {
if (this.events.member) return this.events.member.getDirectionalContent().avatar_url;
else if (this.user) return this.user.avatarUrl;
}
};
var MXID_PATTERN = /@.+:.+/;
var LTR_RTL_PATTERN = /[\u200E\u200F\u202A-\u202F]/;
function shouldDisambiguate(selfUserId, displayName, roomState) {
if (!displayName || displayName === selfUserId) return false;
if (!roomState) return false;
var strippedDisplayName = removeHiddenChars(displayName);
if (!strippedDisplayName) return false;
if (MXID_PATTERN.test(strippedDisplayName)) return true;
if (LTR_RTL_PATTERN.test(displayName)) return true;
if (roomState.getUserIdsWithDisplayName(displayName).some((u) => u !== selfUserId)) return true;
return false;
}
function calculateDisplayName(selfUserId, displayName, disambiguate) {
if (!displayName || displayName === selfUserId) return selfUserId;
if (disambiguate) return removeDirectionOverrideChars(displayName) + " (" + selfUserId + ")";
if (!removeHiddenChars(displayName)) return selfUserId;
return removeDirectionOverrideChars(displayName);
}
//#endregion
//#region node_modules/matrix-events-sdk/lib/NamespacedMap.js
var require_NamespacedMap = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NamespacedMap = void 0;
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return { done: true };
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true, didErr = false, err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it["return"] != null) it["return"]();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
exports.NamespacedMap = /* @__PURE__ */ function() {
/**
* Creates a new map with optional seed data.
* @param {Array<[NS, V]>} initial The seed data.
*/
function NamespacedMap(initial) {
_classCallCheck(this, NamespacedMap);
_defineProperty(this, "internalMap", /* @__PURE__ */ new Map());
if (initial) {
var _iterator = _createForOfIteratorHelper(initial), _step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var val = _step.value;
this.set(val[0], val[1]);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}
/**
* Gets a value from the map. If the value does not exist under
* either namespace option, falsy is returned.
* @param {NS} key The key.
* @returns {Optional<V>} The value, or falsy.
*/
_createClass(NamespacedMap, [
{
key: "get",
value: function get(key) {
if (key.name && this.internalMap.has(key.name)) return this.internalMap.get(key.name);
if (key.altName && this.internalMap.has(key.altName)) return this.internalMap.get(key.altName);
return null;
}
},
{
key: "set",
value: function set(key, val) {
if (key.name) this.internalMap.set(key.name, val);
if (key.altName) this.internalMap.set(key.altName, val);
}
},
{
key: "has",
value: function has(key) {
return !!this.get(key);
}
},
{
key: "delete",
value: function _delete(key) {
if (key.name) this.internalMap["delete"](key.name);
if (key.altName) this.internalMap["delete"](key.altName);
}
},
{
key: "hasNamespaced",
value: function hasNamespaced(key) {
return this.internalMap.has(key);
}
},
{
key: "getNamespaced",
value: function getNamespaced(key) {
return this.internalMap.get(key);
}
}
]);
return NamespacedMap;
}();
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/InvalidEventError.js
var require_InvalidEventError = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidEventError = void 0;
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, { constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
} });
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) _construct = Reflect.construct;
else _construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var instance = new (Function.bind.apply(Parent, a))();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
return _construct.apply(null, arguments);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
exports.InvalidEventError = /* @__PURE__ */ function(_Error) {
_inherits(InvalidEventError, _Error);
var _super = _createSuper(InvalidEventError);
function InvalidEventError(message) {
_classCallCheck(this, InvalidEventError);
return _super.call(this, message);
}
return _createClass(InvalidEventError);
}(/* @__PURE__ */ _wrapNativeSuper(Error));
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/ExtensibleEvent.js
var require_ExtensibleEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensibleEvent = void 0;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
exports.ExtensibleEvent = /* @__PURE__ */ function() {
function ExtensibleEvent(wireFormat) {
_classCallCheck(this, ExtensibleEvent);
this.wireFormat = wireFormat;
}
/**
* Shortcut to wireFormat.content
*/
_createClass(ExtensibleEvent, [{
key: "wireContent",
get: function get() {
return this.wireFormat.content;
}
}]);
return ExtensibleEvent;
}();
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/types.js
var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isOptionalAString = isOptionalAString;
exports.isProvided = isProvided;
/**
* Represents an optional type: can either be T or a falsy value.
*/
/**
* Determines if the given optional string is a defined string.
* @param {Optional<string>} s The input string.
* @returns {boolean} True if the input is a defined string.
*/
function isOptionalAString(s) {
return isProvided(s) && typeof s === "string";
}
/**
* Determines if the given optional was provided a value.
* @param {Optional<T>} s The optional to test.
* @returns {boolean} True if the value is defined.
*/
function isProvided(s) {
return s !== null && s !== void 0;
}
}));
/**
* Represents either just T1, just T2, or T1 and T2 mixed.
*/
//#endregion
//#region node_modules/matrix-events-sdk/lib/NamespacedValue.js
var require_NamespacedValue = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnstableValue = exports.NamespacedValue = void 0;
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
/**
* Represents a simple Matrix namespaced value. This will assume that if a stable prefix
* is provided that the stable prefix should be used when representing the identifier.
*/
var NamespacedValue = /* @__PURE__ */ function() {
function NamespacedValue(stable, unstable) {
_classCallCheck(this, NamespacedValue);
this.stable = stable;
this.unstable = unstable;
if (!this.unstable && !this.stable) throw new Error("One of stable or unstable values must be supplied");
}
_createClass(NamespacedValue, [
{
key: "name",
get: function get() {
if (this.stable) return this.stable;
return this.unstable;
}
},
{
key: "altName",
get: function get() {
if (!this.stable) return null;
return this.unstable;
}
},
{
key: "matches",
value: function matches(val) {
return !!this.name && this.name === val || !!this.altName && this.altName === val;
}
},
{
key: "findIn",
value: function findIn(obj) {
var val;
if (this.name) val = obj === null || obj === void 0 ? void 0 : obj[this.name];
if (!val && this.altName) val = obj === null || obj === void 0 ? void 0 : obj[this.altName];
return val;
}
},
{
key: "includedIn",
value: function includedIn(arr) {
var included = false;
if (this.name) included = arr.includes(this.name);
if (!included && this.altName) included = arr.includes(this.altName);
return included;
}
}
]);
return NamespacedValue;
}();
/**
* Represents a namespaced value which prioritizes the unstable value over the stable
* value.
*/
exports.NamespacedValue = NamespacedValue;
exports.UnstableValue = /* @__PURE__ */ function(_NamespacedValue) {
_inherits(UnstableValue, _NamespacedValue);
var _super = _createSuper(UnstableValue);
function UnstableValue(stable, unstable) {
var _this;
_classCallCheck(this, UnstableValue);
_this = _super.call(this, stable, unstable);
if (!_this.unstable) throw new Error("Unstable value must be supplied");
return _this;
}
_createClass(UnstableValue, [{
key: "name",
get: function get() {
return this.unstable;
}
}, {
key: "altName",
get: function get() {
return this.stable;
}
}]);
return UnstableValue;
}(NamespacedValue);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/message_types.js
var require_message_types = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.M_TEXT = exports.M_NOTICE = exports.M_MESSAGE = exports.M_HTML = exports.M_EMOTE = void 0;
var _NamespacedValue = require_NamespacedValue();
/**
* An m.message event rendering
*/
exports.M_MESSAGE = new _NamespacedValue.UnstableValue("m.message", "org.matrix.msc1767.message");
/**
* The content for an m.text event
*/
exports.M_TEXT = new _NamespacedValue.UnstableValue("m.text", "org.matrix.msc1767.text");
/**
* The content for an m.html event
*/
exports.M_HTML = new _NamespacedValue.UnstableValue("m.html", "org.matrix.msc1767.html");
/**
* The event definition for an m.emote event (in content)
*/
exports.M_EMOTE = new _NamespacedValue.UnstableValue("m.emote", "org.matrix.msc1767.emote");
/**
* The event definition for an m.notice event (in content)
*/
exports.M_NOTICE = new _NamespacedValue.UnstableValue("m.notice", "org.matrix.msc1767.notice");
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/utility/events.js
var require_events = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEventTypeSame = isEventTypeSame;
/**
* Represents a potentially namespaced event type.
*/
/**
* Determines if two event types are the same, including namespaces.
* @param {EventType} given The given event type. This will be compared
* against the expected type.
* @param {EventType} expected The expected event type.
* @returns {boolean} True if the given type matches the expected type.
*/
function isEventTypeSame(given, expected) {
if (typeof given === "string") if (typeof expected === "string") return expected === given;
else return expected.matches(given);
else if (typeof expected === "string") return given.matches(expected);
else {
var expectedNs = expected;
var givenNs = given;
return expectedNs.matches(givenNs.name) || expectedNs.matches(givenNs.altName);
}
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/MessageEvent.js
var require_MessageEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageEvent = void 0;
var _ExtensibleEvent2 = require_ExtensibleEvent();
var _types = require_types();
var _InvalidEventError = require_InvalidEventError();
var _message_types = require_message_types();
var _events = require_events();
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
exports.MessageEvent = /* @__PURE__ */ function(_ExtensibleEvent) {
_inherits(MessageEvent, _ExtensibleEvent);
var _super = _createSuper(MessageEvent);
/**
* The default text for the event.
*/
/**
* The default HTML for the event, if provided.
*/
/**
* All the different renderings of the message. Note that this is the same
* format as an m.message body but may contain elements not found directly
* in the event content: this is because this is interpreted based off the
* other information available in the event.
*/
/**
* Creates a new MessageEvent from a pure format. Note that the event is
* *not* parsed here: it will be treated as a literal m.message primary
* typed event.
* @param {IPartialEvent<M_MESSAGE_EVENT_CONTENT>} wireFormat The event.
*/
function MessageEvent(wireFormat) {
var _this;
_classCallCheck(this, MessageEvent);
_this = _super.call(this, wireFormat);
_defineProperty(_assertThisInitialized(_this), "text", void 0);
_defineProperty(_assertThisInitialized(_this), "html", void 0);
_defineProperty(_assertThisInitialized(_this), "renderings", void 0);
var mmessage = _message_types.M_MESSAGE.findIn(_this.wireContent);
var mtext = _message_types.M_TEXT.findIn(_this.wireContent);
var mhtml = _message_types.M_HTML.findIn(_this.wireContent);
if ((0, _types.isProvided)(mmessage)) {
if (!Array.isArray(mmessage)) throw new _InvalidEventError.InvalidEventError("m.message contents must be an array");
var text = mmessage.find(function(r) {
return !(0, _types.isProvided)(r.mimetype) || r.mimetype === "text/plain";
});
var html = mmessage.find(function(r) {
return r.mimetype === "text/html";
});
if (!text) throw new _InvalidEventError.InvalidEventError("m.message is missing a plain text representation");
_this.text = text.body;
_this.html = html === null || html === void 0 ? void 0 : html.body;
_this.renderings = mmessage;
} else if ((0, _types.isOptionalAString)(mtext)) {
_this.text = mtext;
_this.html = mhtml;
_this.renderings = [{
body: mtext,
mimetype: "text/plain"
}];
if (_this.html) _this.renderings.push({
body: _this.html,
mimetype: "text/html"
});
} else throw new _InvalidEventError.InvalidEventError("Missing textual representation for event");
return _this;
}
/**
* Gets whether this message is considered an "emote". Note that a message
* might be an emote and notice at the same time: while technically possible,
* the event should be interpreted as one or the other.
*/
_createClass(MessageEvent, [
{
key: "isEmote",
get: function get() {
return _message_types.M_EMOTE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_EMOTE.findIn(this.wireFormat.content));
}
},
{
key: "isNotice",
get: function get() {
return _message_types.M_NOTICE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_NOTICE.findIn(this.wireFormat.content));
}
},
{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_MESSAGE);
}
},
{
key: "serializeMMessageOnly",
value: function serializeMMessageOnly() {
var messageRendering = _defineProperty({}, _message_types.M_MESSAGE.name, this.renderings);
if (this.renderings.length === 1) {
var mime = this.renderings[0].mimetype;
if (mime === void 0 || mime === "text/plain") messageRendering = _defineProperty({}, _message_types.M_TEXT.name, this.renderings[0].body);
}
return messageRendering;
}
},
{
key: "serialize",
value: function serialize() {
var _this$html;
return {
type: "m.room.message",
content: _objectSpread(_objectSpread({}, this.serializeMMessageOnly()), {}, {
body: this.text,
msgtype: "m.text",
format: this.html ? "org.matrix.custom.html" : void 0,
formatted_body: (_this$html = this.html) !== null && _this$html !== void 0 ? _this$html : void 0
})
};
}
}
], [{
key: "from",
value: function from(text, html) {
var _content;
return new MessageEvent({
type: _message_types.M_MESSAGE.name,
content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)
});
}
}]);
return MessageEvent;
}(_ExtensibleEvent2.ExtensibleEvent);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/NoticeEvent.js
var require_NoticeEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoticeEvent = void 0;
var _MessageEvent2 = require_MessageEvent();
var _message_types = require_message_types();
var _events = require_events();
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) _get = Reflect.get;
else _get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) return desc.get.call(arguments.length < 3 ? target : receiver);
return desc.value;
};
return _get.apply(this, arguments);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
exports.NoticeEvent = /* @__PURE__ */ function(_MessageEvent) {
_inherits(NoticeEvent, _MessageEvent);
var _super = _createSuper(NoticeEvent);
function NoticeEvent(wireFormat) {
_classCallCheck(this, NoticeEvent);
return _super.call(this, wireFormat);
}
_createClass(NoticeEvent, [
{
key: "isNotice",
get: function get() {
return true;
}
},
{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_NOTICE) || _get(_getPrototypeOf(NoticeEvent.prototype), "isEquivalentTo", this).call(this, primaryEventType);
}
},
{
key: "serialize",
value: function serialize() {
var message = _get(_getPrototypeOf(NoticeEvent.prototype), "serialize", this).call(this);
message.content["msgtype"] = "m.notice";
return message;
}
}
], [{
key: "from",
value: function from(text, html) {
var _content;
return new NoticeEvent({
type: _message_types.M_NOTICE.name,
content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)
});
}
}]);
return NoticeEvent;
}(_MessageEvent2.MessageEvent);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/EmoteEvent.js
var require_EmoteEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmoteEvent = void 0;
var _MessageEvent2 = require_MessageEvent();
var _message_types = require_message_types();
var _events = require_events();
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) _get = Reflect.get;
else _get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) return desc.get.call(arguments.length < 3 ? target : receiver);
return desc.value;
};
return _get.apply(this, arguments);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
exports.EmoteEvent = /* @__PURE__ */ function(_MessageEvent) {
_inherits(EmoteEvent, _MessageEvent);
var _super = _createSuper(EmoteEvent);
function EmoteEvent(wireFormat) {
_classCallCheck(this, EmoteEvent);
return _super.call(this, wireFormat);
}
_createClass(EmoteEvent, [
{
key: "isEmote",
get: function get() {
return true;
}
},
{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_EMOTE) || _get(_getPrototypeOf(EmoteEvent.prototype), "isEquivalentTo", this).call(this, primaryEventType);
}
},
{
key: "serialize",
value: function serialize() {
var message = _get(_getPrototypeOf(EmoteEvent.prototype), "serialize", this).call(this);
message.content["msgtype"] = "m.emote";
return message;
}
}
], [{
key: "from",
value: function from(text, html) {
var _content;
return new EmoteEvent({
type: _message_types.M_EMOTE.name,
content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)
});
}
}]);
return EmoteEvent;
}(_MessageEvent2.MessageEvent);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/interpreters/legacy/MRoomMessage.js
var require_MRoomMessage = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.LEGACY_M_ROOM_MESSAGE = void 0;
exports.parseMRoomMessage = parseMRoomMessage;
var _MessageEvent = require_MessageEvent();
var _NoticeEvent = require_NoticeEvent();
var _EmoteEvent = require_EmoteEvent();
var _NamespacedValue = require_NamespacedValue();
var _message_types = require_message_types();
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
exports.LEGACY_M_ROOM_MESSAGE = new _NamespacedValue.NamespacedValue("m.room.message");
function parseMRoomMessage(wireEvent) {
var _wireEvent$content, _wireEvent$content2, _wireEvent$content3;
if (_message_types.M_MESSAGE.findIn(wireEvent.content) || _message_types.M_TEXT.findIn(wireEvent.content)) return new _MessageEvent.MessageEvent(wireEvent);
var msgtype = (_wireEvent$content = wireEvent.content) === null || _wireEvent$content === void 0 ? void 0 : _wireEvent$content.msgtype;
var text = (_wireEvent$content2 = wireEvent.content) === null || _wireEvent$content2 === void 0 ? void 0 : _wireEvent$content2.body;
var html = ((_wireEvent$content3 = wireEvent.content) === null || _wireEvent$content3 === void 0 ? void 0 : _wireEvent$content3.format) === "org.matrix.custom.html" ? wireEvent.content.formatted_body : null;
if (msgtype === "m.text") {
var _objectSpread2;
return new _MessageEvent.MessageEvent(_objectSpread(_objectSpread({}, wireEvent), {}, { content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread2, _message_types.M_HTML.name, html), _objectSpread2)) }));
} else if (msgtype === "m.notice") {
var _objectSpread3;
return new _NoticeEvent.NoticeEvent(_objectSpread(_objectSpread({}, wireEvent), {}, { content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread3 = {}, _defineProperty(_objectSpread3, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread3, _message_types.M_HTML.name, html), _objectSpread3)) }));
} else if (msgtype === "m.emote") {
var _objectSpread4;
return new _EmoteEvent.EmoteEvent(_objectSpread(_objectSpread({}, wireEvent), {}, { content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread4 = {}, _defineProperty(_objectSpread4, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread4, _message_types.M_HTML.name, html), _objectSpread4)) }));
} else return null;
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/interpreters/modern/MMessage.js
var require_MMessage = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMMessage = parseMMessage;
var _MessageEvent = require_MessageEvent();
var _message_types = require_message_types();
var _EmoteEvent = require_EmoteEvent();
var _NoticeEvent = require_NoticeEvent();
function parseMMessage(wireEvent) {
if (_message_types.M_EMOTE.matches(wireEvent.type)) return new _EmoteEvent.EmoteEvent(wireEvent);
else if (_message_types.M_NOTICE.matches(wireEvent.type)) return new _NoticeEvent.NoticeEvent(wireEvent);
return new _MessageEvent.MessageEvent(wireEvent);
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/poll_types.js
var require_poll_types = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.M_POLL_START = exports.M_POLL_RESPONSE = exports.M_POLL_KIND_UNDISCLOSED = exports.M_POLL_KIND_DISCLOSED = exports.M_POLL_END = void 0;
var _NamespacedValue = require_NamespacedValue();
/**
* Identifier for an undisclosed poll.
*/
exports.M_POLL_KIND_DISCLOSED = new _NamespacedValue.UnstableValue("m.poll.disclosed", "org.matrix.msc3381.poll.disclosed");
/**
* Any poll kind.
*/
exports.M_POLL_KIND_UNDISCLOSED = new _NamespacedValue.UnstableValue("m.poll.undisclosed", "org.matrix.msc3381.poll.undisclosed");
/**
* The m.poll.start type within event content
*/
exports.M_POLL_START = new _NamespacedValue.UnstableValue("m.poll.start", "org.matrix.msc3381.poll.start");
/**
* The m.poll.response type within event content
*/
exports.M_POLL_RESPONSE = new _NamespacedValue.UnstableValue("m.poll.response", "org.matrix.msc3381.poll.response");
/**
* The event definition for an m.poll.end event (in content)
*/
exports.M_POLL_END = new _NamespacedValue.UnstableValue("m.poll.end", "org.matrix.msc3381.poll.end");
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/PollStartEvent.js
var require_PollStartEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.PollStartEvent = exports.PollAnswerSubevent = void 0;
var _poll_types = require_poll_types();
var _MessageEvent2 = require_MessageEvent();
var _message_types = require_message_types();
var _InvalidEventError = require_InvalidEventError();
var _NamespacedValue = require_NamespacedValue();
var _events = require_events();
var _ExtensibleEvent2 = require_ExtensibleEvent();
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
/**
* Represents a poll answer. Note that this is represented as a subtype and is
* not registered as a parsable event - it is implied for usage exclusively
* within the PollStartEvent parsing.
*/
var PollAnswerSubevent = /* @__PURE__ */ function(_MessageEvent) {
_inherits(PollAnswerSubevent, _MessageEvent);
var _super = _createSuper(PollAnswerSubevent);
/**
* The answer ID.
*/
function PollAnswerSubevent(wireFormat) {
var _this;
_classCallCheck(this, PollAnswerSubevent);
_this = _super.call(this, wireFormat);
_defineProperty(_assertThisInitialized(_this), "id", void 0);
var id = wireFormat.content.id;
if (!id || typeof id !== "string") throw new _InvalidEventError.InvalidEventError("Answer ID must be a non-empty string");
_this.id = id;
return _this;
}
_createClass(PollAnswerSubevent, [{
key: "serialize",
value: function serialize() {
return {
type: "org.matrix.sdk.poll.answer",
content: _objectSpread({ id: this.id }, this.serializeMMessageOnly())
};
}
}], [{
key: "from",
value: function from(id, text) {
return new PollAnswerSubevent({
type: "org.matrix.sdk.poll.answer",
content: _defineProperty({ id }, _message_types.M_TEXT.name, text)
});
}
}]);
return PollAnswerSubevent;
}(_MessageEvent2.MessageEvent);
/**
* Represents a poll start event.
*/
exports.PollAnswerSubevent = PollAnswerSubevent;
exports.PollStartEvent = /* @__PURE__ */ function(_ExtensibleEvent) {
_inherits(PollStartEvent, _ExtensibleEvent);
var _super2 = _createSuper(PollStartEvent);
/**
* The question being asked, as a MessageEvent node.
*/
/**
* The interpreted kind of poll. Note that this will infer a value that is known to the
* SDK rather than verbatim - this means unknown types will be represented as undisclosed
* polls.
*
* To get the raw kind, use rawKind.
*/
/**
* The true kind as provided by the event sender. Might not be valid.
*/
/**
* The maximum number of selections a user is allowed to make.
*/
/**
* The possible answers for the poll.
*/
/**
* Creates a new PollStartEvent from a pure format. Note that the event is *not*
* parsed here: it will be treated as a literal m.poll.start primary typed event.
* @param {IPartialEvent<M_POLL_START_EVENT_CONTENT>} wireFormat The event.
*/
function PollStartEvent(wireFormat) {
var _this2;
_classCallCheck(this, PollStartEvent);
_this2 = _super2.call(this, wireFormat);
_defineProperty(_assertThisInitialized(_this2), "question", void 0);
_defineProperty(_assertThisInitialized(_this2), "kind", void 0);
_defineProperty(_assertThisInitialized(_this2), "rawKind", void 0);
_defineProperty(_assertThisInitialized(_this2), "maxSelections", void 0);
_defineProperty(_assertThisInitialized(_this2), "answers", void 0);
var poll = _poll_types.M_POLL_START.findIn(_this2.wireContent);
if (!poll.question) throw new _InvalidEventError.InvalidEventError("A question is required");
_this2.question = new _MessageEvent2.MessageEvent({
type: "org.matrix.sdk.poll.question",
content: poll.question
});
_this2.rawKind = poll.kind;
if (_poll_types.M_POLL_KIND_DISCLOSED.matches(_this2.rawKind)) _this2.kind = _poll_types.M_POLL_KIND_DISCLOSED;
else _this2.kind = _poll_types.M_POLL_KIND_UNDISCLOSED;
_this2.maxSelections = Number.isFinite(poll.max_selections) && poll.max_selections > 0 ? poll.max_selections : 1;
if (!Array.isArray(poll.answers)) throw new _InvalidEventError.InvalidEventError("Poll answers must be an array");
var answers = poll.answers.slice(0, 20).map(function(a) {
return new PollAnswerSubevent({
type: "org.matrix.sdk.poll.answer",
content: a
});
});
if (answers.length <= 0) throw new _InvalidEventError.InvalidEventError("No answers available");
_this2.answers = answers;
return _this2;
}
_createClass(PollStartEvent, [{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_START);
}
}, {
key: "serialize",
value: function serialize() {
var _content2;
return {
type: _poll_types.M_POLL_START.name,
content: (_content2 = {}, _defineProperty(_content2, _poll_types.M_POLL_START.name, {
question: this.question.serialize().content,
kind: this.rawKind,
max_selections: this.maxSelections,
answers: this.answers.map(function(a) {
return a.serialize().content;
})
}), _defineProperty(_content2, _message_types.M_TEXT.name, "".concat(this.question.text, "\n").concat(this.answers.map(function(a, i) {
return "".concat(i + 1, ". ").concat(a.text);
}).join("\n"))), _content2)
};
}
}], [{
key: "from",
value: function from(question, answers, kind) {
var _content3;
var maxSelections = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1;
return new PollStartEvent({
type: _poll_types.M_POLL_START.name,
content: (_content3 = {}, _defineProperty(_content3, _message_types.M_TEXT.name, question), _defineProperty(_content3, _poll_types.M_POLL_START.name, {
question: _defineProperty({}, _message_types.M_TEXT.name, question),
kind: kind instanceof _NamespacedValue.NamespacedValue ? kind.name : kind,
max_selections: maxSelections,
answers: answers.map(function(a) {
return _defineProperty({ id: makeId() }, _message_types.M_TEXT.name, a);
})
}), _content3)
});
}
}]);
return PollStartEvent;
}(_ExtensibleEvent2.ExtensibleEvent);
var LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function makeId() {
return _toConsumableArray(Array(16)).map(function() {
return LETTERS.charAt(Math.floor(Math.random() * LETTERS.length));
}).join("");
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/relationship_types.js
var require_relationship_types = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.REFERENCE_RELATION = void 0;
/**
* Represents any relation type
*/
exports.REFERENCE_RELATION = new (require_NamespacedValue()).NamespacedValue("m.reference");
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/PollResponseEvent.js
var require_PollResponseEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.PollResponseEvent = void 0;
var _ExtensibleEvent2 = require_ExtensibleEvent();
var _poll_types = require_poll_types();
var _InvalidEventError = require_InvalidEventError();
var _relationship_types = require_relationship_types();
var _events = require_events();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
exports.PollResponseEvent = /* @__PURE__ */ function(_ExtensibleEvent) {
_inherits(PollResponseEvent, _ExtensibleEvent);
var _super = _createSuper(PollResponseEvent);
/**
* Creates a new PollResponseEvent from a pure format. Note that the event is *not*
* parsed here: it will be treated as a literal m.poll.response primary typed event.
*
* To validate the response against a poll, call `validateAgainst` after creation.
* @param {IPartialEvent<M_POLL_RESPONSE_EVENT_CONTENT>} wireFormat The event.
*/
function PollResponseEvent(wireFormat) {
var _this;
_classCallCheck(this, PollResponseEvent);
_this = _super.call(this, wireFormat);
_defineProperty(_assertThisInitialized(_this), "internalAnswerIds", void 0);
_defineProperty(_assertThisInitialized(_this), "internalSpoiled", void 0);
_defineProperty(_assertThisInitialized(_this), "pollEventId", void 0);
var rel = _this.wireContent["m.relates_to"];
if (!_relationship_types.REFERENCE_RELATION.matches(rel === null || rel === void 0 ? void 0 : rel.rel_type) || typeof (rel === null || rel === void 0 ? void 0 : rel.event_id) !== "string") throw new _InvalidEventError.InvalidEventError("Relationship must be a reference to an event");
_this.pollEventId = rel.event_id;
_this.validateAgainst(null);
return _this;
}
/**
* Validates the poll response using the poll start event as a frame of reference. This
* is used to determine if the vote is spoiled, whether the answers are valid, etc.
* @param {PollStartEvent} poll The poll start event.
*/
_createClass(PollResponseEvent, [
{
key: "answerIds",
get: function get() {
return this.internalAnswerIds;
}
},
{
key: "spoiled",
get: function get() {
return this.internalSpoiled;
}
},
{
key: "validateAgainst",
value: function validateAgainst(poll) {
var response = _poll_types.M_POLL_RESPONSE.findIn(this.wireContent);
if (!Array.isArray(response === null || response === void 0 ? void 0 : response.answers)) {
this.internalSpoiled = true;
this.internalAnswerIds = [];
return;
}
var answers = response.answers;
if (answers.some(function(a) {
return typeof a !== "string";
}) || answers.length === 0) {
this.internalSpoiled = true;
this.internalAnswerIds = [];
return;
}
if (poll) {
if (answers.some(function(a) {
return !poll.answers.some(function(pa) {
return pa.id === a;
});
})) {
this.internalSpoiled = true;
this.internalAnswerIds = [];
return;
}
answers = answers.slice(0, poll.maxSelections);
}
this.internalAnswerIds = answers;
this.internalSpoiled = false;
}
},
{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_RESPONSE);
}
},
{
key: "serialize",
value: function serialize() {
return {
type: _poll_types.M_POLL_RESPONSE.name,
content: _defineProperty({ "m.relates_to": {
rel_type: _relationship_types.REFERENCE_RELATION.name,
event_id: this.pollEventId
} }, _poll_types.M_POLL_RESPONSE.name, { answers: this.spoiled ? void 0 : this.answerIds })
};
}
}
], [{
key: "from",
value: function from(answers, pollEventId) {
return new PollResponseEvent({
type: _poll_types.M_POLL_RESPONSE.name,
content: _defineProperty({ "m.relates_to": {
rel_type: _relationship_types.REFERENCE_RELATION.name,
event_id: pollEventId
} }, _poll_types.M_POLL_RESPONSE.name, { answers })
});
}
}]);
return PollResponseEvent;
}(_ExtensibleEvent2.ExtensibleEvent);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/events/PollEndEvent.js
var require_PollEndEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.PollEndEvent = void 0;
var _poll_types = require_poll_types();
var _InvalidEventError = require_InvalidEventError();
var _relationship_types = require_relationship_types();
var _MessageEvent = require_MessageEvent();
var _message_types = require_message_types();
var _events = require_events();
var _ExtensibleEvent2 = require_ExtensibleEvent();
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
value: subClass,
writable: true,
configurable: true
} });
Object.defineProperty(subClass, "prototype", { writable: false });
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) return call;
else if (call !== void 0) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
exports.PollEndEvent = /* @__PURE__ */ function(_ExtensibleEvent) {
_inherits(PollEndEvent, _ExtensibleEvent);
var _super = _createSuper(PollEndEvent);
/**
* The poll start event ID referenced by the response.
*/
/**
* The closing message for the event.
*/
/**
* Creates a new PollEndEvent from a pure format. Note that the event is *not*
* parsed here: it will be treated as a literal m.poll.response primary typed event.
* @param {IPartialEvent<M_POLL_END_EVENT_CONTENT>} wireFormat The event.
*/
function PollEndEvent(wireFormat) {
var _this;
_classCallCheck(this, PollEndEvent);
_this = _super.call(this, wireFormat);
_defineProperty(_assertThisInitialized(_this), "pollEventId", void 0);
_defineProperty(_assertThisInitialized(_this), "closingMessage", void 0);
var rel = _this.wireContent["m.relates_to"];
if (!_relationship_types.REFERENCE_RELATION.matches(rel === null || rel === void 0 ? void 0 : rel.rel_type) || typeof (rel === null || rel === void 0 ? void 0 : rel.event_id) !== "string") throw new _InvalidEventError.InvalidEventError("Relationship must be a reference to an event");
_this.pollEventId = rel.event_id;
_this.closingMessage = new _MessageEvent.MessageEvent(_this.wireFormat);
return _this;
}
_createClass(PollEndEvent, [{
key: "isEquivalentTo",
value: function isEquivalentTo(primaryEventType) {
return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_END);
}
}, {
key: "serialize",
value: function serialize() {
return {
type: _poll_types.M_POLL_END.name,
content: _objectSpread(_defineProperty({ "m.relates_to": {
rel_type: _relationship_types.REFERENCE_RELATION.name,
event_id: this.pollEventId
} }, _poll_types.M_POLL_END.name, {}), this.closingMessage.serialize().content)
};
}
}], [{
key: "from",
value: function from(pollEventId, message) {
var _content;
return new PollEndEvent({
type: _poll_types.M_POLL_END.name,
content: (_content = { "m.relates_to": {
rel_type: _relationship_types.REFERENCE_RELATION.name,
event_id: pollEventId
} }, _defineProperty(_content, _poll_types.M_POLL_END.name, {}), _defineProperty(_content, _message_types.M_TEXT.name, message), _content)
});
}
}]);
return PollEndEvent;
}(_ExtensibleEvent2.ExtensibleEvent);
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/interpreters/modern/MPoll.js
var require_MPoll = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMPoll = parseMPoll;
var _poll_types = require_poll_types();
var _PollStartEvent = require_PollStartEvent();
var _PollResponseEvent = require_PollResponseEvent();
var _PollEndEvent = require_PollEndEvent();
function parseMPoll(wireEvent) {
if (_poll_types.M_POLL_START.matches(wireEvent.type)) return new _PollStartEvent.PollStartEvent(wireEvent);
else if (_poll_types.M_POLL_RESPONSE.matches(wireEvent.type)) return new _PollResponseEvent.PollResponseEvent(wireEvent);
else if (_poll_types.M_POLL_END.matches(wireEvent.type)) return new _PollEndEvent.PollEndEvent(wireEvent);
return null;
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/ExtensibleEvents.js
var require_ExtensibleEvents = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensibleEvents = void 0;
var _NamespacedMap = require_NamespacedMap();
var _InvalidEventError = require_InvalidEventError();
var _MRoomMessage = require_MRoomMessage();
var _MMessage = require_MMessage();
var _message_types = require_message_types();
var _poll_types = require_poll_types();
var _MPoll = require_MPoll();
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return { done: true };
return {
done: false,
value: o[i++]
};
},
e: function e(_e) {
throw _e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true, didErr = false, err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it["return"] != null) it["return"]();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
/**
* Utility class for parsing and identifying event types in a renderable form. An
* instance of this class can be created to change rendering preference depending
* on use-case.
*/
var ExtensibleEvents = /* @__PURE__ */ function() {
function ExtensibleEvents() {
_classCallCheck(this, ExtensibleEvents);
_defineProperty(this, "interpreters", new _NamespacedMap.NamespacedMap([
[_MRoomMessage.LEGACY_M_ROOM_MESSAGE, _MRoomMessage.parseMRoomMessage],
[_message_types.M_MESSAGE, _MMessage.parseMMessage],
[_message_types.M_EMOTE, _MMessage.parseMMessage],
[_message_types.M_NOTICE, _MMessage.parseMMessage],
[_poll_types.M_POLL_START, _MPoll.parseMPoll],
[_poll_types.M_POLL_RESPONSE, _MPoll.parseMPoll],
[_poll_types.M_POLL_END, _MPoll.parseMPoll]
]));
_defineProperty(this, "_unknownInterpretOrder", [_message_types.M_MESSAGE]);
}
/**
* Gets the default instance for all extensible event parsing.
*/
_createClass(ExtensibleEvents, [
{
key: "unknownInterpretOrder",
get: function get() {
var _this$_unknownInterpr;
return (_this$_unknownInterpr = this._unknownInterpretOrder) !== null && _this$_unknownInterpr !== void 0 ? _this$_unknownInterpr : [];
},
set: function set(val) {
this._unknownInterpretOrder = val;
}
},
{
key: "registerInterpreter",
value: function registerInterpreter(wireEventType, interpreter) {
this.interpreters.set(wireEventType, interpreter);
}
},
{
key: "parse",
value: function parse(wireFormat) {
try {
if (this.interpreters.hasNamespaced(wireFormat.type)) return this.interpreters.getNamespaced(wireFormat.type)(wireFormat);
var _iterator = _createForOfIteratorHelper(this.unknownInterpretOrder), _step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var tryType = _step.value;
if (this.interpreters.has(tryType)) {
var val = this.interpreters.get(tryType)(wireFormat);
if (val) return val;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return null;
} catch (e) {
if (e instanceof _InvalidEventError.InvalidEventError) return null;
throw e;
}
}
}
], [
{
key: "defaultInstance",
get: function get() {
return ExtensibleEvents._defaultInstance;
}
},
{
key: "unknownInterpretOrder",
get: function get() {
return ExtensibleEvents.defaultInstance.unknownInterpretOrder;
},
set: function set(val) {
ExtensibleEvents.defaultInstance.unknownInterpretOrder = val;
}
},
{
key: "registerInterpreter",
value: function registerInterpreter(wireEventType, interpreter) {
ExtensibleEvents.defaultInstance.registerInterpreter(wireEventType, interpreter);
}
},
{
key: "parse",
value: function parse(wireFormat) {
return ExtensibleEvents.defaultInstance.parse(wireFormat);
}
}
]);
return ExtensibleEvents;
}();
exports.ExtensibleEvents = ExtensibleEvents;
_defineProperty(ExtensibleEvents, "_defaultInstance", new ExtensibleEvents());
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/IPartialEvent.js
var require_IPartialEvent = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/utility/MessageMatchers.js
var require_MessageMatchers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.LegacyMsgType = void 0;
exports.isEventLike = isEventLike;
var _message_types = require_message_types();
/**
* Represents a legacy m.room.message msgtype
*/
var LegacyMsgType;
/**
* Determines if the given partial event looks similar enough to the given legacy msgtype
* to count as that message type.
* @param {IPartialEvent<EitherAnd<IPartialLegacyContent, M_MESSAGE_EVENT_CONTENT>>} event The event.
* @param {LegacyMsgType} msgtype The message type to compare for.
* @returns {boolean} True if the event appears to look similar enough to the msgtype.
*/
exports.LegacyMsgType = LegacyMsgType;
(function(LegacyMsgType) {
LegacyMsgType["Text"] = "m.text";
LegacyMsgType["Notice"] = "m.notice";
LegacyMsgType["Emote"] = "m.emote";
})(LegacyMsgType || (exports.LegacyMsgType = LegacyMsgType = {}));
function isEventLike(event, msgtype) {
var content = event.content;
if (msgtype === LegacyMsgType.Text) return _message_types.M_MESSAGE.matches(event.type) || event.type === "m.room.message" && (content === null || content === void 0 ? void 0 : content["msgtype"]) === "m.text";
else if (msgtype === LegacyMsgType.Emote) return _message_types.M_EMOTE.matches(event.type) || event.type === "m.room.message" && (content === null || content === void 0 ? void 0 : content["msgtype"]) === "m.emote";
else if (msgtype === LegacyMsgType.Notice) return _message_types.M_NOTICE.matches(event.type) || event.type === "m.room.message" && (content === null || content === void 0 ? void 0 : content["msgtype"]) === "m.notice";
return false;
}
}));
//#endregion
//#region node_modules/matrix-events-sdk/lib/index.js
var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var _ExtensibleEvents = require_ExtensibleEvents();
Object.keys(_ExtensibleEvents).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _ExtensibleEvents[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _ExtensibleEvents[key];
}
});
});
var _IPartialEvent = require_IPartialEvent();
Object.keys(_IPartialEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _IPartialEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _IPartialEvent[key];
}
});
});
var _InvalidEventError = require_InvalidEventError();
Object.keys(_InvalidEventError).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _InvalidEventError[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _InvalidEventError[key];
}
});
});
var _NamespacedValue = require_NamespacedValue();
Object.keys(_NamespacedValue).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _NamespacedValue[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _NamespacedValue[key];
}
});
});
var _NamespacedMap = require_NamespacedMap();
Object.keys(_NamespacedMap).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _NamespacedMap[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _NamespacedMap[key];
}
});
});
var _types = require_types();
Object.keys(_types).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _types[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _types[key];
}
});
});
var _MessageMatchers = require_MessageMatchers();
Object.keys(_MessageMatchers).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _MessageMatchers[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _MessageMatchers[key];
}
});
});
var _events = require_events();
Object.keys(_events).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _events[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _events[key];
}
});
});
var _MRoomMessage = require_MRoomMessage();
Object.keys(_MRoomMessage).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _MRoomMessage[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _MRoomMessage[key];
}
});
});
var _MMessage = require_MMessage();
Object.keys(_MMessage).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _MMessage[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _MMessage[key];
}
});
});
var _MPoll = require_MPoll();
Object.keys(_MPoll).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _MPoll[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _MPoll[key];
}
});
});
var _relationship_types = require_relationship_types();
Object.keys(_relationship_types).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _relationship_types[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _relationship_types[key];
}
});
});
var _ExtensibleEvent = require_ExtensibleEvent();
Object.keys(_ExtensibleEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _ExtensibleEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _ExtensibleEvent[key];
}
});
});
var _message_types = require_message_types();
Object.keys(_message_types).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _message_types[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _message_types[key];
}
});
});
var _MessageEvent = require_MessageEvent();
Object.keys(_MessageEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _MessageEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _MessageEvent[key];
}
});
});
var _EmoteEvent = require_EmoteEvent();
Object.keys(_EmoteEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _EmoteEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _EmoteEvent[key];
}
});
});
var _NoticeEvent = require_NoticeEvent();
Object.keys(_NoticeEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _NoticeEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _NoticeEvent[key];
}
});
});
var _poll_types = require_poll_types();
Object.keys(_poll_types).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _poll_types[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _poll_types[key];
}
});
});
var _PollStartEvent = require_PollStartEvent();
Object.keys(_PollStartEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _PollStartEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _PollStartEvent[key];
}
});
});
var _PollResponseEvent = require_PollResponseEvent();
Object.keys(_PollResponseEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _PollResponseEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _PollResponseEvent[key];
}
});
});
var _PollEndEvent = require_PollEndEvent();
Object.keys(_PollEndEvent).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _PollEndEvent[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _PollEndEvent[key];
}
});
});
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
var require_objectWithoutPropertiesLoose = /* @__PURE__ */ __commonJSMin(((exports, module) => {
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/@babel/runtime/helpers/objectWithoutProperties.js
var require_objectWithoutProperties = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var objectWithoutPropertiesLoose = require_objectWithoutPropertiesLoose();
function _objectWithoutProperties(e, t) {
if (null == e) return {};
var o, r, i = objectWithoutPropertiesLoose(e, t);
if (Object.getOwnPropertySymbols) {
var n = Object.getOwnPropertySymbols(e);
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
}
return i;
}
module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports;
}));
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/user.js
var UserEvent = /* @__PURE__ */ function(UserEvent) {
UserEvent["DisplayName"] = "User.displayName";
UserEvent["AvatarUrl"] = "User.avatarUrl";
UserEvent["Presence"] = "User.presence";
UserEvent["CurrentlyActive"] = "User.currentlyActive";
UserEvent["LastPresenceTs"] = "User.lastPresenceTs";
return UserEvent;
}({});
var User = class User extends TypedEventEmitter {
/**
* Construct a new User. A User must have an ID and can optionally have extra information associated with it.
* @param userId - Required. The ID of this user.
* @deprecated use `User.createUser`
*/
constructor(userId) {
super();
this.userId = userId;
(0, import_defineProperty.default)(this, "modified", -1);
/**
* The 'displayname' of the user if known.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "displayName", void 0);
(0, import_defineProperty.default)(this, "rawDisplayName", void 0);
/**
* The 'avatar_url' of the user if known.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "avatarUrl", void 0);
/**
* The presence status message if known.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "presenceStatusMsg", void 0);
/**
* The presence enum if known.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "presence", "offline");
/**
* Timestamp (ms since the epoch) for when we last received presence data for this user.
* We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "lastActiveAgo", 0);
/**
* The time elapsed in ms since the user interacted proactively with the server,
* or we saw a message from the user
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "lastPresenceTs", 0);
/**
* Whether we should consider lastActiveAgo to be an approximation
* and that the user should be seen as active 'now'
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "currentlyActive", false);
/**
* The events describing this user.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "events", {});
this.displayName = userId;
this.rawDisplayName = userId;
this.updateModifiedTime();
}
/**
* Construct a new User whose events will also emit on MatrixClient.
* A User must have an ID and can optionally have extra information associated with it.
* @param userId - Required. The ID of this user.
* @param client - An instance of MatrixClient object
* @returns User object with reEmitter setup on client
*/
static createUser(userId, client) {
var user = new User(userId);
client.reEmitter.reEmit(user, [
UserEvent.AvatarUrl,
UserEvent.DisplayName,
UserEvent.Presence,
UserEvent.CurrentlyActive,
UserEvent.LastPresenceTs
]);
return user;
}
/**
* Update this User with the given presence event. May fire "User.presence",
* "User.avatarUrl" and/or "User.displayName" if this event updates this user's
* properties.
* @param event - The `m.presence` event.
*
* @remarks
* Fires {@link UserEvent.Presence}
* Fires {@link UserEvent.DisplayName}
* Fires {@link UserEvent.AvatarUrl}
*/
setPresenceEvent(event) {
if (event.getType() !== "m.presence") return;
var firstFire = this.events.presence === null;
this.events.presence = event;
var eventsToFire = [];
if (event.getContent().presence !== this.presence || firstFire) eventsToFire.push(UserEvent.Presence);
if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) eventsToFire.push(UserEvent.AvatarUrl);
if (event.getContent().displayname && event.getContent().displayname !== this.displayName) eventsToFire.push(UserEvent.DisplayName);
if (event.getContent().currently_active !== void 0 && event.getContent().currently_active !== this.currentlyActive) eventsToFire.push(UserEvent.CurrentlyActive);
this.presence = event.getContent().presence;
eventsToFire.push(UserEvent.LastPresenceTs);
if (event.getContent().status_msg) this.presenceStatusMsg = event.getContent().status_msg;
if (event.getContent().displayname) this.displayName = event.getContent().displayname;
if (event.getContent().avatar_url) this.avatarUrl = event.getContent().avatar_url;
this.lastActiveAgo = event.getContent().last_active_ago;
this.lastPresenceTs = Date.now();
this.currentlyActive = event.getContent().currently_active;
this.updateModifiedTime();
for (var eventToFire of eventsToFire) this.emit(eventToFire, event, this);
}
/**
* Manually set this user's display name. No event is emitted in response to this
* as there is no underlying MatrixEvent to emit with.
* @param name - The new display name.
*/
setDisplayName(name) {
var oldName = this.displayName;
this.displayName = name;
if (name !== oldName) this.updateModifiedTime();
}
/**
* Manually set this user's non-disambiguated display name. No event is emitted
* in response to this as there is no underlying MatrixEvent to emit with.
* @param name - The new display name.
*/
setRawDisplayName(name) {
this.rawDisplayName = name;
}
/**
* Manually set this user's avatar URL. No event is emitted in response to this
* as there is no underlying MatrixEvent to emit with.
* @param url - The new avatar URL.
*/
setAvatarUrl(url) {
var oldUrl = this.avatarUrl;
this.avatarUrl = url;
if (url !== oldUrl) this.updateModifiedTime();
}
/**
* Update the last modified time to the current time.
*/
updateModifiedTime() {
this.modified = Date.now();
}
/**
* Get the timestamp when this User was last updated. This timestamp is
* updated when this User receives a new Presence event which has updated a
* property on this object. It is updated <i>before</i> firing events.
* @returns The timestamp
*/
getLastModifiedTime() {
return this.modified;
}
/**
* Get the absolute timestamp when this User was last known active on the server.
* It is *NOT* accurate if this.currentlyActive is true.
* @returns The timestamp
*/
getLastActiveTs() {
return this.lastPresenceTs - this.lastActiveAgo;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/event-timeline.js
var Direction = /* @__PURE__ */ function(Direction) {
Direction["Backward"] = "b";
Direction["Forward"] = "f";
return Direction;
}({});
var EventTimeline = class EventTimeline {
/**
* Static helper method to set sender and target properties
*
* @param event - the event whose metadata is to be set
* @param stateContext - the room state to be queried
* @param toStartOfTimeline - if true the event's forwardLooking flag is set false
*/
static setEventMetadata(event, stateContext, toStartOfTimeline) {
event.setMetadata(stateContext, toStartOfTimeline);
}
/**
* Construct a new EventTimeline
*
* <p>An EventTimeline represents a contiguous sequence of events in a room.
*
* <p>As well as keeping track of the events themselves, it stores the state of
* the room at the beginning and end of the timeline, and pagination tokens for
* going backwards and forwards in the timeline.
*
* <p>In order that clients can meaningfully maintain an index into a timeline,
* the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is
* incremented when events are prepended to the timeline. The index of an event
* relative to baseIndex therefore remains constant.
*
* <p>Once a timeline joins up with its neighbour, they are linked together into a
* doubly-linked list.
*
* @param eventTimelineSet - the set of timelines this is part of
*/
constructor(eventTimelineSet) {
var _eventTimelineSet$roo, _eventTimelineSet$roo2;
this.eventTimelineSet = eventTimelineSet;
(0, import_defineProperty.default)(this, "roomId", void 0);
(0, import_defineProperty.default)(this, "name", void 0);
(0, import_defineProperty.default)(this, "events", []);
(0, import_defineProperty.default)(this, "baseIndex", 0);
(0, import_defineProperty.default)(this, "startState", void 0);
(0, import_defineProperty.default)(this, "endState", void 0);
(0, import_defineProperty.default)(this, "startToken", null);
(0, import_defineProperty.default)(this, "endToken", null);
(0, import_defineProperty.default)(this, "prevTimeline", null);
(0, import_defineProperty.default)(this, "nextTimeline", null);
(0, import_defineProperty.default)(this, "paginationRequests", {
[Direction.Backward]: null,
[Direction.Forward]: null
});
this.roomId = (_eventTimelineSet$roo = (_eventTimelineSet$roo2 = eventTimelineSet.room) === null || _eventTimelineSet$roo2 === void 0 ? void 0 : _eventTimelineSet$roo2.roomId) !== null && _eventTimelineSet$roo !== void 0 ? _eventTimelineSet$roo : null;
if (this.roomId) {
this.startState = new RoomState(this.roomId);
this.endState = new RoomState(this.roomId);
}
this.paginationRequests = {
b: null,
f: null
};
this.name = this.roomId + ":" + (/* @__PURE__ */ new Date()).toISOString();
}
/**
* Initialise the start and end state with the given events
*
* <p>This can only be called before any events are added.
*
* @param stateEvents - list of state events to initialise the
* state with.
* @throws Error if an attempt is made to call this after addEvent is called.
*/
initialiseState(stateEvents) {
var _this$startState, _this$endState;
var { timelineWasEmpty } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
if (this.events.length > 0) throw new Error("Cannot initialise state after events are added");
(_this$startState = this.startState) === null || _this$startState === void 0 || _this$startState.setStateEvents(stateEvents, { timelineWasEmpty });
(_this$endState = this.endState) === null || _this$endState === void 0 || _this$endState.setStateEvents(stateEvents, { timelineWasEmpty });
}
/**
* Forks the (live) timeline, taking ownership of the existing directional state of this timeline.
* All attached listeners will keep receiving state updates from the new live timeline state.
* The end state of this timeline gets replaced with an independent copy of the current RoomState,
* and will need a new pagination token if it ever needs to paginate forwards.
* @param direction - EventTimeline.BACKWARDS to get the state at the
* start of the timeline; EventTimeline.FORWARDS to get the state at the end
* of the timeline.
*
* @returns the new timeline
*/
forkLive(direction) {
var forkState = this.getState(direction);
var timeline = new EventTimeline(this.eventTimelineSet);
timeline.startState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();
timeline.endState = forkState;
this.endState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();
return timeline;
}
/**
* Creates an independent timeline, inheriting the directional state from this timeline.
*
* @param direction - EventTimeline.BACKWARDS to get the state at the
* start of the timeline; EventTimeline.FORWARDS to get the state at the end
* of the timeline.
*
* @returns the new timeline
*/
fork(direction) {
var forkState = this.getState(direction);
var timeline = new EventTimeline(this.eventTimelineSet);
timeline.startState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();
timeline.endState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();
return timeline;
}
/**
* Get the ID of the room for this timeline
* @returns room ID
*/
getRoomId() {
return this.roomId;
}
/**
* Get the filter for this timeline's timelineSet (if any)
* @returns filter
*/
getFilter() {
return this.eventTimelineSet.getFilter();
}
/**
* Get the timelineSet for this timeline
* @returns timelineSet
*/
getTimelineSet() {
return this.eventTimelineSet;
}
/**
* Get the base index.
*
* <p>This is an index which is incremented when events are prepended to the
* timeline. An individual event therefore stays at the same index in the array
* relative to the base index (although note that a given event's index may
* well be less than the base index, thus giving that event a negative relative
* index).
*/
getBaseIndex() {
return this.baseIndex;
}
/**
* Get the list of events in this context
*
* @returns An array of MatrixEvents
*/
getEvents() {
return this.events;
}
/**
* Get the room state at the start/end of the timeline
*
* @param direction - EventTimeline.BACKWARDS to get the state at the
* start of the timeline; EventTimeline.FORWARDS to get the state at the end
* of the timeline.
*
* @returns state at the start/end of the timeline
*/
getState(direction) {
if (direction == EventTimeline.BACKWARDS) return this.startState;
else if (direction == EventTimeline.FORWARDS) return this.endState;
else throw new Error("Invalid direction '" + direction + "'");
}
/**
* Get a pagination token
*
* @param direction - EventTimeline.BACKWARDS to get the pagination
* token for going backwards in time; EventTimeline.FORWARDS to get the
* pagination token for going forwards in time.
*
* @returns pagination token
*/
getPaginationToken(direction) {
if (this.roomId) return this.getState(direction).paginationToken;
else if (direction === Direction.Backward) return this.startToken;
else return this.endToken;
}
/**
* Set a pagination token
*
* @param token - pagination token
*
* @param direction - EventTimeline.BACKWARDS to set the pagination
* token for going backwards in time; EventTimeline.FORWARDS to set the
* pagination token for going forwards in time.
*/
setPaginationToken(token, direction) {
if (this.roomId) this.getState(direction).paginationToken = token;
else if (direction === Direction.Backward) this.startToken = token;
else this.endToken = token;
}
/**
* Get the next timeline in the series
*
* @param direction - EventTimeline.BACKWARDS to get the previous
* timeline; EventTimeline.FORWARDS to get the next timeline.
*
* @returns previous or following timeline, if they have been
* joined up.
*/
getNeighbouringTimeline(direction) {
if (direction == EventTimeline.BACKWARDS) return this.prevTimeline;
else if (direction == EventTimeline.FORWARDS) return this.nextTimeline;
else throw new Error("Invalid direction '" + direction + "'");
}
/**
* Set the next timeline in the series
*
* @param neighbour - previous/following timeline
*
* @param direction - EventTimeline.BACKWARDS to set the previous
* timeline; EventTimeline.FORWARDS to set the next timeline.
*
* @throws Error if an attempt is made to set the neighbouring timeline when
* it is already set.
*/
setNeighbouringTimeline(neighbour, direction) {
if (this.getNeighbouringTimeline(direction)) throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: " + direction + ")");
if (direction == EventTimeline.BACKWARDS) this.prevTimeline = neighbour;
else if (direction == EventTimeline.FORWARDS) this.nextTimeline = neighbour;
else throw new Error("Invalid direction '" + direction + "'");
this.setPaginationToken(null, direction);
}
/**
* Add a new event to the timeline, and update the state
*
* @param event - new event
* @param options - addEvent options
*/
addEvent(event, _ref) {
var { toStartOfTimeline, roomState, timelineWasEmpty, addToState } = _ref;
if (!roomState) roomState = toStartOfTimeline ? this.startState : this.endState;
var timelineSet = this.getTimelineSet();
if (timelineSet.room) {
EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline);
if (addToState && event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {
var _roomState;
(_roomState = roomState) === null || _roomState === void 0 || _roomState.setStateEvents([event], { timelineWasEmpty });
if (!event.sender || event.getType() === EventType.RoomMember && !toStartOfTimeline) EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline);
}
}
var insertIndex;
if (toStartOfTimeline) insertIndex = 0;
else insertIndex = this.events.length;
this.events.splice(insertIndex, 0, event);
if (toStartOfTimeline) this.baseIndex++;
}
/**
* Insert a new event into the timeline, and update the state.
*
* TEMPORARY: until we have recursive relations, we need this function
* to exist to allow us to insert events in timeline order, which is our
* best guess for Sync Order.
* This is a copy of addEvent above, modified to allow inserting an event at
* a specific index.
*
* @internal
*/
insertEvent(event, insertIndex, roomState, addToState) {
var timelineSet = this.getTimelineSet();
if (timelineSet.room) {
EventTimeline.setEventMetadata(event, roomState, false);
if (addToState && event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {
roomState.setStateEvents([event], {});
if (!event.sender || event.getType() === EventType.RoomMember) EventTimeline.setEventMetadata(event, roomState, false);
}
}
this.events.splice(insertIndex, 0, event);
}
/**
* Remove an event from the timeline
*
* @param eventId - ID of event to be removed
* @returns removed event, or null if not found
*/
removeEvent(eventId) {
for (var i = this.events.length - 1; i >= 0; i--) {
var ev = this.events[i];
if (ev.getId() == eventId) {
this.events.splice(i, 1);
if (i < this.baseIndex) this.baseIndex--;
return ev;
}
}
return null;
}
/**
* Return a string to identify this timeline, for debugging
*
* @returns name for this timeline
*/
toString() {
return this.name;
}
};
/**
* Symbolic constant for methods which take a 'direction' argument:
* refers to the start of the timeline, or backwards in time.
*/
(0, import_defineProperty.default)(EventTimeline, "BACKWARDS", Direction.Backward);
/**
* Symbolic constant for methods which take a 'direction' argument:
* refers to the end of the timeline, or forwards in time.
*/
(0, import_defineProperty.default)(EventTimeline, "FORWARDS", Direction.Forward);
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/relations.js
var RelationsEvent = /* @__PURE__ */ function(RelationsEvent) {
RelationsEvent["Add"] = "Relations.add";
RelationsEvent["Remove"] = "Relations.remove";
RelationsEvent["Redaction"] = "Relations.redaction";
return RelationsEvent;
}({});
var matchesEventType = function matchesEventType(eventType, targetEventType) {
return [targetEventType, ...arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : []].includes(eventType);
};
/**
* A container for relation events that supports easy access to common ways of
* aggregating such events. Each instance holds events that of a single relation
* type and event type. All of the events also relate to the same original event.
*
* The typical way to get one of these containers is via
* EventTimelineSet#getRelationsForEvent.
*/
var Relations = class extends TypedEventEmitter {
/**
* @param relationType - The type of relation involved, such as "m.annotation", "m.reference", "m.replace", etc.
* @param eventType - The relation event's type, such as "m.reaction", etc.
* @param client - The client which created this instance. For backwards compatibility also accepts a Room.
* @param altEventTypes - alt event types for relation events, for example to support unstable prefixed event types
*/
constructor(relationType, eventType, client, altEventTypes) {
var _this;
super();
_this = this;
this.relationType = relationType;
this.eventType = eventType;
this.altEventTypes = altEventTypes;
(0, import_defineProperty.default)(this, "relationEventIds", /* @__PURE__ */ new Set());
(0, import_defineProperty.default)(this, "relations", /* @__PURE__ */ new Set());
(0, import_defineProperty.default)(this, "annotationsByKey", {});
(0, import_defineProperty.default)(this, "annotationsBySender", {});
(0, import_defineProperty.default)(this, "sortedAnnotationsByKey", []);
(0, import_defineProperty.default)(this, "targetEvent", null);
(0, import_defineProperty.default)(this, "creationEmitted", false);
(0, import_defineProperty.default)(this, "replacementUpdateId", 0);
(0, import_defineProperty.default)(this, "client", void 0);
/**
* Listens for event status changes to remove cancelled events.
*
* @param event - The event whose status has changed
* @param status - The new status
*/
(0, import_defineProperty.default)(this, "onEventStatus", (event, status) => {
if (!event.isSending()) {
event.removeListener(MatrixEventEvent.Status, this.onEventStatus);
return;
}
if (status !== EventStatus.CANCELLED) return;
event.removeListener(MatrixEventEvent.Status, this.onEventStatus);
this.removeEvent(event);
});
/**
* For relations that have been redacted, we want to remove them from
* aggregation data sets and emit an update event.
*
* To do so, we listen for `Event.beforeRedaction`, which happens:
* - after the server accepted the redaction and remote echoed back to us
* - before the original event has been marked redacted in the client
*
* @param redactedEvent - The original relation event that is about to be redacted.
*/
(0, import_defineProperty.default)(this, "onBeforeRedaction", /* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (redactedEvent) {
if (!_this.relations.has(redactedEvent)) return;
_this.relations.delete(redactedEvent);
if (_this.relationType === RelationType.Annotation) _this.removeAnnotationFromAggregation(redactedEvent);
else if (_this.relationType === RelationType.Replace) yield _this.updateTargetEventReplacement();
redactedEvent.removeListener(MatrixEventEvent.BeforeRedaction, _this.onBeforeRedaction);
_this.emit(RelationsEvent.Redaction, redactedEvent);
});
return function(_x) {
return _ref.apply(this, arguments);
};
}());
this.client = client instanceof Room ? client.client : client;
}
/**
* Add relation events to this collection.
*
* @param event - The new relation event to be added.
*/
addEvent(event) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this2.relationEventIds.has(event.getId())) return;
var relation = event.getRelation();
if (!relation) {
logger$2.error("Event must have relation info");
return;
}
var relationType = relation.rel_type;
var eventType = event.getType();
if (_this2.relationType !== relationType || !matchesEventType(eventType, _this2.eventType, _this2.altEventTypes)) {
logger$2.error("Event relation info doesn't match this container");
return;
}
if (event.isSending()) event.on(MatrixEventEvent.Status, _this2.onEventStatus);
_this2.relations.add(event);
_this2.relationEventIds.add(event.getId());
if (_this2.relationType === RelationType.Annotation) _this2.addAnnotationToAggregation(event);
else if (_this2.relationType === RelationType.Replace) yield _this2.updateTargetEventReplacement();
event.on(MatrixEventEvent.BeforeRedaction, _this2.onBeforeRedaction);
_this2.emit(RelationsEvent.Add, event);
_this2.maybeEmitCreated();
})();
}
/**
* Remove relation event from this collection.
*
* @param event - The relation event to remove.
*/
removeEvent(event) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this3.relations.has(event)) return;
_this3.relations.delete(event);
if (_this3.relationType === RelationType.Annotation) _this3.removeAnnotationFromAggregation(event);
else if (_this3.relationType === RelationType.Replace) yield _this3.updateTargetEventReplacement();
_this3.emit(RelationsEvent.Remove, event);
})();
}
/**
* Get all relation events in this collection.
*
* These are currently in the order of insertion to this collection, which
* won't match timeline order in the case of scrollback.
* TODO: Tweak `addEvent` to insert correctly for scrollback.
*
* Relation events in insertion order.
*/
getRelations() {
return [...this.relations];
}
addAnnotationToAggregation(event) {
var _event$getRelation;
var { key } = (_event$getRelation = event.getRelation()) !== null && _event$getRelation !== void 0 ? _event$getRelation : {};
if (!key) return;
var eventsForKey = this.annotationsByKey[key];
if (!eventsForKey) {
eventsForKey = this.annotationsByKey[key] = /* @__PURE__ */ new Set();
this.sortedAnnotationsByKey.push([key, eventsForKey]);
}
eventsForKey.add(event);
this.sortedAnnotationsByKey.sort((a, b) => {
var aEvents = a[1];
return b[1].size - aEvents.size;
});
var sender = event.getSender();
var eventsFromSender = this.annotationsBySender[sender];
if (!eventsFromSender) eventsFromSender = this.annotationsBySender[sender] = /* @__PURE__ */ new Set();
eventsFromSender.add(event);
}
removeAnnotationFromAggregation(event) {
var _event$getRelation2;
var { key } = (_event$getRelation2 = event.getRelation()) !== null && _event$getRelation2 !== void 0 ? _event$getRelation2 : {};
if (!key) return;
var eventsForKey = this.annotationsByKey[key];
if (eventsForKey) {
eventsForKey.delete(event);
this.sortedAnnotationsByKey.sort((a, b) => {
var aEvents = a[1];
return b[1].size - aEvents.size;
});
}
var sender = event.getSender();
var eventsFromSender = this.annotationsBySender[sender];
if (eventsFromSender) eventsFromSender.delete(event);
}
/**
* Get all events in this collection grouped by key and sorted by descending
* event count in each group.
*
* This is currently only supported for the annotation relation type.
*
* An array of [key, events] pairs sorted by descending event count.
* The events are stored in a Set (which preserves insertion order).
*/
getSortedAnnotationsByKey() {
if (this.relationType !== RelationType.Annotation) return null;
return this.sortedAnnotationsByKey;
}
/**
* Get all events in this collection grouped by sender.
*
* This is currently only supported for the annotation relation type.
*
* An object with each relation sender as a key and the matching Set of
* events for that sender as a value.
*/
getAnnotationsBySender() {
if (this.relationType !== RelationType.Annotation) return null;
return this.annotationsBySender;
}
/**
* Returns the most recent (and allowed) m.replace relation, if any.
*
* This is currently only supported for the m.replace relation type,
* once the target event is known, see `addEvent`.
*/
getLastReplacement() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this4.relationType !== RelationType.Replace) return null;
if (!_this4.targetEvent) return null;
var replaceRelation = _this4.targetEvent.getServerAggregatedRelation(RelationType.Replace);
var minTs = replaceRelation === null || replaceRelation === void 0 ? void 0 : replaceRelation.origin_server_ts;
var lastReplacement = _this4.getRelations().reduce((last, event) => {
if (event.getSender() !== _this4.targetEvent.getSender()) return last;
if (minTs && minTs > event.getTs()) return last;
if (last && last.getTs() > event.getTs()) return last;
return event;
}, null);
if (lastReplacement !== null && lastReplacement !== void 0 && lastReplacement.shouldAttemptDecryption() && _this4.client.getCrypto()) yield lastReplacement.attemptDecryption(_this4.client.getCrypto());
else if (lastReplacement !== null && lastReplacement !== void 0 && lastReplacement.isBeingDecrypted()) yield lastReplacement.getDecryptionPromise();
return lastReplacement;
})();
}
setTargetEvent(event) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this5.targetEvent) return;
_this5.targetEvent = event;
if (_this5.relationType === RelationType.Replace) yield _this5.updateTargetEventReplacement();
_this5.maybeEmitCreated();
})();
}
/**
* Updates the target event with the latest replacement.
*
* Multiple replacement updates can be triggered concurrently (for example
* while edits are still being decrypted). A monotonic update counter guards
* against older async resolutions overriding newer replacement selections.
*/
updateTargetEventReplacement() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this6.targetEvent || _this6.targetEvent.isState()) return;
var targetEvent = _this6.targetEvent;
var updateId = ++_this6.replacementUpdateId;
var lastReplacement = yield _this6.getLastReplacement();
if (updateId !== _this6.replacementUpdateId || _this6.targetEvent !== targetEvent) return;
if (!lastReplacement && !targetEvent.replacingEvent()) return;
targetEvent.makeReplaced(lastReplacement !== null && lastReplacement !== void 0 ? lastReplacement : void 0);
})();
}
maybeEmitCreated() {
if (this.creationEmitted) return;
if (!this.targetEvent || !this.relations.size) return;
this.creationEmitted = true;
this.targetEvent.emit(MatrixEventEvent.RelationsCreated, this.relationType, this.eventType);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/relations-container.js
var RelationsContainer = class {
constructor(client, room) {
this.client = client;
this.room = room;
(0, import_defineProperty.default)(this, "relations", /* @__PURE__ */ new Map());
}
/**
* Get a collection of child events to a given event in this timeline set.
*
* @param eventId - The ID of the event that you'd like to access child events for.
* For example, with annotations, this would be the ID of the event being annotated.
* @param relationType - The type of relationship involved, such as "m.annotation", "m.reference", "m.replace", etc.
* @param eventType - The relation event's type, such as "m.reaction", etc.
* @throws If `eventId</code>, <code>relationType</code> or <code>eventType`
* are not valid.
*
* @returns
* A container for relation events or undefined if there are no relation events for
* the relationType.
*/
getChildEventsForEvent(eventId, relationType, eventType) {
var _this$relations$get;
return (_this$relations$get = this.relations.get(eventId)) === null || _this$relations$get === void 0 || (_this$relations$get = _this$relations$get.get(relationType)) === null || _this$relations$get === void 0 ? void 0 : _this$relations$get.get(eventType);
}
getAllChildEventsForEvent(parentEventId) {
var _this$relations$get2;
var relationsForEvent = (_this$relations$get2 = this.relations.get(parentEventId)) !== null && _this$relations$get2 !== void 0 ? _this$relations$get2 : /* @__PURE__ */ new Map();
var events = [];
for (var relationsRecord of relationsForEvent.values()) for (var relations of relationsRecord.values()) events.push(...relations.getRelations());
return events;
}
/**
* Set an event as the target event if any Relations exist for it already.
* Child events can point to other child events as their parent, so this method may be
* called for events which are also logically child events.
*
* @param event - The event to check as relation target.
*/
aggregateParentEvent(event) {
var relationsForEvent = this.relations.get(event.getId());
if (!relationsForEvent) return;
for (var relationsWithRelType of relationsForEvent.values()) for (var relationsWithEventType of relationsWithRelType.values()) relationsWithEventType.setTargetEvent(event);
}
/**
* Add relation events to the relevant relation collection.
*
* @param event - The new child event to be aggregated.
* @param timelineSet - The event timeline set within which to search for the related event if any.
*/
aggregateChildEvent(event, timelineSet) {
if (event.isRedacted() || event.status === EventStatus.CANCELLED) return;
var relation = event.getRelation();
if (!relation) return;
var onEventDecrypted = () => {
if (event.isDecryptionFailure()) {
event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
return;
}
this.aggregateChildEvent(event, timelineSet);
};
if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {
event.once(MatrixEventEvent.Decrypted, onEventDecrypted);
return;
}
var { event_id: relatesToEventId, rel_type: relationType } = relation;
var eventType = event.getType();
var relationsForEvent = this.relations.get(relatesToEventId);
if (!relationsForEvent) {
relationsForEvent = /* @__PURE__ */ new Map();
this.relations.set(relatesToEventId, relationsForEvent);
}
var relationsWithRelType = relationsForEvent.get(relationType);
if (!relationsWithRelType) {
relationsWithRelType = /* @__PURE__ */ new Map();
relationsForEvent.set(relationType, relationsWithRelType);
}
var relationsWithEventType = relationsWithRelType.get(eventType);
if (!relationsWithEventType) {
var _this$room, _ref, _timelineSet$findEven;
relationsWithEventType = new Relations(relationType, eventType, this.client);
relationsWithRelType.set(eventType, relationsWithEventType);
var _room = (_this$room = this.room) !== null && _this$room !== void 0 ? _this$room : timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.room;
var relatesToEvent = (_ref = (_timelineSet$findEven = timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.findEventById(relatesToEventId)) !== null && _timelineSet$findEven !== void 0 ? _timelineSet$findEven : _room === null || _room === void 0 ? void 0 : _room.findEventById(relatesToEventId)) !== null && _ref !== void 0 ? _ref : _room === null || _room === void 0 ? void 0 : _room.getPendingEvent(relatesToEventId);
if (relatesToEvent) relationsWithEventType.setTargetEvent(relatesToEvent);
}
relationsWithEventType.addEvent(event);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/event-timeline-set.js
var DEBUG$1 = true;
/* istanbul ignore next */
var debuglog$2;
if (DEBUG$1) debuglog$2 = logger$2.log.bind(logger$2);
else
/* istanbul ignore next */
debuglog$2 = function debuglog() {};
var DuplicateStrategy = /* @__PURE__ */ function(DuplicateStrategy) {
DuplicateStrategy["Ignore"] = "ignore";
DuplicateStrategy["Replace"] = "replace";
return DuplicateStrategy;
}({});
var EventTimelineSet = class extends TypedEventEmitter {
/**
* Construct a set of EventTimeline objects, typically on behalf of a given
* room. A room may have multiple EventTimelineSets for different levels
* of filtering. The global notification list is also an EventTimelineSet, but
* lacks a room.
*
* <p>This is an ordered sequence of timelines, which may or may not
* be continuous. Each timeline lists a series of events, as well as tracking
* the room state at the start and the end of the timeline (if appropriate).
* It also tracks forward and backward pagination tokens, as well as containing
* links to the next timeline in the sequence.
*
* <p>There is one special timeline - the 'live' timeline, which represents the
* timeline to which events are being added in real-time as they are received
* from the /sync API. Note that you should not retain references to this
* timeline - even if it is the current timeline right now, it may not remain
* so if the server gives us a timeline gap in /sync.
*
* <p>In order that we can find events from their ids later, we also maintain a
* map from event_id to timeline and index.
*
* @param room - Room for this timelineSet. May be null for non-room cases, such as the
* notification timeline.
* @param opts - Options inherited from Room.
* @param client - the Matrix client which owns this EventTimelineSet,
* can be omitted if room is specified.
* @param thread - the thread to which this timeline set relates.
* @param threadListType - the type of thread list represented, if any
* (e.g., All threads or My threads)
*/
constructor(room) {
var _this$room$relations, _this$room, _room$client;
var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var client = arguments.length > 2 ? arguments[2] : void 0;
var thread = arguments.length > 3 ? arguments[3] : void 0;
var threadListType = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : null;
super();
this.room = room;
this.thread = thread;
this.threadListType = threadListType;
(0, import_defineProperty.default)(this, "relations", void 0);
(0, import_defineProperty.default)(this, "timelineSupport", void 0);
(0, import_defineProperty.default)(this, "displayPendingEvents", void 0);
(0, import_defineProperty.default)(this, "liveTimeline", void 0);
(0, import_defineProperty.default)(this, "timelines", void 0);
(0, import_defineProperty.default)(this, "_eventIdToTimeline", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "filter", void 0);
this.timelineSupport = Boolean(opts.timelineSupport);
this.liveTimeline = new EventTimeline(this);
this.displayPendingEvents = opts.pendingEvents !== false;
this.timelines = [this.liveTimeline];
this._eventIdToTimeline = /* @__PURE__ */ new Map();
this.filter = opts.filter;
this.relations = (_this$room$relations = (_this$room = this.room) === null || _this$room === void 0 ? void 0 : _this$room.relations) !== null && _this$room$relations !== void 0 ? _this$room$relations : new RelationsContainer((_room$client = room === null || room === void 0 ? void 0 : room.client) !== null && _room$client !== void 0 ? _room$client : client);
}
/**
* Get all the timelines in this set
* @returns the timelines in this set
*/
getTimelines() {
return this.timelines;
}
/**
* Get the filter object this timeline set is filtered on, if any
* @returns the optional filter for this timelineSet
*/
getFilter() {
return this.filter;
}
/**
* Set the filter object this timeline set is filtered on
* (passed to the server when paginating via /messages).
* @param filter - the filter for this timelineSet
*/
setFilter(filter) {
this.filter = filter;
}
/**
* Get the list of pending sent events for this timelineSet's room, filtered
* by the timelineSet's filter if appropriate.
*
* @returns A list of the sent events
* waiting for remote echo.
*
* @throws If `opts.pendingEventOrdering` was not 'detached'
*/
getPendingEvents() {
if (!this.room || !this.displayPendingEvents) return [];
return this.room.getPendingEvents();
}
/**
* Get the live timeline for this room.
*
* @returns live timeline
*/
getLiveTimeline() {
return this.liveTimeline;
}
/**
* Set the live timeline for this room.
*
* @returns live timeline
*/
setLiveTimeline(timeline) {
this.liveTimeline = timeline;
}
/**
* Return the timeline (if any) this event is in.
* @param eventId - the eventId being sought
* @returns timeline
*/
eventIdToTimeline(eventId) {
return this._eventIdToTimeline.get(eventId);
}
/**
* Track a new event as if it were in the same timeline as an old event,
* replacing it.
* @param oldEventId - event ID of the original event
* @param newEventId - event ID of the replacement event
*/
replaceEventId(oldEventId, newEventId) {
var existingTimeline = this._eventIdToTimeline.get(oldEventId);
if (existingTimeline) {
this._eventIdToTimeline.delete(oldEventId);
this._eventIdToTimeline.set(newEventId, existingTimeline);
}
}
/**
* Reset the live timeline, and start a new one.
*
* <p>This is used when /sync returns a 'limited' timeline.
*
* @param backPaginationToken - token for back-paginating the new timeline
* @param forwardPaginationToken - token for forward-paginating the old live timeline,
* if absent or null, all timelines are reset.
*
* @remarks
* Fires {@link RoomEvent.TimelineReset}
*/
resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
var resetAllTimelines = !this.timelineSupport || !forwardPaginationToken;
var oldTimeline = this.liveTimeline;
var newTimeline = resetAllTimelines ? oldTimeline.forkLive(EventTimeline.FORWARDS) : oldTimeline.fork(EventTimeline.FORWARDS);
if (resetAllTimelines) {
this.timelines = [newTimeline];
this._eventIdToTimeline = /* @__PURE__ */ new Map();
} else this.timelines.push(newTimeline);
if (forwardPaginationToken) oldTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);
newTimeline.setPaginationToken(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : null, EventTimeline.BACKWARDS);
this.liveTimeline = newTimeline;
this.emit(RoomEvent.TimelineReset, this.room, this, resetAllTimelines);
}
/**
* Get the timeline which contains the given event, if any
*
* @param eventId - event ID to look for
* @returns timeline containing
* the given event, or null if unknown
*/
getTimelineForEvent(eventId) {
if (eventId === null || eventId === void 0) return null;
var res = this._eventIdToTimeline.get(eventId);
return res === void 0 ? null : res;
}
/**
* Get an event which is stored in our timelines
*
* @param eventId - event ID to look for
* @returns the given event, or undefined if unknown
*/
findEventById(eventId) {
var tl = this.getTimelineForEvent(eventId);
if (!tl) return;
return tl.getEvents().find(function(ev) {
return ev.getId() == eventId;
});
}
/**
* Add a new timeline to this timeline list
*
* @returns newly-created timeline
*/
addTimeline() {
if (!this.timelineSupport) throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");
var timeline = new EventTimeline(this);
this.timelines.push(timeline);
return timeline;
}
/**
* Add events to a timeline
*
* <p>Will fire "Room.timeline" for each event added.
*
* @param events - A list of events to add.
*
* @param toStartOfTimeline - True to add these events to the start
* (oldest) instead of the end (newest) of the timeline. If true, the oldest
* event will be the <b>last</b> element of 'events'.
*
* @param timeline - timeline to
* add events to.
*
* @param paginationToken - token for the next batch of events
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*
*/
addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken) {
if (!timeline) throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");
if (!toStartOfTimeline && timeline == this.liveTimeline) throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");
if (this.filter) {
events = this.filter.filterRoomTimeline(events);
if (!events.length) return;
}
var direction = toStartOfTimeline ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;
var inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS : EventTimeline.BACKWARDS;
var didUpdate = false;
var lastEventWasNew = false;
for (var event of events) {
var eventId = event.getId();
var existingTimeline = this._eventIdToTimeline.get(eventId);
if (!existingTimeline) {
this.addEventToTimeline(event, timeline, {
toStartOfTimeline,
addToState
});
lastEventWasNew = true;
didUpdate = true;
continue;
}
lastEventWasNew = false;
if (existingTimeline == timeline) {
debuglog$2("Event " + eventId + " already in timeline " + timeline);
continue;
}
var neighbour = timeline.getNeighbouringTimeline(direction);
if (neighbour) {
if (existingTimeline == neighbour) debuglog$2("Event " + eventId + " in neighbouring timeline - switching to " + existingTimeline);
else debuglog$2("Event " + eventId + " already in a different timeline " + existingTimeline);
timeline = existingTimeline;
continue;
}
logger$2.info("Already have timeline for " + eventId + " - joining timeline " + timeline + " to " + existingTimeline);
var existingIsLive = existingTimeline === this.liveTimeline;
var timelineIsLive = timeline === this.liveTimeline;
var backwardsIsLive = direction === EventTimeline.BACKWARDS && existingIsLive;
var forwardsIsLive = direction === EventTimeline.FORWARDS && timelineIsLive;
if (backwardsIsLive || forwardsIsLive) {
if (backwardsIsLive) logger$2.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live (" + existingTimeline + ")");
if (forwardsIsLive) logger$2.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live (" + timeline + ")");
continue;
}
timeline.setNeighbouringTimeline(existingTimeline, direction);
existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);
timeline = existingTimeline;
didUpdate = true;
}
if (lastEventWasNew || !didUpdate) {
if (direction === EventTimeline.FORWARDS && timeline === this.liveTimeline) {
logger$2.warn({
lastEventWasNew,
didUpdate
});
logger$2.warn("Refusing to set forwards pagination token of live timeline " + "".concat(timeline, " to ").concat(paginationToken));
return;
}
timeline.setPaginationToken(paginationToken !== null && paginationToken !== void 0 ? paginationToken : null, direction);
}
}
/**
* Add an event to the end of this live timeline.
*
* @param event - Event to be added
* @param options - addLiveEvent options
*/
addLiveEvent(event, _ref) {
var { duplicateStrategy, fromCache, roomState, timelineWasEmpty, addToState } = _ref;
if (this.filter) {
if (!this.filter.filterRoomTimeline([event]).length) return;
}
var timeline = this._eventIdToTimeline.get(event.getId());
if (timeline) {
if (duplicateStrategy === DuplicateStrategy.Replace) {
debuglog$2("EventTimelineSet.addLiveEvent: replacing duplicate event " + event.getId());
var tlEvents = timeline.getEvents();
for (var j = 0; j < tlEvents.length; j++) if (tlEvents[j].getId() === event.getId()) {
if (!roomState) roomState = timeline.getState(EventTimeline.FORWARDS);
EventTimeline.setEventMetadata(event, roomState, false);
tlEvents[j] = event;
break;
}
} else debuglog$2("EventTimelineSet.addLiveEvent: ignoring duplicate event " + event.getId());
return;
}
this.addEventToTimeline(event, this.liveTimeline, {
toStartOfTimeline: false,
fromCache,
roomState,
timelineWasEmpty,
addToState
});
}
/**
* Add event to the given timeline, and emit Room.timeline. Assumes
* we have already checked we don't know about this event.
*
* Will fire "Room.timeline" for each event added.
*
* @param event - the event to add
* @param timeline - the timeline onto which to add it
* @param options - addEventToTimeline options
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*/
addEventToTimeline(event, timeline, _ref2) {
var { toStartOfTimeline, fromCache = false, roomState, timelineWasEmpty, addToState } = _ref2;
if (timeline.getTimelineSet() !== this) {
var _this$thread;
throw new Error("EventTimelineSet.addEventToTimeline: Timeline=".concat(timeline.toString(), " does not belong \" +\n \"in timelineSet(threadId=").concat((_this$thread = this.thread) === null || _this$thread === void 0 ? void 0 : _this$thread.id, ")"));
}
var eventId = event.getId();
this.relations.aggregateParentEvent(event);
this.relations.aggregateChildEvent(event, this);
if (this.room && !this.canContain(event)) {
var _this$thread2;
var eventDebugString = "event=".concat(eventId);
if (event.threadRootId) eventDebugString += "(belongs to thread=".concat(event.threadRootId, ")");
logger$2.warn("EventTimelineSet.addEventToTimeline: Ignoring ".concat(eventDebugString, " that does not belong ") + "in timeline=".concat(timeline.toString(), " timelineSet(threadId=").concat((_this$thread2 = this.thread) === null || _this$thread2 === void 0 ? void 0 : _this$thread2.id, ")"));
return;
}
timeline.addEvent(event, {
toStartOfTimeline,
roomState,
timelineWasEmpty,
addToState
});
this._eventIdToTimeline.set(eventId, timeline);
var data = {
timeline,
liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache
};
this.emit(RoomEvent.Timeline, event, this.room, Boolean(toStartOfTimeline), false, data);
}
/**
* Insert event to the given timeline, and emit Room.timeline. Assumes
* we have already checked we don't know about this event.
*
* TEMPORARY: until we have recursive relations, we need this function
* to exist to allow us to insert events in timeline order, which is our
* best guess for Sync Order.
* This is a copy of addEventToTimeline above, modified to insert the event
* after the event it relates to, and before any event with a later
* timestamp. This is our best guess at Sync Order.
*
* Will fire "Room.timeline" for each event added.
*
* @internal
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*/
insertEventIntoTimeline(event, timeline, roomState, addToState) {
if (timeline.getTimelineSet() !== this) {
var _this$thread3;
throw new Error("EventTimelineSet.insertEventIntoTimeline: Timeline=".concat(timeline.toString(), " does not belong \" +\n \"in timelineSet(threadId=").concat((_this$thread3 = this.thread) === null || _this$thread3 === void 0 ? void 0 : _this$thread3.id, ")"));
}
var eventId = event.getId();
this.relations.aggregateParentEvent(event);
this.relations.aggregateChildEvent(event, this);
if (this.room && !this.canContain(event)) {
var _this$thread4;
var eventDebugString = "event=".concat(eventId);
if (event.threadRootId) eventDebugString += "(belongs to thread=".concat(event.threadRootId, ")");
logger$2.warn("EventTimelineSet.insertEventIntoTimeline: Ignoring ".concat(eventDebugString, " that does not belong ") + "in timeline=".concat(timeline.toString(), " timelineSet(threadId=").concat((_this$thread4 = this.thread) === null || _this$thread4 === void 0 ? void 0 : _this$thread4.id, ")"));
return;
}
var parentEventId = event.relationEventId;
if (!parentEventId) {
this.addEventToTimeline(event, timeline, {
toStartOfTimeline: false,
fromCache: false,
timelineWasEmpty: false,
roomState,
addToState
});
return;
}
var parentEvent = this.findEventById(parentEventId);
var timelineEvents = timeline.getEvents();
var insertIndex = parentEvent !== void 0 ? timelineEvents.indexOf(parentEvent) : 0;
for (; insertIndex < timelineEvents.length; insertIndex++) if (timelineEvents[insertIndex].getTs() > event.getTs()) break;
timeline.insertEvent(event, insertIndex, roomState, addToState);
this._eventIdToTimeline.set(eventId, timeline);
var data = {
timeline,
liveEvent: false
};
this.emit(RoomEvent.Timeline, event, this.room, false, false, data);
}
/**
* Replaces event with ID oldEventId with one with newEventId, if oldEventId is
* recognised. Otherwise, add to the live timeline. Used to handle remote echos.
*
* @param localEvent - the new event to be added to the timeline
* @param oldEventId - the ID of the original event
* @param newEventId - the ID of the replacement event
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*/
handleRemoteEcho(localEvent, oldEventId, newEventId) {
var existingTimeline = this._eventIdToTimeline.get(oldEventId);
if (existingTimeline) {
this._eventIdToTimeline.delete(oldEventId);
this._eventIdToTimeline.set(newEventId, existingTimeline);
} else if (!this.filter || this.filter.filterRoomTimeline([localEvent]).length) this.addEventToTimeline(localEvent, this.liveTimeline, {
toStartOfTimeline: false,
addToState: false
});
}
/**
* Removes a single event from this room.
*
* @param eventId - The id of the event to remove
*
* @returns the removed event, or null if the event was not found
* in this room.
*/
removeEvent(eventId) {
var timeline = this._eventIdToTimeline.get(eventId);
if (!timeline) return null;
var removed = timeline.removeEvent(eventId);
if (removed) {
this._eventIdToTimeline.delete(eventId);
var data = { timeline };
this.emit(RoomEvent.Timeline, removed, this.room, void 0, true, data);
}
return removed;
}
/**
* Determine where two events appear in the timeline relative to one another
*
* @param eventId1 - The id of the first event
* @param eventId2 - The id of the second event
* @returns -1 if eventId1 precedes eventId2, and +1 eventId1 succeeds
* eventId2. 0 if they are the same event; null if we can't tell (either
* because we don't know about one of the events, or because they are in
* separate timelines which don't join up).
*/
compareEventOrdering(eventId1, eventId2) {
if (eventId1 == eventId2) return 0;
var timeline1 = this._eventIdToTimeline.get(eventId1);
var timeline2 = this._eventIdToTimeline.get(eventId2);
if (timeline1 === void 0) return null;
if (timeline2 === void 0) return null;
if (timeline1 === timeline2) {
var idx1 = void 0;
var idx2 = void 0;
var events = timeline1.getEvents();
for (var idx = 0; idx < events.length && (idx1 === void 0 || idx2 === void 0); idx++) {
var evId = events[idx].getId();
if (evId == eventId1) idx1 = idx;
if (evId == eventId2) idx2 = idx;
}
var difference = idx1 - idx2;
if (difference < 0) return -1;
else if (difference > 0) return 1;
else return 0;
}
var tl = timeline1;
while (tl) {
if (tl === timeline2) return -1;
tl = tl.getNeighbouringTimeline(EventTimeline.FORWARDS);
}
tl = timeline1;
while (tl) {
if (tl === timeline2) return 1;
tl = tl.getNeighbouringTimeline(EventTimeline.BACKWARDS);
}
return null;
}
/**
* Determine whether a given event can sanely be added to this event timeline set,
* for timeline sets relating to a thread, only return true for events in the same
* thread timeline, for timeline sets not relating to a thread only return true
* for events which should be shown in the main room timeline.
* Requires the `room` property to have been set at EventTimelineSet construction time.
*
* @param event - the event to check whether it belongs to this timeline set.
* @throws Error if `room` was not set when constructing this timeline set.
* @returns whether the event belongs to this timeline set.
*/
canContain(event) {
if (!this.room) throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");
var { threadId, shouldLiveInRoom, shouldLiveInThread } = this.room.eventShouldLiveIn(event);
if (this.thread) return this.thread.id === threadId;
if (!shouldLiveInRoom && !shouldLiveInThread) {
var _this$room2;
logger$2.warn("EventTimelineSet:canContain event encountered which cannot be added to any timeline roomId=".concat((_this$room2 = this.room) === null || _this$room2 === void 0 ? void 0 : _this$room2.roomId, " eventId=").concat(event.getId(), " threadId=").concat(event.threadRootId));
}
return shouldLiveInRoom;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/event-status.js
/**
* Enum for event statuses.
* @readonly
*/
var EventStatus = /* @__PURE__ */ function(EventStatus) {
/** The event was not sent and will no longer be retried. */
EventStatus["NOT_SENT"] = "not_sent";
/** The message is being encrypted */
EventStatus["ENCRYPTING"] = "encrypting";
/** The event is in the process of being sent. */
EventStatus["SENDING"] = "sending";
/** The event is in a queue waiting to be sent. */
EventStatus["QUEUED"] = "queued";
/** The event has been sent to the server, but we have not yet received the echo. */
EventStatus["SENT"] = "sent";
/** The event was cancelled before it was successfully sent. */
EventStatus["CANCELLED"] = "cancelled";
return EventStatus;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room-summary.js
/**
* A stripped m.room.member event which contains the key renderable fields from the event,
* sent only in simplified sliding sync (not `/v3/sync`).
* This is very similar to MSC4186Hero from sliding-sync.ts but an internal format with
* camelCase rather than underscores.
*/
/**
* High level summary information for a room, as returned by `/v3/sync`.
*/
/**
* Construct a new Room Summary. A summary can be used for display on a recent
* list, without having to load the entire room list into memory.
* @param roomId - Required. The ID of this room.
* @param info - Optional. The summary info. Additional keys are supported.
*/
var RoomSummary = class {
constructor(roomId, info) {
this.roomId = roomId;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/ReEmitter.js
var ReEmitter = class {
constructor(target) {
this.target = target;
(0, import_defineProperty.default)(this, "reEmitters", /* @__PURE__ */ new WeakMap());
}
reEmit(source, eventNames) {
var _this = this;
var reEmittersByEvent = this.reEmitters.get(source);
if (!reEmittersByEvent) {
reEmittersByEvent = /* @__PURE__ */ new Map();
this.reEmitters.set(source, reEmittersByEvent);
}
var _loop = function _loop(eventName) {
if (reEmittersByEvent.has(eventName)) return 1;
var forSource = function forSource() {
if (eventName === "error" && _this.target.listenerCount("error") === 0) return;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
_this.target.emit(eventName, ...args, source);
};
source.on(eventName, forSource);
reEmittersByEvent.set(eventName, forSource);
};
for (var eventName of eventNames) if (_loop(eventName)) continue;
}
stopReEmitting(source, eventNames) {
var reEmittersByEvent = this.reEmitters.get(source);
if (!reEmittersByEvent) return;
for (var eventName of eventNames) {
source.off(eventName, reEmittersByEvent.get(eventName));
reEmittersByEvent.delete(eventName);
}
if (reEmittersByEvent.size === 0) this.reEmitters.delete(source);
}
};
var TypedReEmitter = class extends ReEmitter {
constructor(target) {
super(target);
}
reEmit(source, eventNames) {
super.reEmit(source, eventNames);
}
stopReEmitting(source, eventNames) {
super.stopReEmitting(source, eventNames);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/sync.js
/**
* https://github.com/matrix-org/matrix-doc/pull/3773
*
* @experimental
*/
var UNREAD_THREAD_NOTIFICATIONS = new ServerControlledNamespacedValue("unread_thread_notifications", "org.matrix.msc3773.unread_thread_notifications");
//#endregion
//#region node_modules/matrix-js-sdk/lib/filter-component.js
/**
* Checks if a value matches a given field value, which may be a * terminated
* wildcard pattern.
* @param actualValue - The value to be compared
* @param filterValue - The filter pattern to be compared
* @returns true if the actualValue matches the filterValue
*/
function matchesWildcard(actualValue, filterValue) {
if (filterValue.endsWith("*")) {
var typePrefix = filterValue.slice(0, -1);
return actualValue.slice(0, typePrefix.length) === typePrefix;
} else return actualValue === filterValue;
}
/**
* FilterComponent is a section of a Filter definition which defines the
* types, rooms, senders filters etc to be applied to a particular type of resource.
* This is all ported over from synapse's Filter object.
*
* N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as
* 'Filters' are referred to as 'FilterCollections'.
*/
var FilterComponent = class {
constructor(filterJson, userId) {
this.filterJson = filterJson;
this.userId = userId;
}
/**
* Checks with the filter component matches the given event
* @param event - event to be checked against the filter
* @returns true if the event matches the filter
*/
check(event) {
var _event$getUnsigned, _bundledRelationships;
var bundledRelationships = ((_event$getUnsigned = event.getUnsigned()) === null || _event$getUnsigned === void 0 ? void 0 : _event$getUnsigned["m.relations"]) || {};
var relations = Object.keys(bundledRelationships);
var relationSenders = [];
if (this.userId && bundledRelationships !== null && bundledRelationships !== void 0 && (_bundledRelationships = bundledRelationships[THREAD_RELATION_TYPE.name]) !== null && _bundledRelationships !== void 0 && _bundledRelationships.current_user_participated) relationSenders.push(this.userId);
return this.checkFields(event.getRoomId(), event.getSender(), event.getType(), event.getContent() ? event.getContent().url !== void 0 : false, relations, relationSenders);
}
/**
* Converts the filter component into the form expected over the wire
*/
toJSON() {
return Object.fromEntries(Object.entries({
types: this.filterJson.types,
not_types: this.filterJson.not_types,
rooms: this.filterJson.rooms,
not_rooms: this.filterJson.not_rooms,
senders: this.filterJson.senders,
not_senders: this.filterJson.not_senders,
contains_url: this.filterJson.contains_url,
[FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name],
[FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name]
}).filter((_ref) => {
var [_key, value] = _ref;
return value;
}));
}
/**
* Checks whether the filter component matches the given event fields.
* @param roomId - the roomId for the event being checked
* @param sender - the sender of the event being checked
* @param eventType - the type of the event being checked
* @param containsUrl - whether the event contains a content.url field
* @param relationTypes - whether has aggregated relation of the given type
* @param relationSenders - whether one of the relation is sent by the user listed
* @returns true if the event fields match the filter
*/
checkFields(roomId, sender, eventType, containsUrl, relationTypes, relationSenders) {
var literalKeys = {
rooms: function rooms(v) {
return roomId === v;
},
senders: function senders(v) {
return sender === v;
},
types: function types(v) {
return matchesWildcard(eventType, v);
}
};
for (var name in literalKeys) {
var matchFunc = literalKeys[name];
var notName = "not_" + name;
var disallowedValues = this.filterJson[notName];
if (disallowedValues !== null && disallowedValues !== void 0 && disallowedValues.some(matchFunc)) return false;
var allowedValues = this.filterJson[name];
if (allowedValues && !allowedValues.some(matchFunc)) return false;
}
var containsUrlFilter = this.filterJson.contains_url;
if (containsUrlFilter !== void 0 && containsUrlFilter !== containsUrl) return false;
var relationTypesFilter = this.filterJson[FILTER_RELATED_BY_REL_TYPES.name];
if (relationTypesFilter !== void 0) {
if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) return false;
}
var relationSendersFilter = this.filterJson[FILTER_RELATED_BY_SENDERS.name];
if (relationSendersFilter !== void 0) {
if (!this.arrayMatchesFilter(relationSendersFilter, relationSenders)) return false;
}
return true;
}
arrayMatchesFilter(filter, values) {
return values.length > 0 && filter.every((value) => {
return values.includes(value);
});
}
/**
* Filters a list of events down to those which match this filter component
* @param events - Events to be checked against the filter component
* @returns events which matched the filter component
*/
filter(events) {
return events.filter(this.check, this);
}
/**
* Returns the limit field for a given filter component, providing a default of
* 10 if none is otherwise specified. Cargo-culted from Synapse.
* @returns the limit for this filter component.
*/
limit() {
return this.filterJson.limit !== void 0 ? this.filterJson.limit : 10;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/filter.js
function ownKeys$17(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;
}
function _objectSpread$17(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$17(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$17(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
*/
function setProp(obj, keyNesting, val) {
var nestedKeys = keyNesting.split(".");
var currentObj = obj;
for (var i = 0; i < nestedKeys.length - 1; i++) {
if (!currentObj[nestedKeys[i]]) currentObj[nestedKeys[i]] = {};
currentObj = currentObj[nestedKeys[i]];
}
currentObj[nestedKeys[nestedKeys.length - 1]] = val;
}
var Filter = class Filter {
/**
* Create a filter from existing data.
*/
static fromJson(userId, filterId, jsonObj) {
var filter = new Filter(userId, filterId);
filter.setDefinition(jsonObj);
return filter;
}
/**
* Construct a new Filter.
* @param userId - The user ID for this filter.
* @param filterId - The filter ID if known.
*/
constructor(userId, filterId) {
this.userId = userId;
this.filterId = filterId;
(0, import_defineProperty.default)(this, "definition", {});
(0, import_defineProperty.default)(this, "roomFilter", void 0);
(0, import_defineProperty.default)(this, "roomTimelineFilter", void 0);
}
/**
* Get the ID of this filter on your homeserver (if known)
* @returns The filter ID
*/
getFilterId() {
return this.filterId;
}
/**
* Get the JSON body of the filter.
* @returns The filter definition
*/
getDefinition() {
return this.definition;
}
/**
* Set the JSON body of the filter
* @param definition - The filter definition
*/
setDefinition(definition) {
this.definition = definition;
var roomFilterJson = definition.room;
var roomFilterFields = {};
if (roomFilterJson) {
if (roomFilterJson.rooms) roomFilterFields.rooms = roomFilterJson.rooms;
if (roomFilterJson.rooms) roomFilterFields.not_rooms = roomFilterJson.not_rooms;
}
this.roomFilter = new FilterComponent(roomFilterFields, this.userId);
this.roomTimelineFilter = new FilterComponent((roomFilterJson === null || roomFilterJson === void 0 ? void 0 : roomFilterJson.timeline) || {}, this.userId);
}
/**
* Get the room.timeline filter component of the filter
* @returns room timeline filter component
*/
getRoomTimelineFilterComponent() {
return this.roomTimelineFilter;
}
/**
* Filter the list of events based on whether they are allowed in a timeline
* based on this filter
* @param events - the list of events being filtered
* @returns the list of events which match the filter
*/
filterRoomTimeline(events) {
if (this.roomFilter) events = this.roomFilter.filter(events);
if (this.roomTimelineFilter) events = this.roomTimelineFilter.filter(events);
return events;
}
/**
* Set the max number of events to return for each room's timeline.
* @param limit - The max number of events to return for each room.
*/
setTimelineLimit(limit) {
setProp(this.definition, "room.timeline.limit", limit);
}
/**
* Enable threads unread notification
*/
setUnreadThreadNotifications(enabled) {
var _this$definition, _this$definition2;
this.definition = _objectSpread$17(_objectSpread$17({}, this.definition), {}, { room: _objectSpread$17(_objectSpread$17({}, (_this$definition = this.definition) === null || _this$definition === void 0 ? void 0 : _this$definition.room), {}, { timeline: _objectSpread$17(_objectSpread$17({}, (_this$definition2 = this.definition) === null || _this$definition2 === void 0 || (_this$definition2 = _this$definition2.room) === null || _this$definition2 === void 0 ? void 0 : _this$definition2.timeline), {}, { [UNREAD_THREAD_NOTIFICATIONS.name]: enabled }) }) });
}
setLazyLoadMembers(enabled) {
setProp(this.definition, "room.state.lazy_load_members", enabled);
}
/**
* Control whether left rooms should be included in responses.
* @param includeLeave - True to make rooms the user has left appear
* in responses.
*/
setIncludeLeaveRooms(includeLeave) {
setProp(this.definition, "room.include_leave", includeLeave);
}
};
(0, import_defineProperty.default)(Filter, "LAZY_LOADING_MESSAGES_FILTER", { lazy_load_members: true });
//#endregion
//#region node_modules/matrix-js-sdk/lib/extensible_events_v1/utilities.js
/**
* Determines if the given optional was provided a value.
* @param s - The optional to test.
* @returns True if the value is defined.
*/
function isProvided(s) {
return s !== null && s !== void 0;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/extensible_events.js
var import_lib$1 = require_lib$1();
new import_lib$1.UnstableValue("m.message", "org.matrix.msc1767.message");
new import_lib$1.UnstableValue("m.text", "org.matrix.msc1767.text");
new import_lib$1.UnstableValue("m.html", "org.matrix.msc1767.html");
new import_lib$1.NamespacedValue("m.reference");
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/topic.js
/**
* Extensible topic event type based on MSC3765
* https://github.com/matrix-org/matrix-spec-proposals/pull/3765
*
* @example
* ```
* {
* "type": "m.room.topic,
* "state_key": "",
* "content": {
* "topic": "All about **pizza**",
* "m.topic": [{
* "body": "All about **pizza**",
* "mimetype": "text/plain",
* }, {
* "body": "All about <b>pizza</b>",
* "mimetype": "text/html",
* }],
* }
* }
* ```
*/
/**
* The event type for an m.topic event (in content)
*/
var M_TOPIC = new NamespacedValue$1("m.topic", null);
/**
* The event content for an m.topic event (in content)
*/
/**
* A previous incorrect form of m.topic used by matrix-js-sdk
* TODO remove this after a few releases
* https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065
*/
/**
* The event definition for an m.topic event (in content)
*/
/**
* The event content for an m.room.topic event
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/content-helpers.js
/**
* Generates the content for a HTML Message event
* @param body - the plaintext body of the message
* @param htmlBody - the HTML representation of the message
* @returns
*/
function makeHtmlMessage(body, htmlBody) {
return {
msgtype: MsgType.Text,
format: "org.matrix.custom.html",
body,
formatted_body: htmlBody
};
}
/**
* Generates the content for a HTML Notice event
* @param body - the plaintext body of the notice
* @param htmlBody - the HTML representation of the notice
* @returns
*/
function makeHtmlNotice(body, htmlBody) {
return {
msgtype: MsgType.Notice,
format: "org.matrix.custom.html",
body,
formatted_body: htmlBody
};
}
/**
* Generates the content for a HTML Emote event
* @param body - the plaintext body of the emote
* @param htmlBody - the HTML representation of the emote
* @returns
*/
function makeHtmlEmote(body, htmlBody) {
return {
msgtype: MsgType.Emote,
format: "org.matrix.custom.html",
body,
formatted_body: htmlBody
};
}
/**
* Generates the content for a Plaintext Message event
* @param body - the plaintext body of the emote
* @returns
*/
function makeTextMessage(body) {
return {
msgtype: MsgType.Text,
body
};
}
/**
* Generates the content for a Plaintext Notice event
* @param body - the plaintext body of the notice
* @returns
*/
function makeNotice(body) {
return {
msgtype: MsgType.Notice,
body
};
}
/**
* Generates the content for a Plaintext Emote event
* @param body - the plaintext body of the emote
* @returns
*/
function makeEmoteMessage(body) {
return {
msgtype: MsgType.Emote,
body
};
}
/**
* Topic event helpers
*/
var makeTopicContent = (topic, htmlTopic) => {
var renderings = [];
if (isProvided(htmlTopic)) renderings.push({
body: htmlTopic,
mimetype: "text/html"
});
if (isProvided(topic)) renderings.push({
body: topic,
mimetype: "text/plain"
});
return {
topic,
[M_TOPIC.name]: { "m.text": renderings }
};
};
/**
* Flatten beacon info event content
*/
var parseBeaconInfoContent = (content) => {
var _M_TIMESTAMP$findIn;
var { description, timeout, live } = content;
var timestamp = (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : void 0;
var asset = M_ASSET.findIn(content);
return {
description,
timeout,
live,
assetType: asset === null || asset === void 0 ? void 0 : asset.type,
timestamp
};
};
var parseBeaconContent = (content) => {
var _M_TIMESTAMP$findIn2;
var location = M_LOCATION.findIn(content);
var timestamp = (_M_TIMESTAMP$findIn2 = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn2 !== void 0 ? _M_TIMESTAMP$findIn2 : void 0;
return {
description: location === null || location === void 0 ? void 0 : location.description,
uri: location === null || location === void 0 ? void 0 : location.uri,
timestamp
};
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/beacon.js
var BeaconEvent = /* @__PURE__ */ function(BeaconEvent) {
BeaconEvent["New"] = "Beacon.new";
BeaconEvent["Update"] = "Beacon.update";
BeaconEvent["LivenessChange"] = "Beacon.LivenessChange";
BeaconEvent["Destroy"] = "Beacon.Destroy";
BeaconEvent["LocationUpdate"] = "Beacon.LocationUpdate";
return BeaconEvent;
}({});
var isTimestampInDuration = (startTimestamp, durationMs, timestamp) => timestamp >= startTimestamp && startTimestamp + durationMs >= timestamp;
var getBeaconInfoIdentifier = (event) => "".concat(event.getRoomId(), "_").concat(event.getStateKey());
var Beacon = class extends TypedEventEmitter {
constructor(rootEvent) {
super();
this.rootEvent = rootEvent;
(0, import_defineProperty.default)(this, "roomId", void 0);
(0, import_defineProperty.default)(this, "_beaconInfo", void 0);
(0, import_defineProperty.default)(this, "_isLive", void 0);
(0, import_defineProperty.default)(this, "livenessWatchTimeout", void 0);
(0, import_defineProperty.default)(this, "_latestLocationEvent", void 0);
(0, import_defineProperty.default)(this, "clearLatestLocation", () => {
this._latestLocationEvent = void 0;
this.emit(BeaconEvent.LocationUpdate, this.latestLocationState);
});
this.roomId = this.rootEvent.getRoomId();
this.setBeaconInfo(this.rootEvent);
}
get isLive() {
return !!this._isLive;
}
get identifier() {
return getBeaconInfoIdentifier(this.rootEvent);
}
get beaconInfoId() {
return this.rootEvent.getId();
}
get beaconInfoOwner() {
return this.rootEvent.getStateKey();
}
get beaconInfoEventType() {
return this.rootEvent.getType();
}
get beaconInfo() {
return this._beaconInfo;
}
get latestLocationState() {
return this._latestLocationEvent && parseBeaconContent(this._latestLocationEvent.getContent());
}
get latestLocationEvent() {
return this._latestLocationEvent;
}
update(beaconInfoEvent) {
if (getBeaconInfoIdentifier(beaconInfoEvent) !== this.identifier) throw new Error("Invalid updating event");
if (beaconInfoEvent.getTs() < this.rootEvent.getTs()) return;
this.rootEvent = beaconInfoEvent;
this.setBeaconInfo(this.rootEvent);
this.emit(BeaconEvent.Update, beaconInfoEvent, this);
this.clearLatestLocation();
}
destroy() {
if (this.livenessWatchTimeout) clearTimeout(this.livenessWatchTimeout);
this._isLive = false;
this.emit(BeaconEvent.Destroy, this.identifier);
}
/**
* Monitor liveness of a beacon
* Emits BeaconEvent.LivenessChange when beacon expires
*/
monitorLiveness() {
if (this.livenessWatchTimeout) clearTimeout(this.livenessWatchTimeout);
this.checkLiveness();
if (!this.beaconInfo) return;
if (this.isLive) {
var expiryInMs = this.beaconInfo.timestamp + this.beaconInfo.timeout - Date.now();
if (expiryInMs > 1) this.livenessWatchTimeout = setTimeout(() => {
this.monitorLiveness();
}, expiryInMs);
} else if (this.beaconInfo.timestamp > Date.now()) this.livenessWatchTimeout = setTimeout(() => {
this.monitorLiveness();
}, this.beaconInfo.timestamp - Date.now());
}
/**
* Process Beacon locations
* Emits BeaconEvent.LocationUpdate
*/
addLocations(beaconLocationEvents) {
var _validLocationEvents$;
if (!this.isLive) return;
var latestLocationEvent = (_validLocationEvents$ = beaconLocationEvents.filter((event) => {
var parsed = parseBeaconContent(event.getContent());
if (!parsed.uri || !parsed.timestamp) return false;
var { timestamp } = parsed;
return this._beaconInfo.timestamp && isTimestampInDuration(this._beaconInfo.timestamp, this._beaconInfo.timeout, timestamp) && (!this.latestLocationState || timestamp > this.latestLocationState.timestamp);
}).sort(sortEventsByLatestContentTimestamp)) === null || _validLocationEvents$ === void 0 ? void 0 : _validLocationEvents$[0];
if (latestLocationEvent) {
this._latestLocationEvent = latestLocationEvent;
this.emit(BeaconEvent.LocationUpdate, this.latestLocationState);
}
}
setBeaconInfo(event) {
this._beaconInfo = parseBeaconInfoContent(event.getContent());
this.checkLiveness();
}
checkLiveness() {
var prevLiveness = this.isLive;
if (!this.beaconInfo) return;
var startTimestamp = this.beaconInfo.timestamp > Date.now() ? this.beaconInfo.timestamp - 36e4 : this.beaconInfo.timestamp;
this._isLive = !!this._beaconInfo.live && !!startTimestamp && isTimestampInDuration(startTimestamp, this._beaconInfo.timeout, Date.now());
if (prevLiveness !== this.isLive) this.emit(BeaconEvent.LivenessChange, this.isLive, this);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/read-receipt.js
function ownKeys$16(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;
}
function _objectSpread$16(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$16(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$16(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* Create a synthetic receipt for the given event
* @param userId - The user ID if the receipt sender
* @param event - The event that is to be acknowledged
* @param receiptType - The type of receipt
* @param unthreaded - the receipt is unthreaded
* @returns a new event with the synthetic receipt in it
*/
function synthesizeReceipt(userId, event, receiptType) {
var unthreaded = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
return new MatrixEvent({
content: { [event.getId()]: { [receiptType]: { [userId]: _objectSpread$16({ ts: event.getTs() }, !unthreaded && { thread_id: threadIdForReceipt(event) }) } } },
type: EventType.Receipt,
room_id: event.getRoomId()
});
}
var ReceiptPairRealIndex = 0;
var ReceiptPairSyntheticIndex = 1;
var ReadReceipt = class extends TypedEventEmitter {
constructor() {
super(...arguments);
(0, import_defineProperty.default)(this, "receipts", new MapWithDefault(() => /* @__PURE__ */ new Map()));
(0, import_defineProperty.default)(this, "receiptCacheByEventId", /* @__PURE__ */ new Map());
}
/**
* Gets the latest receipt for a given user in the room
* @param userId - The id of the user for which we want the receipt
* @param ignoreSynthesized - Whether to ignore synthesized receipts or not
* @param receiptType - Optional. The type of the receipt we want to get
* @returns the latest receipts of the chosen type for the chosen user
*/
getReadReceiptForUserId(userId) {
var _this$receipts$get$ge, _this$receipts$get;
var ignoreSynthesized = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var receiptType = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ReceiptType.Read;
var [realReceipt, syntheticReceipt] = (_this$receipts$get$ge = (_this$receipts$get = this.receipts.get(receiptType)) === null || _this$receipts$get === void 0 ? void 0 : _this$receipts$get.get(userId)) !== null && _this$receipts$get$ge !== void 0 ? _this$receipts$get$ge : [null, null];
if (ignoreSynthesized) return realReceipt;
return syntheticReceipt !== null && syntheticReceipt !== void 0 ? syntheticReceipt : realReceipt;
}
compareReceipts(a, b) {
var _this$getUnfilteredTi;
return (_this$getUnfilteredTi = this.getUnfilteredTimelineSet().compareEventOrdering(a.eventId, b.eventId)) !== null && _this$getUnfilteredTi !== void 0 ? _this$getUnfilteredTi : a.data.ts - b.data.ts;
}
/**
* Get the ID of the event that a given user has read up to, or null if:
* - we have received no read receipts for them, or
* - the receipt we have points at an event we don't have, or
* - the thread ID in the receipt does not match the thread root of the
* referenced event.
*
* (The event might not exist if it is not loaded, and the thread ID might
* not match if the event has moved thread because it was redacted.)
*
* @param userId - The user ID to get read receipt event ID for
* @param ignoreSynthesized - If true, return only receipts that have been
* sent by the server, not implicit ones generated
* by the JS SDK.
* @returns ID of the latest existing event that the given user has read, or null.
*/
getEventReadUpTo(userId) {
var ignoreSynthesized = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var latestReceipt = this.getLatestReceipt(userId, ignoreSynthesized);
if (!latestReceipt) return null;
return this.receiptPointsAtConsistentEvent(latestReceipt) ? latestReceipt.eventId : null;
}
/**
* Returns true if the event pointed at by this receipt exists, and its
* threadRootId is consistent with the thread information in the receipt.
*/
receiptPointsAtConsistentEvent(receipt) {
var _receipt$data;
var event = this.findEventById(receipt.eventId);
if (!event) return false;
if (!((_receipt$data = receipt.data) !== null && _receipt$data !== void 0 && _receipt$data.thread_id)) return true;
if (receipt.data.thread_id === "main") {
if (inMainTimelineForReceipt(event)) return true;
} else if (event.threadRootId === receipt.data.thread_id) return true;
logger$2.warn("Ignoring receipt because its thread_id (".concat(receipt.data.thread_id, ") disagrees ") + "with the thread root (".concat(event.threadRootId, ") of the referenced event ") + "(event ID = ".concat(receipt.eventId, ")"));
return false;
}
getLatestReceipt(userId, ignoreSynthesized) {
var _ref, _ref2;
var publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);
var privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);
var comparison;
if (publicReadReceipt !== null && publicReadReceipt !== void 0 && publicReadReceipt.eventId && privateReadReceipt !== null && privateReadReceipt !== void 0 && privateReadReceipt.eventId) comparison = this.compareReceipts(publicReadReceipt, privateReadReceipt);
if (!comparison) return (_ref = privateReadReceipt !== null && privateReadReceipt !== void 0 ? privateReadReceipt : publicReadReceipt) !== null && _ref !== void 0 ? _ref : null;
return (_ref2 = comparison < 0 ? privateReadReceipt : publicReadReceipt) !== null && _ref2 !== void 0 ? _ref2 : null;
}
addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic) {
var _pair$ReceiptPairSynt2, _pair$ReceiptPairSynt3;
var receiptTypesMap = this.receipts.getOrCreate(receiptType);
var pair = receiptTypesMap.get(userId);
if (!pair) {
pair = [null, null];
receiptTypesMap.set(userId, pair);
}
var existingReceipt = pair[ReceiptPairRealIndex];
if (synthetic) {
var _pair$ReceiptPairSynt;
existingReceipt = (_pair$ReceiptPairSynt = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt !== void 0 ? _pair$ReceiptPairSynt : pair[ReceiptPairRealIndex];
}
var wrappedReceipt = {
eventId,
data: receipt
};
if (existingReceipt) {
if (this.compareReceipts(existingReceipt, wrappedReceipt) >= 0) return;
}
var realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt;
var syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex];
var ordering = null;
if (realReceipt && syntheticReceipt) ordering = this.getUnfilteredTimelineSet().compareEventOrdering(realReceipt.eventId, syntheticReceipt.eventId);
var preferSynthetic = ordering === null || ordering < 0;
var cachedReceipt = (_pair$ReceiptPairSynt2 = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt2 !== void 0 ? _pair$ReceiptPairSynt2 : pair[ReceiptPairRealIndex];
if (synthetic && preferSynthetic) pair[ReceiptPairSyntheticIndex] = wrappedReceipt;
else if (!synthetic) {
pair[ReceiptPairRealIndex] = wrappedReceipt;
if (!preferSynthetic) pair[ReceiptPairSyntheticIndex] = null;
}
if (cachedReceipt === ((_pair$ReceiptPairSynt3 = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt3 !== void 0 ? _pair$ReceiptPairSynt3 : pair[ReceiptPairRealIndex])) return;
if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) {
var previousEventId = cachedReceipt.eventId;
this.receiptCacheByEventId.set(previousEventId, this.receiptCacheByEventId.get(previousEventId).filter((r) => {
return r.type !== receiptType || r.userId !== userId;
}));
if (this.receiptCacheByEventId.get(previousEventId).length < 1) this.receiptCacheByEventId.delete(previousEventId);
}
if (!this.receiptCacheByEventId.get(eventId)) this.receiptCacheByEventId.set(eventId, []);
this.receiptCacheByEventId.get(eventId).push({
userId,
type: receiptType,
data: receipt
});
}
/**
* Get a list of receipts for the given event.
* @param event - the event to get receipts for
* @returns A list of receipts with a userId, type and data keys or
* an empty list.
*/
getReceiptsForEvent(event) {
return this.receiptCacheByEventId.get(event.getId()) || [];
}
/**
* Look in this room/thread's timeline to find an event. If `this` is a
* room, we look in all threads, but if `this` is a thread, we look only
* inside this thread.
*/
/**
* This issue should also be addressed on synapse's side and is tracked as part
* of https://github.com/matrix-org/synapse/issues/14837
*
* Retrieves the read receipt for the logged in user and checks if it matches
* the last event in the room and whether that event originated from the logged
* in user.
* Under those conditions we can consider the context as read. This is useful
* because we never send read receipts against our own events
* @param userId - the logged in user
*/
fixupNotifications(userId) {
var receipt = this.getReadReceiptForUserId(userId, false);
var lastEvent = this.timeline[this.timeline.length - 1];
if (lastEvent && (receipt === null || receipt === void 0 ? void 0 : receipt.eventId) === lastEvent.getId() && userId === lastEvent.getSender()) {
this.setUnread(NotificationCountType.Total, 0);
this.setUnread(NotificationCountType.Highlight, 0);
}
}
/**
* Add a temporary local-echo receipt to the room to reflect in the
* client the fact that we've sent one.
* @param userId - The user ID if the receipt sender
* @param e - The event that is to be acknowledged
* @param receiptType - The type of receipt
* @param unthreaded - the receipt is unthreaded
*/
addLocalEchoReceipt(userId, e, receiptType) {
var unthreaded = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
this.addReceipt(synthesizeReceipt(userId, e, receiptType, unthreaded), true);
}
/**
* Get a list of user IDs who have <b>read up to</b> the given event.
* @param event - the event to get read receipts for.
* @returns A list of user IDs.
*/
getUsersReadUpTo(event) {
return this.getReceiptsForEvent(event).filter(function(receipt) {
return isSupportedReceiptType(receipt.type);
}).map(function(receipt) {
return receipt.userId;
});
}
};
new import_lib$1.UnstableValue("m.poll.disclosed", "org.matrix.msc3381.poll.disclosed");
new import_lib$1.UnstableValue("m.poll.undisclosed", "org.matrix.msc3381.poll.undisclosed");
new import_lib$1.UnstableValue("m.poll.start", "org.matrix.msc3381.poll.start");
/**
* The m.poll.start type within event content
*/
/**
* A poll answer.
*/
/**
* The event definition for an m.poll.start event (in content)
*/
/**
* The content for an m.poll.start event
*/
/**
* The namespaced value for m.poll.response
*/
var M_POLL_RESPONSE = new import_lib$1.UnstableValue("m.poll.response", "org.matrix.msc3381.poll.response");
/**
* The m.poll.response type within event content
*/
/**
* The event definition for an m.poll.response event (in content)
*/
/**
* The content for an m.poll.response event
*/
/**
* The namespaced value for m.poll.end
*/
var M_POLL_END = new import_lib$1.UnstableValue("m.poll.end", "org.matrix.msc3381.poll.end");
/**
* The event definition for an m.poll.end event (in content)
*/
/**
* The content for an m.poll.end event
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/poll.js
var PollEvent = /* @__PURE__ */ function(PollEvent) {
PollEvent["New"] = "Poll.new";
PollEvent["End"] = "Poll.end";
PollEvent["Update"] = "Poll.update";
PollEvent["Responses"] = "Poll.Responses";
PollEvent["Destroy"] = "Poll.Destroy";
PollEvent["UndecryptableRelations"] = "Poll.UndecryptableRelations";
return PollEvent;
}({});
var filterResponseRelations = (relationEvents, pollEndTimestamp) => {
return { responseEvents: relationEvents.filter((event) => {
if (event.isDecryptionFailure()) return;
return M_POLL_RESPONSE.matches(event.getType()) && event.getTs() <= pollEndTimestamp;
}) };
};
var Poll = class extends TypedEventEmitter {
constructor(rootEvent, matrixClient, room) {
super();
this.rootEvent = rootEvent;
this.matrixClient = matrixClient;
this.room = room;
(0, import_defineProperty.default)(this, "roomId", void 0);
(0, import_defineProperty.default)(this, "pollEvent", void 0);
(0, import_defineProperty.default)(this, "_isFetchingResponses", false);
(0, import_defineProperty.default)(this, "relationsNextBatch", void 0);
(0, import_defineProperty.default)(this, "responses", null);
(0, import_defineProperty.default)(this, "endEvent", void 0);
/**
* Keep track of undecryptable relations
* As incomplete result sets affect poll results
*/
(0, import_defineProperty.default)(this, "undecryptableRelationEventIds", /* @__PURE__ */ new Set());
(0, import_defineProperty.default)(this, "countUndecryptableEvents", (events) => {
var undecryptableEventIds = events.filter((event) => event.isDecryptionFailure()).map((event) => event.getId());
var previousCount = this.undecryptableRelationsCount;
this.undecryptableRelationEventIds = new Set([...this.undecryptableRelationEventIds, ...undecryptableEventIds]);
if (this.undecryptableRelationsCount !== previousCount) this.emit(PollEvent.UndecryptableRelations, this.undecryptableRelationsCount);
});
if (!this.rootEvent.getRoomId() || !this.rootEvent.getId()) throw new Error("Invalid poll start event.");
this.roomId = this.rootEvent.getRoomId();
this.pollEvent = this.rootEvent.unstableExtensibleEvent;
}
get pollId() {
return this.rootEvent.getId();
}
get endEventId() {
var _this$endEvent;
return (_this$endEvent = this.endEvent) === null || _this$endEvent === void 0 ? void 0 : _this$endEvent.getId();
}
get isEnded() {
return !!this.endEvent;
}
get isFetchingResponses() {
return this._isFetchingResponses;
}
get undecryptableRelationsCount() {
return this.undecryptableRelationEventIds.size;
}
getResponses() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this.responses) return _this.responses;
if (!_this.isFetchingResponses) yield _this.fetchResponses();
return _this.responses;
})();
}
/**
*
* @param event - event with a relation to the rootEvent
* @returns void
*/
onNewRelation(event) {
var _this$endEvent2;
if (M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) {
this.endEvent = event;
this.refilterResponsesOnEnd();
this.emit(PollEvent.End);
}
if (!this.responses) return;
var pollEndTimestamp = ((_this$endEvent2 = this.endEvent) === null || _this$endEvent2 === void 0 ? void 0 : _this$endEvent2.getTs()) || Number.MAX_SAFE_INTEGER;
var { responseEvents } = filterResponseRelations([event], pollEndTimestamp);
this.countUndecryptableEvents([event]);
if (responseEvents.length) {
responseEvents.forEach((event) => {
this.responses.addEvent(event);
});
this.emit(PollEvent.Responses, this.responses);
}
}
fetchResponses() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this2$endEvent, _allRelations$nextBat;
_this2._isFetchingResponses = true;
var allRelations = yield _this2.matrixClient.relations(_this2.roomId, _this2.rootEvent.getId(), "m.reference", void 0, { from: _this2.relationsNextBatch || void 0 });
yield Promise.all(allRelations.events.map((event) => _this2.matrixClient.decryptEventIfNeeded(event)));
var responses = _this2.responses || new Relations("m.reference", M_POLL_RESPONSE.name, _this2.matrixClient, [M_POLL_RESPONSE.altName]);
var pollEndEvent = allRelations.events.find((event) => M_POLL_END.matches(event.getType()));
if (_this2.validateEndEvent(pollEndEvent)) {
_this2.endEvent = pollEndEvent;
_this2.refilterResponsesOnEnd();
_this2.emit(PollEvent.End);
}
var pollCloseTimestamp = ((_this2$endEvent = _this2.endEvent) === null || _this2$endEvent === void 0 ? void 0 : _this2$endEvent.getTs()) || Number.MAX_SAFE_INTEGER;
var { responseEvents } = filterResponseRelations(allRelations.events, pollCloseTimestamp);
responseEvents.forEach((event) => {
responses.addEvent(event);
});
_this2.relationsNextBatch = (_allRelations$nextBat = allRelations.nextBatch) !== null && _allRelations$nextBat !== void 0 ? _allRelations$nextBat : void 0;
_this2.responses = responses;
_this2.countUndecryptableEvents(allRelations.events);
if (_this2.relationsNextBatch) _this2.fetchResponses();
else _this2._isFetchingResponses = false;
_this2.emit(PollEvent.Responses, _this2.responses);
})();
}
/**
* Only responses made before the poll ended are valid
* Refilter after an end event is recieved
* To ensure responses are valid
*/
refilterResponsesOnEnd() {
var _this$endEvent3;
if (!this.responses) return;
var pollEndTimestamp = ((_this$endEvent3 = this.endEvent) === null || _this$endEvent3 === void 0 ? void 0 : _this$endEvent3.getTs()) || Number.MAX_SAFE_INTEGER;
this.responses.getRelations().forEach((event) => {
if (event.getTs() > pollEndTimestamp) {
var _this$responses;
(_this$responses = this.responses) === null || _this$responses === void 0 || _this$responses.removeEvent(event);
}
});
this.emit(PollEvent.Responses, this.responses);
}
validateEndEvent(endEvent) {
if (!endEvent) return false;
/**
* Repeated end events are ignored -
* only the first (valid) closure event by origin_server_ts is counted.
*/
if (this.endEvent && this.endEvent.getTs() < endEvent.getTs()) return false;
/**
* MSC3381
* If a m.poll.end event is received from someone other than the poll creator or user with permission to redact
* others' messages in the room, the event must be ignored by clients due to being invalid.
*/
var roomCurrentState = this.room.currentState;
var endEventSender = endEvent.getSender();
return !!endEventSender && (endEventSender === this.rootEvent.getSender() || roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender));
}
};
/**
* Tests whether the event is a start, response or end poll event.
*
* @param event - Event to test
* @returns true if the event is a poll event, else false
*/
var isPollEvent = (event) => {
var eventType = event.getType();
return import_lib$1.M_POLL_START.matches(eventType) || M_POLL_RESPONSE.matches(eventType) || M_POLL_END.matches(eventType);
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room-receipts.js
/**
* The latest receipts we have for a room.
*/
var RoomReceipts = class {
constructor(room) {
(0, import_defineProperty.default)(this, "room", void 0);
(0, import_defineProperty.default)(this, "threadedReceipts", void 0);
(0, import_defineProperty.default)(this, "unthreadedReceipts", void 0);
(0, import_defineProperty.default)(this, "danglingReceipts", void 0);
/**
* Look for dangling receipts for the given event ID,
* and add them to the thread of unthread receipts if found.
* @param event - the event to look for
*/
(0, import_defineProperty.default)(this, "onTimelineEvent", (event) => {
var eventId = event.getId();
if (!eventId) return;
var danglingReceipts = this.danglingReceipts.remove(eventId);
danglingReceipts === null || danglingReceipts === void 0 || danglingReceipts.forEach((danglingReceipt) => {
if (danglingReceipt.receipt.thread_id) this.threadedReceipts.set(danglingReceipt.receipt.thread_id, danglingReceipt.eventId, danglingReceipt.receiptType, danglingReceipt.userId, danglingReceipt.receipt.ts, danglingReceipt.synthetic);
else this.unthreadedReceipts.set(eventId, danglingReceipt.receiptType, danglingReceipt.userId, danglingReceipt.receipt.ts, danglingReceipt.synthetic);
});
});
this.room = room;
this.threadedReceipts = new ThreadedReceipts(room);
this.unthreadedReceipts = new ReceiptsByUser(room);
this.danglingReceipts = new DanglingReceipts();
room.on(RoomEvent.Timeline, this.onTimelineEvent);
}
/**
* Remember the receipt information supplied. For each receipt:
*
* If we don't have the event for this receipt, store it as "dangling" so we
* can process it later.
*
* Otherwise store it per-user in either the threaded store for its
* thread_id, or the unthreaded store if there is no thread_id.
*
* Ignores any receipt that is before an existing receipt for the same user
* (in the same thread, if applicable). "Before" is defined by the
* unfilteredTimelineSet of the room.
*/
add(receiptContent, synthetic) {
for (var [_eventId, eventReceipt] of Object.entries(receiptContent)) for (var [_receiptType, receiptsByUser] of Object.entries(eventReceipt)) for (var [_userId, _receipt] of Object.entries(receiptsByUser)) if (!this.room.findEventById(_eventId)) this.danglingReceipts.add(new DanglingReceipt(_eventId, _receiptType, _userId, _receipt, synthetic));
else if (_receipt.thread_id) this.threadedReceipts.set(_receipt.thread_id, _eventId, _receiptType, _userId, _receipt.ts, synthetic);
else this.unthreadedReceipts.set(_eventId, _receiptType, _userId, _receipt.ts, synthetic);
}
hasUserReadEvent(userId, eventId) {
var unthreaded = this.unthreadedReceipts.get(userId);
if (unthreaded) {
if (isAfterOrSame(unthreaded.eventId, eventId, this.room)) return true;
}
var event = this.room.findEventById(eventId);
if (!event) {
logger$2.warn("hasUserReadEvent event ID ".concat(eventId, " not found in room ").concat(this.room.roomId, ": this shouldn't happen!"));
return false;
}
var threadId = threadIdForReceipt(event);
var threaded = this.threadedReceipts.get(threadId, userId);
if (threaded) {
if (isAfterOrSame(threaded.eventId, eventId, this.room)) return true;
}
if (this.userSentLatestEventInThread(threadId, userId)) return true;
return false;
}
/**
* @returns true if the thread with this ID can be found, and the supplied
* user sent the latest message in it.
*/
userSentLatestEventInThread(threadId, userId) {
var _this$room$getThread;
var timeline = threadId === "main" ? this.room.getLiveTimeline().getEvents() : (_this$room$getThread = this.room.getThread(threadId)) === null || _this$room$getThread === void 0 ? void 0 : _this$room$getThread.timeline;
return !!(timeline && timeline.length > 0 && timeline[timeline.length - 1].getSender() === userId);
}
};
/**
* The information "inside" a receipt once it has been stored inside
* RoomReceipts - what eventId it refers to, its type, and its ts.
*
* Does not contain userId or threadId since these are stored as keys of the
* maps in RoomReceipts.
*/
var ReceiptInfo = class {
constructor(eventId, receiptType, ts) {
this.eventId = eventId;
this.receiptType = receiptType;
this.ts = ts;
}
};
/**
* Everything we know about a receipt that is "dangling" because we can't find
* the event to which it refers.
*/
var DanglingReceipt = class {
constructor(eventId, receiptType, userId, receipt, synthetic) {
this.eventId = eventId;
this.receiptType = receiptType;
this.userId = userId;
this.receipt = receipt;
this.synthetic = synthetic;
}
};
var UserReceipts = class {
constructor(room) {
(0, import_defineProperty.default)(this, "room", void 0);
/**
* The real receipt for this user.
*/
(0, import_defineProperty.default)(this, "real", void 0);
/**
* The synthetic receipt for this user. If this is defined, it is later than real.
*/
(0, import_defineProperty.default)(this, "synthetic", void 0);
this.room = room;
this.real = void 0;
this.synthetic = void 0;
}
set(synthetic, receiptInfo) {
if (synthetic) this.synthetic = receiptInfo;
else this.real = receiptInfo;
if (this.synthetic && this.real) {
if (isAfterOrSame(this.real.eventId, this.synthetic.eventId, this.room)) this.synthetic = void 0;
}
}
/**
* Return the latest receipt we have - synthetic if we have one (and it's
* later), otherwise real.
*/
get() {
var _this$synthetic;
return (_this$synthetic = this.synthetic) !== null && _this$synthetic !== void 0 ? _this$synthetic : this.real;
}
/**
* Return the latest receipt we have of the specified type (synthetic or not).
*/
getByType(synthetic) {
return synthetic ? this.synthetic : this.real;
}
};
/**
* The latest receipt info we have, either for a single thread, or all the
* unthreaded receipts for a room.
*
* userId: ReceiptInfo
*/
var ReceiptsByUser = class {
constructor(room) {
(0, import_defineProperty.default)(this, "room", void 0);
/** map of userId: UserReceipts */
(0, import_defineProperty.default)(this, "data", void 0);
this.room = room;
this.data = /* @__PURE__ */ new Map();
}
/**
* Add the supplied receipt to our structure, if it is not earlier than the
* one we already hold for this user.
*/
set(eventId, receiptType, userId, ts, synthetic) {
var userReceipts = getOrCreate(this.data, userId, () => new UserReceipts(this.room));
var existingReceipt = userReceipts.getByType(synthetic);
if (existingReceipt && isAfter(existingReceipt.eventId, eventId, this.room)) return;
userReceipts.set(synthetic, new ReceiptInfo(eventId, receiptType, ts));
}
/**
* Find the latest receipt we have for this user. (Note - there is only one
* receipt per user, because we are already inside a specific thread or
* unthreaded list.)
*
* If there is a later synthetic receipt for this user, return that.
* Otherwise, return the real receipt.
*
* @returns the found receipt info, or undefined if we have no receipt for this user.
*/
get(userId) {
var _this$data$get;
return (_this$data$get = this.data.get(userId)) === null || _this$data$get === void 0 ? void 0 : _this$data$get.get();
}
};
/**
* The latest threaded receipts we have for a room.
*/
var ThreadedReceipts = class {
constructor(room) {
(0, import_defineProperty.default)(this, "room", void 0);
/** map of threadId: ReceiptsByUser */
(0, import_defineProperty.default)(this, "data", void 0);
this.room = room;
this.data = /* @__PURE__ */ new Map();
}
/**
* Add the supplied receipt to our structure, if it is not earlier than one
* we already hold for this user in this thread.
*/
set(threadId, eventId, receiptType, userId, ts, synthetic) {
getOrCreate(this.data, threadId, () => new ReceiptsByUser(this.room)).set(eventId, receiptType, userId, ts, synthetic);
}
/**
* Find the latest threaded receipt for the supplied user in the supplied thread.
*
* @returns the found receipt info or undefined if we don't have one.
*/
get(threadId, userId) {
var _this$data$get2;
return (_this$data$get2 = this.data.get(threadId)) === null || _this$data$get2 === void 0 ? void 0 : _this$data$get2.get(userId);
}
};
/**
* All the receipts that we have received but can't process because we can't
* find the event they refer to.
*
* We hold on to them so we can process them if their event arrives later.
*/
var DanglingReceipts = class {
constructor() {
/**
* eventId: DanglingReceipt[]
*/
(0, import_defineProperty.default)(this, "data", /* @__PURE__ */ new Map());
}
/**
* Remember the supplied dangling receipt.
*/
add(danglingReceipt) {
getOrCreate(this.data, danglingReceipt.eventId, () => []).push(danglingReceipt);
}
/**
* Remove and return the dangling receipts for the given event ID.
* @param eventId - the event ID to look for
* @returns the found dangling receipts, or undefined if we don't have one.
*/
remove(eventId) {
var danglingReceipts = this.data.get(eventId);
this.data.delete(eventId);
return danglingReceipts;
}
};
function getOrCreate(m, key, createFn) {
var found = m.get(key);
if (found) return found;
else {
var created = createFn();
m.set(key, created);
return created;
}
}
/**
* Is left after right (or the same)?
*
* Only returns true if both events can be found, and left is after or the same
* as right.
*
* @returns left \>= right
*/
function isAfterOrSame(leftEventId, rightEventId, room) {
var comparison = room.compareEventOrdering(leftEventId, rightEventId);
return comparison !== null && comparison >= 0;
}
/**
* Is left strictly after right?
*
* Only returns true if both events can be found, and left is strictly after right.
*
* @returns left \> right
*/
function isAfter(leftEventId, rightEventId, room) {
var comparison = room.compareEventOrdering(leftEventId, rightEventId);
return comparison !== null && comparison > 0;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/compare-event-ordering.js
/**
* Determine the order of two events in a room.
*
* In principle this should use the same order as the server, but in practice
* this is difficult for events that were not received over the Sync API. See
* MSC4033 for details.
*
* This implementation leans on the order of events within their timelines, and
* falls back to comparing event timestamps when they are in different
* timelines.
*
* See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are
* tracking the work to fix this.
*
* @param room - the room we are looking in
* @param leftEventId - the id of the first event
* @param rightEventId - the id of the second event
* @returns -1 if left \< right, 1 if left \> right, 0 if left == right, null if
* we can't tell (because we can't find the events).
*/
function compareEventOrdering(room, leftEventId, rightEventId) {
var leftEvent = room.findEventById(leftEventId);
var rightEvent = room.findEventById(rightEventId);
if (!leftEvent || !rightEvent) return null;
var isLeftEventInMainTimeline = inMainTimelineForReceipt(leftEvent);
var isRightEventInMainTimeline = inMainTimelineForReceipt(rightEvent);
if (isLeftEventInMainTimeline && isRightEventInMainTimeline) return compareEventsInMainTimeline(room, leftEventId, rightEventId, leftEvent, rightEvent);
else return compareEventsInThreads(leftEventId, rightEventId, leftEvent, rightEvent);
}
function compareEventsInMainTimeline(room, leftEventId, rightEventId, leftEvent, rightEvent) {
var timelineSet = room.getUnfilteredTimelineSet();
var compareSameTimeline = timelineSet.compareEventOrdering(leftEventId, rightEventId);
if (compareSameTimeline !== null) return compareSameTimeline;
if (timelineSet.getTimelineForEvent(leftEventId) === timelineSet.getLiveTimeline()) return 1;
if (timelineSet.getTimelineForEvent(rightEventId) === timelineSet.getLiveTimeline()) return -1;
return guessOrderBasedOnTimestamp(leftEvent, rightEvent);
}
function compareEventsInThreads(leftEventId, rightEventId, leftEvent, rightEvent) {
var leftEventThreadId = threadIdForReceipt(leftEvent);
var rightEventThreadId = threadIdForReceipt(rightEvent);
var leftThread = leftEvent.getThread();
if (leftThread && leftEventThreadId === rightEventThreadId) return leftThread.timelineSet.compareEventOrdering(leftEventId, rightEventId);
else return guessOrderBasedOnTimestamp(leftEvent, rightEvent);
}
/**
* Guess the order of events based on server timestamp. This is not good, but
* difficult to avoid without MSC4033.
*
* See https://github.com/matrix-org/matrix-js-sdk/issues/3325
*/
function guessOrderBasedOnTimestamp(leftEvent, rightEvent) {
var leftTs = leftEvent.getTs();
var rightTs = rightEvent.getTs();
if (leftTs < rightTs) return -1;
else if (leftTs > rightTs) return 1;
else return 0;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/method.js
var Method = /* @__PURE__ */ function(Method) {
Method["Get"] = "GET";
Method["Put"] = "PUT";
Method["Post"] = "POST";
Method["Delete"] = "DELETE";
Method["Options"] = "OPTIONS";
Method["Head"] = "HEAD";
Method["Patch"] = "PATCH";
return Method;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/errors.js
function ownKeys$15(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;
}
function _objectSpread$15(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$15(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$15(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* Construct a generic HTTP error. This is a JavaScript Error with additional information
* specific to HTTP responses.
* @param msg - The error message to include.
* @param httpStatus - The HTTP response status code.
* @param httpHeaders - The HTTP response headers.
*/
var HTTPError = class extends Error {
constructor(msg, httpStatus, httpHeaders) {
super(msg);
this.httpStatus = httpStatus;
this.httpHeaders = httpHeaders;
}
/**
* Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).
*
* If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side
* recommendation for the retry period.
*
* @returns Whether this error is due to rate-limiting.
*/
isRateLimitError() {
return this.httpStatus === 429;
}
/**
* @returns The recommended delay in milliseconds to wait before retrying
* the request that triggered this error, or null if no delay is recommended.
* @throws Error if the recommended delay is an invalid value.
* @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.
*/
getRetryAfterMs() {
var _this$httpHeaders;
var retryAfter = (_this$httpHeaders = this.httpHeaders) === null || _this$httpHeaders === void 0 ? void 0 : _this$httpHeaders.get("Retry-After");
if (retryAfter != null) {
if (/^\d+$/.test(retryAfter)) {
var ms = Number.parseInt(retryAfter) * 1e3;
if (!Number.isFinite(ms)) throw new Error("Retry-After header integer value is too large");
return ms;
}
var date = new Date(retryAfter);
if (date.toUTCString() !== retryAfter) throw new Error("Retry-After header value is not a valid HTTP-date or non-negative decimal integer");
return date.getTime() - Date.now();
}
return null;
}
};
var MatrixError = class MatrixError extends HTTPError {
/**
* Construct a Matrix error. This is a JavaScript Error with additional
* information specific to the standard Matrix error response.
* @param errorJson - The Matrix error JSON returned from the homeserver.
* @param httpStatus - The numeric HTTP status code given
* @param httpHeaders - The HTTP response headers given
*/
constructor() {
var errorJson = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var httpStatus = arguments.length > 1 ? arguments[1] : void 0;
var url = arguments.length > 2 ? arguments[2] : void 0;
var event = arguments.length > 3 ? arguments[3] : void 0;
var httpHeaders = arguments.length > 4 ? arguments[4] : void 0;
var message = errorJson.error || "Unknown message";
if (httpStatus) message = "[".concat(httpStatus, "] ").concat(message);
if (url) message = "".concat(message, " (").concat(url, ")");
super("MatrixError: ".concat(message), httpStatus, httpHeaders);
this.url = url;
this.event = event;
(0, import_defineProperty.default)(this, "errcode", void 0);
(0, import_defineProperty.default)(this, "error", void 0);
(0, import_defineProperty.default)(this, "data", void 0);
this.errcode = errorJson.errcode;
this.error = errorJson.error;
this.name = errorJson.errcode || "Unknown error code";
this.data = errorJson;
}
isRateLimitError() {
return this.errcode === "M_LIMIT_EXCEEDED" || (this.errcode === "M_UNKNOWN" || this.errcode === void 0) && super.isRateLimitError();
}
getRetryAfterMs() {
var headerValue = super.getRetryAfterMs();
if (headerValue !== null) return headerValue;
if (this.errcode === "M_LIMIT_EXCEEDED" && "retry_after_ms" in this.data) {
if (!Number.isInteger(this.data.retry_after_ms)) throw new Error("retry_after_ms is not an integer");
return this.data.retry_after_ms;
}
return null;
}
/**
* @returns this error expressed as a JSON payload
* for use by Widget API error responses.
*/
asWidgetApiErrorData() {
var _this$httpStatus, _this$url, _this$errcode, _this$data$error;
var headers = {};
if (this.httpHeaders) for (var [name, value] of this.httpHeaders) headers[name] = value;
return {
http_status: (_this$httpStatus = this.httpStatus) !== null && _this$httpStatus !== void 0 ? _this$httpStatus : 400,
http_headers: headers,
url: (_this$url = this.url) !== null && _this$url !== void 0 ? _this$url : "",
response: _objectSpread$15({
errcode: (_this$errcode = this.errcode) !== null && _this$errcode !== void 0 ? _this$errcode : "M_UNKNOWN",
error: (_this$data$error = this.data.error) !== null && _this$data$error !== void 0 ? _this$data$error : "Unknown message"
}, this.data)
};
}
/**
* @returns a new {@link MatrixError} from a JSON payload
* received from Widget API error responses.
*/
static fromWidgetApiErrorData(data) {
return new MatrixError(data.response, data.http_status, data.url, void 0, new Headers(data.http_headers));
}
};
/**
* @returns The recommended delay in milliseconds to wait before retrying the request.
* @param error - The error to check for a retry delay.
* @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.
*/
function safeGetRetryAfterMs(error, defaultMs) {
if (!(error instanceof HTTPError) || !error.isRateLimitError()) return defaultMs;
try {
var _error$getRetryAfterM;
return (_error$getRetryAfterM = error.getRetryAfterMs()) !== null && _error$getRetryAfterM !== void 0 ? _error$getRetryAfterM : defaultMs;
} catch (_unused) {
return defaultMs;
}
}
/**
* Construct a ConnectionError. This is a JavaScript Error indicating
* that a request failed because of some error with the connection, either
* CORS was not correctly configured on the server, the server didn't response,
* the request timed out, or the internet connection on the client side went down.
*/
var ConnectionError = class extends Error {
constructor(message, cause) {
super(message + (cause ? ": ".concat(cause.message) : ""));
}
get name() {
return "ConnectionError";
}
};
/**
* Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,
* and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.
* Assumed to be a temporary failure.
*/
var TokenRefreshError = class extends Error {
constructor(cause) {
var _cause$message;
super((_cause$message = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _cause$message !== void 0 ? _cause$message : "");
}
get name() {
return "TokenRefreshError";
}
};
/**
* Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,
* and attempting to refresh said token failed in a way indicative of token invalidation.
*/
var TokenRefreshLogoutError = class extends Error {
constructor(cause) {
var _cause$message2;
super((_cause$message2 = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _cause$message2 !== void 0 ? _cause$message2 : "");
}
get name() {
return "TokenRefreshLogoutError";
}
};
var MatrixSafetyErrorCode = new NamespacedValue$1(null, "ORG.MATRIX.MSC4387_SAFETY");
/***
* This error is thrown when the homeserver refuses to handle an action due to a
* safety concern.
* @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387
*/
var MatrixSafetyError = class extends MatrixError {
constructor() {
super(...arguments);
/**
* The kinds of harms detected by the server.
* @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.
*/
(0, import_defineProperty.default)(this, "harms", void 0);
/**
* The date at which a request can be reattempted.
*/
(0, import_defineProperty.default)(this, "expiry", void 0);
var body = arguments.length <= 0 ? void 0 : arguments[0];
this.harms = new Set(body && "harms" in body && Array.isArray(body.harms) ? body.harms : []);
this.message = "".concat(super.message, " (").concat([...this.harms].join(", "), ")");
if (body && "expiry" in body && typeof body.expiry === "number") this.expiry = new Date(body.expiry);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/interface.js
/**
* @experimental
* Unencrypted access and (optional) refresh token
*/
/**
* @experimental
* Function that performs token refresh using the given refreshToken.
* Returns a promise that resolves to the refreshed access and (optional) refresh tokens.
*
* Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}
*/
/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */
/** Options object for `FetchHttpApi.requestOtherUrl`. */
var HttpApiEvent = /* @__PURE__ */ function(HttpApiEvent) {
HttpApiEvent["SessionLoggedOut"] = "Session.logged_out";
HttpApiEvent["NoConsent"] = "no_consent";
return HttpApiEvent;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/utils.js
var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1);
function timeoutSignal(ms) {
var controller = new AbortController();
setTimeout(() => {
controller.abort();
}, ms);
return controller.signal;
}
function anySignal(signals) {
var controller = new AbortController();
function cleanup() {
for (var signal of signals) signal.removeEventListener("abort", onAbort);
}
function onAbort() {
controller.abort();
cleanup();
}
for (var signal of signals) {
if (signal.aborted) {
onAbort();
break;
}
signal.addEventListener("abort", onAbort);
}
return {
signal: controller.signal,
cleanup
};
}
/**
* Attempt to turn an HTTP error response into a Javascript Error.
*
* If it is a JSON response, we will parse it into a MatrixError. Otherwise
* we return a generic Error.
*
* @param response - response object
* @param body - raw body of the response
* @returns
*/
function parseErrorResponse(response, body) {
var _contentType, _contentType2;
var httpHeaders = isXhr(response) ? new Headers(response.getAllResponseHeaders().trim().split(/[\r\n]+/).map((header) => {
var colonIdx = header.indexOf(":");
return [header.substring(0, colonIdx), header.substring(colonIdx + 1)];
})) : response.headers;
var contentType;
try {
contentType = getResponseContentType(httpHeaders);
} catch (e) {
return e;
}
if (((_contentType = contentType) === null || _contentType === void 0 ? void 0 : _contentType.type) === "application/json" && body) {
var errorBody = JSON.parse(body);
if (errorBody.errcode && MatrixSafetyErrorCode.matches(errorBody.errcode)) return new MatrixSafetyError(errorBody, response.status, isXhr(response) ? response.responseURL : response.url, void 0, httpHeaders);
return new MatrixError(errorBody, response.status, isXhr(response) ? response.responseURL : response.url, void 0, httpHeaders);
}
if (((_contentType2 = contentType) === null || _contentType2 === void 0 ? void 0 : _contentType2.type) === "text/plain") return new HTTPError("Server returned ".concat(response.status, " error: ").concat(body), response.status, httpHeaders);
return new HTTPError("Server returned ".concat(response.status, " error"), response.status, httpHeaders);
}
function isXhr(response) {
return "getResponseHeader" in response;
}
/**
* extract the Content-Type header from response headers, and
* parse it to a `{type, parameters}` object.
*
* returns null if no content-type header could be found.
*
* @param response - response object
* @returns parsed content-type header, or null if not found
*/
function getResponseContentType(headers) {
var contentType = headers.get("Content-Type");
if (contentType === null) return null;
try {
return (0, import_content_type.parse)(contentType);
} catch (e) {
throw new Error("Error parsing Content-Type '".concat(contentType, "': ").concat(e));
}
}
/**
* Retries a network operation run in a callback.
* @param maxAttempts - maximum attempts to try
* @param callback - callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.
* @returns the result of the network operation
* @throws {@link ConnectionError} If after maxAttempts the callback still throws ConnectionError
*/
function retryNetworkOperation(_x, _x2) {
return _retryNetworkOperation.apply(this, arguments);
}
/**
* Calculate the backoff time for a request retry attempt.
* This produces wait times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the
* failure was due to a rate limited request, the time specified in the error is returned.
*
* Returns -1 if the error is not retryable, or if we reach the maximum number of attempts.
*
* @param err - The error thrown by the http call
* @param attempts - The number of attempts made so far, including the one that just failed.
* @param retryConnectionError - Whether to retry on {@link ConnectionError} (CORS, connection is down, etc.)
*/
function _retryNetworkOperation() {
_retryNetworkOperation = (0, import_asyncToGenerator.default)(function* (maxAttempts, callback) {
var attempts = 0;
var lastConnectionError = null;
while (attempts < maxAttempts) try {
if (attempts > 0) {
var timeout = 1e3 * Math.pow(2, attempts);
logger$2.log("network operation failed ".concat(attempts, " times, retrying in ").concat(timeout, "ms..."));
yield sleep(timeout);
}
return yield callback();
} catch (err) {
if (err instanceof ConnectionError) {
attempts += 1;
lastConnectionError = err;
} else throw err;
}
throw lastConnectionError;
});
return _retryNetworkOperation.apply(this, arguments);
}
function calculateRetryBackoff(err, attempts, retryConnectionError) {
if (attempts > 4) return -1;
if (err instanceof ConnectionError && !retryConnectionError) return -1;
if (err.httpStatus && Math.floor(err.httpStatus / 100) === 4 && err.httpStatus !== 429) return -1;
if (err.name === "AbortError") return -1;
if (err.name === "M_TOO_LARGE") return -1;
return safeGetRetryAfterMs(err, 1e3 * Math.pow(2, attempts));
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/refresh.js
/**
* This is an internal module. See {@link MatrixHttpApi} for the public class.
*/
var TokenRefreshOutcome = /* @__PURE__ */ function(TokenRefreshOutcome) {
TokenRefreshOutcome["Success"] = "success";
TokenRefreshOutcome["Failure"] = "failure";
TokenRefreshOutcome["Logout"] = "logout";
return TokenRefreshOutcome;
}({});
var REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;
var REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1e3;
/**
* This class is responsible for managing the access token and refresh token for authenticated requests.
* It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.
*/
var TokenRefresher = class {
constructor(opts) {
this.opts = opts;
/**
* Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.
* @private
*/
(0, import_defineProperty.default)(this, "tokenRefreshPromise", void 0);
(0, import_defineProperty.default)(this, "latestTokenRefreshExpiry", void 0);
}
/**
* This function is called before every request to ensure that the access token is valid.
* @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken
* handler if an M_UNKNOWN_TOKEN error is encountered.
*/
prepareForRequest() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this.refreshIfNeeded();
return {
accessToken: _this.opts.accessToken,
refreshToken: _this.opts.refreshToken,
expiry: _this.latestTokenRefreshExpiry
};
})();
}
refreshIfNeeded() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this2.tokenRefreshPromise) return _this2.tokenRefreshPromise;
if (!_this2.latestTokenRefreshExpiry) return;
if (_this2.latestTokenRefreshExpiry.getTime() - Date.now() <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) yield _this2._handleUnknownToken();
})();
}
/**
* This function is called when an M_UNKNOWN_TOKEN error is encountered.
* It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.
* @param snapshot - the snapshot returned by prepareForRequest
* @param attempt - the number of attempts made for this request so far
* @returns a TokenRefreshOutcome indicating the result of the refresh attempt
*/
handleUnknownToken(snapshot, attempt) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this3._handleUnknownToken(snapshot, attempt);
})();
}
_handleUnknownToken(snapshot, attempt) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (snapshot !== null && snapshot !== void 0 && snapshot.expiry) {
if (snapshot.expiry.getTime() - Date.now() >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) return TokenRefreshOutcome.Logout;
}
if (!snapshot || (snapshot === null || snapshot === void 0 ? void 0 : snapshot.accessToken) === _this4.opts.accessToken) {
var _this4$tokenRefreshPr;
(_this4$tokenRefreshPr = _this4.tokenRefreshPromise) !== null && _this4$tokenRefreshPr !== void 0 || (_this4.tokenRefreshPromise = _this4.doTokenRefresh(attempt));
try {
return yield _this4.tokenRefreshPromise;
} finally {
_this4.tokenRefreshPromise = void 0;
}
}
return TokenRefreshOutcome.Success;
})();
}
/**
* Attempt to refresh access tokens.
* On success, sets new access and refresh tokens in opts.
* @returns Promise that resolves to a boolean - true when token was refreshed successfully
*/
doTokenRefresh(attempt) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this5.opts.refreshToken || !_this5.opts.tokenRefreshFunction) {
var _this5$opts$logger;
(_this5$opts$logger = _this5.opts.logger) === null || _this5$opts$logger === void 0 || _this5$opts$logger.error("Unable to refresh token - no refresh token or refresh function");
return TokenRefreshOutcome.Logout;
}
if (attempt && attempt > 1) yield sleep(1e3 * Math.min(32, 2 ** attempt));
try {
var _this5$opts$logger2, _this5$opts$logger3;
(_this5$opts$logger2 = _this5.opts.logger) === null || _this5$opts$logger2 === void 0 || _this5$opts$logger2.debug("Attempting to refresh token");
var { accessToken, refreshToken, expiry } = yield _this5.opts.tokenRefreshFunction(_this5.opts.refreshToken);
_this5.opts.accessToken = accessToken;
_this5.opts.refreshToken = refreshToken;
_this5.latestTokenRefreshExpiry = expiry;
(_this5$opts$logger3 = _this5.opts.logger) === null || _this5$opts$logger3 === void 0 || _this5$opts$logger3.debug("... token refresh complete, new token expiry:", expiry);
return TokenRefreshOutcome.Success;
} catch (error) {
var _this5$opts$logger5;
if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {
var _this5$opts$logger4;
(_this5$opts$logger4 = _this5.opts.logger) === null || _this5$opts$logger4 === void 0 || _this5$opts$logger4.error("Failed to refresh token", error);
return TokenRefreshOutcome.Logout;
}
(_this5$opts$logger5 = _this5.opts.logger) === null || _this5$opts$logger5 === void 0 || _this5$opts$logger5.warn("Failed to refresh token", error);
return TokenRefreshOutcome.Failure;
}
})();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/fetch.js
/**
* This is an internal module. See {@link MatrixHttpApi} for the public class.
*/
function ownKeys$14(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;
}
function _objectSpread$14(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$14(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$14(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var FetchHttpApi = class {
constructor(eventEmitter, opts) {
var _opts$useAuthorizatio;
this.eventEmitter = eventEmitter;
this.opts = opts;
(0, import_defineProperty.default)(this, "abortController", new AbortController());
(0, import_defineProperty.default)(this, "tokenRefresher", void 0);
checkObjectHasKeys(opts, ["baseUrl", "prefix"]);
if (!opts.onlyData) throw new Error("Constructing FetchHttpApi without `onlyData=true` is no longer supported.");
opts.useAuthorizationHeader = (_opts$useAuthorizatio = opts.useAuthorizationHeader) !== null && _opts$useAuthorizatio !== void 0 ? _opts$useAuthorizatio : true;
this.tokenRefresher = new TokenRefresher(opts);
}
abort() {
this.abortController.abort();
this.abortController = new AbortController();
}
fetch(resource, options) {
if (this.opts.fetchFn) return this.opts.fetchFn(resource, options);
return globalThis.fetch(resource, options);
}
/**
* Sets the base URL for the identity server
* @param url - The new base url
*/
setIdBaseUrl(url) {
this.opts.idBaseUrl = url;
}
idServerRequest(method, path, params, prefix, accessToken) {
if (!this.opts.idBaseUrl) throw new Error("No identity server base URL set");
var queryParams = void 0;
var body = void 0;
if (method === Method.Get) queryParams = params;
else body = params;
var fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);
var opts = {
json: true,
headers: {}
};
if (accessToken) opts.headers.Authorization = "Bearer ".concat(accessToken);
return this.requestOtherUrl(method, fullUri, body, opts);
}
/**
* Perform an authorised request to the homeserver.
* @param method - The HTTP method e.g. "GET".
* @param path - The HTTP path <b>after</b> the supplied prefix e.g.
* "/createRoom".
*
* @param queryParams - A dict of query params (these will NOT be
* urlencoded). If unspecified, there will be no query params.
*
* @param body - The HTTP JSON body.
*
* @param paramOpts - additional options.
* When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted
* when an expired token is encountered. Used to only attempt token refresh once.
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
*/
authedRequest(method, path) {
var queryParams = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
var body = arguments.length > 3 ? arguments[3] : void 0;
var paramOpts = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {};
return this.doAuthedRequest(1, method, path, queryParams, body, paramOpts);
}
doAuthedRequest(attempt, method, path, queryParams, body) {
var _arguments = arguments, _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var paramOpts = _arguments.length > 5 && _arguments[5] !== void 0 ? _arguments[5] : {};
var opts = deepCopy(paramOpts);
opts.abortSignal = paramOpts.abortSignal;
var requestSnapshot = yield _this.tokenRefresher.prepareForRequest();
if (requestSnapshot.accessToken) {
if (_this.opts.useAuthorizationHeader) {
if (!opts.headers) opts.headers = {};
if (!opts.headers.Authorization) opts.headers.Authorization = "Bearer ".concat(requestSnapshot.accessToken);
if (queryParams.access_token) delete queryParams.access_token;
} else if (!queryParams.access_token) queryParams.access_token = requestSnapshot.accessToken;
}
try {
return yield _this.request(method, path, queryParams, body, opts);
} catch (error) {
if (!(error instanceof MatrixError)) throw error;
if (error.errcode === "M_UNKNOWN_TOKEN") {
var outcome = yield _this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);
if (outcome === TokenRefreshOutcome.Success) return _this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);
if (outcome === TokenRefreshOutcome.Failure) throw new TokenRefreshError(error);
if (!(opts !== null && opts !== void 0 && opts.inhibitLogoutEmit)) _this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);
} else if (error.errcode == "M_CONSENT_NOT_GIVEN") _this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);
throw error;
}
})();
}
/**
* Perform a request to the homeserver without any credentials.
* @param method - The HTTP method e.g. "GET".
* @param path - The HTTP path <b>after</b> the supplied prefix e.g.
* "/createRoom".
*
* @param queryParams - A dict of query params (these will NOT be
* urlencoded). If unspecified, there will be no query params.
*
* @param body - The HTTP JSON body.
*
* @param opts - additional options
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
*/
request(method, path, queryParams, body, opts) {
var fullUri = this.getUrl(path, queryParams, opts === null || opts === void 0 ? void 0 : opts.prefix, opts === null || opts === void 0 ? void 0 : opts.baseUrl);
return this.requestOtherUrl(method, fullUri, body, opts);
}
/**
* Perform a request to an arbitrary URL.
* @param method - The HTTP method e.g. "GET".
* @param url - The HTTP URL object.
*
* @param body - The HTTP JSON body.
*
* @param opts - additional options
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
*/
requestOtherUrl(method, url, body) {
var _arguments2 = arguments, _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this2$opts$logger, _opts$localTimeoutMs, _opts$keepAlive, _body$constructor;
var opts = _arguments2.length > 3 && _arguments2[3] !== void 0 ? _arguments2[3] : {};
if (opts.json !== void 0 && opts.rawResponseBody !== void 0) throw new Error("Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`");
var urlForLogs = _this2.sanitizeUrlForLogs(url);
(_this2$opts$logger = _this2.opts.logger) === null || _this2$opts$logger === void 0 || _this2$opts$logger.debug("FetchHttpApi: --> ".concat(method, " ").concat(urlForLogs));
var headers = Object.assign({}, opts.headers || {});
var jsonResponse = !opts.rawResponseBody && opts.json !== false;
if (jsonResponse) {
if (!headers["Accept"]) headers["Accept"] = "application/json";
}
var timeout = (_opts$localTimeoutMs = opts.localTimeoutMs) !== null && _opts$localTimeoutMs !== void 0 ? _opts$localTimeoutMs : _this2.opts.localTimeoutMs;
var keepAlive = (_opts$keepAlive = opts.keepAlive) !== null && _opts$keepAlive !== void 0 ? _opts$keepAlive : false;
var signals = [_this2.abortController.signal];
if (timeout !== void 0) signals.push(timeoutSignal(timeout));
if (opts.abortSignal) signals.push(opts.abortSignal);
var data;
if (opts.json !== false && (body === null || body === void 0 || (_body$constructor = body.constructor) === null || _body$constructor === void 0 ? void 0 : _body$constructor.name) === Object.name) {
data = JSON.stringify(body);
if (!headers["Content-Type"]) headers["Content-Type"] = "application/json";
} else data = body;
var { signal, cleanup } = anySignal(signals);
var cacheMode = "Authorization" in headers ? void 0 : "no-cache";
var res;
var start = Date.now();
try {
var _this2$opts$logger2;
res = yield _this2.fetch(url, {
signal,
method,
body: data,
headers,
mode: "cors",
redirect: "follow",
referrer: "",
referrerPolicy: "no-referrer",
cache: cacheMode,
credentials: "omit",
keepalive: keepAlive,
priority: opts.priority
});
(_this2$opts$logger2 = _this2.opts.logger) === null || _this2$opts$logger2 === void 0 || _this2$opts$logger2.debug("FetchHttpApi: <-- ".concat(method, " ").concat(urlForLogs, " [").concat(Date.now() - start, "ms ").concat(res.status, "]"));
} catch (e) {
var _this2$opts$logger3;
(_this2$opts$logger3 = _this2.opts.logger) === null || _this2$opts$logger3 === void 0 || _this2$opts$logger3.debug("FetchHttpApi: <-- ".concat(method, " ").concat(urlForLogs, " [").concat(Date.now() - start, "ms ").concat(e, "]"));
if (e.name === "AbortError") throw e;
throw new ConnectionError("fetch failed", e);
} finally {
cleanup();
}
if (!res.ok) throw parseErrorResponse(res, yield res.text());
if (opts.rawResponseBody) return yield res.blob();
else if (jsonResponse) return yield res.json();
else return yield res.text();
})();
}
sanitizeUrlForLogs(url) {
try {
var asUrl;
if (typeof url === "string") asUrl = new URL(url);
else asUrl = url;
var sanitizedQs = new URLSearchParams();
for (var key of asUrl.searchParams.keys()) sanitizedQs.append(key, "xxx");
var sanitizedQsString = sanitizedQs.toString();
var sanitizedQsUrlPiece = sanitizedQsString ? "?".concat(sanitizedQsString) : "";
return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;
} catch (_unused) {
return "??";
}
}
/**
* Form and return a homeserver request URL based on the given path params and prefix.
* @param path - The HTTP path <b>after</b> the supplied prefix e.g. "/createRoom".
* @param queryParams - A dict of query params (these will NOT be urlencoded).
* @param prefix - The full prefix to use e.g. "/_matrix/client/v2_alpha", defaulting to this.opts.prefix.
* @param baseUrl - The baseUrl to use e.g. "https://matrix.org", defaulting to this.opts.baseUrl.
* @returns URL
*/
getUrl(path, queryParams, prefix, baseUrl) {
var baseUrlWithFallback = baseUrl !== null && baseUrl !== void 0 ? baseUrl : this.opts.baseUrl;
var baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith("/") ? baseUrlWithFallback.slice(0, -1) : baseUrlWithFallback;
var url = new URL(baseUrlWithoutTrailingSlash + (prefix !== null && prefix !== void 0 ? prefix : this.opts.prefix) + path);
if (this.opts.extraParams || queryParams) encodeParams(_objectSpread$14(_objectSpread$14({}, this.opts.extraParams), queryParams), url.searchParams);
return url;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/prefix.js
var ClientPrefix = /* @__PURE__ */ function(ClientPrefix) {
/**
* A constant representing the URI path for Client-Server API endpoints versioned at v1.
*/
ClientPrefix["V1"] = "/_matrix/client/v1";
/**
* A constant representing the URI path for Client-Server API endpoints versioned at v3.
*/
ClientPrefix["V3"] = "/_matrix/client/v3";
/**
* A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.
*/
ClientPrefix["Unstable"] = "/_matrix/client/unstable";
return ClientPrefix;
}({});
var IdentityPrefix = /* @__PURE__ */ function(IdentityPrefix) {
/**
* URI path for the v2 identity API
*/
IdentityPrefix["V2"] = "/_matrix/identity/v2";
return IdentityPrefix;
}({});
var MediaPrefix = /* @__PURE__ */ function(MediaPrefix) {
/**
* A constant representing the URI path for Client-Server API Media endpoints versioned at v1.
*/
MediaPrefix["V1"] = "/_matrix/media/v1";
/**
* A constant representing the URI path for Client-Server API Media endpoints versioned at v3.
*/
MediaPrefix["V3"] = "/_matrix/media/v3";
return MediaPrefix;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/realtime-callbacks.js
var TIMER_CHECK_PERIOD_MS = 1e3;
var count = 0;
var realCallbackKey;
var callbackList = [];
/* istanbul ignore next */
var debuglog$1 = function debuglog() {};
/**
* reimplementation of window.setTimeout, which will call the callback if
* the wallclock time goes past the deadline.
*
* @param func - callback to be called after a delay
* @param delayMs - number of milliseconds to delay by
*
* @returns an identifier for this callback, which may be passed into
* clearTimeout later.
*/
function setTimeout$1(func, delayMs) {
for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) params[_key - 2] = arguments[_key];
delayMs = delayMs || 0;
if (delayMs < 0) delayMs = 0;
var runAt = Date.now() + delayMs;
var key = count++;
debuglog$1("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")");
var data = {
runAt,
func,
params,
key
};
var idx = binarySearch(callbackList, function(el) {
return el.runAt - runAt;
});
callbackList.splice(idx, 0, data);
scheduleRealCallback();
return key;
}
/**
* reimplementation of window.clearTimeout, which mirrors setTimeout
*
* @param key - result from an earlier setTimeout call
*/
function clearTimeout$1(key) {
if (callbackList.length === 0) return;
var i;
for (i = 0; i < callbackList.length; i++) if (callbackList[i].key == key) {
callbackList.splice(i, 1);
break;
}
if (i === 0) scheduleRealCallback();
}
function scheduleRealCallback() {
if (realCallbackKey) globalThis.clearTimeout(realCallbackKey);
var first = callbackList[0];
if (!first) {
debuglog$1("scheduleRealCallback: no more callbacks, not rescheduling");
return;
}
var timestamp = Date.now();
var delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);
debuglog$1("scheduleRealCallback: now:", timestamp, "delay:", delayMs);
realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);
}
function runCallbacks() {
var timestamp = Date.now();
debuglog$1("runCallbacks: now:", timestamp);
var callbacksToRun = [];
while (true) {
var first = callbackList[0];
if (!first || first.runAt > timestamp) break;
var cb = callbackList.shift();
debuglog$1("runCallbacks: popping", cb.key);
callbacksToRun.push(cb);
}
scheduleRealCallback();
for (var _cb of callbacksToRun) try {
_cb.func.apply(globalThis, _cb.params);
} catch (e) {
logger$2.error("Uncaught exception in callback function", e);
}
}
function binarySearch(array, func) {
var min = 0;
var max = array.length;
while (min < max) {
var mid = min + max >> 1;
if (func(array[mid]) > 0) max = mid;
else min = mid + 1;
}
return min;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/http-api/index.js
var MatrixHttpApi = class extends FetchHttpApi {
constructor() {
super(...arguments);
(0, import_defineProperty.default)(this, "uploads", []);
}
/**
* Upload content to the homeserver
*
* @param file - The object to upload. On a browser, something that
* can be sent to XMLHttpRequest.send (typically a File). Under node.js,
* a Buffer, String or ReadStream.
*
* @param opts - options object
*
* @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
uploadContent(file) {
var _opts$includeFilename, _opts$abortController, _opts$type, _opts$name;
var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var includeFilename = (_opts$includeFilename = opts.includeFilename) !== null && _opts$includeFilename !== void 0 ? _opts$includeFilename : true;
var abortController = (_opts$abortController = opts.abortController) !== null && _opts$abortController !== void 0 ? _opts$abortController : new AbortController();
var contentType = ((_opts$type = opts.type) !== null && _opts$type !== void 0 ? _opts$type : file.type) || "application/octet-stream";
var fileName = (_opts$name = opts.name) !== null && _opts$name !== void 0 ? _opts$name : file.name;
var upload = {
loaded: 0,
total: 0,
abortController
};
var uploadResolvers = Promise.withResolvers();
if (globalThis.XMLHttpRequest) {
var xhr = new globalThis.XMLHttpRequest();
var timeoutFn = function timeoutFn() {
xhr.abort();
uploadResolvers.reject(/* @__PURE__ */ new Error("Timeout"));
};
var timeoutTimer = setTimeout$1(timeoutFn, 3e4);
xhr.onreadystatechange = function() {
switch (xhr.readyState) {
case globalThis.XMLHttpRequest.DONE:
clearTimeout$1(timeoutTimer);
try {
if (xhr.status === 0) throw new DOMException(xhr.statusText, "AbortError");
if (!xhr.responseText) throw new Error("No response body.");
if (xhr.status >= 400) uploadResolvers.reject(parseErrorResponse(xhr, xhr.responseText));
else uploadResolvers.resolve(JSON.parse(xhr.responseText));
} catch (err) {
if (err.name === "AbortError") {
uploadResolvers.reject(err);
return;
}
uploadResolvers.reject(new ConnectionError("request failed", err));
}
break;
}
};
xhr.upload.onprogress = (ev) => {
var _opts$progressHandler;
clearTimeout$1(timeoutTimer);
upload.loaded = ev.loaded;
upload.total = ev.total;
timeoutTimer = setTimeout$1(timeoutFn, 3e4);
(_opts$progressHandler = opts.progressHandler) === null || _opts$progressHandler === void 0 || _opts$progressHandler.call(opts, {
loaded: ev.loaded,
total: ev.total
});
};
var url = this.getUrl("/upload", void 0, MediaPrefix.V3);
if (includeFilename && fileName) url.searchParams.set("filename", encodeURIComponent(fileName));
if (!this.opts.useAuthorizationHeader && this.opts.accessToken) url.searchParams.set("access_token", encodeURIComponent(this.opts.accessToken));
xhr.open(Method.Post, url.href);
if (this.opts.useAuthorizationHeader && this.opts.accessToken) xhr.setRequestHeader("Authorization", "Bearer " + this.opts.accessToken);
xhr.setRequestHeader("Content-Type", contentType);
xhr.send(file);
abortController.signal.addEventListener("abort", () => {
xhr.abort();
});
} else {
var queryParams = {};
if (includeFilename && fileName) queryParams.filename = fileName;
var headers = { "Content-Type": contentType };
this.authedRequest(Method.Post, "/upload", queryParams, file, {
prefix: MediaPrefix.V3,
headers,
abortSignal: abortController.signal
}).then(uploadResolvers.resolve, uploadResolvers.reject);
}
upload.promise = uploadResolvers.promise.finally(() => {
removeElement(this.uploads, (elem) => elem === upload);
});
abortController.signal.addEventListener("abort", () => {
removeElement(this.uploads, (elem) => elem === upload);
uploadResolvers.reject(new DOMException("Aborted", "AbortError"));
});
this.uploads.push(upload);
return upload.promise;
}
cancelUpload(promise) {
var upload = this.uploads.find((u) => u.promise === promise);
if (upload) {
upload.abortController.abort();
return true;
}
return false;
}
getCurrentUploads() {
return this.uploads;
}
/**
* Get the content repository url with query parameters.
* @returns An object with a 'base', 'path' and 'params' for base URL,
* path and query parameters respectively.
*/
getContentUri() {
return {
base: this.opts.baseUrl,
path: MediaPrefix.V3 + "/upload",
params: { access_token: this.opts.accessToken }
};
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/serverCapabilities.js
var CAPABILITIES_CACHE_MS = 360 * 60 * 1e3;
var CAPABILITIES_RETRY_MS = 30 * 1e3;
var RoomVersionStability = /* @__PURE__ */ function(RoomVersionStability) {
RoomVersionStability["Stable"] = "stable";
RoomVersionStability["Unstable"] = "unstable";
return RoomVersionStability;
}({});
/**
* A representation of the capabilities advertised by a homeserver as defined by
* [Capabilities negotiation](https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3capabilities).
*/
/**
* Manages storing and periodically refreshing the server capabilities.
*/
var ServerCapabilities = class {
constructor(logger, http) {
var _this = this;
this.logger = logger;
this.http = http;
(0, import_defineProperty.default)(this, "capabilities", void 0);
(0, import_defineProperty.default)(this, "retryTimeout", void 0);
(0, import_defineProperty.default)(this, "refreshTimeout", void 0);
/**
* Fetches the latest server capabilities from the homeserver and returns them, or rejects
* on failure.
*/
(0, import_defineProperty.default)(this, "fetchCapabilities", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
_this.capabilities = (yield _this.http.authedRequest(Method.Get, "/capabilities"))["capabilities"];
return _this.capabilities;
}));
(0, import_defineProperty.default)(this, "poll", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
try {
yield _this.fetchCapabilities();
_this.clearTimeouts();
_this.refreshTimeout = setTimeout(_this.poll, CAPABILITIES_CACHE_MS);
_this.logger.debug("Fetched new server capabilities");
} catch (e) {
_this.clearTimeouts();
var howLong = Math.floor(CAPABILITIES_RETRY_MS + Math.random() * 5e3);
_this.retryTimeout = setTimeout(_this.poll, howLong);
_this.logger.warn("Failed to refresh capabilities: retrying in ".concat(howLong, "ms"), e);
}
}));
}
/**
* Starts periodically fetching the server capabilities.
*/
start() {
this.poll().then();
}
/**
* Stops the service
*/
stop() {
this.clearTimeouts();
}
/**
* Returns the cached capabilities, or undefined if none are cached.
* @returns the current capabilities, if any.
*/
getCachedCapabilities() {
return this.capabilities;
}
clearTimeouts() {
if (this.refreshTimeout) {
clearInterval(this.refreshTimeout);
this.refreshTimeout = void 0;
}
if (this.retryTimeout) {
clearTimeout(this.retryTimeout);
this.retryTimeout = void 0;
}
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room-sticky-events.js
var logger$1 = logger$2.getChild("RoomStickyEvents");
var RoomStickyEventsEvent = /* @__PURE__ */ function(RoomStickyEventsEvent) {
RoomStickyEventsEvent["Update"] = "RoomStickyEvents.Update";
return RoomStickyEventsEvent;
}({});
function assertIsUserId(value) {
if (typeof value !== "string") throw new Error("Not a string");
if (!value.startsWith("@")) throw new Error("Not a userId");
}
/**
* Tracks sticky events on behalf of one room, and fires an event
* whenever a sticky event is updated or replaced.
*/
var RoomStickyEventsStore = class RoomStickyEventsStore extends TypedEventEmitter {
constructor() {
super(...arguments);
/**
* Sticky event map is a nested map of:
* eventType -> `content.sticky_key sender` -> StickyMatrixEvent[]
*
* The events are ordered in latest to earliest expiry, so that the first event
* in the array will always be the "current" one.
*/
(0, import_defineProperty.default)(this, "stickyEventsMap", /* @__PURE__ */ new Map());
/**
* These are sticky events that have no sticky key and therefore exist outside the tuple
* system above. They are just held in this Set until they expire.
*/
(0, import_defineProperty.default)(this, "unkeyedStickyEvents", /* @__PURE__ */ new Set());
(0, import_defineProperty.default)(this, "stickyEventTimer", void 0);
(0, import_defineProperty.default)(this, "nextStickyEventExpiryTs", Number.MAX_SAFE_INTEGER);
/**
* Clean out any expired sticky events.
*/
(0, import_defineProperty.default)(this, "cleanExpiredStickyEvents", () => {
var now = Date.now();
var removedEvents = [];
this.nextStickyEventExpiryTs = Number.MAX_SAFE_INTEGER;
for (var [eventType, innerEvents] of this.stickyEventsMap.entries()) {
var _this$stickyEventsMap;
for (var [innerMapKey, [currentEvent, ...previousEvents]] of innerEvents) if (now >= currentEvent.unstableStickyExpiresAt) {
logger$1.debug("Expiring sticky event", currentEvent.getId());
removedEvents.push(currentEvent);
this.stickyEventsMap.get(eventType).delete(innerMapKey);
} else {
this.stickyEventsMap.get(eventType).set(innerMapKey, [currentEvent, ...previousEvents.filter((e) => e.unstableStickyExpiresAt <= now)]);
this.nextStickyEventExpiryTs = Math.min(this.nextStickyEventExpiryTs, currentEvent.unstableStickyExpiresAt);
}
if (((_this$stickyEventsMap = this.stickyEventsMap.get(eventType)) === null || _this$stickyEventsMap === void 0 ? void 0 : _this$stickyEventsMap.size) === 0) this.stickyEventsMap.delete(eventType);
}
for (var event of this.unkeyedStickyEvents) if (now >= event.unstableStickyExpiresAt) {
logger$1.debug("Expiring sticky event", event.getId());
this.unkeyedStickyEvents.delete(event);
removedEvents.push(event);
} else this.nextStickyEventExpiryTs = Math.min(this.nextStickyEventExpiryTs, event.unstableStickyExpiresAt);
if (removedEvents.length) this.emit(RoomStickyEventsEvent.Update, [], [], removedEvents);
this.scheduleStickyTimer();
});
}
/**
* Sort two sticky events by order of expiry. This assumes the sticky events have the same
* `type`, `sticky_key` and `sender`.
* @returns A positive value if event A will expire sooner, or a negative value if event B will expire sooner.
*/
static sortStickyEvent(eventA, eventB) {
var _eventB$getId, _eventA$getId;
if (eventB.getTs() !== eventA.getTs()) return eventB.getTs() - eventA.getTs();
if (((_eventB$getId = eventB.getId()) !== null && _eventB$getId !== void 0 ? _eventB$getId : "") > ((_eventA$getId = eventA.getId()) !== null && _eventA$getId !== void 0 ? _eventA$getId : "")) return 1;
throw Error("Comparing two sticky events with the same event ID is not allowed.");
}
/**
* Generate the correct key for an event to be found in the inner maps of `stickyEventsMap`.
* @param stickyKey The sticky key of an event.
* @param sender The sender of the event.
*/
static stickyMapKey(stickyKey, sender) {
return "".concat(stickyKey).concat(sender);
}
/**
* Get all sticky events that are currently active.
* @returns An iterable set of events.
*/
*getStickyEvents() {
yield* this.unkeyedStickyEvents;
for (var innerMap of this.stickyEventsMap.values()) for (var events of innerMap.values()) yield events[0];
}
/**
* Get an active sticky event that match the given `type`, `sender`, and `stickyKey`
* @param type The event `type`.
* @param sender The sender of the sticky event.
* @param stickyKey The sticky key used by the event.
* @returns A matching active sticky event, or undefined.
*/
getKeyedStickyEvent(sender, type, stickyKey) {
var _this$stickyEventsMap2;
assertIsUserId(sender);
return (_this$stickyEventsMap2 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap2 === void 0 || (_this$stickyEventsMap2 = _this$stickyEventsMap2.get(RoomStickyEventsStore.stickyMapKey(stickyKey, sender))) === null || _this$stickyEventsMap2 === void 0 ? void 0 : _this$stickyEventsMap2[0];
}
/**
* Get active sticky events without a sticky key that match the given `type` and `sender`.
* @param type The event `type`.
* @param sender The sender of the sticky event.
* @returns An array of matching sticky events.
*/
getUnkeyedStickyEvent(sender, type) {
return [...this.unkeyedStickyEvents].filter((ev) => ev.getType() === type && ev.getSender() === sender);
}
/**
* Adds a sticky event into the local sticky event map.
*
* NOTE: This will not cause `RoomEvent.StickyEvents` to be emitted.
*
* @throws If the `event` does not contain valid sticky data.
* @param event The MatrixEvent that contains sticky data.
* @returns An object describing whether the event was added to the map,
* and the previous event it may have replaced.
*/
addStickyEvent(event) {
var _this$stickyEventsMap3, _this$stickyEventsMap4, _this$stickyEventsMap5;
var stickyKey = event.getContent().msc4354_sticky_key;
if (typeof stickyKey !== "string" && stickyKey !== void 0) throw new Error("".concat(event.getId(), " is missing msc4354_sticky_key"));
if (event.unstableStickyExpiresAt === void 0) throw new Error("".concat(event.getId(), " is missing msc4354_sticky.duration_ms"));
var sender = event.getSender();
var type = event.getType();
assertIsUserId(sender);
if (event.unstableStickyExpiresAt <= Date.now()) {
logger$1.info("ignored sticky event with older expiration time than current time", stickyKey);
return { added: false };
}
if (!sender.startsWith("@")) throw new Error("Expected sender to start with @");
var stickyEvent = event;
if (stickyKey === void 0) {
this.unkeyedStickyEvents.add(stickyEvent);
this.nextStickyEventExpiryTs = Math.min(event.unstableStickyExpiresAt, this.nextStickyEventExpiryTs);
this.scheduleStickyTimer();
return { added: true };
}
var innerMapKey = RoomStickyEventsStore.stickyMapKey(stickyKey, sender);
var currentEventSet = [stickyEvent, ...(_this$stickyEventsMap3 = (_this$stickyEventsMap4 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap4 === void 0 ? void 0 : _this$stickyEventsMap4.get(innerMapKey)) !== null && _this$stickyEventsMap3 !== void 0 ? _this$stickyEventsMap3 : []].sort(RoomStickyEventsStore.sortStickyEvent);
if (!this.stickyEventsMap.has(type)) this.stickyEventsMap.set(type, /* @__PURE__ */ new Map());
(_this$stickyEventsMap5 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap5 === void 0 || _this$stickyEventsMap5.set(innerMapKey, currentEventSet);
this.nextStickyEventExpiryTs = Math.min(stickyEvent.unstableStickyExpiresAt, this.nextStickyEventExpiryTs);
this.scheduleStickyTimer();
return {
added: currentEventSet[0] === stickyEvent,
prevEvent: currentEventSet === null || currentEventSet === void 0 ? void 0 : currentEventSet[1]
};
}
/**
* Add a series of sticky events, emitting `RoomEvent.StickyEvents` if any
* changes were made.
* @param events A set of new sticky events.
*/
addStickyEvents(events) {
var added = [];
var updated = [];
for (var event of events) try {
var result = this.addStickyEvent(event);
if (result.added) if (result.prevEvent) updated.push({
current: event,
previous: result.prevEvent
});
else added.push(event);
} catch (ex) {
logger$1.warn("ignored invalid sticky event", ex);
}
if (added.length || updated.length) this.emit(RoomStickyEventsEvent.Update, added, updated, []);
this.scheduleStickyTimer();
}
/**
* Schedule the sticky event expiry timer. The timer will
* run immediately if an event has already expired.
*/
scheduleStickyTimer() {
if (this.stickyEventTimer) {
clearTimeout(this.stickyEventTimer);
this.stickyEventTimer = void 0;
}
if (this.nextStickyEventExpiryTs === Number.MAX_SAFE_INTEGER) return;
this.stickyEventTimer = setTimeout(this.cleanExpiredStickyEvents, this.nextStickyEventExpiryTs - Date.now());
}
/**
* Handles incoming event redactions. Checks the sticky map
* for any active sticky events being redacted.
* @param redactedEvent The MatrixEvent OR event ID of the event being redacted. MAY not be a sticky event.
*/
handleRedaction(redactedEvent) {
var redactEventId = typeof redactedEvent === "string" ? redactedEvent : redactedEvent.getId();
for (var event of this.unkeyedStickyEvents) if (event.getId() === redactEventId) {
this.unkeyedStickyEvents.delete(event);
this.emit(RoomStickyEventsEvent.Update, [], [], [event]);
return;
}
if (typeof redactedEvent !== "string" && !redactedEvent.isRedacted()) {
var _innerMap$get, _this$stickyEventsMap6;
var stickyKey = redactedEvent.getContent().msc4354_sticky_key;
if (typeof stickyKey !== "string" && stickyKey !== void 0) return;
var eventType = redactedEvent.getType();
var sender = redactedEvent.getSender();
assertIsUserId(sender);
var innerMap = this.stickyEventsMap.get(eventType);
if (!innerMap) return;
var mapKey = RoomStickyEventsStore.stickyMapKey(stickyKey, sender);
var [currentEvent, ...previousEvents] = (_innerMap$get = innerMap.get(mapKey)) !== null && _innerMap$get !== void 0 ? _innerMap$get : [];
if (!currentEvent) return;
logger$1.debug("Redaction for ".concat(redactEventId, " under sticky key ").concat(stickyKey));
var newEvents = previousEvents.filter((e) => !e.isRedacted()).sort(RoomStickyEventsStore.sortStickyEvent);
(_this$stickyEventsMap6 = this.stickyEventsMap.get(eventType)) === null || _this$stickyEventsMap6 === void 0 || _this$stickyEventsMap6.set(mapKey, newEvents);
if (newEvents.length) this.emit(RoomStickyEventsEvent.Update, [], [{
previous: currentEvent,
current: newEvents[0]
}], []);
else {
innerMap.delete(mapKey);
if (innerMap.size === 0) this.stickyEventsMap.delete(eventType);
this.emit(RoomStickyEventsEvent.Update, [], [], [currentEvent]);
}
return;
}
for (var _innerMap of this.stickyEventsMap.values()) for (var [_currentEvent] of _innerMap.values()) {
if (_currentEvent.getId() !== redactEventId) continue;
return this.handleRedaction(_currentEvent);
}
}
/**
* Clear all events and stop the timer from firing.
*/
clear() {
this.stickyEventsMap.clear();
this.nextStickyEventExpiryTs = Number.MAX_SAFE_INTEGER;
this.scheduleStickyTimer();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room.js
function ownKeys$13(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;
}
function _objectSpread$13(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$13(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$13(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var SAFE_ROOM_VERSIONS = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
];
var MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;
var NotificationCountType = /* @__PURE__ */ function(NotificationCountType) {
NotificationCountType["Highlight"] = "highlight";
NotificationCountType["Total"] = "total";
return NotificationCountType;
}({});
var RoomEvent = /* @__PURE__ */ function(RoomEvent) {
RoomEvent["MyMembership"] = "Room.myMembership";
RoomEvent["Tags"] = "Room.tags";
RoomEvent["AccountData"] = "Room.accountData";
RoomEvent["Receipt"] = "Room.receipt";
RoomEvent["Name"] = "Room.name";
RoomEvent["Redaction"] = "Room.redaction";
RoomEvent["RedactionCancelled"] = "Room.redactionCancelled";
RoomEvent["LocalEchoUpdated"] = "Room.localEchoUpdated";
RoomEvent["Timeline"] = "Room.timeline";
RoomEvent["TimelineReset"] = "Room.timelineReset";
RoomEvent["TimelineRefresh"] = "Room.TimelineRefresh";
RoomEvent["OldStateUpdated"] = "Room.OldStateUpdated";
RoomEvent["CurrentStateUpdated"] = "Room.CurrentStateUpdated";
RoomEvent["HistoryImportedWithinTimeline"] = "Room.historyImportedWithinTimeline";
RoomEvent["UnreadNotifications"] = "Room.UnreadNotifications";
RoomEvent["Summary"] = "Room.Summary";
return RoomEvent;
}({});
var Room = class extends ReadReceipt {
/**
* Construct a new Room.
*
* <p>For a room, we store an ordered sequence of timelines, which may or may not
* be continuous. Each timeline lists a series of events, as well as tracking
* the room state at the start and the end of the timeline. It also tracks
* forward and backward pagination tokens, as well as containing links to the
* next timeline in the sequence.
*
* <p>There is one special timeline - the 'live' timeline, which represents the
* timeline to which events are being added in real-time as they are received
* from the /sync API. Note that you should not retain references to this
* timeline - even if it is the current timeline right now, it may not remain
* so if the server gives us a timeline gap in /sync.
*
* <p>In order that we can find events from their ids later, we also maintain a
* map from event_id to timeline and index.
*
* @param roomId - Required. The ID of this room.
* @param client - Required. The client, used to lazy load members.
* @param myUserId - Required. The ID of the syncing user.
* @param opts - Configuration options
*/
constructor(roomId, client, myUserId) {
var _this;
var opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
super();
_this = this;
this.roomId = roomId;
this.client = client;
this.myUserId = myUserId;
this.opts = opts;
(0, import_defineProperty.default)(this, "reEmitter", void 0);
(0, import_defineProperty.default)(this, "txnToEvent", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "notificationCounts", {});
(0, import_defineProperty.default)(this, "bumpStamp", void 0);
(0, import_defineProperty.default)(this, "threadNotifications", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "cachedThreadReadReceipts", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "oldestThreadedReceiptTs", Infinity);
/**
* A record of the latest unthread receipts per user
* This is useful in determining whether a user has read a thread or not
*/
(0, import_defineProperty.default)(this, "unthreadedReceipts", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "timelineSets", void 0);
(0, import_defineProperty.default)(this, "polls", /* @__PURE__ */ new Map());
/**
* Empty array if the timeline sets have not been initialised. After initialisation:
* 0: All threads
* 1: Threads the current user has participated in
*/
(0, import_defineProperty.default)(this, "threadsTimelineSets", []);
(0, import_defineProperty.default)(this, "filteredTimelineSets", {});
(0, import_defineProperty.default)(this, "timelineNeedsRefresh", false);
(0, import_defineProperty.default)(this, "pendingEventList", void 0);
(0, import_defineProperty.default)(this, "blacklistUnverifiedDevices", void 0);
(0, import_defineProperty.default)(this, "selfMembership", void 0);
/**
* A `Hero` is a stripped `m.room.member` event which contains the important renderable fields from the event.
*
* It is used in MSC4186 (Simplified Sliding Sync) as a replacement for the old `summary` field.
*
* When we are doing old-style (`/v3/sync`) sync, we simulate the SSS behaviour by constructing
* a `Hero` object based on the user id we get from the summary. Obviously, in that case,
* the `Hero` will lack a `displayName` or `avatarUrl`.
*/
(0, import_defineProperty.default)(this, "heroes", null);
(0, import_defineProperty.default)(this, "getTypeWarning", false);
(0, import_defineProperty.default)(this, "membersPromise", void 0);
/**
* The human-readable display name for this room.
*/
(0, import_defineProperty.default)(this, "name", void 0);
/**
* The un-homoglyphed name for this room.
*/
(0, import_defineProperty.default)(this, "normalizedName", void 0);
/**
* Dict of room tags; the keys are the tag name and the values
* are any metadata associated with the tag - e.g. `{ "fav" : { order: 1 } }`
*/
(0, import_defineProperty.default)(this, "tags", {});
/**
* accountData Dict of per-room account_data events; the keys are the
* event type and the values are the events.
*/
(0, import_defineProperty.default)(this, "accountData", /* @__PURE__ */ new Map());
/**
* The room summary.
*/
(0, import_defineProperty.default)(this, "summary", null);
/**
* oldState The state of the room at the time of the oldest event in the live timeline.
*
* @deprecated Present for backwards compatibility.
* Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead
*/
(0, import_defineProperty.default)(this, "oldState", void 0);
/**
* currentState The state of the room at the time of the newest event in the timeline.
*
* @deprecated Present for backwards compatibility.
* Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.
*/
(0, import_defineProperty.default)(this, "currentState", void 0);
(0, import_defineProperty.default)(this, "relations", void 0);
/**
* A collection of events known by the client
* This is not a comprehensive list of the threads that exist in this room
*/
(0, import_defineProperty.default)(this, "threads", /* @__PURE__ */ new Map());
/**
* A mapping of eventId to all visibility changes to apply
* to the event, by chronological order, as per
* https://github.com/matrix-org/matrix-doc/pull/3531
*
* # Invariants
*
* - within each list, all events are classed by
* chronological order;
* - all events are events such that
* `asVisibilityEvent()` returns a non-null `IVisibilityChange`;
* - within each list with key `eventId`, all events
* are in relation to `eventId`.
*
* @experimental
*/
(0, import_defineProperty.default)(this, "visibilityEvents", /* @__PURE__ */ new Map());
/**
* The latest receipts (synthetic and real) for each user in each thread
* (and unthreaded).
*/
(0, import_defineProperty.default)(this, "roomReceipts", new RoomReceipts(this));
/**
* Stores and tracks sticky events
*/
(0, import_defineProperty.default)(this, "stickyEvents", new RoomStickyEventsStore());
(0, import_defineProperty.default)(this, "threadTimelineSetsPromise", null);
(0, import_defineProperty.default)(this, "threadsReady", false);
(0, import_defineProperty.default)(this, "updateThreadRootEvents", (thread, toStartOfTimeline, recreateEvent) => {
if (thread.length) {
var _this$threadsTimeline;
this.updateThreadRootEvent((_this$threadsTimeline = this.threadsTimelineSets) === null || _this$threadsTimeline === void 0 ? void 0 : _this$threadsTimeline[0], thread, toStartOfTimeline, recreateEvent);
if (thread.hasCurrentUserParticipated) {
var _this$threadsTimeline2;
this.updateThreadRootEvent((_this$threadsTimeline2 = this.threadsTimelineSets) === null || _this$threadsTimeline2 === void 0 ? void 0 : _this$threadsTimeline2[1], thread, toStartOfTimeline, recreateEvent);
}
}
});
(0, import_defineProperty.default)(this, "updateThreadRootEvent", (timelineSet, thread, toStartOfTimeline, recreateEvent) => {
if (timelineSet && thread.rootEvent) {
if (recreateEvent) timelineSet.removeEvent(thread.id);
if (Thread.hasServerSideSupport) timelineSet.addLiveEvent(thread.rootEvent, {
duplicateStrategy: DuplicateStrategy.Replace,
fromCache: false,
roomState: this.currentState,
addToState: false
});
else timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), {
toStartOfTimeline,
addToState: false
});
}
});
(0, import_defineProperty.default)(this, "tryApplyRedaction", (event) => {
if (event.isRedaction()) {
var redactId = event.event.redacts;
var redactedEvent = redactId ? this.findEventById(redactId) : void 0;
if (redactId) try {
this.stickyEvents.handleRedaction(redactedEvent || redactId);
} catch (ex) {
logger$2.error("Failed to handle redaction for sticky event", ex);
}
if (redactedEvent) this.applyEventAsRedaction(event, redactedEvent);
} else if (event.getType() === EventType.RoomMember) {
var membership = event.getContent()["membership"];
if (membership !== KnownMembership.Ban && !(membership === KnownMembership.Leave && event.getStateKey() !== event.getSender())) return;
if (event.getContent()["org.matrix.msc4293.redact_events"] !== true) return;
if (!this.getLiveTimeline().getState(Direction.Forward).maySendRedactionForEvent(event, event.getSender())) return;
for (var toRedact of this.getTimelineSets().map((s) => s.getTimelines()).reduce((p, c) => {
p.push(...c);
return p;
}, []).map((t) => t.getEvents().filter((e) => e.getSender() === event.getStateKey())).reduce((p, c) => {
p.push(...c);
return c;
}, [])) this.applyEventAsRedaction(event, toRedact);
}
});
this.setMaxListeners(100);
this.reEmitter = new TypedReEmitter(this);
opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;
this.name = roomId;
this.normalizedName = roomId;
this.relations = new RelationsContainer(this.client, this);
this.on(RoomEvent.Receipt, this.onReceipt);
this.reEmitter.reEmit(this.stickyEvents, [RoomStickyEventsEvent.Update]);
this.timelineSets = [new EventTimelineSet(this, opts)];
this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);
this.fixUpLegacyTimelineFields();
if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {
this.pendingEventList = [];
this.client.store.getPendingEvents(this.roomId).then((events) => {
var mapper = this.client.getEventMapper({ decrypt: false });
events.forEach(/* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (serializedEvent) {
var event = mapper(serializedEvent);
yield client.decryptEventIfNeeded(event);
event.setStatus(EventStatus.NOT_SENT);
_this.addPendingEvent(event, event.getTxnId());
});
return function(_x) {
return _ref.apply(this, arguments);
};
}());
});
}
if (!this.opts.lazyLoadMembers) this.membersPromise = Promise.resolve(false);
else this.membersPromise = void 0;
}
createThreadsTimelineSets() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this2$client;
if (_this2.threadTimelineSetsPromise) return _this2.threadTimelineSetsPromise;
if ((_this2$client = _this2.client) !== null && _this2$client !== void 0 && _this2$client.supportsThreads()) try {
_this2.threadTimelineSetsPromise = Promise.all([_this2.createThreadTimelineSet(), _this2.createThreadTimelineSet(ThreadFilterType.My)]);
var timelineSets = yield _this2.threadTimelineSetsPromise;
_this2.threadsTimelineSets[0] = timelineSets[0];
_this2.threadsTimelineSets[1] = timelineSets[1];
return timelineSets;
} catch (_unused) {
_this2.threadTimelineSetsPromise = null;
return null;
}
return null;
})();
}
/**
* Bulk decrypt critical events in a room
*
* Critical events represents the minimal set of events to decrypt
* for a typical UI to function properly
*
* - Last event of every room (to generate likely message preview)
* - All events up to the read receipt (to calculate an accurate notification count)
*
* @returns Signals when all events have been decrypted
*/
decryptCriticalEvents() {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this3.client.getCrypto()) return;
var readReceiptEventId = _this3.getEventReadUpTo(_this3.client.getUserId(), true);
var events = _this3.getLiveTimeline().getEvents();
var readReceiptTimelineIndex = events.findIndex((matrixEvent) => {
return matrixEvent.event.event_id === readReceiptEventId;
});
var decryptionPromises = events.slice(readReceiptTimelineIndex).reverse().map((event) => _this3.client.decryptEventIfNeeded(event));
yield Promise.allSettled(decryptionPromises);
})();
}
/**
* Bulk decrypt events in a room
*
* @returns Signals when all events have been decrypted
*/
decryptAllEvents() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this4.client.getCrypto()) return;
var decryptionPromises = _this4.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map((event) => _this4.client.decryptEventIfNeeded(event));
yield Promise.allSettled(decryptionPromises);
})();
}
/**
* Gets the creator of the room
* @returns The creator of the room, or null if it could not be determined
*/
getCreator() {
var _createEvent$getSende;
var createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
return (_createEvent$getSende = createEvent === null || createEvent === void 0 ? void 0 : createEvent.getSender()) !== null && _createEvent$getSende !== void 0 ? _createEvent$getSende : null;
}
/**
* Gets the version of the room
* @returns The version of the room
*/
getVersion() {
return this.currentState.getRoomVersion();
}
/**
* Determines the recommended room version for the room. This returns an
* object with 3 properties: `version` as the new version the
* room should be upgraded to (may be the same as the current version);
* `needsUpgrade` to indicate if the room actually can be
* upgraded (ie: does the current version not match?); and `urgent`
* to indicate if the new version patches a vulnerability in a previous
* version.
* @returns
* Resolves to the version the room should be upgraded to.
*/
getRecommendedVersion() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var capabilities = {};
try {
capabilities = yield _this5.client.getCapabilities();
} catch (_unused2) {}
var versionCap = capabilities["m.room_versions"];
if (!versionCap) {
versionCap = {
default: "10",
available: {}
};
for (var safeVer of SAFE_ROOM_VERSIONS) versionCap.available[safeVer] = RoomVersionStability.Stable;
}
var result = _this5.checkVersionAgainstCapability(versionCap);
if (result.urgent && result.needsUpgrade) {
logger$2.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");
try {
capabilities = yield _this5.client.fetchCapabilities();
} catch (e) {
logger$2.warn("Failed to refresh room version capabilities", e);
}
versionCap = capabilities["m.room_versions"];
if (!versionCap) {
logger$2.warn("No room version capability - assuming upgrade required.");
return result;
} else result = _this5.checkVersionAgainstCapability(versionCap);
}
return result;
})();
}
checkVersionAgainstCapability(versionCap) {
var currentVersion = this.getVersion();
logger$2.log("[".concat(this.roomId, "] Current version: ").concat(currentVersion));
logger$2.log("[".concat(this.roomId, "] Version capability: "), versionCap);
var result = {
version: currentVersion,
needsUpgrade: false,
urgent: false
};
if (currentVersion === versionCap.default) return result;
if (!Object.keys(versionCap.available).filter((v) => versionCap.available[v] === "stable").includes(currentVersion)) {
result.version = versionCap.default;
result.needsUpgrade = true;
result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);
if (result.urgent) logger$2.warn("URGENT upgrade required on ".concat(this.roomId));
else logger$2.warn("Non-urgent upgrade required on ".concat(this.roomId));
return result;
}
return result;
}
/**
* Determines whether the given user is permitted to perform a room upgrade
* @param userId - The ID of the user to test against
* @returns True if the given user is permitted to upgrade the room
*/
userMayUpgradeRoom(userId) {
return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);
}
/**
* Get the list of pending sent events for this room
*
* @returns A list of the sent events
* waiting for remote echo.
*
* @throws If `opts.pendingEventOrdering` was not 'detached'
*/
getPendingEvents() {
if (!this.pendingEventList) throw new Error("Cannot call getPendingEvents with pendingEventOrdering == " + this.opts.pendingEventOrdering);
return this.pendingEventList;
}
/**
* Removes a pending event for this room
*
* @returns True if an element was removed.
*/
removePendingEvent(eventId) {
if (!this.pendingEventList) throw new Error("Cannot call removePendingEvent with pendingEventOrdering == " + this.opts.pendingEventOrdering);
var removed = removeElement(this.pendingEventList, function(ev) {
return ev.getId() == eventId;
}, false);
this.savePendingEvents();
return removed;
}
/**
* Check whether the pending event list contains a given event by ID.
* If pending event ordering is not "detached" then this returns false.
*
* @param eventId - The event ID to check for.
*/
hasPendingEvent(eventId) {
var _this$pendingEventLis, _this$pendingEventLis2;
return (_this$pendingEventLis = (_this$pendingEventLis2 = this.pendingEventList) === null || _this$pendingEventLis2 === void 0 ? void 0 : _this$pendingEventLis2.some((event) => event.getId() === eventId)) !== null && _this$pendingEventLis !== void 0 ? _this$pendingEventLis : false;
}
/**
* Get a specific event from the pending event list, if configured, null otherwise.
*
* @param eventId - The event ID to check for.
*/
getPendingEvent(eventId) {
var _this$pendingEventLis3, _this$pendingEventLis4;
return (_this$pendingEventLis3 = (_this$pendingEventLis4 = this.pendingEventList) === null || _this$pendingEventLis4 === void 0 ? void 0 : _this$pendingEventLis4.find((event) => event.getId() === eventId)) !== null && _this$pendingEventLis3 !== void 0 ? _this$pendingEventLis3 : null;
}
/**
* Get the live unfiltered timeline for this room.
*
* @returns live timeline
*/
getLiveTimeline() {
return this.getUnfilteredTimelineSet().getLiveTimeline();
}
/**
* The live event timeline for this room, with the oldest event at index 0.
*
* @deprecated Present for backwards compatibility.
* Use getLiveTimeline().getEvents() instead
*/
get timeline() {
return this.getLiveTimeline().getEvents();
}
/**
* Get the timestamp of the last message in the room
*
* @returns the timestamp of the last message in the room
*/
getLastActiveTimestamp() {
var events = this.getLiveTimeline().getEvents();
if (events.length) return events[events.length - 1].getTs();
else return Number.MIN_SAFE_INTEGER;
}
/**
* Returns the last live event of this room.
* "last" means latest timestamp.
* Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
* Unfortunately, this information is currently not available in the client.
* See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
* "live of this room" means from all live timelines: the room and the threads.
*
* @returns MatrixEvent if there is a last event; else undefined.
*/
getLastLiveEvent() {
var _lastRoomEvent$getTs, _lastThreadEvent$getT;
var roomEvents = this.getLiveTimeline().getEvents();
var lastRoomEvent = roomEvents[roomEvents.length - 1];
var lastThread = this.getLastThread();
if (!lastThread) return lastRoomEvent;
var lastThreadEvent = lastThread.events[lastThread.events.length - 1];
return ((_lastRoomEvent$getTs = lastRoomEvent === null || lastRoomEvent === void 0 ? void 0 : lastRoomEvent.getTs()) !== null && _lastRoomEvent$getTs !== void 0 ? _lastRoomEvent$getTs : 0) > ((_lastThreadEvent$getT = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT !== void 0 ? _lastThreadEvent$getT : 0) ? lastRoomEvent : lastThreadEvent;
}
/**
* Returns the last thread of this room.
* "last" means latest timestamp of the last thread event.
* Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
* Unfortunately, this information is currently not available in the client.
* See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
*
* @returns the thread with the most recent event in its live time line. undefined if there is no thread.
*/
getLastThread() {
return this.getThreads().reduce((lastThread, thread) => {
var _threadEvent$getTs, _lastThreadEvent$getT2;
if (!lastThread) return thread;
var threadEvent = thread.events[thread.events.length - 1];
var lastThreadEvent = lastThread.events[lastThread.events.length - 1];
if (((_threadEvent$getTs = threadEvent === null || threadEvent === void 0 ? void 0 : threadEvent.getTs()) !== null && _threadEvent$getTs !== void 0 ? _threadEvent$getTs : 0) >= ((_lastThreadEvent$getT2 = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT2 !== void 0 ? _lastThreadEvent$getT2 : 0)) return thread;
return lastThread;
}, void 0);
}
/**
* @returns the membership type (join | leave | invite | knock) for the logged in user
*/
getMyMembership() {
var _this$selfMembership;
return (_this$selfMembership = this.selfMembership) !== null && _this$selfMembership !== void 0 ? _this$selfMembership : KnownMembership.Leave;
}
/**
* If this room is a DM we're invited to,
* try to find out who invited us
* @returns user id of the inviter
*/
getDMInviter() {
var me = this.getMember(this.myUserId);
if (me) return me.getDMInviter();
if (this.selfMembership === KnownMembership.Invite) {
if (this.getInvitedAndJoinedMemberCount() === 2) {
var _this$heroes;
return (_this$heroes = this.heroes) === null || _this$heroes === void 0 || (_this$heroes = _this$heroes[0]) === null || _this$heroes === void 0 ? void 0 : _this$heroes.userId;
}
}
}
/**
* Assuming this room is a DM room, tries to guess with which user.
* @returns user id of the other member (could be syncing user)
*/
guessDMUserId() {
var me = this.getMember(this.myUserId);
if (me) {
var inviterId = me.getDMInviter();
if (inviterId) return inviterId;
}
if (Array.isArray(this.heroes) && this.heroes.length) return this.heroes[0].userId;
var anyMember = this.currentState.getMembers().find((m) => m.userId !== this.myUserId);
if (anyMember) return anyMember.userId;
return this.myUserId;
}
/**
* Gets the "functional members" in this room.
*
* Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the
* current membership states of those users.
*
* @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md.
*/
getFunctionalMembers() {
var mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, "");
if (Array.isArray(mFunctionalMembers === null || mFunctionalMembers === void 0 ? void 0 : mFunctionalMembers.getContent().service_members)) return mFunctionalMembers.getContent().service_members;
return [];
}
getAvatarFallbackMember() {
var _this$heroes2;
var functionalMembers = this.getFunctionalMembers();
var nonFunctionalMemberCount = 0;
this.getMembers().forEach((m) => {
if (m.membership !== "join" && m.membership !== "invite") return;
if (functionalMembers.includes(m.userId)) return;
nonFunctionalMemberCount++;
});
if (nonFunctionalMemberCount > 2) return;
var nonFunctionalHeroes = (_this$heroes2 = this.heroes) === null || _this$heroes2 === void 0 ? void 0 : _this$heroes2.filter((h) => !functionalMembers.includes(h.userId));
var hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length;
if (hasHeroes) {
for (var hero of nonFunctionalHeroes) if (!hero.fromMSC4186) {
var member = this.getMember(hero.userId);
if (member) return member;
} else {
var heroMember = new RoomMember(this.roomId, hero.userId);
heroMember.setMembershipEvent(new MatrixEvent({
event_id: "$" + this.roomId + hero.userId + (/* @__PURE__ */ new Date()).getTime(),
type: EventType.RoomMember,
state_key: hero.userId,
content: {
displayname: hero.displayName,
avatar_url: hero.avatarUrl
}
}));
return heroMember;
}
var availableMember = nonFunctionalHeroes.map((hero) => {
return this.getMember(hero.userId);
}).find((member) => !!member);
if (availableMember) return availableMember;
}
var members = this.getMembers();
var nonFunctionalMembers = members === null || members === void 0 ? void 0 : members.filter((m) => !functionalMembers.includes(m.userId));
if (nonFunctionalMembers.length <= 2) {
var _availableMember = nonFunctionalMembers.find((m) => {
return m.userId !== this.myUserId;
});
if (_availableMember) return _availableMember;
}
if (hasHeroes) {
var availableUser = nonFunctionalHeroes.map((hero) => {
return this.client.getUser(hero.userId);
}).find((user) => !!user);
if (availableUser) {
var _member = new RoomMember(this.roomId, availableUser.userId);
_member.user = availableUser;
return _member;
}
}
}
/**
* Sets the membership this room was received as during sync
* @param membership - join | leave | invite
*/
updateMyMembership(membership) {
var prevMembership = this.selfMembership;
this.selfMembership = membership;
if (prevMembership !== membership) {
if (membership === KnownMembership.Leave) this.cleanupAfterLeaving();
this.emit(RoomEvent.MyMembership, this, membership, prevMembership);
}
}
loadMembersFromServer() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var lastSyncToken = _this6.client.store.getSyncToken();
return (yield _this6.client.members(_this6.roomId, void 0, KnownMembership.Leave, lastSyncToken !== null && lastSyncToken !== void 0 ? lastSyncToken : void 0)).chunk;
})();
}
loadMembers() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var fromServer = false;
var rawMembersEvents = yield _this7.client.store.getOutOfBandMembers(_this7.roomId);
if (rawMembersEvents === null || _this7.hasEncryptionStateEvent()) {
fromServer = true;
rawMembersEvents = yield _this7.loadMembersFromServer();
logger$2.log("LL: got ".concat(rawMembersEvents.length, " ") + "members from server for room ".concat(_this7.roomId));
}
return {
memberEvents: rawMembersEvents.filter(noUnsafeEventProps).map(_this7.client.getEventMapper()),
fromServer
};
})();
}
/**
* Check if loading of out-of-band-members has completed
*
* @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).
* False if the load is not started or is in progress.
*/
membersLoaded() {
if (!this.opts.lazyLoadMembers) return true;
return this.currentState.outOfBandMembersReady();
}
/**
* Preloads the member list in case lazy loading
* of memberships is in use. Can be called multiple times,
* it will only preload once.
* @returns when preloading is done and
* accessing the members on the room will take
* all members in the room into account
*/
loadMembersIfNeeded() {
if (this.membersPromise) return this.membersPromise;
this.currentState.markOutOfBandMembersStarted();
var inMemoryUpdate = this.loadMembers().then((result) => {
this.currentState.setOutOfBandMembers(result.memberEvents);
this.recalculate();
return result.fromServer;
}).catch((err) => {
this.membersPromise = void 0;
this.currentState.markOutOfBandMembersFailed();
throw err;
});
inMemoryUpdate.then((fromServer) => {
if (fromServer) {
var oobMembers = this.currentState.getMembers().filter((m) => m.isOutOfBand()).map((m) => {
var _m$events$member;
return (_m$events$member = m.events.member) === null || _m$events$member === void 0 ? void 0 : _m$events$member.event;
});
logger$2.log("LL: telling store to write ".concat(oobMembers.length) + " members for room ".concat(this.roomId));
return this.client.store.setOutOfBandMembers(this.roomId, oobMembers).catch((err) => {
logger$2.log("LL: storing OOB room members failed, oh well", err);
});
}
}).catch((err) => {
logger$2.error(err);
});
this.membersPromise = inMemoryUpdate;
return this.membersPromise;
}
/**
* Removes the lazily loaded members from storage if needed
*/
clearLoadedMembersIfNeeded() {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this8.opts.lazyLoadMembers && _this8.membersPromise) {
yield _this8.loadMembersIfNeeded();
yield _this8.client.store.clearOutOfBandMembers(_this8.roomId);
_this8.currentState.clearOutOfBandMembers();
_this8.membersPromise = void 0;
}
})();
}
/**
* called when sync receives this room in the leave section
* to do cleanup after leaving a room. Possibly called multiple times.
*/
cleanupAfterLeaving() {
this.clearLoadedMembersIfNeeded().catch((err) => {
logger$2.error("error after clearing loaded members from " + "room ".concat(this.roomId, " after leaving"));
logger$2.log(err);
});
}
/**
* Empty out the current live timeline and re-request it. This is used when
* historical messages are imported into the room via MSC2716 `/batch_send`
* because the client may already have that section of the timeline loaded.
* We need to force the client to throw away their current timeline so that
* when they back paginate over the area again with the historical messages
* in between, it grabs the newly imported messages. We can listen for
* `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready
* to be discovered in the room and the timeline needs a refresh. The SDK
* emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a
* valid marker and can check the needs refresh status via
* `room.getTimelineNeedsRefresh()`.
*/
refreshLiveTimeline() {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
var liveTimelineBefore = _this9.getLiveTimeline();
var forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);
var backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);
var eventsBefore = liveTimelineBefore.getEvents();
var mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];
logger$2.log("[refreshLiveTimeline for ".concat(_this9.roomId, "] at ") + "mostRecentEventInTimeline=".concat(mostRecentEventInTimeline && mostRecentEventInTimeline.getId(), " ") + "liveTimelineBefore=".concat(liveTimelineBefore.toString(), " ") + "forwardPaginationToken=".concat(forwardPaginationToken, " ") + "backwardPaginationToken=".concat(backwardPaginationToken));
var timelineSet = _this9.getUnfilteredTimelineSet();
var newTimeline = null;
if (!mostRecentEventInTimeline) newTimeline = yield _this9.client.getLatestTimeline(timelineSet);
else {
_this9.resetLiveTimeline(null, null);
_this9.emit(RoomEvent.TimelineRefresh, _this9, timelineSet);
newTimeline = yield _this9.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId());
}
var liveTimeline = timelineSet.getLiveTimeline();
if (!liveTimeline || liveTimeline.getPaginationToken(Direction.Forward) === null && liveTimeline.getPaginationToken(Direction.Backward) === null && liveTimeline.getEvents().length === 0) {
logger$2.log("[refreshLiveTimeline for ".concat(_this9.roomId, "] using our new live timeline"));
newTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);
timelineSet.setLiveTimeline(newTimeline);
_this9.fixUpLegacyTimelineFields();
} else logger$2.log("[refreshLiveTimeline for ".concat(_this9.roomId, "] `/sync` or some other request beat us to creating a new ") + "live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.");
_this9.setTimelineNeedsRefresh(false);
_this9.emit(RoomEvent.TimelineRefresh, _this9, timelineSet);
})();
}
/**
* Reset the live timeline of all timelineSets, and start new ones.
*
* <p>This is used when /sync returns a 'limited' timeline.
*
* @param backPaginationToken - token for back-paginating the new timeline
* @param forwardPaginationToken - token for forward-paginating the old live timeline,
* if absent or null, all timelines are reset, removing old ones (including the previous live
* timeline which would otherwise be unable to paginate forwards without this token).
* Removing just the old live timeline whilst preserving previous ones is not supported.
*/
resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
for (var timelineSet of this.timelineSets) timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : void 0, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : void 0);
for (var thread of this.threads.values()) thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);
this.fixUpLegacyTimelineFields();
}
/**
* Fix up this.timeline, this.oldState and this.currentState
*
* @internal
*/
fixUpLegacyTimelineFields() {
var previousOldState = this.oldState;
var previousCurrentState = this.currentState;
this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS);
this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);
if (previousOldState !== this.oldState) this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);
if (previousCurrentState !== this.currentState) {
this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);
this.reEmitter.stopReEmitting(previousCurrentState, [
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update,
RoomStateEvent.Marker,
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange
]);
this.reEmitter.reEmit(this.currentState, [
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update,
RoomStateEvent.Marker,
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange
]);
}
}
onReceipt(event) {
if (this.hasEncryptionStateEvent()) this.clearNotificationsOnReceipt(event);
}
clearNotificationsOnReceipt(event) {
var threadIds = [];
var hasUnthreadedReceipt = false;
var content = event.getContent();
for (var receiptGroup of Object.values(content)) for (var [receiptType, userReceipt] of Object.entries(receiptGroup)) {
if (!isSupportedReceiptType(receiptType)) continue;
if (!userReceipt) continue;
for (var [userId, singleReceipt] of Object.entries(userReceipt)) {
if (!singleReceipt || typeof singleReceipt !== "object") continue;
var typedSingleReceipt = singleReceipt;
if (userId !== this.client.getUserId()) continue;
if (typedSingleReceipt.thread_id === void 0) hasUnthreadedReceipt = true;
else if (typeof typedSingleReceipt.thread_id === "string") threadIds.push(typedSingleReceipt.thread_id);
}
}
if (hasUnthreadedReceipt) {
threadIds = this.getThreads().filter((thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 || this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0).map((thread) => thread.id);
threadIds.push("main");
}
for (var threadId of threadIds) {
var _this$getThread;
var maxHistory = 20;
var timeline = threadId === "main" ? this.getLiveTimeline() : (_this$getThread = this.getThread(threadId)) === null || _this$getThread === void 0 ? void 0 : _this$getThread.liveTimeline;
if (!timeline) {
logger$2.warn("Couldn't find timeline for thread ID ".concat(threadId, " in room ").concat(this.roomId));
continue;
}
var events = timeline.getEvents();
var highlightCount = 0;
for (var i = events.length - 1; i >= 0; i--) {
var _pushActions$tweaks;
if (i === events.length - maxHistory) return;
var _event = events[i];
if (this.hasUserReadEvent(this.client.getUserId(), _event.getId())) break;
var pushActions = this.client.getPushActionsForEvent(_event);
highlightCount += pushActions !== null && pushActions !== void 0 && (_pushActions$tweaks = pushActions.tweaks) !== null && _pushActions$tweaks !== void 0 && _pushActions$tweaks.highlight ? 1 : 0;
}
if (threadId === "main") this.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);
else this.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, highlightCount);
}
}
/**
* Return the timeline sets for this room.
* @returns array of timeline sets for this room
*/
getTimelineSets() {
return this.timelineSets;
}
/**
* Helper to return the main unfiltered timeline set for this room
* @returns room's unfiltered timeline set
*/
getUnfilteredTimelineSet() {
return this.timelineSets[0];
}
/**
* Get the timeline which contains the given event from the unfiltered set, if any
*
* @param eventId - event ID to look for
* @returns timeline containing
* the given event, or null if unknown
*/
getTimelineForEvent(eventId) {
var event = this.findEventById(eventId);
var thread = this.findThreadForEvent(event);
if (thread) return thread.timelineSet.getTimelineForEvent(eventId);
else return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);
}
/**
* Add a new timeline to this room's unfiltered timeline set
*
* @returns newly-created timeline
*/
addTimeline() {
return this.getUnfilteredTimelineSet().addTimeline();
}
/**
* Whether the timeline needs to be refreshed in order to pull in new
* historical messages that were imported.
* @param value - The value to set
*/
setTimelineNeedsRefresh(value) {
this.timelineNeedsRefresh = value;
}
/**
* Whether the timeline needs to be refreshed in order to pull in new
* historical messages that were imported.
* @returns .
*/
getTimelineNeedsRefresh() {
return this.timelineNeedsRefresh;
}
/**
* Get an event which is stored in our unfiltered timeline set, or in a thread
*
* @param eventId - event ID to look for
* @returns the given event, or undefined if unknown
*/
findEventById(eventId) {
var event = this.getUnfilteredTimelineSet().findEventById(eventId);
if (!event) {
var threads = this.getThreads();
for (var i = 0; i < threads.length; i++) {
event = threads[i].findEventById(eventId);
if (event) return event;
}
}
return event;
}
/**
* Get one of the notification counts for this room
* @param type - The type of notification count to get. default: 'total'
* @returns The notification count, or undefined if there is no count
* for this type.
*/
getUnreadNotificationCount() {
var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : NotificationCountType.Total;
var count = this.getRoomUnreadNotificationCount(type);
for (var threadNotification of this.threadNotifications.values()) {
var _threadNotification$t;
count += (_threadNotification$t = threadNotification[type]) !== null && _threadNotification$t !== void 0 ? _threadNotification$t : 0;
}
return count;
}
/**
* Get the notification for the event context (room or thread timeline)
*/
getUnreadCountForEventContext() {
var _ref2;
var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : NotificationCountType.Total;
var event = arguments.length > 1 ? arguments[1] : void 0;
return (_ref2 = !!event.threadRootId && !event.isThreadRoot ? this.getThreadUnreadNotificationCount(event.threadRootId, type) : this.getRoomUnreadNotificationCount(type)) !== null && _ref2 !== void 0 ? _ref2 : 0;
}
/**
* Get one of the notification counts for this room
* @param type - The type of notification count to get. default: 'total'
* @returns The notification count, or undefined if there is no count
* for this type.
*/
getRoomUnreadNotificationCount() {
var _this$notificationCou;
var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : NotificationCountType.Total;
return (_this$notificationCou = this.notificationCounts[type]) !== null && _this$notificationCou !== void 0 ? _this$notificationCou : 0;
}
/**
* Get one of the notification counts for a thread
* @param threadId - the root event ID
* @param type - The type of notification count to get. default: 'total'
* @returns The notification count, or undefined if there is no count
* for this type.
*/
getThreadUnreadNotificationCount(threadId) {
var _this$threadNotificat, _this$threadNotificat2;
var type = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : NotificationCountType.Total;
return (_this$threadNotificat = (_this$threadNotificat2 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat2 === void 0 ? void 0 : _this$threadNotificat2[type]) !== null && _this$threadNotificat !== void 0 ? _this$threadNotificat : 0;
}
/**
* Checks if the current room has unread thread notifications
* @returns
*/
hasThreadUnreadNotification() {
for (var notification of this.threadNotifications.values()) {
var _notification$highlig, _notification$total;
if (((_notification$highlig = notification.highlight) !== null && _notification$highlig !== void 0 ? _notification$highlig : 0) > 0 || ((_notification$total = notification.total) !== null && _notification$total !== void 0 ? _notification$total : 0) > 0) return true;
}
return false;
}
/**
* Swet one of the notification count for a thread
* @param threadId - the root event ID
* @param type - The type of notification count to get. default: 'total'
* @returns
*/
setThreadUnreadNotificationCount(threadId, type, count) {
var _this$threadNotificat3, _this$threadNotificat4;
var notification = _objectSpread$13({
highlight: (_this$threadNotificat3 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat3 === void 0 ? void 0 : _this$threadNotificat3.highlight,
total: (_this$threadNotificat4 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat4 === void 0 ? void 0 : _this$threadNotificat4.total
}, { [type]: count });
this.threadNotifications.set(threadId, notification);
this.emit(RoomEvent.UnreadNotifications, notification, threadId);
}
/**
* @returns the notification count type for all the threads in the room
*/
get threadsAggregateNotificationType() {
var type = null;
for (var threadNotification of this.threadNotifications.values()) {
var _threadNotification$h, _threadNotification$t2;
if (((_threadNotification$h = threadNotification.highlight) !== null && _threadNotification$h !== void 0 ? _threadNotification$h : 0) > 0) return NotificationCountType.Highlight;
else if (((_threadNotification$t2 = threadNotification.total) !== null && _threadNotification$t2 !== void 0 ? _threadNotification$t2 : 0) > 0 && !type) type = NotificationCountType.Total;
}
return type;
}
/**
* Resets the total thread notifications for all threads in this room to zero,
* excluding any threads whose IDs are given in `exceptThreadIds`.
*
* If the room is not encrypted, also resets the highlight notification count to zero
* for the same set of threads.
*
* This is intended for use from the sync code since we calculate highlight notification
* counts locally from decrypted messages. We want to partially trust the total from the
* server such that we clear notifications when read receipts arrive. The weird name is
* intended to reflect this. You probably do not want to use this.
*
* @param exceptThreadIds - The thread IDs to exclude from the reset.
*/
resetThreadUnreadNotificationCountFromSync() {
var exceptThreadIds = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
var isEncrypted = this.hasEncryptionStateEvent();
for (var [threadId, notifs] of this.threadNotifications) if (!exceptThreadIds.includes(threadId)) {
notifs.total = 0;
if (!isEncrypted) notifs.highlight = 0;
}
this.emit(RoomEvent.UnreadNotifications);
}
/**
* Set the bump stamp for this room. This can be used for sorting rooms when the timeline
* entries are unknown. Used in MSC4186: Simplified Sliding Sync.
* @param bumpStamp The bump_stamp value from the server
*/
setBumpStamp(bumpStamp) {
this.bumpStamp = bumpStamp;
}
/**
* Get the bump stamp for this room. This can be used for sorting rooms when the timeline
* entries are unknown. Used in MSC4186: Simplified Sliding Sync.
* @returns The bump stamp for the room, if it exists.
*/
getBumpStamp() {
return this.bumpStamp;
}
/**
* Set one of the notification counts for this room
* @param type - The type of notification count to set.
* @param count - The new count
*/
setUnreadNotificationCount(type, count) {
this.notificationCounts[type] = count;
this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);
}
setUnread(type, count) {
return this.setUnreadNotificationCount(type, count);
}
/**
* Takes a legacy room summary (/v3/sync as opposed to MSC4186) and updates the room with it.
*
* @param summary - The room summary to update the room with
*/
setSummary(summary) {
var _summary$mHeroes;
var heroes = (_summary$mHeroes = summary["m.heroes"]) === null || _summary$mHeroes === void 0 ? void 0 : _summary$mHeroes.map((h) => ({
userId: h,
fromMSC4186: false
}));
var joinedCount = summary["m.joined_member_count"];
var invitedCount = summary["m.invited_member_count"];
if (Number.isInteger(joinedCount)) this.currentState.setJoinedMemberCount(joinedCount);
if (Number.isInteger(invitedCount)) this.currentState.setInvitedMemberCount(invitedCount);
if (Array.isArray(heroes)) this.heroes = heroes.filter((h) => {
return h.userId != this.myUserId;
});
this.emit(RoomEvent.Summary, summary);
}
/**
* Takes information from the MSC4186 room summary and updates the room with it.
*
* @param heroes - The room's hero members
* @param joinedCount - The number of joined members
* @param invitedCount - The number of invited members
*/
setMSC4186SummaryData(heroes, joinedCount, invitedCount) {
if (heroes) this.heroes = heroes.filter((h) => h.user_id !== this.myUserId).map((h) => ({
userId: h.user_id,
displayName: h.displayname,
avatarUrl: h.avatar_url,
fromMSC4186: true
}));
if (joinedCount !== void 0 && Number.isInteger(joinedCount)) this.currentState.setJoinedMemberCount(joinedCount);
if (invitedCount !== void 0 && Number.isInteger(invitedCount)) this.currentState.setInvitedMemberCount(invitedCount);
this.emit(RoomEvent.Summary, {
"m.heroes": this.heroes ? this.heroes.map((h) => h.userId) : [],
"m.joined_member_count": joinedCount,
"m.invited_member_count": invitedCount
});
}
/**
* Whether to send encrypted messages to devices within this room.
* @param value - true to blacklist unverified devices, null
* to use the global value for this room.
*/
setBlacklistUnverifiedDevices(value) {
this.blacklistUnverifiedDevices = value;
}
/**
* Whether to send encrypted messages to devices within this room.
* @returns true if blacklisting unverified devices, null
* if the global value should be used for this room.
*/
getBlacklistUnverifiedDevices() {
if (this.blacklistUnverifiedDevices === void 0) return null;
return this.blacklistUnverifiedDevices;
}
/**
* Get the avatar URL for a room if one was set.
* @param baseUrl - The homeserver base URL. See
* {@link MatrixClient#getHomeserverUrl}.
* @param width - The desired width of the thumbnail.
* @param height - The desired height of the thumbnail.
* @param resizeMethod - The thumbnail resize method to use, either
* "crop" or "scale".
* @param allowDefault - True to allow an identicon for this room if an
* avatar URL wasn't explicitly set. Default: true. (Deprecated)
* @param useAuthentication - (optional) If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support for
* authenticated media will not be checked - it is the caller's responsibility
* to do so before calling this function. Note also that useAuthentication
* implies allowRedirects. Defaults to false (unauthenticated endpoints).
* @returns the avatar URL or null.
*/
getAvatarUrl(baseUrl, width, height, resizeMethod) {
var allowDefault = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
var useAuthentication = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false;
var mainUrl = this.getMxcAvatarUrl();
if (!mainUrl && !allowDefault) return null;
if (mainUrl) return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod, void 0, void 0, useAuthentication);
return null;
}
/**
* Get the mxc avatar url for the room, if one was set.
* @returns the mxc avatar url or falsy
*/
getMxcAvatarUrl() {
var _this$currentState$ge;
var url = (_this$currentState$ge = this.currentState.getStateEvents(EventType.RoomAvatar, "")) === null || _this$currentState$ge === void 0 ? void 0 : _this$currentState$ge.getContent().url;
return url && typeof url === "string" ? url : null;
}
/**
* Get this room's canonical alias
* The alias returned by this function may not necessarily
* still point to this room.
* @returns The room's canonical alias, or null if there is none
*/
getCanonicalAlias() {
var _this$currentState$ge2;
var canonicalAlias = (_this$currentState$ge2 = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, "")) === null || _this$currentState$ge2 === void 0 ? void 0 : _this$currentState$ge2.getContent().alias;
return canonicalAlias && typeof canonicalAlias === "string" ? canonicalAlias : null;
}
/**
* Get this room's alternative aliases
* @returns The room's alternative aliases, or an empty array
*/
getAltAliases() {
var _this$currentState$ge3;
var altAliases = (_this$currentState$ge3 = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, "")) === null || _this$currentState$ge3 === void 0 ? void 0 : _this$currentState$ge3.getContent().alt_aliases;
if (Array.isArray(altAliases)) return altAliases.filter((alias) => typeof alias === "string");
return [];
}
/**
* Add events to a timeline
*
* <p>Will fire "Room.timeline" for each event added.
*
* @param events - A list of events to add.
*
* @param toStartOfTimeline - True to add these events to the start
* (oldest) instead of the end (newest) of the timeline. If true, the oldest
* event will be the <b>last</b> element of 'events'.
*
* @param timeline - timeline to
* add events to.
*
* @param paginationToken - token for the next batch of events
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*/
addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken) {
timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken);
}
/**
* Get the instance of the thread associated with the current event
* @param eventId - the ID of the current event
* @returns a thread instance if known
*/
getThread(eventId) {
var _this$threads$get;
return (_this$threads$get = this.threads.get(eventId)) !== null && _this$threads$get !== void 0 ? _this$threads$get : null;
}
/**
* Get all the known threads in the room
*/
getThreads() {
return Array.from(this.threads.values());
}
/**
* Get a member from the current room state.
* @param userId - The user ID of the member.
* @returns The member or `null`.
*/
getMember(userId) {
return this.currentState.getMember(userId);
}
/**
* Get all currently loaded members from the current
* room state.
* @returns Room members
*/
getMembers() {
return this.currentState.getMembers();
}
/**
* Get a list of members whose membership state is "join".
* @returns A list of currently joined members.
*/
getJoinedMembers() {
return this.getMembersWithMembership(KnownMembership.Join);
}
/**
* Returns the number of joined members in this room
* This method caches the result.
* This is a wrapper around the method of the same name in roomState, returning
* its result for the room's current state.
* @returns The number of members in this room whose membership is 'join'
*/
getJoinedMemberCount() {
return this.currentState.getJoinedMemberCount();
}
/**
* Returns the number of invited members in this room
* @returns The number of members in this room whose membership is 'invite'
*/
getInvitedMemberCount() {
return this.currentState.getInvitedMemberCount();
}
/**
* Returns the number of invited + joined members in this room
* @returns The number of members in this room whose membership is 'invite' or 'join'
*/
getInvitedAndJoinedMemberCount() {
return this.getInvitedMemberCount() + this.getJoinedMemberCount();
}
/**
* Get a list of members with given membership state.
* @param membership - The membership state.
* @returns A list of members with the given membership state.
*/
getMembersWithMembership(membership) {
return this.currentState.getMembers().filter(function(m) {
return m.membership === membership;
});
}
/**
* Get a list of members we should be encrypting for in this room
* @returns A list of members who
* we should encrypt messages for in this room.
*/
getEncryptionTargetMembers() {
var _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this0.loadMembersIfNeeded();
var members = _this0.getMembersWithMembership(KnownMembership.Join);
if (_this0.shouldEncryptForInvitedMembers()) members = members.concat(_this0.getMembersWithMembership(KnownMembership.Invite));
return members;
})();
}
/**
* Determine whether we should encrypt messages for invited users in this room
* @returns if we should encrypt messages for invited users
*/
shouldEncryptForInvitedMembers() {
var _ev$getContent;
var ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, "");
return (ev === null || ev === void 0 || (_ev$getContent = ev.getContent()) === null || _ev$getContent === void 0 ? void 0 : _ev$getContent.history_visibility) !== "joined";
}
/**
* Get the default room name (i.e. what a given user would see if the
* room had no m.room.name)
* @param userId - The userId from whose perspective we want
* to calculate the default name
* @returns The default room name
*/
getDefaultRoomName(userId) {
return this.calculateRoomName(userId, true);
}
/**
* Check if the given user_id has the given membership state.
* @param userId - The user ID to check.
* @param membership - The membership e.g. `'join'`
* @returns True if this user_id has the given membership state.
*/
hasMembershipState(userId, membership) {
var member = this.getMember(userId);
if (!member) return false;
return member.membership === membership;
}
/**
* Add a timelineSet for this room with the given filter
* @param filter - The filter to be applied to this timelineSet
* @param opts - Configuration options
* @returns The timelineSet
*/
getOrCreateFilteredTimelineSet(filter) {
var { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
if (this.filteredTimelineSets[filter.filterId]) return this.filteredTimelineSets[filter.filterId];
var opts = Object.assign({
filter,
pendingEvents
}, this.opts);
var timelineSet = new EventTimelineSet(this, opts);
this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
if (useSyncEvents) {
this.filteredTimelineSets[filter.filterId] = timelineSet;
this.timelineSets.push(timelineSet);
}
var unfilteredLiveTimeline = this.getLiveTimeline();
if (prepopulateTimeline) {
unfilteredLiveTimeline.getEvents().forEach(function(event) {
timelineSet.addLiveEvent(event, { addToState: false });
});
var timeline = unfilteredLiveTimeline;
while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS);
timelineSet.getLiveTimeline().setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);
} else if (useSyncEvents) {
var livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);
timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);
}
return timelineSet;
}
getThreadListFilter() {
var _arguments = arguments, _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
var filterType = _arguments.length > 0 && _arguments[0] !== void 0 ? _arguments[0] : ThreadFilterType.All;
var myUserId = _this1.client.getUserId();
var filter = new Filter(myUserId);
var definition = { room: { timeline: { [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name] } } };
if (filterType === ThreadFilterType.My) definition.room.timeline[FILTER_RELATED_BY_SENDERS.name] = [myUserId];
filter.setDefinition(definition);
filter.filterId = yield _this1.client.getOrCreateFilter("THREAD_PANEL_".concat(_this1.roomId, "_").concat(filterType), filter);
return filter;
})();
}
createThreadTimelineSet(filterType) {
var _this10 = this;
return (0, import_asyncToGenerator.default)(function* () {
var timelineSet;
if (Thread.hasServerSideListSupport) {
timelineSet = new EventTimelineSet(_this10, _objectSpread$13(_objectSpread$13({}, _this10.opts), {}, { pendingEvents: false }), void 0, void 0, filterType !== null && filterType !== void 0 ? filterType : ThreadFilterType.All);
_this10.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
} else if (Thread.hasServerSideSupport) {
var filter = yield _this10.getThreadListFilter(filterType);
timelineSet = _this10.getOrCreateFilteredTimelineSet(filter, {
prepopulateTimeline: false,
useSyncEvents: false,
pendingEvents: false
});
} else {
timelineSet = new EventTimelineSet(_this10, { pendingEvents: false });
Array.from(_this10.threads).forEach((_ref3) => {
var [, thread] = _ref3;
if (thread.length === 0) return;
var currentUserParticipated = thread.timeline.some((event) => {
return event.getSender() === _this10.client.getUserId();
});
if (filterType !== ThreadFilterType.My || currentUserParticipated) timelineSet.getLiveTimeline().addEvent(thread.rootEvent, {
toStartOfTimeline: false,
addToState: false
});
});
}
return timelineSet;
})();
}
/**
* Takes the given thread root events and creates threads for them.
*/
processThreadRoots(events, toStartOfTimeline) {
if (!this.client.supportsThreads()) return;
for (var rootEvent of events) {
EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);
if (!this.getThread(rootEvent.getId())) this.createThread(rootEvent.getId(), rootEvent, [], toStartOfTimeline);
}
}
/**
* Fetch the bare minimum of room threads required for the thread list to work reliably.
* With server support that means fetching one page.
* Without server support that means fetching as much at once as the server allows us to.
*/
fetchRoomThreads() {
var _this11 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this11.threadsReady || !_this11.client.supportsThreads()) return;
if (Thread.hasServerSideListSupport) yield Promise.all([_this11.fetchRoomThreadList(ThreadFilterType.All), _this11.fetchRoomThreadList(ThreadFilterType.My)]);
else {
var allThreadsFilter = yield _this11.getThreadListFilter();
var { chunk: events } = yield _this11.client.createMessagesRequest(_this11.roomId, "", Number.MAX_SAFE_INTEGER, Direction.Backward, allThreadsFilter);
if (!events.length) return;
var threadRoots = events.map(_this11.client.getEventMapper()).sort((eventA, eventB) => {
/**
* `origin_server_ts` in a decentralised world is far from ideal
* but for lack of any better, we will have to use this
* Long term the sorting should be handled by homeservers and this
* is only meant as a short term patch
*/
var threadAMetadata = eventA.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);
var threadBMetadata = eventB.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);
return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;
});
var latestMyThreadsRootEvent;
var roomState = _this11.getLiveTimeline().getState(EventTimeline.FORWARDS);
for (var rootEvent of threadRoots) {
var _this11$threadsTimeli;
var _opts = {
duplicateStrategy: DuplicateStrategy.Ignore,
fromCache: false,
addToState: false,
roomState
};
(_this11$threadsTimeli = _this11.threadsTimelineSets[0]) === null || _this11$threadsTimeli === void 0 || _this11$threadsTimeli.addLiveEvent(rootEvent, _opts);
var threadRelationship = rootEvent.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);
if (threadRelationship !== null && threadRelationship !== void 0 && threadRelationship.current_user_participated) {
var _this11$threadsTimeli2;
(_this11$threadsTimeli2 = _this11.threadsTimelineSets[1]) === null || _this11$threadsTimeli2 === void 0 || _this11$threadsTimeli2.addLiveEvent(rootEvent, _opts);
latestMyThreadsRootEvent = rootEvent;
}
}
_this11.processThreadRoots(threadRoots, true);
_this11.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);
if (latestMyThreadsRootEvent) _this11.client.decryptEventIfNeeded(latestMyThreadsRootEvent);
}
_this11.on(ThreadEvent.NewReply, _this11.onThreadReply);
_this11.on(ThreadEvent.Update, _this11.onThreadUpdate);
_this11.on(ThreadEvent.Delete, _this11.onThreadDelete);
_this11.threadsReady = true;
})();
}
/**
* Process a list of poll events.
*
* @param events - List of events
*/
processPollEvents(events) {
var _this12 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var event of events) try {
if (!event.isEncrypted() && !isPollEvent(event)) continue;
/**
* Try to decrypt the event. Promise resolution does not guarantee a successful decryption.
* Retry is handled in {@link processPollEvent}.
*/
yield _this12.client.decryptEventIfNeeded(event);
_this12.processPollEvent(event);
} catch (err) {
logger$2.warn("Error processing poll event", event.getId(), err);
}
})();
}
/**
* Processes poll events:
* If the event has a decryption failure, it will listen for decryption and tries again.
* If it is a poll start event (`m.poll.start`),
* it creates and stores a Poll model and emits a PollEvent.New event.
* If the event is related to a poll, it will add it to the poll.
* Noop for other cases.
*
* @param event - Event that could be a poll event
*/
processPollEvent(event) {
var _this13 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (event.isDecryptionFailure()) {
event.once(MatrixEventEvent.Decrypted, (maybeDecryptedEvent) => {
_this13.processPollEvent(maybeDecryptedEvent);
});
return;
}
if (import_lib$1.M_POLL_START.matches(event.getType())) {
try {
var poll = new Poll(event, _this13.client, _this13);
_this13.polls.set(event.getId(), poll);
_this13.emit(PollEvent.New, poll);
event.once(MatrixEventEvent.BeforeRedaction, (redactedEvent) => {
_this13.polls.delete(redactedEvent.getId());
});
} catch (_unused3) {}
return;
}
var relationEventId = event.relationEventId;
if (relationEventId && _this13.polls.has(relationEventId)) {
var _poll = _this13.polls.get(relationEventId);
_poll === null || _poll === void 0 || _poll.onNewRelation(event);
}
})();
}
/**
* Fetch a single page of threadlist messages for the specific thread filter
* @internal
*/
fetchRoomThreadList(filter) {
var _this14 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this14.client.supportsThreads()) return;
if (_this14.threadsTimelineSets.length === 0) return;
var timelineSet = filter === ThreadFilterType.My ? _this14.threadsTimelineSets[1] : _this14.threadsTimelineSets[0];
var { chunk: events, end } = yield _this14.client.createThreadListMessagesRequest(_this14.roomId, null, void 0, Direction.Backward, timelineSet.threadListType, timelineSet.getFilter());
timelineSet.getLiveTimeline().setPaginationToken(end !== null && end !== void 0 ? end : null, Direction.Backward);
if (!events.length) return;
var matrixEvents = events.map(_this14.client.getEventMapper());
_this14.processThreadRoots(matrixEvents, true);
var roomState = _this14.getLiveTimeline().getState(EventTimeline.FORWARDS);
for (var rootEvent of matrixEvents) timelineSet.addLiveEvent(rootEvent, {
duplicateStrategy: DuplicateStrategy.Replace,
fromCache: false,
roomState,
addToState: false
});
})();
}
onThreadUpdate(thread) {
this.updateThreadRootEvents(thread, false, false);
}
onThreadReply(thread) {
this.updateThreadRootEvents(thread, false, true);
}
onThreadDelete(thread) {
var _timeline$getEvents;
this.threads.delete(thread.id);
var timeline = this.getTimelineForEvent(thread.id);
var roomEvent = timeline === null || timeline === void 0 || (_timeline$getEvents = timeline.getEvents()) === null || _timeline$getEvents === void 0 ? void 0 : _timeline$getEvents.find((it) => it.getId() === thread.id);
if (roomEvent) thread.clearEventMetadata(roomEvent);
else logger$2.debug("onThreadDelete: Could not find root event in room timeline");
for (var timelineSet of this.threadsTimelineSets) timelineSet.removeEvent(thread.id);
}
/**
* Forget the timelineSet for this room with the given filter
*
* @param filter - the filter whose timelineSet is to be forgotten
*/
removeFilteredTimelineSet(filter) {
var timelineSet = this.filteredTimelineSets[filter.filterId];
delete this.filteredTimelineSets[filter.filterId];
var i = this.timelineSets.indexOf(timelineSet);
if (i > -1) this.timelineSets.splice(i, 1);
}
/**
* Determine which timeline(s) a given event should live in
* Thread roots live in both the main timeline and their corresponding thread timeline
* Relations, redactions, replies to thread relation events live only in the thread timeline
* Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline
* Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless.
* Otherwise, the event lives in the main timeline only.
*
* Note: when a redaction is applied, the redacted event, events relating
* to it, and the redaction event itself, will all move to the main thread.
* This method classifies them as inside the thread of the redacted event.
* They are moved later as part of makeRedacted.
* This will change if MSC3389 is merged.
*/
eventShouldLiveIn(event, events, roots) {
var _this$client;
if (!((_this$client = this.client) !== null && _this$client !== void 0 && _this$client.supportsThreads())) return {
shouldLiveInRoom: true,
shouldLiveInThread: false
};
if (event.isThreadRoot || roots !== null && roots !== void 0 && roots.has(event.getId())) return {
shouldLiveInRoom: true,
shouldLiveInThread: true,
threadId: event.getId()
};
var isThreadRelation = event.isRelation(THREAD_RELATION_TYPE.name);
var parentEventId = event.getAssociatedId();
var threadRootId = event.threadRootId;
if (!!parentEventId && !isThreadRelation && (threadRootId === parentEventId || roots !== null && roots !== void 0 && roots.has(parentEventId))) return {
shouldLiveInRoom: true,
shouldLiveInThread: false
};
var parentEvent;
if (parentEventId) {
var _this$findEventById;
parentEvent = (_this$findEventById = this.findEventById(parentEventId)) !== null && _this$findEventById !== void 0 ? _this$findEventById : events === null || events === void 0 ? void 0 : events.find((e) => e.getId() === parentEventId);
}
if (parentEvent && !isThreadRelation) return this.eventShouldLiveIn(parentEvent, events, roots);
if (threadRootId != void 0) return {
shouldLiveInRoom: false,
shouldLiveInThread: true,
threadId: threadRootId
};
if (!parentEventId || !!event.replyEventId) return {
shouldLiveInRoom: true,
shouldLiveInThread: false
};
return {
shouldLiveInRoom: false,
shouldLiveInThread: false
};
}
findThreadForEvent(event) {
if (!event) return null;
var { threadId } = this.eventShouldLiveIn(event);
return threadId ? this.getThread(threadId) : null;
}
addThreadedEvents(threadId, events) {
var toStartOfTimeline = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
var thread = this.getThread(threadId);
if (thread) thread.addEvents(events, toStartOfTimeline);
else {
var _this$findEventById2;
var rootEvent = (_this$findEventById2 = this.findEventById(threadId)) !== null && _this$findEventById2 !== void 0 ? _this$findEventById2 : events.find((e) => e.getId() === threadId);
this.createThread(threadId, rootEvent, events, toStartOfTimeline);
}
}
/**
* Adds events to a thread's timeline. Will fire "Thread.update"
*/
processThreadedEvents(events, toStartOfTimeline) {
events.forEach(this.tryApplyRedaction);
var eventsByThread = {};
for (var event of events) {
var _eventsByThread;
var { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);
if (shouldLiveInThread && !eventsByThread[threadId]) eventsByThread[threadId] = [];
(_eventsByThread = eventsByThread[threadId]) === null || _eventsByThread === void 0 || _eventsByThread.push(event);
}
Object.entries(eventsByThread).map((_ref4) => {
var [threadId, threadEvents] = _ref4;
return this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline);
});
}
createThread(threadId, rootEvent) {
var _this$cachedThreadRea;
var events = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
var toStartOfTimeline = arguments.length > 3 ? arguments[3] : void 0;
if (this.threads.has(threadId)) return this.threads.get(threadId);
if (rootEvent) {
var relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId());
if (relatedEvents !== null && relatedEvents !== void 0 && relatedEvents.length) events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));
}
var thread = new Thread(threadId, rootEvent, {
room: this,
client: this.client,
pendingEventOrdering: this.opts.pendingEventOrdering,
receipts: (_this$cachedThreadRea = this.cachedThreadReadReceipts.get(threadId)) !== null && _this$cachedThreadRea !== void 0 ? _this$cachedThreadRea : []
});
this.reEmitter.reEmit(thread, [
ThreadEvent.Delete,
ThreadEvent.Update,
ThreadEvent.NewReply,
RoomEvent.Timeline,
RoomEvent.TimelineReset
]);
this.cachedThreadReadReceipts.delete(threadId);
this.threads.set(thread.id, thread);
thread.addEvents(events, false);
if (this.threadsReady && thread.initialEventsFetched) this.updateThreadRootEvents(thread, toStartOfTimeline, false);
this.emit(ThreadEvent.New, thread, toStartOfTimeline);
return thread;
}
/**
* Applies an event as a redaction of another event, regardless of whether the redacting
* event is actually a redaction.
*
* Callers should use tryApplyRedaction instead.
*
* @param redactionEvent The event which redacts an event.
* @param redactedEvent The event being redacted.
* @private
*/
applyEventAsRedaction(redactionEvent, redactedEvent) {
var threadRootId = redactedEvent.threadRootId;
redactedEvent.makeRedacted(redactionEvent, this);
if (redactedEvent.isState()) {
var currentStateEvent = this.currentState.getStateEvents(redactedEvent.getType(), redactedEvent.getStateKey());
if ((currentStateEvent === null || currentStateEvent === void 0 ? void 0 : currentStateEvent.getId()) === redactedEvent.getId()) this.currentState.setStateEvents([redactedEvent]);
}
this.emit(RoomEvent.Redaction, redactionEvent, this, threadRootId);
this.visibilityEvents.delete(redactedEvent.getId());
if (redactedEvent.isVisibilityEvent()) this.redactVisibilityChangeEvent(redactionEvent);
}
processLiveEvent(event) {
this.tryApplyRedaction(event);
if (event.isVisibilityEvent()) this.applyNewVisibilityEvent(event);
this.applyPendingVisibilityEvents(event);
if (!event.getUnsigned().transaction_id && event.getSender() === this.myUserId) {
for (var [tid, localEvent] of this.txnToEvent) if (localEvent.getId() === event.getId()) {
logger$2.debug("processLiveEvent: found sent event without txn ID: ", tid, event.getId());
var unsigned = event.getUnsigned();
unsigned.transaction_id = tid;
event.setUnsigned(unsigned);
break;
}
}
}
/**
* Add an event to the end of this room's live timelines. Will fire
* "Room.timeline".
*
* @param event - Event to be added
* @param addLiveEventOptions - addLiveEvent options
* @internal
*
* @remarks
* Fires {@link RoomEvent.Timeline}
*/
addLiveEvent(event, addLiveEventOptions) {
var { duplicateStrategy, timelineWasEmpty, fromCache, addToState } = addLiveEventOptions;
for (var timelineSet of this.timelineSets) timelineSet.addLiveEvent(event, {
duplicateStrategy,
fromCache,
timelineWasEmpty,
addToState
});
if (event.sender && event.getType() !== EventType.RoomRedaction) this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);
}
/**
* Add a pending outgoing event to this room.
*
* <p>The event is added to either the pendingEventList, or the live timeline,
* depending on the setting of opts.pendingEventOrdering.
*
* <p>This is an internal method, intended for use by MatrixClient.
*
* @param event - The event to add.
*
* @param txnId - Transaction id for this outgoing event
*
* @throws if the event doesn't have status SENDING, or we aren't given a
* unique transaction id.
*
* @remarks
* Fires {@link RoomEvent.LocalEchoUpdated}
*/
addPendingEvent(event, txnId) {
if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) throw new Error("addPendingEvent called on an event with status " + event.status);
if (this.txnToEvent.get(txnId)) throw new Error("addPendingEvent called on an event with known txnId " + txnId);
EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS), false);
this.txnToEvent.set(txnId, event);
if (this.pendingEventList) {
if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {
logger$2.warn("Setting event as NOT_SENT due to messages in the same state");
event.setStatus(EventStatus.NOT_SENT);
}
this.pendingEventList.push(event);
this.savePendingEvents();
if (event.isRelation()) this.aggregateNonLiveRelation(event);
if (event.isRedaction()) {
var redactId = event.event.redacts;
var redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);
if (!redactedEvent && redactId) redactedEvent = this.findEventById(redactId);
if (redactedEvent) {
redactedEvent.markLocallyRedacted(event);
this.emit(RoomEvent.Redaction, event, this, redactedEvent.threadRootId);
}
}
} else for (var timelineSet of this.timelineSets) if (timelineSet.getFilter()) {
if (timelineSet.getFilter().filterRoomTimeline([event]).length) timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
toStartOfTimeline: false,
addToState: false
});
} else timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
toStartOfTimeline: false,
addToState: false
});
this.emit(RoomEvent.LocalEchoUpdated, event, this);
}
/**
* Persists all pending events to local storage
*
* If the current room is encrypted only encrypted events will be persisted
* all messages that are not yet encrypted will be discarded
*
* This is because the flow of EVENT_STATUS transition is
* `queued => sending => encrypting => sending => sent`
*
* Steps 3 and 4 are skipped for unencrypted room.
* It is better to discard an unencrypted message rather than persisting
* it locally for everyone to read
*/
savePendingEvents() {
if (this.pendingEventList) {
var pendingEvents = this.pendingEventList.map((event) => {
return _objectSpread$13(_objectSpread$13({}, event.event), {}, { txn_id: event.getTxnId() });
}).filter((event) => {
var isEventEncrypted = event.type === EventType.RoomMessageEncrypted;
var isRoomEncrypted = this.hasEncryptionStateEvent();
return isEventEncrypted || !isRoomEncrypted;
});
this.client.store.setPendingEvents(this.roomId, pendingEvents);
}
}
/**
* Used to aggregate the local echo for a relation, and also
* for re-applying a relation after it's redaction has been cancelled,
* as the local echo for the redaction of the relation would have
* un-aggregated the relation. Note that this is different from regular messages,
* which are just kept detached for their local echo.
*
* Also note that live events are aggregated in the live EventTimelineSet.
* @param event - the relation event that needs to be aggregated.
*/
aggregateNonLiveRelation(event) {
this.relations.aggregateChildEvent(event);
}
getEventForTxnId(txnId) {
return this.txnToEvent.get(txnId);
}
/**
* Deal with the echo of a message we sent.
*
* <p>We move the event to the live timeline if it isn't there already, and
* update it.
*
* @param remoteEvent - The event received from
* /sync
* @param localEvent - The local echo, which
* should be either in the pendingEventList or the timeline.
*
* @internal
*
* @remarks
* Fires {@link RoomEvent.LocalEchoUpdated}
*/
handleRemoteEcho(remoteEvent, localEvent) {
var oldEventId = localEvent.getId();
var newEventId = remoteEvent.getId();
var oldStatus = localEvent.status;
logger$2.debug("Got remote echo for event ".concat(oldEventId, " -> ").concat(newEventId, " old status ").concat(oldStatus));
this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id);
if (this.pendingEventList) this.removePendingEvent(oldEventId);
localEvent.handleRemoteEcho(remoteEvent.event);
var { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);
var thread = threadId ? this.getThread(threadId) : null;
thread === null || thread === void 0 || thread.setEventMetadata(localEvent);
thread === null || thread === void 0 || thread.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
if (shouldLiveInRoom) for (var timelineSet of this.timelineSets) timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);
}
/**
* Update the status / event id on a pending event, to reflect its transmission
* progress.
*
* <p>This is an internal method.
*
* @param event - local echo event
* @param newStatus - status to assign
* @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.
*
* @remarks
* Fires {@link RoomEvent.LocalEchoUpdated}
*/
updatePendingEvent(event, newStatus, newEventId) {
logger$2.log("setting pendingEvent status to ".concat(newStatus, " in ").concat(event.getRoomId(), " ") + "event ID ".concat(event.getId(), " -> ").concat(newEventId));
if (newStatus == EventStatus.SENT && !newEventId) throw new Error("updatePendingEvent called with status=SENT, but no new event id");
if (newStatus == EventStatus.SENT) {
if (this.getTimelineForEvent(newEventId)) {
var remoteEvent = this.findEventById(newEventId);
if (!(remoteEvent === null || remoteEvent === void 0 ? void 0 : remoteEvent.getUnsigned().transaction_id) && remoteEvent) {
var unsigned = remoteEvent.getUnsigned();
unsigned.transaction_id = event.getTxnId();
remoteEvent.setUnsigned(unsigned);
this.removeEvent(remoteEvent.getId());
this.handleRemoteEcho(remoteEvent, event);
}
return;
}
}
var oldStatus = event.status;
var oldEventId = event.getId();
if (!oldStatus) throw new Error("updatePendingEventStatus called on an event which is not a local echo.");
var allowed = ALLOWED_TRANSITIONS[oldStatus];
if (!(allowed !== null && allowed !== void 0 && allowed.includes(newStatus))) throw new Error("Invalid EventStatus transition ".concat(oldStatus, "->").concat(newStatus));
event.setStatus(newStatus);
if (newStatus == EventStatus.SENT) {
event.replaceLocalEventId(newEventId);
var { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);
var thread = threadId ? this.getThread(threadId) : void 0;
thread === null || thread === void 0 || thread.setEventMetadata(event);
thread === null || thread === void 0 || thread.timelineSet.replaceEventId(oldEventId, newEventId);
if (shouldLiveInRoom) for (var timelineSet of this.timelineSets) timelineSet.replaceEventId(oldEventId, newEventId);
} else if (newStatus == EventStatus.CANCELLED) {
if (this.pendingEventList) {
var removedEvent = this.getPendingEvent(oldEventId);
this.removePendingEvent(oldEventId);
if (removedEvent !== null && removedEvent !== void 0 && removedEvent.isRedaction()) this.revertRedactionLocalEcho(removedEvent);
}
this.removeEvent(oldEventId);
}
this.savePendingEvents();
this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);
}
revertRedactionLocalEcho(redactionEvent) {
var redactId = redactionEvent.event.redacts;
if (!redactId) return;
var redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
if (redactedEvent) {
redactedEvent.unmarkLocallyRedacted();
this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);
if (redactedEvent.isRelation()) this.aggregateNonLiveRelation(redactedEvent);
}
}
assertTimelineSetsAreLive() {
for (var i = 0; i < this.timelineSets.length; i++) {
var liveTimeline = this.timelineSets[i].getLiveTimeline();
if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) throw new Error("live timeline " + i + " is no longer live - it has a pagination token (" + liveTimeline.getPaginationToken(EventTimeline.FORWARDS) + ")");
if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) throw new Error("live timeline ".concat(i, " is no longer live - it has a neighbouring timeline"));
}
}
/**
* Add some events to this room. This can include state events, message
* events and typing notifications. These events are treated as "live" so
* they will go to the end of the timeline.
*
* @param events - A list of events to add.
* @param addLiveEventOptions - addLiveEvent options
* @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.
*/
addLiveEvents(events, addLiveEventOptions) {
var _this15 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { duplicateStrategy, fromCache, timelineWasEmpty = false, addToState } = addLiveEventOptions;
if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");
_this15.assertTimelineSetsAreLive();
var threadRoots = _this15.findThreadRoots(events);
var eventsByThread = {};
var options = {
duplicateStrategy,
fromCache,
timelineWasEmpty,
addToState
};
var neighbouringEvents = [...events];
for (var event of events) {
var _eventsByThread$threa;
_this15.processLiveEvent(event);
if (event.getUnsigned().transaction_id) {
var existingEvent = _this15.txnToEvent.get(event.getUnsigned().transaction_id);
if (existingEvent) {
_this15.handleRemoteEcho(event, existingEvent);
continue;
}
}
var { shouldLiveInRoom, shouldLiveInThread, threadId = "" } = _this15.eventShouldLiveIn(event, neighbouringEvents, threadRoots);
if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) try {
var parentEvent = new MatrixEvent(yield _this15.client.fetchRoomEvent(_this15.roomId, event.relationEventId));
neighbouringEvents.push(parentEvent);
if (parentEvent.threadRootId) {
threadRoots.add(parentEvent.threadRootId);
var unsigned = event.getUnsigned();
unsigned[UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;
event.setUnsigned(unsigned);
}
({shouldLiveInRoom, shouldLiveInThread, threadId = ""} = _this15.eventShouldLiveIn(event, neighbouringEvents, threadRoots));
} catch (e) {
logger$2.error("Failed to load parent event of unhandled relation", e);
}
if (shouldLiveInThread && !eventsByThread[threadId]) eventsByThread[threadId] = [];
(_eventsByThread$threa = eventsByThread[threadId]) === null || _eventsByThread$threa === void 0 || _eventsByThread$threa.push(event);
if (shouldLiveInRoom) _this15.addLiveEvent(event, options);
else if (!shouldLiveInThread && event.isRelation()) _this15.relations.aggregateChildEvent(event);
}
Object.entries(eventsByThread).forEach((_ref5) => {
var [threadId, threadEvents] = _ref5;
_this15.addThreadedEvents(threadId, threadEvents, false);
});
})();
}
partitionThreadedEvents(events) {
var ROOM = 0;
var THREAD = 1;
var UNKNOWN_RELATION = 2;
if (this.client.supportsThreads()) {
var threadRoots = this.findThreadRoots(events);
return events.reduce((memo, event) => {
var { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(event, events, threadRoots);
if (shouldLiveInRoom) memo[ROOM].push(event);
if (shouldLiveInThread) {
event.setThreadId(threadId !== null && threadId !== void 0 ? threadId : "");
memo[THREAD].push(event);
}
if (!shouldLiveInThread && !shouldLiveInRoom) memo[UNKNOWN_RELATION].push(event);
return memo;
}, [
[],
[],
[]
]);
} else return [
events,
[],
[]
];
}
/**
* Given some events, find the IDs of all the thread roots that are referred to by them.
*/
findThreadRoots(events) {
var threadRoots = /* @__PURE__ */ new Set();
for (var event of events) {
var threadRootId = event.threadRootId;
if (threadRootId != void 0) threadRoots.add(threadRootId);
}
return threadRoots;
}
/**
* Add a receipt event to the room.
* @param event - The m.receipt event.
* @param synthetic - True if this event is implicit.
*/
addReceipt(event) {
var synthetic = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var content = event.getContent();
this.roomReceipts.add(content, synthetic);
Object.keys(content).forEach((eventId) => {
Object.keys(content[eventId]).forEach((receiptType) => {
Object.keys(content[eventId][receiptType]).forEach((userId) => {
var _receipt$thread_id, _this$unthreadedRecei, _this$unthreadedRecei2;
var receipt = content[eventId][receiptType][userId];
var receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === "main";
var receiptDestination = receiptForMainTimeline ? this : this.threads.get((_receipt$thread_id = receipt.thread_id) !== null && _receipt$thread_id !== void 0 ? _receipt$thread_id : "");
if (receiptDestination) {
receiptDestination.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);
if (!synthetic && this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {
var lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];
if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {
receiptDestination.setUnread(NotificationCountType.Total, 0);
receiptDestination.setUnread(NotificationCountType.Highlight, 0);
}
}
} else {
var _this$cachedThreadRea2;
this.cachedThreadReadReceipts.set(receipt.thread_id, [...(_this$cachedThreadRea2 = this.cachedThreadReadReceipts.get(receipt.thread_id)) !== null && _this$cachedThreadRea2 !== void 0 ? _this$cachedThreadRea2 : [], {
eventId,
receiptType,
userId,
receipt,
synthetic
}]);
}
if (userId === this.client.getUserId() && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) this.oldestThreadedReceiptTs = receipt.ts;
if (!receipt.thread_id && receipt.ts > ((_this$unthreadedRecei = (_this$unthreadedRecei2 = this.unthreadedReceipts.get(userId)) === null || _this$unthreadedRecei2 === void 0 ? void 0 : _this$unthreadedRecei2.ts) !== null && _this$unthreadedRecei !== void 0 ? _this$unthreadedRecei : 0)) this.unthreadedReceipts.set(userId, receipt);
});
});
});
this.emit(RoomEvent.Receipt, event, this);
}
/**
* Adds/handles ephemeral events such as typing notifications and read receipts.
* @param events - A list of events to process
*/
addEphemeralEvents(events) {
for (var event of events) if (event.getType() === EventType.Typing) this.currentState.setTypingEvent(event);
else if (event.getType() === EventType.Receipt) this.addReceipt(event);
}
/**
* Removes events from this room.
* @param eventIds - A list of eventIds to remove.
*/
removeEvents(eventIds) {
for (var eventId of eventIds) this.removeEvent(eventId);
}
/**
* Removes a single event from this room.
*
* @param eventId - The id of the event to remove
*
* @returns true if the event was removed from any of the room's timeline sets
*/
removeEvent(eventId) {
var removedAny = false;
for (var timelineSet of this.timelineSets) {
var removed = timelineSet.removeEvent(eventId);
if (removed) {
if (removed.isRedaction()) this.revertRedactionLocalEcho(removed);
removedAny = true;
}
}
return removedAny;
}
/**
* Recalculate various aspects of the room, including the room name and
* room summary. Call this any time the room's current state is modified.
* May fire "Room.name" if the room name is updated.
*
* @remarks
* Fires {@link RoomEvent.Name}
*/
recalculate() {
var membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);
if (membershipEvent) {
var membership = membershipEvent.getContent().membership;
this.updateMyMembership(membership);
if (membership === KnownMembership.Invite) (membershipEvent.getUnsigned().invite_room_state || []).forEach((strippedEvent) => {
if (!this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key)) this.currentState.setStateEvents([new MatrixEvent({
type: strippedEvent.type,
state_key: strippedEvent.state_key,
content: strippedEvent.content,
event_id: "$fake" + Date.now(),
room_id: this.roomId,
sender: this.myUserId
})]);
});
}
var oldName = this.name;
this.name = this.calculateRoomName(this.myUserId);
this.normalizedName = normalize(this.name);
this.summary = new RoomSummary(this.roomId, { title: this.name });
if (oldName !== this.name) this.emit(RoomEvent.Name, this);
}
/**
* Update the room-tag event for the room. The previous one is overwritten.
* @param event - the m.tag event
*/
addTags(event) {
this.tags = event.getContent().tags || {};
this.emit(RoomEvent.Tags, event, this);
}
/**
* Update the account_data events for this room, overwriting events of the same type.
* @param events - an array of account_data events to add
*/
addAccountData(events) {
for (var event of events) {
if (event.getType() === "m.tag") this.addTags(event);
var eventType = event.getType();
var lastEvent = this.accountData.get(eventType);
this.accountData.set(eventType, event);
this.emit(RoomEvent.AccountData, event, this, lastEvent);
}
}
/**
* Access account_data event of given event type for this room
* @param type - the type of account_data event to be accessed
* @returns the account_data event in question
*/
getAccountData(type) {
return this.accountData.get(type);
}
/**
* Get an iterator of currently active sticky events.
*/
_unstable_getStickyEvents() {
return this.stickyEvents.getStickyEvents();
}
/**
* Get a sticky event that match the given `type`, `sender`, and `stickyKey`
* @param type The event `type`.
* @param sender The sender of the sticky event.
* @param stickyKey The sticky key used by the event.
* @returns A matching active sticky event, or undefined.
*/
_unstable_getKeyedStickyEvent(sender, type, stickyKey) {
return this.stickyEvents.getKeyedStickyEvent(sender, type, stickyKey);
}
/**
* Get active sticky events without a sticky key that match the given `type` and `sender`.
* @param type The event `type`.
* @param sender The sender of the sticky event.
* @returns An array of matching sticky events.
*/
_unstable_getUnkeyedStickyEvent(sender, type) {
return this.stickyEvents.getUnkeyedStickyEvent(sender, type);
}
/**
* Add a series of sticky events, emitting `RoomEvent.StickyEvents` if any
* changes were made.
* @param events A set of new sticky events.
* @internal
*/
_unstable_addStickyEvents(events) {
return this.stickyEvents.addStickyEvents(events);
}
/**
* Returns whether the syncing user has permission to send a message in the room
* @returns true if the user should be permitted to send
* message events into the room.
*/
maySendMessage() {
return this.getMyMembership() === KnownMembership.Join && (this.hasEncryptionStateEvent() ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId) : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId));
}
/**
* Returns whether the given user has permissions to issue an invite for this room.
* @param userId - the ID of the Matrix user to check permissions for
* @returns true if the user should be permitted to issue invites for this room.
*/
canInvite(userId) {
var canInvite = this.getMyMembership() === KnownMembership.Join;
var powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, "");
var powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();
var me = this.getMember(userId);
if (powerLevels && me && powerLevels.invite > me.powerLevel) canInvite = false;
return canInvite;
}
/**
* Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
* @returns the join_rule applied to this room
*/
getJoinRule() {
return this.currentState.getJoinRule();
}
/**
* Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
* @returns the history_visibility applied to this room
*/
getHistoryVisibility() {
return this.currentState.getHistoryVisibility();
}
/**
* Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
* @returns the history_visibility applied to this room
*/
getGuestAccess() {
return this.currentState.getGuestAccess();
}
/**
* Returns the type of the room from the `m.room.create` event content or undefined if none is set
* @returns the type of the room.
*/
getType() {
var createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
if (!createEvent) {
if (!this.getTypeWarning) {
logger$2.warn("[getType] Room " + this.roomId + " does not have an m.room.create event");
this.getTypeWarning = true;
}
return;
}
return createEvent.getContent()[RoomCreateTypeField];
}
/**
* Returns whether the room is a space-room as defined by MSC1772.
* @returns true if the room's type is RoomType.Space
*/
isSpaceRoom() {
return this.getType() === RoomType.Space;
}
/**
* Returns whether the room is a call-room as defined by MSC3417.
* @returns true if the room's type is RoomType.UnstableCall
*/
isCallRoom() {
return this.getType() === RoomType.UnstableCall;
}
/**
* Returns whether the room is a video room.
* @returns true if the room's type is RoomType.ElementVideo
*/
isElementVideoRoom() {
return this.getType() === RoomType.ElementVideo;
}
/**
* Find the predecessor of this room.
*
* @param msc3946ProcessDynamicPredecessor - if true, look for an
* m.room.predecessor state event and use it if found (MSC3946).
* @returns null if this room has no predecessor. Otherwise, returns
* the roomId, last eventId and viaServers of the predecessor room.
*
* If msc3946ProcessDynamicPredecessor is true, use m.predecessor events
* as well as m.room.create events to find predecessors.
*
* Note: if an m.predecessor event is used, eventId may be undefined
* since last_known_event_id is optional.
*
* Note: viaServers may be undefined, and will definitely be undefined if
* this predecessor comes from a RoomCreate event (rather than a
* RoomPredecessor, which has the optional via_servers property).
*/
findPredecessor() {
var msc3946ProcessDynamicPredecessor = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
var currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);
if (!currentState) return null;
return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);
}
roomNameGenerator(state) {
if (this.client.roomNameGenerator) {
var name = this.client.roomNameGenerator(this.roomId, state);
if (name !== null) return name;
}
switch (state.type) {
case RoomNameType.Actual: return state.name;
case RoomNameType.Generated: switch (state.subtype) {
case "Inviting": return "Inviting ".concat(memberNamesToRoomName(state.names, state.count));
default: return memberNamesToRoomName(state.names, state.count);
}
case RoomNameType.EmptyRoom: if (state.oldName) return "Empty room (was ".concat(state.oldName, ")");
else return "Empty room";
}
}
/**
* This is an internal method. Calculates the name of the room from the current
* room state.
* @param userId - The client's user ID. Used to filter room members
* correctly.
* @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there
* was no m.room.name event.
* @returns The calculated room name.
*/
calculateRoomName(userId) {
if (!(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false)) {
var _this$currentState$ge4;
var name = (_this$currentState$ge4 = this.currentState.getStateEvents(EventType.RoomName, "")) === null || _this$currentState$ge4 === void 0 ? void 0 : _this$currentState$ge4.getContent().name;
if (name && typeof name === "string") return this.roomNameGenerator({
type: RoomNameType.Actual,
name
});
}
var alias = this.getCanonicalAlias();
if (alias) return this.roomNameGenerator({
type: RoomNameType.Actual,
name: alias
});
var inviteJoinCount = this.currentState.getJoinedMemberCount() + this.currentState.getInvitedMemberCount() - 1;
var excludedUserIds = this.getFunctionalMembers();
var otherNames = [];
if (this.heroes) this.heroes.forEach((hero) => {
if (excludedUserIds.includes(hero.userId)) {
inviteJoinCount--;
return;
}
if (hero.displayName) otherNames.push(hero.displayName);
else {
var member = this.getMember(hero.userId);
otherNames.push(member ? member.name : hero.userId);
}
});
else {
var otherMembers = this.currentState.getMembers().filter((m) => {
return m.userId !== userId && (m.membership === KnownMembership.Invite || m.membership === KnownMembership.Join);
});
otherMembers = otherMembers.filter((_ref6) => {
var { userId } = _ref6;
if (excludedUserIds.includes(userId)) {
inviteJoinCount--;
return false;
}
return true;
});
var collator = new Intl.Collator();
otherMembers.sort((a, b) => collator.compare(a.userId, b.userId));
otherMembers = otherMembers.slice(0, 5);
otherNames = otherMembers.map((m) => m.name);
}
if (inviteJoinCount) return this.roomNameGenerator({
type: RoomNameType.Generated,
names: otherNames,
count: inviteJoinCount
});
if (this.getMyMembership() == KnownMembership.Join) {
var thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);
if (thirdPartyInvites !== null && thirdPartyInvites !== void 0 && thirdPartyInvites.length) {
var thirdPartyNames = thirdPartyInvites.map((i) => {
return i.getContent().display_name;
});
return this.roomNameGenerator({
type: RoomNameType.Generated,
subtype: "Inviting",
names: thirdPartyNames,
count: thirdPartyNames.length + 1
});
}
}
var leftNames = otherNames;
if (!leftNames.length) leftNames = this.currentState.getMembers().filter((m) => {
return m.userId !== userId && m.membership !== KnownMembership.Invite && m.membership !== KnownMembership.Join;
}).map((m) => m.name);
var oldName;
if (leftNames.length) oldName = this.roomNameGenerator({
type: RoomNameType.Generated,
names: leftNames,
count: leftNames.length + 1
});
return this.roomNameGenerator({
type: RoomNameType.EmptyRoom,
oldName
});
}
/**
* When we receive a new visibility change event:
*
* - store this visibility change alongside the timeline, in case we
* later need to apply it to an event that we haven't received yet;
* - if we have already received the event whose visibility has changed,
* patch it to reflect the visibility change and inform listeners.
*/
applyNewVisibilityEvent(event) {
var visibilityChange = event.asVisibilityChange();
if (!visibilityChange) return;
var userId = event.getSender();
if (!userId) return;
if (!(EVENT_VISIBILITY_CHANGE_TYPE.name && this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId) || EVENT_VISIBILITY_CHANGE_TYPE.altName && this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId))) return;
var visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);
if (visibilityEventsOnOriginalEvent) {
var index = visibilityEventsOnOriginalEvent.length - 1;
var min = Math.max(0, visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH);
for (; index >= min; --index) if (visibilityEventsOnOriginalEvent[index].getTs() < event.getTs()) break;
if (index === -1) visibilityEventsOnOriginalEvent.unshift(event);
else visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);
} else this.visibilityEvents.set(visibilityChange.eventId, [event]);
var originalEvent = this.findEventById(visibilityChange.eventId);
if (!originalEvent) return;
originalEvent.applyVisibilityEvent(visibilityChange);
}
redactVisibilityChangeEvent(event) {
if (!event.isVisibilityEvent) throw new Error("expected a visibility change event");
var relation = event.getRelation();
var originalEventId = relation === null || relation === void 0 ? void 0 : relation.event_id;
var visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId);
if (!visibilityEventsOnOriginalEvent) return;
var index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());
if (index === -1) return;
visibilityEventsOnOriginalEvent.splice(index, 1);
if (index === visibilityEventsOnOriginalEvent.length) {
var originalEvent = this.findEventById(originalEventId);
if (!originalEvent) return;
if (index === 0) {
this.visibilityEvents.delete(originalEventId);
originalEvent.applyVisibilityEvent();
} else {
var newVisibility = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1].asVisibilityChange();
if (!newVisibility) throw new Error("at this stage, visibility changes should be well-formed");
originalEvent.applyVisibilityEvent(newVisibility);
}
}
}
/**
* When we receive an event whose visibility has been altered by
* a (more recent) visibility change event, patch the event in
* place so that clients now not to display it.
*
* @param event - Any matrix event. If this event has at least one a
* pending visibility change event, apply the latest visibility
* change event.
*/
applyPendingVisibilityEvents(event) {
var visibilityEvents = this.visibilityEvents.get(event.getId());
if (!visibilityEvents || visibilityEvents.length == 0) return;
var visibilityEvent = visibilityEvents[visibilityEvents.length - 1];
var visibilityChange = visibilityEvent.asVisibilityChange();
if (!visibilityChange) return;
if (visibilityChange.visible) {}
if (visibilityEvent.getTs() < event.getTs()) return;
event.applyVisibilityEvent(visibilityChange);
}
/**
* Find when a client has gained thread capabilities by inspecting the oldest
* threaded receipt
* @returns the timestamp of the oldest threaded receipt
*/
getOldestThreadedReceiptTs() {
return this.oldestThreadedReceiptTs;
}
/**
* Determines if the given user has read a particular event ID with the known
* history of the room. This is not a definitive check as it relies only on
* what is available to the room at the time of execution.
*
* @param userId - The user ID to check the read state of.
* @param eventId - The event ID to check if the user read.
* @returns true if the user has read the event, false otherwise.
*/
hasUserReadEvent(userId, eventId) {
return this.roomReceipts.hasUserReadEvent(userId, eventId);
}
/**
* Returns the most recent unthreaded receipt for a given user
* @param userId - the MxID of the User
* @returns an unthreaded Receipt. Can be undefined if receipts have been disabled
* or a user chooses to use private read receipts (or we have simply not received
* a receipt from this user yet).
*/
getLastUnthreadedReceiptFor(userId) {
return this.unthreadedReceipts.get(userId);
}
/**
* This issue should also be addressed on synapse's side and is tracked as part
* of https://github.com/matrix-org/synapse/issues/14837
*
*
* We consider a room fully read if the current user has sent
* the last event in the live timeline of that context and if the read receipt
* we have on record matches.
* This also detects all unread threads and applies the same logic to those
* contexts
*/
fixupNotifications(userId) {
super.fixupNotifications(userId);
for (var thread of this.getThreads().filter((thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0)) thread.fixupNotifications(userId);
}
/**
* Determine the order of two events in this room.
*
* In principle this should use the same order as the server, but in practice
* this is difficult for events that were not received over the Sync API. See
* MSC4033 for details.
*
* This implementation leans on the order of events within their timelines, and
* falls back to comparing event timestamps when they are in different
* timelines.
*
* See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are
* tracking the work to fix this.
*
* @param leftEventId - the id of the first event
* @param rightEventId - the id of the second event
* @returns -1 if left \< right, 1 if left \> right, 0 if left == right, null if
* we can't tell (because we can't find the events).
*/
compareEventOrdering(leftEventId, rightEventId) {
return compareEventOrdering(this, leftEventId, rightEventId);
}
/**
* Return true if this room has an `m.room.encryption` state event.
*
* If this returns `true`, events sent to this room should be encrypted (and `MatrixClient.sendEvent` and friends
* will encrypt outgoing events).
*/
hasEncryptionStateEvent() {
var _this$getLiveTimeline;
return Boolean((_this$getLiveTimeline = this.getLiveTimeline().getState(EventTimeline.FORWARDS)) === null || _this$getLiveTimeline === void 0 ? void 0 : _this$getLiveTimeline.getStateEvents(EventType.RoomEncryption, ""));
}
};
var ALLOWED_TRANSITIONS = {
[EventStatus.ENCRYPTING]: [
EventStatus.SENDING,
EventStatus.NOT_SENT,
EventStatus.CANCELLED
],
[EventStatus.SENDING]: [
EventStatus.ENCRYPTING,
EventStatus.QUEUED,
EventStatus.NOT_SENT,
EventStatus.SENT
],
[EventStatus.QUEUED]: [
EventStatus.SENDING,
EventStatus.NOT_SENT,
EventStatus.CANCELLED
],
[EventStatus.SENT]: [],
[EventStatus.NOT_SENT]: [
EventStatus.SENDING,
EventStatus.QUEUED,
EventStatus.CANCELLED
],
[EventStatus.CANCELLED]: []
};
var RoomNameType = /* @__PURE__ */ function(RoomNameType) {
RoomNameType[RoomNameType["EmptyRoom"] = 0] = "EmptyRoom";
RoomNameType[RoomNameType["Generated"] = 1] = "Generated";
RoomNameType[RoomNameType["Actual"] = 2] = "Actual";
return RoomNameType;
}({});
function memberNamesToRoomName(names, count) {
var countWithoutMe = count - 1;
if (!names.length) return "Empty room";
else if (names.length === 1 && countWithoutMe <= 1) return names[0];
else if (names.length === 2 && countWithoutMe <= 2) return "".concat(names[0], " and ").concat(names[1]);
else if (countWithoutMe > 1) return "".concat(names[0], " and ").concat(countWithoutMe, " others");
else return "".concat(names[0], " and 1 other");
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/feature.js
var ServerSupport = /* @__PURE__ */ function(ServerSupport) {
ServerSupport[ServerSupport["Stable"] = 0] = "Stable";
ServerSupport[ServerSupport["Unstable"] = 1] = "Unstable";
ServerSupport[ServerSupport["Unsupported"] = 2] = "Unsupported";
return ServerSupport;
}({});
var Feature = /* @__PURE__ */ function(Feature) {
Feature["Thread"] = "Thread";
Feature["ThreadUnreadNotifications"] = "ThreadUnreadNotifications";
/**
* @deprecated this is now exposed as a capability not a feature
*/
Feature["LoginTokenRequest"] = "LoginTokenRequest";
Feature["RelationBasedRedactions"] = "RelationBasedRedactions";
Feature["AccountDataDeletion"] = "AccountDataDeletion";
Feature["RelationsRecursion"] = "RelationsRecursion";
Feature["IntentionalMentions"] = "IntentionalMentions";
return Feature;
}({});
var featureSupportResolver = {
[Feature.Thread]: {
unstablePrefixes: ["org.matrix.msc3440"],
matrixVersion: "v1.3"
},
[Feature.ThreadUnreadNotifications]: {
unstablePrefixes: ["org.matrix.msc3771", "org.matrix.msc3773"],
matrixVersion: "v1.4"
},
[Feature.LoginTokenRequest]: { unstablePrefixes: ["org.matrix.msc3882"] },
[Feature.RelationBasedRedactions]: { unstablePrefixes: ["org.matrix.msc3912"] },
[Feature.AccountDataDeletion]: { unstablePrefixes: ["org.matrix.msc3391"] },
[Feature.RelationsRecursion]: {
unstablePrefixes: ["org.matrix.msc3981"],
matrixVersion: "v1.10"
},
[Feature.IntentionalMentions]: {
unstablePrefixes: ["org.matrix.msc3952_intentional_mentions"],
matrixVersion: "v1.7"
}
};
function buildFeatureSupportMap(_x) {
return _buildFeatureSupportMap.apply(this, arguments);
}
function _buildFeatureSupportMap() {
_buildFeatureSupportMap = (0, import_asyncToGenerator.default)(function* (versions) {
var supportMap = /* @__PURE__ */ new Map();
for (var [feature, supportCondition] of Object.entries(featureSupportResolver)) {
var _versions$versions$in, _versions$versions, _supportCondition$uns, _supportCondition$uns2;
var supportMatrixVersion = (_versions$versions$in = (_versions$versions = versions.versions) === null || _versions$versions === void 0 ? void 0 : _versions$versions.includes(supportCondition.matrixVersion || "")) !== null && _versions$versions$in !== void 0 ? _versions$versions$in : false;
var supportUnstablePrefixes = (_supportCondition$uns = (_supportCondition$uns2 = supportCondition.unstablePrefixes) === null || _supportCondition$uns2 === void 0 ? void 0 : _supportCondition$uns2.every((unstablePrefix) => {
var _versions$unstable_fe;
return ((_versions$unstable_fe = versions.unstable_features) === null || _versions$unstable_fe === void 0 ? void 0 : _versions$unstable_fe[unstablePrefix]) === true;
})) !== null && _supportCondition$uns !== void 0 ? _supportCondition$uns : false;
if (supportMatrixVersion) supportMap.set(feature, ServerSupport.Stable);
else if (supportUnstablePrefixes) supportMap.set(feature, ServerSupport.Unstable);
else supportMap.set(feature, ServerSupport.Unsupported);
}
return supportMap;
});
return _buildFeatureSupportMap.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/sync.js
function ownKeys$12(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;
}
function _objectSpread$12(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$12(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$12(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var BUFFER_PERIOD_MS$1 = 80 * 1e3;
var FAILED_SYNC_ERROR_THRESHOLD$1 = 3;
var SyncState = /* @__PURE__ */ function(SyncState) {
/** Emitted after we try to sync more than `FAILED_SYNC_ERROR_THRESHOLD`
* times and are still failing. Or when we enounter a hard error like the
* token being invalid. */
SyncState["Error"] = "ERROR";
/** Emitted after the first sync events are ready (this could even be sync
* events from the cache) */
SyncState["Prepared"] = "PREPARED";
/** Emitted when the sync loop is no longer running */
SyncState["Stopped"] = "STOPPED";
/** Emitted after each sync request happens */
SyncState["Syncing"] = "SYNCING";
/** Emitted after a connectivity error and we're ready to start syncing again */
SyncState["Catchup"] = "CATCHUP";
/** Emitted for each time we try reconnecting. Will switch to `Error` after
* we reach the `FAILED_SYNC_ERROR_THRESHOLD`
*/
SyncState["Reconnecting"] = "RECONNECTING";
return SyncState;
}({});
var MSC2716_ROOM_VERSIONS = ["org.matrix.msc2716v3"];
function getFilterName(userId, suffix) {
return "FILTER_SYNC_".concat(userId) + (suffix ? "_" + suffix : "");
}
/**
* Options passed into the constructor of SyncApi by MatrixClient
*/
var SetPresence = /* @__PURE__ */ function(SetPresence) {
SetPresence["Offline"] = "offline";
SetPresence["Online"] = "online";
SetPresence["Unavailable"] = "unavailable";
return SetPresence;
}({});
/** add default settings to an IStoredClientOpts */
function defaultClientOpts(opts) {
return _objectSpread$12({
initialSyncLimit: 8,
resolveInvitesToProfiles: false,
pollTimeout: 30 * 1e3,
pendingEventOrdering: PendingEventOrdering.Chronological,
threadSupport: false
}, opts);
}
function defaultSyncApiOpts(syncOpts) {
return _objectSpread$12({ canResetEntireTimeline: (_roomId) => false }, syncOpts);
}
var SyncApi = class {
/**
* Construct an entity which is able to sync with a homeserver.
* @param client - The matrix client instance to use.
* @param opts - client config options
* @param syncOpts - sync-specific options passed by the client
* @internal
*/
constructor(client, opts, syncOpts) {
var _this = this;
this.client = client;
(0, import_defineProperty.default)(this, "opts", void 0);
(0, import_defineProperty.default)(this, "syncOpts", void 0);
(0, import_defineProperty.default)(this, "_peekRoom", null);
(0, import_defineProperty.default)(this, "currentSyncRequest", void 0);
(0, import_defineProperty.default)(this, "abortController", void 0);
(0, import_defineProperty.default)(this, "syncState", null);
(0, import_defineProperty.default)(this, "syncStateData", void 0);
(0, import_defineProperty.default)(this, "catchingUp", false);
(0, import_defineProperty.default)(this, "running", false);
(0, import_defineProperty.default)(this, "keepAliveTimer", void 0);
(0, import_defineProperty.default)(this, "connectionReturnedResolvers", void 0);
(0, import_defineProperty.default)(this, "notifEvents", []);
(0, import_defineProperty.default)(this, "failedSyncCount", 0);
(0, import_defineProperty.default)(this, "storeIsInvalid", false);
(0, import_defineProperty.default)(this, "presence", void 0);
(0, import_defineProperty.default)(this, "getPushRules", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
try {
_this.syncOpts.logger.debug("Getting push rules...");
var result = yield _this.client.getPushRules();
_this.syncOpts.logger.debug("Got push rules");
_this.client.pushRules = result;
} catch (err) {
_this.syncOpts.logger.error("Getting push rules failed", err);
if (_this.shouldAbortSync(err)) return;
_this.syncOpts.logger.debug("Waiting for saved sync before retrying push rules...");
yield _this.recoverFromSyncStartupError(_this.savedSyncPromise, err);
return _this.getPushRules();
}
}));
(0, import_defineProperty.default)(this, "buildDefaultFilter", () => {
var filter = new Filter(this.client.credentials.userId);
if (this.client.canSupport.get(Feature.ThreadUnreadNotifications) !== ServerSupport.Unsupported) filter.setUnreadThreadNotifications(true);
return filter;
});
(0, import_defineProperty.default)(this, "prepareLazyLoadingForSync", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
_this.syncOpts.logger.debug("Prepare lazy loading for sync...");
if (_this.client.isGuest()) _this.opts.lazyLoadMembers = false;
if (_this.opts.lazyLoadMembers) {
_this.syncOpts.logger.debug("Enabling lazy load on sync filter...");
if (!_this.opts.filter) _this.opts.filter = _this.buildDefaultFilter();
_this.opts.filter.setLazyLoadMembers(true);
}
}));
(0, import_defineProperty.default)(this, "storeClientOptions", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
try {
_this.syncOpts.logger.debug("Storing client options...");
yield _this.client.storeClientOptions();
_this.syncOpts.logger.debug("Stored client options");
} catch (err) {
_this.syncOpts.logger.error("Storing client options failed", err);
throw err;
}
}));
(0, import_defineProperty.default)(this, "getFilter", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
_this.syncOpts.logger.debug("Getting filter...");
var filter;
if (_this.opts.filter) filter = _this.opts.filter;
else filter = _this.buildDefaultFilter();
var filterId;
try {
filterId = yield _this.client.getOrCreateFilter(getFilterName(_this.client.credentials.userId), filter);
} catch (err) {
_this.syncOpts.logger.error("Getting filter failed", err);
if (_this.shouldAbortSync(err)) return {};
_this.syncOpts.logger.debug("Waiting for saved sync before retrying filter...");
yield _this.recoverFromSyncStartupError(_this.savedSyncPromise, err);
return _this.getFilter();
}
return {
filter,
filterId
};
}));
(0, import_defineProperty.default)(this, "savedSyncPromise", void 0);
/**
* Event handler for the 'online' event
* This event is generally unreliable and precise behaviour
* varies between browsers, so we poll for connectivity too,
* but this might help us reconnect a little faster.
*/
(0, import_defineProperty.default)(this, "onOnline", () => {
this.syncOpts.logger.debug("Browser thinks we are back online");
this.startKeepAlives(0);
});
this.opts = defaultClientOpts(opts);
this.syncOpts = defaultSyncApiOpts(syncOpts);
if (client.getNotifTimelineSet()) client.reEmitter.reEmit(client.getNotifTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);
}
createRoom(roomId) {
var room = _createAndReEmitRoom(this.client, roomId, this.opts);
room.on(RoomStateEvent.Marker, (markerEvent, markerFoundOptions) => {
this.onMarkerStateEvent(room, markerEvent, markerFoundOptions);
});
return room;
}
/** When we see the marker state change in the room, we know there is some
* new historical messages imported by MSC2716 `/batch_send` somewhere in
* the room and we need to throw away the timeline to make sure the
* historical messages are shown when we paginate `/messages` again.
* @param room - The room where the marker event was sent
* @param markerEvent - The new marker event
* @param setStateOptions - When `timelineWasEmpty` is set
* as `true`, the given marker event will be ignored
*/
onMarkerStateEvent(room, markerEvent) {
var { timelineWasEmpty } = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
if (timelineWasEmpty) {
this.syncOpts.logger.debug("MarkerState: Ignoring markerEventId=".concat(markerEvent.getId(), " in roomId=").concat(room.roomId, " ") + "because the timeline was empty before the marker arrived which means there is nothing to refresh.");
return;
}
if (MSC2716_ROOM_VERSIONS.includes(room.getVersion()) || markerEvent.getSender() === room.getCreator()) {
this.syncOpts.logger.debug("MarkerState: Timeline needs to be refreshed because " + "a new markerEventId=".concat(markerEvent.getId(), " was sent in roomId=").concat(room.roomId));
room.setTimelineNeedsRefresh(true);
room.emit(RoomEvent.HistoryImportedWithinTimeline, markerEvent, room);
} else this.syncOpts.logger.debug("MarkerState: Ignoring markerEventId=".concat(markerEvent.getId(), " in roomId=").concat(room.roomId, " because ") + "MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.");
}
/**
* Sync rooms the user has left.
* @returns Resolved when they've been added to the store.
*/
syncLeftRooms() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _data$rooms;
var client = _this2.client;
var filter = new Filter(_this2.client.credentials.userId);
filter.setTimelineLimit(1);
filter.setIncludeLeaveRooms(true);
var localTimeoutMs = _this2.opts.pollTimeout + BUFFER_PERIOD_MS$1;
var filterId = yield client.getOrCreateFilter(getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter);
var qps = {
"timeout": 0,
"filter": filterId,
"org.matrix.msc4222.use_state_after": true
};
var data = yield client.http.authedRequest(Method.Get, "/sync", qps, void 0, { localTimeoutMs });
var leaveRooms = [];
if ((_data$rooms = data.rooms) !== null && _data$rooms !== void 0 && _data$rooms.leave) leaveRooms = _this2.mapSyncResponseToRoomArray(data.rooms.leave);
return (yield Promise.all(leaveRooms.map(/* @__PURE__ */ function() {
var _ref5 = (0, import_asyncToGenerator.default)(function* (leaveObj) {
var room = leaveObj.room;
if (!leaveObj.isBrandNewRoom) return;
leaveObj.timeline = leaveObj.timeline || {
prev_batch: null,
events: []
};
room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, EventTimeline.BACKWARDS);
var { timelineEvents } = yield _this2.mapAndInjectRoomEvents(leaveObj);
room.recalculate();
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
_this2.processEventsForNotifs(room, timelineEvents);
return room;
});
return function(_x) {
return _ref5.apply(this, arguments);
};
}()))).filter(Boolean);
})();
}
/**
* Peek into a room. This will result in the room in question being synced so it
* is accessible via getRooms(). Live updates for the room will be provided.
* @param roomId - The room ID to peek into.
* @param limit - The number of timeline events to initially retrieve.
* @returns A promise which resolves once the room has been added to the
* store.
*/
peek(roomId) {
var _this$_peekRoom;
var limit = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
if (((_this$_peekRoom = this._peekRoom) === null || _this$_peekRoom === void 0 ? void 0 : _this$_peekRoom.roomId) === roomId) return Promise.resolve(this._peekRoom);
var client = this.client;
this._peekRoom = this.createRoom(roomId);
return this.client.roomInitialSync(roomId, limit).then((response) => {
var _this$_peekRoom2;
if (((_this$_peekRoom2 = this._peekRoom) === null || _this$_peekRoom2 === void 0 ? void 0 : _this$_peekRoom2.roomId) !== roomId) throw new Error("Peeking aborted");
response.messages = response.messages || { chunk: [] };
response.messages.chunk = response.messages.chunk || [];
response.state = response.state || [];
var oldStateEvents = deepCopy(response.state).map(client.getEventMapper());
var stateEvents = response.state.map(client.getEventMapper());
var messages = response.messages.chunk.map(client.getEventMapper());
if (Array.isArray(response.presence)) response.presence.map(client.getEventMapper()).forEach(function(presenceEvent) {
var user = client.store.getUser(presenceEvent.getContent().user_id);
if (user) user.setPresenceEvent(presenceEvent);
else {
user = User.createUser(presenceEvent.getContent().user_id, client);
user.setPresenceEvent(presenceEvent);
client.store.storeUser(user);
}
client.emit(ClientEvent.Event, presenceEvent);
});
if (response.messages.start) this._peekRoom.oldState.paginationToken = response.messages.start;
this._peekRoom.oldState.setStateEvents(oldStateEvents);
this._peekRoom.currentState.setStateEvents(stateEvents);
this.resolveInvites(this._peekRoom);
this._peekRoom.recalculate();
this._peekRoom.addEventsToTimeline(messages.reverse(), true, true, this._peekRoom.getLiveTimeline(), response.messages.start);
client.store.storeRoom(this._peekRoom);
client.emit(ClientEvent.Room, this._peekRoom);
this.peekPoll(this._peekRoom);
return this._peekRoom;
});
}
/**
* Stop polling for updates in the peeked room. NOPs if there is no room being
* peeked.
*/
stopPeeking() {
this._peekRoom = null;
}
/**
* Do a peek room poll.
* @param token - from= token
*/
peekPoll(peekRoom, token) {
var _this$abortController, _this3 = this;
if (this._peekRoom !== peekRoom) {
this.syncOpts.logger.debug("Stopped peeking in room %s", peekRoom.roomId);
return;
}
this.client.http.authedRequest(Method.Get, "/events", {
room_id: peekRoom.roomId,
timeout: String(30 * 1e3),
from: token
}, void 0, {
localTimeoutMs: 50 * 1e3,
abortSignal: (_this$abortController = this.abortController) === null || _this$abortController === void 0 ? void 0 : _this$abortController.signal
}).then(/* @__PURE__ */ function() {
var _ref6 = (0, import_asyncToGenerator.default)(function* (res) {
if (_this3._peekRoom !== peekRoom) {
_this3.syncOpts.logger.debug("Stopped peeking in room %s", peekRoom.roomId);
return;
}
res.chunk.filter(function(e) {
return e.type === "m.presence";
}).map(_this3.client.getEventMapper()).forEach((presenceEvent) => {
var user = _this3.client.store.getUser(presenceEvent.getContent().user_id);
if (user) user.setPresenceEvent(presenceEvent);
else {
user = User.createUser(presenceEvent.getContent().user_id, _this3.client);
user.setPresenceEvent(presenceEvent);
_this3.client.store.storeUser(user);
}
_this3.client.emit(ClientEvent.Event, presenceEvent);
});
var events = res.chunk.filter(function(e) {
return e.room_id === peekRoom.roomId && e.event_id;
}).map(_this3.client.getEventMapper());
yield peekRoom.addLiveEvents(events, { addToState: true });
_this3.peekPoll(peekRoom, res.end);
});
return function(_x2) {
return _ref6.apply(this, arguments);
};
}(), (err) => {
this.syncOpts.logger.error("[%s] Peek poll failed: %s", peekRoom.roomId, err);
setTimeout(() => {
this.peekPoll(peekRoom, token);
}, 30 * 1e3);
});
}
/**
* Returns the current state of this sync object
* @see MatrixClient#event:"sync"
*/
getSyncState() {
return this.syncState;
}
/**
* Returns the additional data object associated with
* the current sync state, or null if there is no
* such data.
* Sync errors, if available, are put in the 'error' key of
* this object.
*/
getSyncStateData() {
var _this$syncStateData;
return (_this$syncStateData = this.syncStateData) !== null && _this$syncStateData !== void 0 ? _this$syncStateData : null;
}
recoverFromSyncStartupError(savedSyncPromise, error) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield savedSyncPromise;
var keepaliveProm = _this4.startKeepAlives();
_this4.updateSyncState(SyncState.Error, { error });
yield keepaliveProm;
})();
}
shouldAbortSync(error) {
if (error.errcode === "M_UNKNOWN_TOKEN") {
this.syncOpts.logger.warn("Token no longer valid - assuming logout");
this.stop();
this.updateSyncState(SyncState.Error, { error });
return true;
}
return false;
}
/**
* Main entry point
*/
sync() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _globalThis$window, _globalThis$window$ad;
_this5.running = true;
_this5.abortController = new AbortController();
(_globalThis$window = globalThis.window) === null || _globalThis$window === void 0 || (_globalThis$window$ad = _globalThis$window.addEventListener) === null || _globalThis$window$ad === void 0 || _globalThis$window$ad.call(_globalThis$window, "online", _this5.onOnline, false);
if (_this5.client.isGuest()) return _this5.doSync({});
_this5.syncOpts.logger.debug("Getting saved sync token...");
var savedSyncTokenPromise = _this5.client.store.getSavedSyncToken().then((tok) => {
_this5.syncOpts.logger.debug("Got saved sync token");
return tok;
});
_this5.savedSyncPromise = _this5.client.store.getSavedSync().then((savedSync) => {
_this5.syncOpts.logger.debug("Got reply from saved sync, exists? ".concat(!!savedSync));
if (savedSync) return _this5.syncFromCache(savedSync);
}).catch((err) => {
_this5.syncOpts.logger.error("Getting saved sync failed", err);
});
yield _this5.getPushRules();
yield _this5.prepareLazyLoadingForSync();
yield _this5.storeClientOptions();
var { filterId, filter } = yield _this5.getFilter();
if (!filter) return;
_this5.client.resetNotifTimelineSet();
if (!_this5.currentSyncRequest) {
var firstSyncFilter = filterId;
var savedSyncToken = yield savedSyncTokenPromise;
if (savedSyncToken) _this5.syncOpts.logger.debug("Sending first sync request...");
else {
_this5.syncOpts.logger.debug("Sending initial sync request...");
var initialFilter = _this5.buildDefaultFilter();
initialFilter.setDefinition(filter.getDefinition());
initialFilter.setTimelineLimit(_this5.opts.initialSyncLimit);
firstSyncFilter = JSON.stringify(initialFilter.getDefinition());
}
_this5.currentSyncRequest = _this5.doSyncRequest({ filter: firstSyncFilter }, savedSyncToken);
}
_this5.syncOpts.logger.debug("Waiting for saved sync before starting sync processing...");
yield _this5.savedSyncPromise;
return _this5.doSync({ filter: filterId });
})();
}
/**
* Stops the sync object from syncing.
*/
stop() {
var _globalThis$window2, _globalThis$window2$r, _this$abortController2;
this.syncOpts.logger.debug("SyncApi.stop");
(_globalThis$window2 = globalThis.window) === null || _globalThis$window2 === void 0 || (_globalThis$window2$r = _globalThis$window2.removeEventListener) === null || _globalThis$window2$r === void 0 || _globalThis$window2$r.call(_globalThis$window2, "online", this.onOnline, false);
this.running = false;
(_this$abortController2 = this.abortController) === null || _this$abortController2 === void 0 || _this$abortController2.abort();
if (this.keepAliveTimer) {
clearTimeout(this.keepAliveTimer);
this.keepAliveTimer = void 0;
}
}
/**
* Retry a backed off syncing request immediately. This should only be used when
* the user <b>explicitly</b> attempts to retry their lost connection.
* @returns True if this resulted in a request being retried.
*/
retryImmediately() {
if (!this.connectionReturnedResolvers) return false;
this.startKeepAlives(0);
return true;
}
/**
* Process a single set of cached sync data.
* @param savedSync - a saved sync that was persisted by a store. This
* should have been acquired via client.store.getSavedSync().
*/
syncFromCache(savedSync) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
_this6.syncOpts.logger.debug("sync(): not doing HTTP hit, instead returning stored /sync data");
var nextSyncToken = savedSync.nextBatch;
_this6.client.store.setSyncToken(nextSyncToken);
var syncEventData = {
nextSyncToken,
catchingUp: false,
fromCache: true
};
var data = {
next_batch: nextSyncToken,
rooms: savedSync.roomsData,
account_data: { events: savedSync.accountData }
};
try {
yield _this6.processSyncResponse(syncEventData, data);
} catch (e) {
_this6.syncOpts.logger.error("Error processing cached sync", e);
}
if (!_this6.storeIsInvalid) _this6.updateSyncState(SyncState.Prepared, syncEventData);
})();
}
/**
* Invoke me to do /sync calls
*/
doSync(syncOptions) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
while (_this7.running) {
var syncToken = _this7.client.store.getSyncToken();
var data = void 0;
try {
if (!_this7.currentSyncRequest) _this7.currentSyncRequest = _this7.doSyncRequest(syncOptions, syncToken);
data = yield _this7.currentSyncRequest;
} catch (e) {
if (yield _this7.onSyncError(e)) return;
continue;
} finally {
_this7.currentSyncRequest = void 0;
}
_this7.client.store.setSyncToken(data.next_batch);
_this7.failedSyncCount = 0;
var syncEventData = {
oldSyncToken: syncToken !== null && syncToken !== void 0 ? syncToken : void 0,
nextSyncToken: data.next_batch,
catchingUp: _this7.catchingUp
};
try {
yield _this7.processSyncResponse(syncEventData, data);
} catch (e) {
_this7.syncOpts.logger.error("Caught /sync error", e);
_this7.client.emit(ClientEvent.SyncUnexpectedError, e);
}
yield _this7.client.store.setSyncData(data);
syncEventData.catchingUp = _this7.catchingUp;
if (!syncOptions.hasSyncedBefore) {
_this7.updateSyncState(SyncState.Prepared, syncEventData);
syncOptions.hasSyncedBefore = true;
}
if (_this7.syncOpts.cryptoCallbacks) yield _this7.syncOpts.cryptoCallbacks.onSyncCompleted(syncEventData);
_this7.updateSyncState(SyncState.Syncing, syncEventData);
if (_this7.client.store.wantsSave()) yield _this7.client.store.save();
}
if (!_this7.running) {
_this7.syncOpts.logger.debug("Sync no longer running: exiting.");
if (_this7.connectionReturnedResolvers) {
_this7.connectionReturnedResolvers.reject();
_this7.connectionReturnedResolvers = void 0;
}
_this7.updateSyncState(SyncState.Stopped);
}
})();
}
doSyncRequest(syncOptions, syncToken) {
var _this$abortController3;
var qps = this.getSyncParams(syncOptions, syncToken);
return this.client.http.authedRequest(Method.Get, "/sync", qps, void 0, {
localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS$1,
abortSignal: (_this$abortController3 = this.abortController) === null || _this$abortController3 === void 0 ? void 0 : _this$abortController3.signal
});
}
getSyncParams(syncOptions, syncToken) {
var timeout = this.opts.pollTimeout;
if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) {
this.catchingUp = true;
timeout = 0;
}
var filter = syncOptions.filter;
if (this.client.isGuest() && !filter) filter = this.getGuestFilter();
var qps = {
filter,
timeout,
"org.matrix.msc4222.use_state_after": true
};
if (this.opts.disablePresence) qps.set_presence = SetPresence.Offline;
else if (this.presence !== void 0) qps.set_presence = this.presence;
if (syncToken) qps.since = syncToken;
else qps._cacheBuster = Date.now();
if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState())) qps.timeout = 0;
return qps;
}
/**
* Specify the set_presence value to be used for subsequent calls to the Sync API.
* @param presence - the presence to specify to set_presence of sync calls
*/
setPresence(presence) {
this.presence = presence;
}
onSyncError(err) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this8.running) {
_this8.syncOpts.logger.debug("Sync no longer running: exiting");
if (_this8.connectionReturnedResolvers) {
_this8.connectionReturnedResolvers.reject();
_this8.connectionReturnedResolvers = void 0;
}
_this8.updateSyncState(SyncState.Stopped);
return true;
}
_this8.syncOpts.logger.error("/sync error %s", err);
if (_this8.shouldAbortSync(err)) return true;
_this8.failedSyncCount++;
_this8.syncOpts.logger.debug("Number of consecutive failed sync requests:", _this8.failedSyncCount);
_this8.syncOpts.logger.debug("Starting keep-alive");
var keepAlivePromise = _this8.startKeepAlives();
_this8.currentSyncRequest = void 0;
_this8.updateSyncState(_this8.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD$1 ? SyncState.Error : SyncState.Reconnecting, { error: err });
if ((yield keepAlivePromise) && _this8.getSyncState() === SyncState.Error) _this8.updateSyncState(SyncState.Catchup, { catchingUp: true });
return false;
})();
}
/**
* Process data returned from a sync response and propagate it
* into the model objects
*
* @param syncEventData - Object containing sync tokens associated with this sync
* @param data - The response from /sync
*/
processSyncResponse(syncEventData, data) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _data$presence, _data$account_data, _this9$syncOpts$crypt, _data$device_unused_f;
var client = _this9.client;
if (Array.isArray((_data$presence = data.presence) === null || _data$presence === void 0 ? void 0 : _data$presence.events)) data.presence.events.filter(noUnsafeEventProps).map(client.getEventMapper()).forEach(function(presenceEvent) {
var user = client.store.getUser(presenceEvent.getSender());
if (user) user.setPresenceEvent(presenceEvent);
else {
user = User.createUser(presenceEvent.getSender(), client);
user.setPresenceEvent(presenceEvent);
client.store.storeUser(user);
}
client.emit(ClientEvent.Event, presenceEvent);
});
if (Array.isArray((_data$account_data = data.account_data) === null || _data$account_data === void 0 ? void 0 : _data$account_data.events)) {
var events = data.account_data.events.filter(noUnsafeEventProps).map(client.getEventMapper());
var prevEventsMap = events.reduce((m, c) => {
m[c.getType()] = client.store.getAccountData(c.getType());
return m;
}, {});
client.store.storeAccountDataEvents(events);
events.forEach(function(accountDataEvent) {
if (accountDataEvent.getType() === EventType.PushRules) {
var rules = accountDataEvent.getContent();
client.setPushRules(rules);
}
var prevEvent = prevEventsMap[accountDataEvent.getType()];
client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);
return accountDataEvent;
});
}
if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) {
var toDeviceMessages = data.to_device.events.filter(noUnsafeEventProps);
var receivedToDeviceMessages;
if (_this9.syncOpts.cryptoCallbacks) receivedToDeviceMessages = yield _this9.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(toDeviceMessages);
else receivedToDeviceMessages = toDeviceMessages.map((rawEvent) => ({
message: rawEvent,
encryptionInfo: null
}));
processToDeviceMessages(receivedToDeviceMessages, client);
} else _this9.catchingUp = false;
var inviteRooms = [];
var joinRooms = [];
var leaveRooms = [];
var knockRooms = [];
if (data.rooms) {
if (data.rooms.invite) inviteRooms = _this9.mapSyncResponseToRoomArray(data.rooms.invite);
if (data.rooms.join) joinRooms = _this9.mapSyncResponseToRoomArray(data.rooms.join);
if (data.rooms.leave) leaveRooms = _this9.mapSyncResponseToRoomArray(data.rooms.leave);
if (data.rooms.knock) knockRooms = _this9.mapSyncResponseToRoomArray(data.rooms.knock);
}
_this9.notifEvents = [];
yield Promise.all(inviteRooms.map(/* @__PURE__ */ function() {
var _ref7 = (0, import_asyncToGenerator.default)(function* (inviteObj) {
var room = inviteObj.room;
var stateEvents = _this9.mapSyncEventsFormat(inviteObj.invite_state, room);
yield _this9.injectRoomEvents(room, stateEvents, void 0);
if (inviteObj.isBrandNewRoom) {
room.recalculate();
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
} else room.recalculate();
stateEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
});
return function(_x3) {
return _ref7.apply(this, arguments);
};
}()));
yield Promise.all(joinRooms.map(/* @__PURE__ */ function() {
var _ref8 = (0, import_asyncToGenerator.default)(function* (joinObj) {
var _joinObj$UNREAD_THREA;
var room = joinObj.room;
var stateEvents = _this9.mapSyncEventsFormat(joinObj.state, room);
var stateAfterEvents = _this9.mapSyncEventsFormat(joinObj["org.matrix.msc4222.state_after"], room);
var timelineEvents = _this9.mapSyncEventsFormat(joinObj.timeline, room, false);
var ephemeralEvents = _this9.mapSyncEventsFormat(joinObj.ephemeral);
var accountDataEvents = _this9.mapSyncEventsFormat(joinObj.account_data);
var stickyEvents = _this9.mapSyncEventsFormat(joinObj.msc4354_sticky);
var eventsFormingFinalState = joinObj["org.matrix.msc4222.state_after"] ? stateAfterEvents : stateEvents.concat(timelineEvents);
var encrypted = _this9.isRoomEncrypted(room, eventsFormingFinalState);
if (joinObj.unread_notifications) {
/**
* We track unread notifications ourselves in encrypted rooms, so don't
* bother setting it here. We trust our calculations better than the
* server's for this case, and therefore will assume that our non-zero
* count is accurate.
* XXX: this is known faulty as the push rule for `.m.room.encrypted` may be disabled so server
* may issue notification counts of 0 which we wrongly trust.
* https://github.com/matrix-org/matrix-spec-proposals/pull/2654 would fix this
*
* @see import("./client").fixNotificationCountOnDecryption
*/
if (!encrypted || joinObj.unread_notifications.notification_count === 0) {
var _joinObj$unread_notif;
room.setUnreadNotificationCount(NotificationCountType.Total, (_joinObj$unread_notif = joinObj.unread_notifications.notification_count) !== null && _joinObj$unread_notif !== void 0 ? _joinObj$unread_notif : 0);
}
if (!encrypted || room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {
var _joinObj$unread_notif2;
room.setUnreadNotificationCount(NotificationCountType.Highlight, (_joinObj$unread_notif2 = joinObj.unread_notifications.highlight_count) !== null && _joinObj$unread_notif2 !== void 0 ? _joinObj$unread_notif2 : 0);
}
}
var unreadThreadNotifications = (_joinObj$UNREAD_THREA = joinObj[UNREAD_THREAD_NOTIFICATIONS.name]) !== null && _joinObj$UNREAD_THREA !== void 0 ? _joinObj$UNREAD_THREA : joinObj[UNREAD_THREAD_NOTIFICATIONS.altName];
if (unreadThreadNotifications) {
room.resetThreadUnreadNotificationCountFromSync(Object.keys(unreadThreadNotifications));
for (var [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) {
if (!encrypted || unreadNotification.notification_count === 0) {
var _unreadNotification$n;
room.setThreadUnreadNotificationCount(threadId, NotificationCountType.Total, (_unreadNotification$n = unreadNotification.notification_count) !== null && _unreadNotification$n !== void 0 ? _unreadNotification$n : 0);
}
var hasNoNotifications = room.getThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight) <= 0;
if (!encrypted || encrypted && hasNoNotifications) {
var _unreadNotification$h;
room.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, (_unreadNotification$h = unreadNotification.highlight_count) !== null && _unreadNotification$h !== void 0 ? _unreadNotification$h : 0);
}
}
} else room.resetThreadUnreadNotificationCountFromSync();
joinObj.timeline = joinObj.timeline || {};
if (joinObj.isBrandNewRoom) {
if (joinObj.timeline.prev_batch !== null) room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);
} else if (joinObj.timeline.limited) {
var limited = true;
for (var i = timelineEvents.length - 1; i >= 0; i--) {
var eventId = timelineEvents[i].getId();
if (room.getTimelineForEvent(eventId)) {
_this9.syncOpts.logger.debug("Already have event ".concat(eventId, " in limited sync - not resetting"));
limited = false;
timelineEvents.splice(0, i);
break;
}
}
if (limited) {
var _syncEventData$oldSyn;
room.resetLiveTimeline(joinObj.timeline.prev_batch, _this9.syncOpts.canResetEntireTimeline(room.roomId) ? null : (_syncEventData$oldSyn = syncEventData.oldSyncToken) !== null && _syncEventData$oldSyn !== void 0 ? _syncEventData$oldSyn : null);
client.resetNotifTimelineSet();
}
}
if (_this9.syncOpts.cryptoCallbacks) {
for (var e of eventsFormingFinalState) if (e.isState() && e.getType() === EventType.RoomEncryption && e.getStateKey() === "") yield _this9.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);
}
for (var ev of timelineEvents.filter((ev) => ev.isState())) yield _this9.client.decryptEventIfNeeded(ev);
try {
if ("org.matrix.msc4222.state_after" in joinObj) yield _this9.injectRoomEvents(room, void 0, stateAfterEvents, timelineEvents, syncEventData.fromCache);
else yield _this9.injectRoomEvents(room, stateEvents, void 0, timelineEvents, syncEventData.fromCache);
} catch (e) {
_this9.syncOpts.logger.error("Failed to process events on room ".concat(room.roomId, ":"), e);
}
if (joinObj.summary) room.setSummary(joinObj.summary);
room.addEphemeralEvents(ephemeralEvents);
room.addAccountData(accountDataEvents);
var stickyEventsAndStickyEventsFromTheTimeline = stickyEvents.concat(timelineEvents.filter((e) => e.unstableStickyInfo !== void 0));
room._unstable_addStickyEvents(stickyEventsAndStickyEventsFromTheTimeline);
room.recalculate();
if (joinObj.isBrandNewRoom) {
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
}
_this9.processEventsForNotifs(room, timelineEvents);
var emitEvent = (e) => client.emit(ClientEvent.Event, e);
stateEvents.forEach(emitEvent);
timelineEvents.forEach(emitEvent);
ephemeralEvents.forEach(emitEvent);
accountDataEvents.forEach(emitEvent);
stickyEvents.filter((stickyEvent) => !timelineEvents.some((timelineEvent) => timelineEvent.getId() === stickyEvent.getId())).forEach(emitEvent);
room.decryptCriticalEvents();
});
return function(_x4) {
return _ref8.apply(this, arguments);
};
}()));
yield Promise.all(leaveRooms.map(/* @__PURE__ */ function() {
var _ref9 = (0, import_asyncToGenerator.default)(function* (leaveObj) {
var room = leaveObj.room;
var { timelineEvents, stateEvents, stateAfterEvents } = yield _this9.mapAndInjectRoomEvents(leaveObj);
var accountDataEvents = _this9.mapSyncEventsFormat(leaveObj.account_data);
room.addAccountData(accountDataEvents);
room.recalculate();
if (leaveObj.isBrandNewRoom) {
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
}
_this9.processEventsForNotifs(room, timelineEvents);
stateEvents === null || stateEvents === void 0 || stateEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
stateAfterEvents === null || stateAfterEvents === void 0 || stateAfterEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
timelineEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
accountDataEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
});
return function(_x5) {
return _ref9.apply(this, arguments);
};
}()));
yield Promise.all(knockRooms.map(/* @__PURE__ */ function() {
var _ref0 = (0, import_asyncToGenerator.default)(function* (knockObj) {
var room = knockObj.room;
var stateEvents = _this9.mapSyncEventsFormat(knockObj.knock_state, room);
yield _this9.injectRoomEvents(room, stateEvents, void 0);
if (knockObj.isBrandNewRoom) {
room.recalculate();
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
} else room.recalculate();
stateEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
});
return function(_x6) {
return _ref0.apply(this, arguments);
};
}()));
if (syncEventData.oldSyncToken && _this9.notifEvents.length) {
_this9.notifEvents.sort(function(a, b) {
return a.getTs() - b.getTs();
});
_this9.notifEvents.forEach(function(event) {
var _client$getNotifTimel;
(_client$getNotifTimel = client.getNotifTimelineSet()) === null || _client$getNotifTimel === void 0 || _client$getNotifTimel.addLiveEvent(event, { addToState: true });
});
}
if (data.device_lists) {
if (_this9.syncOpts.cryptoCallbacks) yield _this9.syncOpts.cryptoCallbacks.processDeviceLists(data.device_lists);
}
yield (_this9$syncOpts$crypt = _this9.syncOpts.cryptoCallbacks) === null || _this9$syncOpts$crypt === void 0 ? void 0 : _this9$syncOpts$crypt.processKeyCounts(data.device_one_time_keys_count, (_data$device_unused_f = data.device_unused_fallback_key_types) !== null && _data$device_unused_f !== void 0 ? _data$device_unused_f : data["org.matrix.msc2732.device_unused_fallback_key_types"]);
})();
}
/**
* Starts polling the connectivity check endpoint
* @param delay - How long to delay until the first poll.
* defaults to a short, randomised interval (to prevent
* tight-looping if /versions succeeds but /sync etc. fail).
* @returns which resolves once the connection returns
*/
startKeepAlives(delay) {
if (delay === void 0) delay = 2e3 + Math.floor(Math.random() * 5e3);
if (this.keepAliveTimer !== null) clearTimeout(this.keepAliveTimer);
if (delay > 0) this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);
else this.pokeKeepAlive();
if (!this.connectionReturnedResolvers) this.connectionReturnedResolvers = Promise.withResolvers();
return this.connectionReturnedResolvers.promise;
}
/**
* Make a dummy call to /_matrix/client/versions, to see if the HS is
* reachable.
*
* On failure, schedules a call back to itself. On success, resolves
* this.connectionReturnedResolvers.
*
* @param connDidFail - True if a connectivity failure has been detected. Optional.
*/
pokeKeepAlive() {
var _this$abortController4;
var connDidFail = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
if (!this.running) {
clearTimeout(this.keepAliveTimer);
if (this.connectionReturnedResolvers) {
this.connectionReturnedResolvers.reject("SyncApi.stop() was called");
this.connectionReturnedResolvers = void 0;
}
return;
}
var success = () => {
clearTimeout(this.keepAliveTimer);
if (this.connectionReturnedResolvers) {
this.connectionReturnedResolvers.resolve(connDidFail);
this.connectionReturnedResolvers = void 0;
}
};
this.client.http.request(Method.Get, "/_matrix/client/versions", void 0, void 0, {
prefix: "",
localTimeoutMs: 15 * 1e3,
abortSignal: (_this$abortController4 = this.abortController) === null || _this$abortController4 === void 0 ? void 0 : _this$abortController4.signal
}).then(() => {
success();
}, (err) => {
if (err.httpStatus == 400 || err.httpStatus == 404) this.keepAliveTimer = setTimeout(success, 2e3);
else {
connDidFail = true;
this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this, connDidFail), 5e3 + Math.floor(Math.random() * 5e3));
this.updateSyncState(SyncState.Error, { error: err });
}
});
}
mapSyncResponseToRoomArray(obj) {
var client = this.client;
return Object.keys(obj).filter((k) => !unsafeProp(k)).map((roomId) => {
var room = client.store.getRoom(roomId);
var isBrandNewRoom = false;
if (!room) {
room = this.createRoom(roomId);
isBrandNewRoom = true;
}
return _objectSpread$12(_objectSpread$12({}, obj[roomId]), {}, {
room,
isBrandNewRoom
});
});
}
mapSyncEventsFormat(obj, room) {
var decrypt = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
if (!obj || !Array.isArray(obj.events)) return [];
var mapper = this.client.getEventMapper({ decrypt });
return obj.events.filter(noUnsafeEventProps).map(function(e) {
if (room) e.room_id = room.roomId;
return mapper(e);
});
}
/**
*/
resolveInvites(room) {
if (!room || !this.opts.resolveInvitesToProfiles) return;
var client = this.client;
room.getMembersWithMembership(KnownMembership.Invite).forEach(function(member) {
if (member.requestedProfileInfo) return;
member.requestedProfileInfo = true;
var user = client.getUser(member.userId);
var promise;
if (user) promise = Promise.resolve({
avatar_url: user.avatarUrl,
displayname: user.displayName
});
else promise = client.getProfileInfo(member.userId);
promise.then(function(info) {
var inviteEvent = member.events.member;
if ((inviteEvent === null || inviteEvent === void 0 ? void 0 : inviteEvent.getContent().membership) !== KnownMembership.Invite) return;
inviteEvent.getContent().avatar_url = info.avatar_url;
inviteEvent.getContent().displayname = info.displayname;
member.setMembershipEvent(inviteEvent, room.currentState);
}, function(err) {});
});
}
findEncryptionEvent(events) {
return events === null || events === void 0 ? void 0 : events.find((e) => e.getType() === EventType.RoomEncryption && e.getStateKey() === "");
}
isRoomEncrypted(room, eventsFormingFinalState) {
return room.hasEncryptionStateEvent() || !!this.findEncryptionEvent(eventsFormingFinalState);
}
mapAndInjectRoomEvents(wrappedRoom) {
var _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
var stateEvents = _this0.mapSyncEventsFormat(wrappedRoom.state, wrappedRoom.room);
var stateAfterEvents = _this0.mapSyncEventsFormat(wrappedRoom["org.matrix.msc4222.state_after"], wrappedRoom.room);
var timelineEvents = _this0.mapSyncEventsFormat(wrappedRoom.timeline, wrappedRoom.room);
if ("org.matrix.msc4222.state_after" in wrappedRoom) yield _this0.injectRoomEvents(wrappedRoom.room, void 0, stateAfterEvents, timelineEvents);
else yield _this0.injectRoomEvents(wrappedRoom.room, stateEvents, void 0, timelineEvents);
return {
timelineEvents,
stateEvents,
stateAfterEvents
};
})();
}
/**
* Injects events into a room's model.
* @param stateEventList - A list of state events. This is the state
* at the *START* of the timeline list if it is supplied.
* @param stateAfterEventList - A list of state events. This is the state
* at the *END* of the timeline list if it is supplied.
* @param timelineEventList - A list of timeline events, including threaded. Lower index
* is earlier in time. Higher index is later.
* @param fromCache - whether the sync response came from cache
*
* No more than one of stateEventList and stateAfterEventList must be supplied. If
* stateEventList is supplied, the events in timelineEventList are added to the state
* after stateEventList. If stateAfterEventList is supplied, the events in timelineEventList
* are not added to the state.
*/
injectRoomEvents(room, stateEventList, stateAfterEventList, timelineEventList) {
var _arguments = arguments, _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
var fromCache = _arguments.length > 4 && _arguments[4] !== void 0 ? _arguments[4] : false;
var eitherStateEventList = stateAfterEventList !== null && stateAfterEventList !== void 0 ? stateAfterEventList : stateEventList;
var liveTimeline = room.getLiveTimeline();
var timelineWasEmpty = liveTimeline.getEvents().length == 0;
if (timelineWasEmpty) {
for (var ev of eitherStateEventList) _this1.client.getPushActionsForEvent(ev);
liveTimeline.initialiseState(eitherStateEventList, { timelineWasEmpty });
}
_this1.resolveInvites(room);
room.recalculate();
if (!timelineWasEmpty) {
room.oldState.setStateEvents(eitherStateEventList);
room.currentState.setStateEvents(eitherStateEventList);
}
yield room.addLiveEvents(timelineEventList || [], {
fromCache,
timelineWasEmpty,
addToState: stateAfterEventList === void 0
});
_this1.client.processBeaconEvents(room, timelineEventList);
})();
}
/**
* Takes a list of timelineEvents and adds and adds to notifEvents
* as appropriate.
* This must be called after the room the events belong to has been stored.
*
* @param timelineEventList - A list of timeline events. Lower index
* is earlier in time. Higher index is later.
*/
processEventsForNotifs(room, timelineEventList) {
if (this.client.getNotifTimelineSet()) for (var event of timelineEventList) {
var _pushActions$tweaks;
var pushActions = this.client.getPushActionsForEvent(event);
if (pushActions !== null && pushActions !== void 0 && pushActions.notify && (_pushActions$tweaks = pushActions.tweaks) !== null && _pushActions$tweaks !== void 0 && _pushActions$tweaks.highlight) this.notifEvents.push(event);
}
}
getGuestFilter() {
return "{}";
}
/**
* Sets the sync state and emits an event to say so
* @param newState - The new state string
* @param data - Object of additional data to emit in the event
*/
updateSyncState(newState, data) {
var old = this.syncState;
this.syncState = newState;
this.syncStateData = data;
this.client.emit(ClientEvent.Sync, this.syncState, old, data);
}
};
function _createAndReEmitRoom(client, roomId, opts) {
var { timelineSupport } = client;
var room = new Room(roomId, client, client.getUserId(), {
lazyLoadMembers: opts.lazyLoadMembers,
pendingEventOrdering: opts.pendingEventOrdering,
timelineSupport
});
client.reEmitter.reEmit(room, [
RoomEvent.Name,
RoomEvent.Redaction,
RoomEvent.RedactionCancelled,
RoomEvent.Receipt,
RoomEvent.Tags,
RoomEvent.LocalEchoUpdated,
RoomEvent.AccountData,
RoomEvent.MyMembership,
RoomEvent.Timeline,
RoomEvent.TimelineReset,
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update,
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange
]);
room.on(RoomStateEvent.NewMember, (event, state, member) => {
var _client$getUser;
member.user = (_client$getUser = client.getUser(member.userId)) !== null && _client$getUser !== void 0 ? _client$getUser : void 0;
client.reEmitter.reEmit(member, [
RoomMemberEvent.Name,
RoomMemberEvent.Typing,
RoomMemberEvent.PowerLevel,
RoomMemberEvent.Membership
]);
});
return room;
}
/**
* Process a list of (decrypted, where possible) received to-device events.
*
* Emits the appropriate {@link ClientEvent.ReceivedToDeviceMessage} event.
* Also converts the events into `MatrixEvent`s, and emits the now deprecated {@link ClientEvent.ToDeviceEvent} events for compatibility.
* */
function processToDeviceMessages(toDeviceMessages, client) {
var cancelledKeyVerificationTxns = [];
toDeviceMessages.map((processedMessage) => {
if (processedMessage.message.type === "m.key.verification.cancel") {
var txnId = processedMessage.message.content["transaction_id"];
if (txnId) cancelledKeyVerificationTxns.push(txnId);
}
return processedMessage;
}).forEach(function(processedEvent) {
var toDeviceEvent = processedEvent.message;
var content = toDeviceEvent.content;
var deprecatedCompatibilityEvent = new MatrixEvent(Object.assign({}, toDeviceEvent));
if (toDeviceEvent.type === "m.key.verification.start" || toDeviceEvent.type === "m.key.verification.request") {
var txnId = content["transaction_id"];
if (cancelledKeyVerificationTxns.includes(txnId)) deprecatedCompatibilityEvent.flagCancelled();
}
if (processedEvent.encryptionInfo) deprecatedCompatibilityEvent.makeEncrypted(EventType.RoomMessageEncrypted, { ciphertext: "" }, processedEvent.encryptionInfo.senderCurve25519KeyBase64, "");
client.emit(ClientEvent.ToDeviceEvent, deprecatedCompatibilityEvent);
client.emit(ClientEvent.ReceivedToDeviceMessage, processedEvent);
});
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/store/stub.js
/**
* This is an internal module.
*/
/**
* Construct a stub store. This does no-ops on most store methods.
*/
var StubStore = class {
constructor() {
(0, import_defineProperty.default)(this, "accountData", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "fromToken", null);
}
/** @returns whether or not the database was newly created in this session. */
isNewlyCreated() {
return Promise.resolve(true);
}
/**
* Get the sync token.
*/
getSyncToken() {
return this.fromToken;
}
/**
* Set the sync token.
*/
setSyncToken(token) {
this.fromToken = token;
}
/**
* No-op.
*/
storeRoom(room) {}
/**
* No-op.
*/
getRoom(roomId) {
return null;
}
/**
* No-op.
* @returns An empty array.
*/
getRooms() {
return [];
}
/**
* Permanently delete a room.
*/
removeRoom(roomId) {}
/**
* No-op.
* @returns An empty array.
*/
getRoomSummaries() {
return [];
}
/**
* No-op.
*/
storeUser(user) {}
/**
* No-op.
*/
getUser(userId) {
return null;
}
/**
* No-op.
*/
getUsers() {
return [];
}
/**
* No-op.
*/
scrollback(room, limit) {
return [];
}
/**
* No-op.
*/
setUserCreator(creator) {}
/**
* Store events for a room.
* @param room - The room to store events for.
* @param events - The events to store.
* @param token - The token associated with these events.
* @param toStart - True if these are paginated results.
*/
storeEvents(room, events, token, toStart) {}
/**
* Store a filter.
*/
storeFilter(filter) {}
/**
* Retrieve a filter.
* @returns A filter or null.
*/
getFilter(userId, filterId) {
return null;
}
/**
* Retrieve a filter ID with the given name.
* @param filterName - The filter name.
* @returns The filter ID or null.
*/
getFilterIdByName(filterName) {
return null;
}
/**
* Set a filter name to ID mapping.
*/
setFilterIdByName(filterName, filterId) {}
/**
* Store user-scoped account data events
* @param events - The events to store.
*/
storeAccountDataEvents(events) {}
/**
* Get account data event by event type
* @param eventType - The event type being queried
*/
getAccountData(eventType) {}
/**
* setSyncData does nothing as there is no backing data store.
*
* @param syncData - The sync data
* @returns An immediately resolved promise.
*/
setSyncData(syncData) {
return Promise.resolve();
}
/**
* We never want to save because we have nothing to save to.
*
* @returns If the store wants to save
*/
wantsSave() {
return false;
}
/**
* Save does nothing as there is no backing data store.
*/
save() {
return Promise.resolve();
}
/**
* Startup does nothing.
* @returns An immediately resolved promise.
*/
startup() {
return Promise.resolve();
}
/**
* @returns Promise which resolves with a sync response to restore the
* client state to where it was at the last save, or null if there
* is no saved sync data.
*/
getSavedSync() {
return Promise.resolve(null);
}
/**
* @returns If there is a saved sync, the nextBatch token
* for this sync, otherwise null.
*/
getSavedSyncToken() {
return Promise.resolve(null);
}
/**
* Delete all data from this store. Does nothing since this store
* doesn't store anything.
* @returns An immediately resolved promise.
*/
deleteAllData() {
return Promise.resolve();
}
getOutOfBandMembers() {
return Promise.resolve(null);
}
setOutOfBandMembers(roomId, membershipEvents) {
return Promise.resolve();
}
clearOutOfBandMembers() {
return Promise.resolve();
}
getClientOptions() {
return Promise.resolve(void 0);
}
storeClientOptions(options) {
return Promise.resolve();
}
getPendingEvents(roomId) {
return (0, import_asyncToGenerator.default)(function* () {
return [];
})();
}
setPendingEvents(roomId, events) {
return Promise.resolve();
}
saveToDeviceBatches(batch) {
return (0, import_asyncToGenerator.default)(function* () {
return Promise.resolve();
})();
}
getOldestToDeviceBatch() {
return Promise.resolve(null);
}
removeToDeviceBatch(id) {
return (0, import_asyncToGenerator.default)(function* () {
return Promise.resolve();
})();
}
destroy() {
return (0, import_asyncToGenerator.default)(function* () {})();
}
};
//#endregion
//#region node_modules/sdp-transform/lib/grammar.js
var require_grammar = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var grammar = module.exports = {
v: [{
name: "version",
reg: /^(\d*)$/
}],
o: [{
name: "origin",
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: [
"username",
"sessionId",
"sessionVersion",
"netType",
"ipVer",
"address"
],
format: "%s %s %d %s IP%d %s"
}],
s: [{ name: "name" }],
i: [{ name: "description" }],
u: [{ name: "uri" }],
e: [{ name: "email" }],
p: [{ name: "phone" }],
z: [{ name: "timezones" }],
r: [{ name: "repeats" }],
t: [{
name: "timing",
reg: /^(\d*) (\d*)/,
names: ["start", "stop"],
format: "%d %d"
}],
c: [{
name: "connection",
reg: /^IN IP(\d) (\S*)/,
names: ["version", "ip"],
format: "IN IP%d %s"
}],
b: [{
push: "bandwidth",
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ["type", "limit"],
format: "%s:%s"
}],
m: [{
reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/,
names: [
"type",
"port",
"protocol",
"payloads"
],
format: "%s %d %s %s"
}],
a: [
{
push: "rtp",
reg: /^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: [
"payload",
"codec",
"rate",
"encoding"
],
format: function(o) {
return o.encoding ? "rtpmap:%d %s/%s/%s" : o.rate ? "rtpmap:%d %s/%s" : "rtpmap:%d %s";
}
},
{
push: "fmtp",
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ["payload", "config"],
format: "fmtp:%d %s"
},
{
name: "control",
reg: /^control:(.*)/,
format: "control:%s"
},
{
name: "rtcp",
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: [
"port",
"netType",
"ipVer",
"address"
],
format: function(o) {
return o.address != null ? "rtcp:%d %s IP%d %s" : "rtcp:%d";
}
},
{
push: "rtcpFbTrrInt",
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ["payload", "value"],
format: "rtcp-fb:%s trr-int %d"
},
{
push: "rtcpFb",
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: [
"payload",
"type",
"subtype"
],
format: function(o) {
return o.subtype != null ? "rtcp-fb:%s %s %s" : "rtcp-fb:%s %s";
}
},
{
push: "ext",
reg: /^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,
names: [
"value",
"direction",
"encrypt-uri",
"uri",
"config"
],
format: function(o) {
return "extmap:%d" + (o.direction ? "/%s" : "%v") + (o["encrypt-uri"] ? " %s" : "%v") + " %s" + (o.config ? " %s" : "");
}
},
{
name: "extmapAllowMixed",
reg: /^(extmap-allow-mixed)/
},
{
push: "crypto",
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: [
"id",
"suite",
"config",
"sessionConfig"
],
format: function(o) {
return o.sessionConfig != null ? "crypto:%d %s %s %s" : "crypto:%d %s %s";
}
},
{
name: "setup",
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{
name: "connectionType",
reg: /^connection:(new|existing)/,
format: "connection:%s"
},
{
name: "mid",
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{
push: "msid",
reg: /^msid:([\w-]+)(?: ([\w-]+))?/,
names: ["id", "appdata"],
format: "msid:%s %s"
},
{
name: "ptime",
reg: /^ptime:(\d*(?:\.\d*)*)/,
format: "ptime:%d"
},
{
name: "maxptime",
reg: /^maxptime:(\d*(?:\.\d*)*)/,
format: "maxptime:%d"
},
{
name: "direction",
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{
name: "icelite",
reg: /^(ice-lite)/
},
{
name: "iceUfrag",
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{
name: "icePwd",
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{
name: "fingerprint",
reg: /^fingerprint:(\S*) (\S*)/,
names: ["type", "hash"],
format: "fingerprint:%s %s"
},
{
push: "candidates",
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,
names: [
"foundation",
"component",
"transport",
"priority",
"ip",
"port",
"type",
"raddr",
"rport",
"tcptype",
"generation",
"network-id",
"network-cost"
],
format: function(o) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += o.raddr != null ? " raddr %s rport %d" : "%v%v";
str += o.tcptype != null ? " tcptype %s" : "%v";
if (o.generation != null) str += " generation %d";
str += o["network-id"] != null ? " network-id %d" : "%v";
str += o["network-cost"] != null ? " network-cost %d" : "%v";
return str;
}
},
{
name: "endOfCandidates",
reg: /^(end-of-candidates)/
},
{
name: "remoteCandidates",
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{
name: "iceOptions",
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,
names: [
"id",
"attribute",
"value"
],
format: function(o) {
var str = "ssrc:%d";
if (o.attribute != null) {
str += " %s";
if (o.value != null) str += ":%s";
}
return str;
}
},
{
push: "ssrcGroups",
reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,
names: ["semantics", "ssrcs"],
format: "ssrc-group:%s %s"
},
{
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ["semantic", "token"],
format: "msid-semantic: %s %s"
},
{
push: "groups",
reg: /^group:(\w*) (.*)/,
names: ["type", "mids"],
format: "group:%s %s"
},
{
name: "rtcpMux",
reg: /^(rtcp-mux)/
},
{
name: "rtcpRsize",
reg: /^(rtcp-rsize)/
},
{
name: "sctpmap",
reg: /^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,
names: [
"sctpmapNumber",
"app",
"maxMessageSize"
],
format: function(o) {
return o.maxMessageSize != null ? "sctpmap:%s %s %s" : "sctpmap:%s %s";
}
},
{
name: "xGoogleFlag",
reg: /^x-google-flag:([^\s]*)/,
format: "x-google-flag:%s"
},
{
push: "rids",
reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,
names: [
"id",
"direction",
"params"
],
format: function(o) {
return o.params ? "rid:%s %s %s" : "rid:%s %s";
}
},
{
push: "imageattrs",
reg: /* @__PURE__ */ new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),
names: [
"pt",
"dir1",
"attrs1",
"dir2",
"attrs2"
],
format: function(o) {
return "imageattr:%s %s %s" + (o.dir2 ? " %s %s" : "");
}
},
{
name: "simulcast",
reg: /* @__PURE__ */ new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),
names: [
"dir1",
"list1",
"dir2",
"list2"
],
format: function(o) {
return "simulcast:%s %s" + (o.dir2 ? " %s %s" : "");
}
},
{
name: "simulcast_03",
reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/,
names: ["value"],
format: "simulcast: %s"
},
{
name: "framerate",
reg: /^framerate:(\d+(?:$|\.\d+))/,
format: "framerate:%s"
},
{
name: "sourceFilter",
reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,
names: [
"filterMode",
"netType",
"addressTypes",
"destAddress",
"srcList"
],
format: "source-filter: %s %s %s %s %s"
},
{
name: "bundleOnly",
reg: /^(bundle-only)/
},
{
name: "label",
reg: /^label:(.+)/,
format: "label:%s"
},
{
name: "sctpPort",
reg: /^sctp-port:(\d+)$/,
format: "sctp-port:%s"
},
{
name: "maxMessageSize",
reg: /^max-message-size:(\d+)$/,
format: "max-message-size:%s"
},
{
push: "tsRefClocks",
reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/,
names: ["clksrc", "clksrcExt"],
format: function(o) {
return "ts-refclk:%s" + (o.clksrcExt != null ? "=%s" : "");
}
},
{
name: "mediaClk",
reg: /^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,
names: [
"id",
"mediaClockName",
"mediaClockValue",
"rateNumerator",
"rateDenominator"
],
format: function(o) {
var str = "mediaclk:";
str += o.id != null ? "id=%s %s" : "%v%s";
str += o.mediaClockValue != null ? "=%s" : "";
str += o.rateNumerator != null ? " rate=%s" : "";
str += o.rateDenominator != null ? "/%s" : "";
return str;
}
},
{
name: "keywords",
reg: /^keywds:(.+)$/,
format: "keywds:%s"
},
{
name: "content",
reg: /^content:(.+)/,
format: "content:%s"
},
{
name: "bfcpFloorCtrl",
reg: /^floorctrl:(c-only|s-only|c-s)/,
format: "floorctrl:%s"
},
{
name: "bfcpConfId",
reg: /^confid:(\d+)/,
format: "confid:%s"
},
{
name: "bfcpUserId",
reg: /^userid:(\d+)/,
format: "userid:%s"
},
{
name: "bfcpFloorId",
reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,
names: ["id", "mStream"],
format: "floorid:%s mstrm:%s"
},
{
push: "invalid",
names: ["value"]
}
]
};
Object.keys(grammar).forEach(function(key) {
grammar[key].forEach(function(obj) {
if (!obj.reg) obj.reg = /(.*)/;
if (!obj.format) obj.format = "%s";
});
});
}));
//#endregion
//#region node_modules/sdp-transform/lib/parser.js
var require_parser = /* @__PURE__ */ __commonJSMin(((exports) => {
var toIntIfInt = function(v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function(match, location, names, rawName) {
if (rawName && !names) location[rawName] = toIntIfInt(match[1]);
else for (var i = 0; i < names.length; i += 1) if (match[i + 1] != null) location[names[i]] = toIntIfInt(match[i + 1]);
};
var parseReg = function(obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) location[obj.push] = [];
else if (needsBlank && !location[obj.name]) location[obj.name] = {};
var keyLocation = obj.push ? {} : needsBlank ? location[obj.name] : location;
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) location[obj.push].push(keyLocation);
};
var grammar = require_grammar();
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function(sdp) {
var session = {}, media = [], location = session;
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function(l) {
var type = l[0];
var content = l.slice(2);
if (type === "m") {
media.push({
rtp: [],
fmtp: []
});
location = media[media.length - 1];
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) return parseReg(obj, location, content);
}
});
session.media = media;
return session;
};
var paramReducer = function(acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) acc[s[0]] = toIntIfInt(s[1]);
else if (s.length === 1 && expr.length > 1) acc[s[0]] = void 0;
return acc;
};
exports.parseParams = function(str) {
return str.split(/;\s?/).reduce(paramReducer, {});
};
exports.parseFmtpConfig = exports.parseParams;
exports.parsePayloads = function(str) {
return str.toString().split(" ").map(Number);
};
exports.parseRemoteCandidates = function(str) {
var candidates = [];
var parts = str.split(" ").map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
return candidates;
};
exports.parseImageAttributes = function(str) {
return str.split(" ").map(function(item) {
return item.substring(1, item.length - 1).split(",").reduce(paramReducer, {});
});
};
exports.parseSimulcastStreamList = function(str) {
return str.split(";").map(function(stream) {
return stream.split(",").map(function(format) {
var scid, paused = false;
if (format[0] !== "~") scid = toIntIfInt(format);
else {
scid = toIntIfInt(format.substring(1, format.length));
paused = true;
}
return {
scid,
paused
};
});
});
};
}));
//#endregion
//#region node_modules/sdp-transform/lib/writer.js
var require_writer = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var grammar = require_grammar();
var formatRegExp = /%[sdv%]/g;
var format = function(formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function(x) {
if (i >= len) return x;
var arg = args[i];
i += 1;
switch (x) {
case "%%": return "%";
case "%s": return String(arg);
case "%d": return Number(arg);
case "%v": return "";
}
});
};
var makeLine = function(type, obj, location) {
var str = obj.format instanceof Function ? obj.format(obj.push ? location : location[obj.name]) : obj.format;
var args = [type + "=" + str];
if (obj.names) for (var i = 0; i < obj.names.length; i += 1) {
var n = obj.names[i];
if (obj.name) args.push(location[obj.name][n]);
else args.push(location[obj.names[i]]);
}
else args.push(location[obj.name]);
return format.apply(null, args);
};
var defaultOuterOrder = [
"v",
"o",
"s",
"i",
"u",
"e",
"p",
"c",
"b",
"t",
"r",
"z",
"a"
];
var defaultInnerOrder = [
"i",
"c",
"b",
"a"
];
module.exports = function(session, opts) {
opts = opts || {};
if (session.version == null) session.version = 0;
if (session.name == null) session.name = " ";
session.media.forEach(function(mLine) {
if (mLine.payloads == null) mLine.payloads = "";
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
outerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in session && session[obj.name] != null) sdp.push(makeLine(type, obj, session));
else if (obj.push in session && session[obj.push] != null) session[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
});
});
session.media.forEach(function(mLine) {
sdp.push(makeLine("m", grammar.m[0], mLine));
innerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in mLine && mLine[obj.name] != null) sdp.push(makeLine(type, obj, mLine));
else if (obj.push in mLine && mLine[obj.push] != null) mLine[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
});
});
});
return sdp.join("\r\n") + "\r\n";
};
}));
//#endregion
//#region node_modules/sdp-transform/lib/index.js
var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
var parser = require_parser();
var writer = require_writer();
require_grammar();
exports.write = writer;
exports.parse = parser.parse;
exports.parseParams = parser.parseParams;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
exports.parseImageAttributes = parser.parseImageAttributes;
exports.parseSimulcastStreamList = parser.parseSimulcastStreamList;
}));
//#endregion
//#region node_modules/matrix-js-sdk/lib/base64.js
/**
* Base64 encoding and decoding utilities
*/
function toBase64$1(uint8Array, options) {
if (typeof uint8Array.toBase64 === "function") return uint8Array.toBase64(options);
var base64 = btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), ""));
if (options.omitPadding) base64 = base64.replace(/={1,2}$/, "");
if (options.alphabet === "base64url") base64 = base64.replace(/\+/g, "-").replace(/\//g, "_");
return base64;
}
/**
* Encode a typed array of uint8 as base64.
* @param uint8Array - The data to encode.
* @returns The base64.
*/
function encodeBase64(uint8Array) {
return toBase64$1(uint8Array, {
alphabet: "base64",
omitPadding: false
});
}
/**
* Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.
* @param uint8Array - The data to encode.
* @returns The unpadded base64.
*/
function encodeUnpaddedBase64Url(uint8Array) {
return toBase64$1(uint8Array, {
alphabet: "base64url",
omitPadding: true
});
}
function fromBase64(base64, options) {
if (typeof Uint8Array.fromBase64 === "function") return Uint8Array.fromBase64(base64, options);
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
}
/**
* Decode a base64 (or base64url) string to a typed array of uint8.
* @param base64 - The base64 to decode.
* @returns The decoded data.
*/
function decodeBase64(base64) {
return fromBase64(base64.replace(/-/g, "+").replace(/_/g, "/"), {
alphabet: "base64",
lastChunkHandling: "loose"
});
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/randomstring.js
/**
* String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}
* (can be combined with other such exports or other characters by appending strings)
*/
var LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
/**
* String representing the uppercase latin alphabet for use in secureRandomStringFrom
* (can be combined with other such exports or other characters by appending strings)
*/
var UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* String representing the arabic numerals for use in secureRandomStringFrom
* (can be combined with other such exports or other characters by appending strings)
*/
var DIGITS = "0123456789";
/**
* Generates a random string of uppercase and lowercase letters plus digits using a
* cryptographically secure random number generator.
* @param len The length of the string to generate
* @returns Random string of uppercase and lowercase letters plus digits of length `len`
*/
function secureRandomString(len) {
return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);
}
/**
* Generate a cryptographically secure random string using characters given.
*
* @param len - The length of the string to generate (must be positive and less than 32768).
* @param chars - The characters to use in the random string (between 2 and 256 characters long).
* @returns Random string of characters of length `len`.
*/
function secureRandomStringFrom(len, chars) {
if (chars.length < 2 || chars.length > 256) throw new Error("Character set must be between 2 and 256 characters long");
if (len < 1 || len > 32768) throw new Error("Requested random string length must be between 1 and 32768");
var randomValueCutoff = 256 - 256 % chars.length;
var entropyBuffer = new Uint8Array(Math.floor(len * 1.3));
var entropyBufferPos = entropyBuffer.length;
var result = [];
while (result.length < len) {
if (entropyBufferPos === entropyBuffer.length) {
globalThis.crypto.getRandomValues(entropyBuffer);
entropyBufferPos = 0;
}
var randomByte = entropyBuffer[entropyBufferPos++];
if (randomByte < randomValueCutoff) result.push(chars[randomByte % chars.length]);
}
return result.join("");
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/callEventTypes.js
var SDPStreamMetadataKey = new NamespacedValue$1("sdp_stream_metadata", "org.matrix.msc3077.sdp_stream_metadata");
var SDPStreamMetadataPurpose = /* @__PURE__ */ function(SDPStreamMetadataPurpose) {
SDPStreamMetadataPurpose["Usermedia"] = "m.usermedia";
SDPStreamMetadataPurpose["Screenshare"] = "m.screenshare";
return SDPStreamMetadataPurpose;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/audioContext.js
var audioContext = null;
var refCount = 0;
/**
* Acquires a reference to the shared AudioContext.
* It's highly recommended to reuse this AudioContext rather than creating your
* own, because multiple AudioContexts can be problematic in some browsers.
* Make sure to call releaseContext when you're done using it.
* @returns The shared AudioContext
*/
var acquireContext = () => {
if (audioContext === null) audioContext = new AudioContext();
refCount++;
return audioContext;
};
/**
* Signals that one of the references to the shared AudioContext has been
* released, allowing the context and associated hardware resources to be
* cleaned up if nothing else is using it.
*/
var releaseContext = () => {
refCount--;
if (refCount === 0) {
var _audioContext;
(_audioContext = audioContext) === null || _audioContext === void 0 || _audioContext.close();
audioContext = null;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/callFeed.js
var POLLING_INTERVAL = 200;
var SPEAKING_SAMPLE_COUNT = 8;
var CallFeedEvent = /* @__PURE__ */ function(CallFeedEvent) {
CallFeedEvent["NewStream"] = "new_stream";
CallFeedEvent["MuteStateChanged"] = "mute_state_changed";
CallFeedEvent["LocalVolumeChanged"] = "local_volume_changed";
CallFeedEvent["VolumeChanged"] = "volume_changed";
CallFeedEvent["ConnectedChanged"] = "connected_changed";
CallFeedEvent["Speaking"] = "speaking";
CallFeedEvent["Disposed"] = "disposed";
return CallFeedEvent;
}({});
var CallFeed = class CallFeed extends TypedEventEmitter {
constructor(opts) {
super();
(0, import_defineProperty.default)(this, "stream", void 0);
(0, import_defineProperty.default)(this, "sdpMetadataStreamId", void 0);
(0, import_defineProperty.default)(this, "userId", void 0);
(0, import_defineProperty.default)(this, "deviceId", void 0);
(0, import_defineProperty.default)(this, "purpose", void 0);
(0, import_defineProperty.default)(this, "speakingVolumeSamples", void 0);
(0, import_defineProperty.default)(this, "client", void 0);
(0, import_defineProperty.default)(this, "call", void 0);
(0, import_defineProperty.default)(this, "roomId", void 0);
(0, import_defineProperty.default)(this, "audioMuted", void 0);
(0, import_defineProperty.default)(this, "videoMuted", void 0);
(0, import_defineProperty.default)(this, "localVolume", 1);
(0, import_defineProperty.default)(this, "measuringVolumeActivity", false);
(0, import_defineProperty.default)(this, "audioContext", void 0);
(0, import_defineProperty.default)(this, "analyser", void 0);
(0, import_defineProperty.default)(this, "frequencyBinCount", void 0);
(0, import_defineProperty.default)(this, "speakingThreshold", -60);
(0, import_defineProperty.default)(this, "speaking", false);
(0, import_defineProperty.default)(this, "volumeLooperTimeout", void 0);
(0, import_defineProperty.default)(this, "_disposed", false);
(0, import_defineProperty.default)(this, "_connected", false);
(0, import_defineProperty.default)(this, "onAddTrack", () => {
this.emit(CallFeedEvent.NewStream, this.stream);
});
(0, import_defineProperty.default)(this, "onCallState", (state) => {
if (state === CallState.Connected) this.connected = true;
else if (state === CallState.Connecting) this.connected = false;
});
(0, import_defineProperty.default)(this, "volumeLooper", () => {
if (!this.analyser) return;
if (!this.measuringVolumeActivity) return;
this.analyser.getFloatFrequencyData(this.frequencyBinCount);
var maxVolume = -Infinity;
for (var volume of this.frequencyBinCount) if (volume > maxVolume) maxVolume = volume;
this.speakingVolumeSamples.shift();
this.speakingVolumeSamples.push(maxVolume);
this.emit(CallFeedEvent.VolumeChanged, maxVolume);
var newSpeaking = false;
for (var _volume of this.speakingVolumeSamples) if (_volume > this.speakingThreshold) {
newSpeaking = true;
break;
}
if (this.speaking !== newSpeaking) {
this.speaking = newSpeaking;
this.emit(CallFeedEvent.Speaking, this.speaking);
}
this.volumeLooperTimeout = setTimeout(this.volumeLooper, POLLING_INTERVAL);
});
this.client = opts.client;
this.call = opts.call;
this.roomId = opts.roomId;
this.userId = opts.userId;
this.deviceId = opts.deviceId;
this.purpose = opts.purpose;
this.audioMuted = opts.audioMuted;
this.videoMuted = opts.videoMuted;
this.speakingVolumeSamples = new Array(SPEAKING_SAMPLE_COUNT).fill(-Infinity);
this.sdpMetadataStreamId = opts.stream.id;
this.updateStream(null, opts.stream);
this.stream = opts.stream;
if (this.hasAudioTrack) this.initVolumeMeasuring();
if (opts.call) {
opts.call.addListener(CallEvent.State, this.onCallState);
this.onCallState(opts.call.state);
}
}
get connected() {
return this.isLocal() || this._connected;
}
set connected(connected) {
this._connected = connected;
this.emit(CallFeedEvent.ConnectedChanged, this.connected);
}
get hasAudioTrack() {
return this.stream.getAudioTracks().length > 0;
}
updateStream(oldStream, newStream) {
if (newStream === oldStream) return;
var wasMeasuringVolumeActivity = this.measuringVolumeActivity;
if (oldStream) {
oldStream.removeEventListener("addtrack", this.onAddTrack);
this.measureVolumeActivity(false);
}
this.stream = newStream;
newStream.addEventListener("addtrack", this.onAddTrack);
if (this.hasAudioTrack) {
this.initVolumeMeasuring();
if (wasMeasuringVolumeActivity) this.measureVolumeActivity(true);
} else this.measureVolumeActivity(false);
this.emit(CallFeedEvent.NewStream, this.stream);
}
initVolumeMeasuring() {
if (!this.hasAudioTrack) return;
if (!this.audioContext) this.audioContext = acquireContext();
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 512;
this.analyser.smoothingTimeConstant = .1;
this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser);
this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount);
}
/**
* Returns callRoom member
* @returns member of the callRoom
*/
getMember() {
var _callRoom$getMember;
var callRoom = this.client.getRoom(this.roomId);
return (_callRoom$getMember = callRoom === null || callRoom === void 0 ? void 0 : callRoom.getMember(this.userId)) !== null && _callRoom$getMember !== void 0 ? _callRoom$getMember : null;
}
/**
* Returns true if CallFeed is local, otherwise returns false
* @returns is local?
*/
isLocal() {
return this.userId === this.client.getUserId() && (this.deviceId === void 0 || this.deviceId === this.client.getDeviceId());
}
/**
* Returns true if audio is muted or if there are no audio
* tracks, otherwise returns false
* @returns is audio muted?
*/
isAudioMuted() {
return this.stream.getAudioTracks().length === 0 || this.audioMuted;
}
/**
* Returns true video is muted or if there are no video
* tracks, otherwise returns false
* @returns is video muted?
*/
isVideoMuted() {
return this.stream.getVideoTracks().length === 0 || this.videoMuted;
}
isSpeaking() {
return this.speaking;
}
/**
* Replaces the current MediaStream with a new one.
* The stream will be different and new stream as remote parties are
* concerned, but this can be used for convenience locally to set up
* volume listeners automatically on the new stream etc.
* @param newStream - new stream with which to replace the current one
*/
setNewStream(newStream) {
this.updateStream(this.stream, newStream);
}
/**
* Set one or both of feed's internal audio and video video mute state
* Either value may be null to leave it as-is
* @param audioMuted - is the feed's audio muted?
* @param videoMuted - is the feed's video muted?
*/
setAudioVideoMuted(audioMuted, videoMuted) {
if (audioMuted !== null) {
if (this.audioMuted !== audioMuted) this.speakingVolumeSamples.fill(-Infinity);
this.audioMuted = audioMuted;
}
if (videoMuted !== null) this.videoMuted = videoMuted;
this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);
}
/**
* Starts emitting volume_changed events where the emitter value is in decibels
* @param enabled - emit volume changes
*/
measureVolumeActivity(enabled) {
if (enabled) {
if (!this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;
this.measuringVolumeActivity = true;
this.volumeLooper();
} else {
this.measuringVolumeActivity = false;
this.speakingVolumeSamples.fill(-Infinity);
this.emit(CallFeedEvent.VolumeChanged, -Infinity);
}
}
setSpeakingThreshold(threshold) {
this.speakingThreshold = threshold;
}
clone() {
var mediaHandler = this.client.getMediaHandler();
var stream = this.stream.clone();
logger$2.log("CallFeed clone() cloning stream (originalStreamId=".concat(this.stream.id, ", newStreamId").concat(stream.id, ")"));
if (this.purpose === SDPStreamMetadataPurpose.Usermedia) mediaHandler.userMediaStreams.push(stream);
else mediaHandler.screensharingStreams.push(stream);
return new CallFeed({
client: this.client,
roomId: this.roomId,
userId: this.userId,
deviceId: this.deviceId,
stream,
purpose: this.purpose,
audioMuted: this.audioMuted,
videoMuted: this.videoMuted
});
}
dispose() {
var _this$stream, _this$call;
clearTimeout(this.volumeLooperTimeout);
(_this$stream = this.stream) === null || _this$stream === void 0 || _this$stream.removeEventListener("addtrack", this.onAddTrack);
(_this$call = this.call) === null || _this$call === void 0 || _this$call.removeListener(CallEvent.State, this.onCallState);
if (this.audioContext) {
this.audioContext = void 0;
this.analyser = void 0;
releaseContext();
}
this._disposed = true;
this.emit(CallFeedEvent.Disposed);
}
get disposed() {
return this._disposed;
}
set disposed(value) {
this._disposed = value;
}
getLocalVolume() {
return this.localVolume;
}
setLocalVolume(localVolume) {
this.localVolume = localVolume;
this.emit(CallFeedEvent.LocalVolumeChanged, localVolume);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/callEventHandler.js
var RING_GRACE_PERIOD = 3e3;
var CallEventHandlerEvent = /* @__PURE__ */ function(CallEventHandlerEvent) {
CallEventHandlerEvent["Incoming"] = "Call.incoming";
return CallEventHandlerEvent;
}({});
var CallEventHandler = class {
constructor(client) {
(0, import_defineProperty.default)(this, "calls", void 0);
(0, import_defineProperty.default)(this, "callEventBuffer", void 0);
(0, import_defineProperty.default)(this, "nextSeqByCall", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "toDeviceEventBuffers", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "client", void 0);
(0, import_defineProperty.default)(this, "candidateEventsByCall", void 0);
(0, import_defineProperty.default)(this, "eventBufferPromiseChain", void 0);
(0, import_defineProperty.default)(this, "onSync", () => {
var currentEventBuffer = this.callEventBuffer;
this.callEventBuffer = [];
if (this.eventBufferPromiseChain) this.eventBufferPromiseChain = this.eventBufferPromiseChain.then(() => this.evaluateEventBuffer(currentEventBuffer));
else this.eventBufferPromiseChain = this.evaluateEventBuffer(currentEventBuffer);
});
(0, import_defineProperty.default)(this, "onRoomTimeline", (event) => {
this.callEventBuffer.push(event);
});
(0, import_defineProperty.default)(this, "onToDeviceEvent", (event) => {
var content = event.getContent();
if (!content.call_id) {
this.callEventBuffer.push(event);
return;
}
if (!this.nextSeqByCall.has(content.call_id)) this.nextSeqByCall.set(content.call_id, 0);
if (content.seq === void 0) {
this.callEventBuffer.push(event);
return;
}
var nextSeq = this.nextSeqByCall.get(content.call_id) || 0;
if (content.seq !== nextSeq) {
if (!this.toDeviceEventBuffers.has(content.call_id)) this.toDeviceEventBuffers.set(content.call_id, []);
var buffer = this.toDeviceEventBuffers.get(content.call_id);
var index = buffer.findIndex((e) => e.getContent().seq > content.seq);
if (index === -1) buffer.push(event);
else buffer.splice(index, 0, event);
} else {
var callId = content.call_id;
this.callEventBuffer.push(event);
this.nextSeqByCall.set(callId, content.seq + 1);
var _buffer = this.toDeviceEventBuffers.get(callId);
var nextEvent = _buffer && _buffer.shift();
while (nextEvent && nextEvent.getContent().seq === this.nextSeqByCall.get(callId)) {
this.callEventBuffer.push(nextEvent);
this.nextSeqByCall.set(callId, nextEvent.getContent().seq + 1);
nextEvent = _buffer.shift();
}
}
});
this.client = client;
this.calls = /* @__PURE__ */ new Map();
this.callEventBuffer = [];
this.candidateEventsByCall = /* @__PURE__ */ new Map();
}
start() {
this.client.on(ClientEvent.Sync, this.onSync);
this.client.on(RoomEvent.Timeline, this.onRoomTimeline);
this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
stop() {
this.client.removeListener(ClientEvent.Sync, this.onSync);
this.client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);
this.client.removeListener(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
evaluateEventBuffer(eventBuffer) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
yield Promise.all(eventBuffer.map((event) => _this.client.decryptEventIfNeeded(event)));
var callEvents = eventBuffer.filter((event) => {
var eventType = event.getType();
return eventType.startsWith("m.call.") || eventType.startsWith("org.matrix.call.");
});
var ignoreCallIds = /* @__PURE__ */ new Set();
for (var event of callEvents) {
var eventType = event.getType();
if (eventType === EventType.CallAnswer || eventType === EventType.CallHangup) ignoreCallIds.add(event.getContent().call_id);
}
for (var _event of callEvents) {
var _eventType = _event.getType();
var callId = _event.getContent().call_id;
if (_eventType === EventType.CallInvite && ignoreCallIds.has(callId)) continue;
try {
yield _this.handleCallEvent(_event);
} catch (e) {
logger$2.error("CallEventHandler evaluateEventBuffer() caught exception handling call event", e);
}
}
})();
}
handleCallEvent(event) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _getGroupCallById;
_this2.client.emit(ClientEvent.ReceivedVoipEvent, event);
var content = event.getContent();
var callRoomId = event.getRoomId() || ((_getGroupCallById = _this2.client.groupCallEventHandler.getGroupCallById(content.conf_id)) === null || _getGroupCallById === void 0 || (_getGroupCallById = _getGroupCallById.room) === null || _getGroupCallById === void 0 ? void 0 : _getGroupCallById.roomId);
var groupCallId = content.conf_id;
var type = event.getType();
var senderId = event.getSender();
var call = content.call_id ? _this2.calls.get(content.call_id) : void 0;
var opponentDeviceId;
var groupCall;
if (groupCallId) {
groupCall = _this2.client.groupCallEventHandler.getGroupCallById(groupCallId);
if (!groupCall) {
logger$2.warn("CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=".concat(groupCallId, ", type=").concat(type, ")"));
return;
}
opponentDeviceId = content.device_id;
if (!opponentDeviceId) {
logger$2.warn("CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=".concat(senderId, ")"));
groupCall.emit(GroupCallEvent.Error, new GroupCallUnknownDeviceError(senderId));
return;
}
if (content.dest_session_id !== _this2.client.getSessionId()) {
logger$2.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");
return;
}
}
var weSentTheEvent = senderId === _this2.client.credentials.userId && (opponentDeviceId === void 0 || opponentDeviceId === _this2.client.getDeviceId());
if (!callRoomId) return;
if (type === EventType.CallInvite) {
var _this2$client$getTurn, _createNewMatrixCall, _groupCall;
if (weSentTheEvent) return;
if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) return;
if (call && call.state === CallState.Ended) return;
if (call) logger$2.warn("CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=".concat(content.call_id, ")"));
if (content.invitee && content.invitee !== _this2.client.getUserId()) return;
var timeUntilTurnCresExpire = ((_this2$client$getTurn = _this2.client.getTurnServersExpiry()) !== null && _this2$client$getTurn !== void 0 ? _this2$client$getTurn : 0) - Date.now();
logger$2.info("CallEventHandler handleCallEvent() current turn creds expire in " + timeUntilTurnCresExpire + " ms");
call = (_createNewMatrixCall = createNewMatrixCall(_this2.client, callRoomId, {
forceTURN: _this2.client.forceTURN,
opponentDeviceId,
groupCallId,
opponentSessionId: content.sender_session_id
})) !== null && _createNewMatrixCall !== void 0 ? _createNewMatrixCall : void 0;
if (!call) {
logger$2.log("CallEventHandler handleCallEvent() this client does not support WebRTC (callId=".concat(content.call_id, ")"));
return;
}
call.callId = content.call_id;
var stats = (_groupCall = groupCall) === null || _groupCall === void 0 ? void 0 : _groupCall.getGroupCallStats();
if (stats) call.initStats(stats);
try {
yield call.initWithInvite(event);
} catch (e) {
if (e instanceof CallError) if (e.code === GroupCallErrorCode.UnknownDevice) {
var _groupCall2;
(_groupCall2 = groupCall) === null || _groupCall2 === void 0 || _groupCall2.emit(GroupCallEvent.Error, e);
} else logger$2.error(e);
}
_this2.calls.set(call.callId, call);
if (_this2.candidateEventsByCall.get(call.callId)) for (var ev of _this2.candidateEventsByCall.get(call.callId)) call.onRemoteIceCandidatesReceived(ev);
var existingCall;
for (var thisCall of _this2.calls.values()) {
var _call$getOpponentMemb;
var isCalling = [
CallState.WaitLocalMedia,
CallState.CreateOffer,
CallState.InviteSent
].includes(thisCall.state);
if (call.roomId === thisCall.roomId && thisCall.direction === CallDirection.Outbound && ((_call$getOpponentMemb = call.getOpponentMember()) === null || _call$getOpponentMemb === void 0 ? void 0 : _call$getOpponentMemb.userId) === thisCall.invitee && isCalling) {
existingCall = thisCall;
break;
}
}
if (existingCall) if (existingCall.callId > call.callId) {
logger$2.log("CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=".concat(call.callId, ", outgoingId=").concat(existingCall.callId, ")"));
existingCall.replacedBy(call);
} else {
logger$2.log("CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=".concat(call.callId, ", outgoingId=").concat(existingCall.callId, ")"));
call.hangup(CallErrorCode.Replaced, true);
}
else _this2.client.emit(CallEventHandlerEvent.Incoming, call);
return;
} else if (type === EventType.CallCandidates) {
if (weSentTheEvent) return;
if (!call) {
if (!_this2.candidateEventsByCall.has(content.call_id)) _this2.candidateEventsByCall.set(content.call_id, []);
_this2.candidateEventsByCall.get(content.call_id).push(event);
} else call.onRemoteIceCandidatesReceived(event);
return;
} else if ([EventType.CallHangup, EventType.CallReject].includes(type)) {
if (!call) {
var _createNewMatrixCall2;
call = (_createNewMatrixCall2 = createNewMatrixCall(_this2.client, callRoomId, {
opponentDeviceId,
opponentSessionId: content.sender_session_id
})) !== null && _createNewMatrixCall2 !== void 0 ? _createNewMatrixCall2 : void 0;
if (call) {
call.callId = content.call_id;
call.initWithHangup(event);
_this2.calls.set(content.call_id, call);
}
} else if (call.state !== CallState.Ended) {
if (type === EventType.CallHangup) call.onHangupReceived(content);
else call.onRejectReceived(content);
if (call.state === CallState.Ended) _this2.calls.delete(content.call_id);
}
return;
}
if (!call || !call.hasPeerConnection) {
logger$2.info("CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=".concat(type, ")"));
return;
}
if (event.getContent().party_id === call.ourPartyId) return;
switch (type) {
case EventType.CallAnswer:
if (weSentTheEvent) {
if (call.state === CallState.Ringing) call.onAnsweredElsewhere(content);
} else call.onAnswerReceived(event);
break;
case EventType.CallSelectAnswer:
call.onSelectAnswerReceived(event);
break;
case EventType.CallNegotiate:
call.onNegotiateReceived(event);
break;
case EventType.CallAssertedIdentity:
case EventType.CallAssertedIdentityPrefix:
call.onAssertedIdentityReceived(event);
break;
case EventType.CallSDPStreamMetadataChanged:
case EventType.CallSDPStreamMetadataChangedPrefix:
call.onSDPStreamMetadataChangedReceived(event);
break;
}
})();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/groupCallEventHandler.js
var GroupCallEventHandlerEvent = /* @__PURE__ */ function(GroupCallEventHandlerEvent) {
GroupCallEventHandlerEvent["Incoming"] = "GroupCall.incoming";
GroupCallEventHandlerEvent["Outgoing"] = "GroupCall.outgoing";
GroupCallEventHandlerEvent["Ended"] = "GroupCall.ended";
GroupCallEventHandlerEvent["Participants"] = "GroupCall.participants";
return GroupCallEventHandlerEvent;
}({});
var GroupCallEventHandler = class {
constructor(client) {
this.client = client;
(0, import_defineProperty.default)(this, "groupCalls", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "roomDeferreds", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "onRoomsChanged", (room) => {
this.createGroupCallForRoom(room);
});
(0, import_defineProperty.default)(this, "onRoomStateChanged", (event, state) => {
if (event.getType() === EventType.GroupCallPrefix) {
var groupCallId = event.getStateKey();
var content = event.getContent();
var currentGroupCall = this.groupCalls.get(state.roomId);
if (!currentGroupCall && !content["m.terminated"] && !event.isRedacted()) this.createGroupCallFromRoomStateEvent(event);
else if (currentGroupCall && currentGroupCall.groupCallId === groupCallId) {
if (content["m.terminated"] || event.isRedacted()) currentGroupCall.terminate(false);
else if (content["m.type"] !== currentGroupCall.type) logger$2.warn("GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=".concat(state.roomId, ")"));
} else if (currentGroupCall && currentGroupCall.groupCallId !== groupCallId) logger$2.warn("GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=".concat(state.roomId, ")"));
}
});
}
start() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this.client.getSyncState() !== SyncState.Syncing) {
logger$2.debug("GroupCallEventHandler start() waiting for client to start syncing");
yield new Promise((resolve) => {
var onSync = () => {
if (_this.client.getSyncState() === SyncState.Syncing) {
_this.client.off(ClientEvent.Sync, onSync);
return resolve();
}
};
_this.client.on(ClientEvent.Sync, onSync);
});
}
for (var room of _this.client.getRooms()) _this.createGroupCallForRoom(room);
_this.client.on(ClientEvent.Room, _this.onRoomsChanged);
_this.client.on(RoomStateEvent.Events, _this.onRoomStateChanged);
})();
}
stop() {
this.client.removeListener(ClientEvent.Room, this.onRoomsChanged);
this.client.removeListener(RoomStateEvent.Events, this.onRoomStateChanged);
}
getRoomDeferred(roomId) {
var deferred = this.roomDeferreds.get(roomId);
if (deferred === void 0) {
var resolveFunc;
deferred = { prom: new Promise((resolve) => {
resolveFunc = resolve;
}) };
deferred.resolve = resolveFunc;
this.roomDeferreds.set(roomId, deferred);
}
return deferred;
}
waitUntilRoomReadyForGroupCalls(roomId) {
return this.getRoomDeferred(roomId).prom;
}
getGroupCallById(groupCallId) {
return [...this.groupCalls.values()].find((groupCall) => groupCall.groupCallId === groupCallId);
}
createGroupCallForRoom(room) {
var callEvents = room.currentState.getStateEvents(EventType.GroupCallPrefix);
for (var callEvent of callEvents.sort((a, b) => b.getTs() - a.getTs())) {
if (callEvent.getContent()["m.terminated"] || callEvent.isRedacted()) continue;
logger$2.debug("GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=".concat(callEvent.getStateKey(), ", ts=").concat(callEvent.getTs(), ", roomId=").concat(room.roomId, ", numOfPossibleCalls=").concat(callEvents.length, ")"));
this.createGroupCallFromRoomStateEvent(callEvent);
break;
}
this.getRoomDeferred(room.roomId).resolve();
}
createGroupCallFromRoomStateEvent(event) {
var roomId = event.getRoomId();
var content = event.getContent();
var room = this.client.getRoom(roomId);
if (!room) {
logger$2.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=".concat(roomId, ")"));
return;
}
var groupCallId = event.getStateKey();
var callType = content["m.type"];
if (!Object.values(GroupCallType).includes(callType)) {
logger$2.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=".concat(callType, ", roomId=").concat(roomId, ")"));
return;
}
var callIntent = content["m.intent"];
if (!Object.values(GroupCallIntent).includes(callIntent)) {
logger$2.warn("Received invalid group call intent (type=".concat(callType, ", roomId=").concat(roomId, ")"));
return;
}
var isPtt = Boolean(content["io.element.ptt"]);
var dataChannelOptions;
if (content !== null && content !== void 0 && content.dataChannelsEnabled && content !== null && content !== void 0 && content.dataChannelOptions) {
var { ordered, maxPacketLifeTime, maxRetransmits, protocol } = content.dataChannelOptions;
dataChannelOptions = {
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
}
var groupCall = new GroupCall(this.client, room, callType, isPtt, callIntent, groupCallId, (content === null || content === void 0 ? void 0 : content.dataChannelsEnabled) || this.client.isVoipWithNoMediaAllowed, dataChannelOptions, this.client.isVoipWithNoMediaAllowed, this.client.useLivekitForGroupCalls, content["io.element.livekit_service_url"]);
this.groupCalls.set(room.roomId, groupCall);
this.client.emit(GroupCallEventHandlerEvent.Incoming, groupCall);
return groupCall;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStats.js
var ConnectionStats = class {
constructor() {
(0, import_defineProperty.default)(this, "bandwidth", {});
(0, import_defineProperty.default)(this, "bitrate", {});
(0, import_defineProperty.default)(this, "packetLoss", {});
(0, import_defineProperty.default)(this, "transport", []);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStatsBuilder.js
var ConnectionStatsBuilder = class {
static buildBandwidthReport(now) {
var availableIncomingBitrate = now.availableIncomingBitrate;
var availableOutgoingBitrate = now.availableOutgoingBitrate;
return {
download: availableIncomingBitrate ? Math.round(availableIncomingBitrate / 1e3) : 0,
upload: availableOutgoingBitrate ? Math.round(availableOutgoingBitrate / 1e3) : 0
};
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/transportStatsBuilder.js
var TransportStatsBuilder = class {
static buildReport(report, now, conferenceStatsTransport, isFocus) {
var localUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.localCandidateId);
var remoteUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.remoteCandidateId);
if (remoteUsedCandidate && localUsedCandidate) {
var remoteIpAddress = remoteUsedCandidate.ip !== void 0 ? remoteUsedCandidate.ip : remoteUsedCandidate.address;
var remotePort = remoteUsedCandidate.port;
var ip = "".concat(remoteIpAddress, ":").concat(remotePort);
var localIpAddress = localUsedCandidate.ip !== void 0 ? localUsedCandidate.ip : localUsedCandidate.address;
var localPort = localUsedCandidate.port;
var localIp = "".concat(localIpAddress, ":").concat(localPort);
var type = remoteUsedCandidate.protocol;
if (!conferenceStatsTransport.some((t) => t.ip === ip && t.type === type && t.localIp === localIp)) conferenceStatsTransport.push({
ip,
type,
localIp,
isFocus,
localCandidateType: localUsedCandidate.candidateType,
remoteCandidateType: remoteUsedCandidate.candidateType,
networkType: localUsedCandidate.networkType,
rtt: now.currentRoundTripTime ? now.currentRoundTripTime * 1e3 : NaN
});
}
return conferenceStatsTransport;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaSsrcHandler.js
var import_lib = require_lib();
var MediaSsrcHandler = class {
constructor() {
(0, import_defineProperty.default)(this, "ssrcToMid", {
local: /* @__PURE__ */ new Map(),
remote: /* @__PURE__ */ new Map()
});
}
findMidBySsrc(ssrc, type) {
var mid;
this.ssrcToMid[type].forEach((ssrcs, m) => {
if (ssrcs.find((s) => s == ssrc)) {
mid = m;
return;
}
});
return mid;
}
parse(description, type) {
var sdp = (0, import_lib.parse)(description);
var ssrcToMid = /* @__PURE__ */ new Map();
sdp.media.forEach((m) => {
if (!!m.mid && m.type === "video" || m.type === "audio") {
var _m$ssrcs;
var ssrcs = [];
(_m$ssrcs = m.ssrcs) === null || _m$ssrcs === void 0 || _m$ssrcs.forEach((ssrc) => {
if (ssrc.attribute === "cname") ssrcs.push("".concat(ssrc.id));
});
ssrcToMid.set("".concat(m.mid), ssrcs);
}
});
this.ssrcToMid[type] = ssrcToMid;
}
getSsrcToMidMap(type) {
return this.ssrcToMid[type];
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackHandler.js
var MediaTrackHandler = class {
constructor(pc) {
this.pc = pc;
}
getLocalTracks(kind) {
var isNotNullAndKind = (track) => {
return track !== null && track.kind === kind;
};
return this.pc.getTransceivers().filter((t) => t.currentDirection === "sendonly" || t.currentDirection === "sendrecv").filter((t) => t.sender !== null).map((t) => t.sender).map((s) => s.track).filter(isNotNullAndKind);
}
getTackById(trackId) {
return this.pc.getTransceivers().map((t) => {
if ((t === null || t === void 0 ? void 0 : t.sender.track) !== null && t.sender.track.id === trackId) return t.sender.track;
if ((t === null || t === void 0 ? void 0 : t.receiver.track) !== null && t.receiver.track.id === trackId) return t.receiver.track;
}).find((t) => t !== void 0);
}
getLocalTrackIdByMid(mid) {
var _transceiver$sender;
var transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);
return transceiver === null || transceiver === void 0 || (_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 || (_transceiver$sender = _transceiver$sender.track) === null || _transceiver$sender === void 0 ? void 0 : _transceiver$sender.id;
}
getRemoteTrackIdByMid(mid) {
var _transceiver$receiver;
var transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);
return transceiver === null || transceiver === void 0 || (_transceiver$receiver = transceiver.receiver) === null || _transceiver$receiver === void 0 || (_transceiver$receiver = _transceiver$receiver.track) === null || _transceiver$receiver === void 0 ? void 0 : _transceiver$receiver.id;
}
getActiveSimulcastStreams() {
return 3;
}
getTransceiverByTrackId(trackId) {
return this.pc.getTransceivers().find((t) => {
return t.receiver.track.id === trackId || t.sender.track !== null && t.sender.track.id === trackId;
});
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackStats.js
var MediaTrackStats = class {
constructor(trackId, type, kind) {
this.trackId = trackId;
this.type = type;
this.kind = kind;
(0, import_defineProperty.default)(this, "loss", {
packetsTotal: 0,
packetsLost: 0,
isDownloadStream: false
});
(0, import_defineProperty.default)(this, "bitrate", {
download: 0,
upload: 0
});
(0, import_defineProperty.default)(this, "resolution", {
width: -1,
height: -1
});
(0, import_defineProperty.default)(this, "audioConcealment", {
concealedAudio: 0,
totalAudioDuration: 0
});
(0, import_defineProperty.default)(this, "framerate", 0);
(0, import_defineProperty.default)(this, "jitter", 0);
(0, import_defineProperty.default)(this, "codec", "");
(0, import_defineProperty.default)(this, "isAlive", true);
(0, import_defineProperty.default)(this, "isMuted", false);
(0, import_defineProperty.default)(this, "isEnabled", true);
}
getType() {
return this.type;
}
setLoss(loss) {
this.loss = loss;
}
getLoss() {
return this.loss;
}
setResolution(resolution) {
this.resolution = resolution;
}
getResolution() {
return this.resolution;
}
setFramerate(framerate) {
this.framerate = framerate;
}
getFramerate() {
return this.framerate;
}
setBitrate(bitrate) {
this.bitrate = bitrate;
}
getBitrate() {
return this.bitrate;
}
setCodec(codecShortType) {
this.codec = codecShortType;
return true;
}
getCodec() {
return this.codec;
}
resetBitrate() {
this.bitrate = {
download: 0,
upload: 0
};
}
set alive(isAlive) {
this.isAlive = isAlive;
}
/**
* A MediaTrackState is alive if the corresponding MediaStreamTrack track bound to a transceiver and the
* MediaStreamTrack is in state MediaStreamTrack.readyState === live
*/
get alive() {
return this.isAlive;
}
set muted(isMuted) {
this.isMuted = isMuted;
}
/**
* A MediaTrackState.isMuted corresponding to MediaStreamTrack.muted.
* But these values only match if MediaTrackState.isAlive.
*/
get muted() {
return this.isMuted;
}
set enabled(isEnabled) {
this.isEnabled = isEnabled;
}
/**
* A MediaTrackState.isEnabled corresponding to MediaStreamTrack.enabled.
* But these values only match if MediaTrackState.isAlive.
*/
get enabled() {
return this.isEnabled;
}
setJitter(jitter) {
this.jitter = jitter;
}
/**
* Jitter in milliseconds
*/
getJitter() {
return this.jitter;
}
/**
* Audio concealment ration (conceled duration / total duration)
*/
setAudioConcealment(concealedAudioDuration, totalAudioDuration) {
this.audioConcealment.concealedAudio = concealedAudioDuration;
this.audioConcealment.totalAudioDuration = totalAudioDuration;
}
getAudioConcealment() {
return this.audioConcealment;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackStatsHandler.js
var MediaTrackStatsHandler = class {
constructor(mediaSsrcHandler, mediaTrackHandler) {
this.mediaSsrcHandler = mediaSsrcHandler;
this.mediaTrackHandler = mediaTrackHandler;
(0, import_defineProperty.default)(this, "track2stats", /* @__PURE__ */ new Map());
}
/**
* Find tracks by rtc stats
* Argument report is any because the stats api is not consistent:
* For example `trackIdentifier`, `mid` not existing in every implementations
* https://www.w3.org/TR/webrtc-stats/#dom-rtcinboundrtpstreamstats
* https://developer.mozilla.org/en-US/docs/Web/API/RTCInboundRtpStreamStats
*/
findTrack2Stats(report, type) {
var trackID;
if (report.trackIdentifier) trackID = report.trackIdentifier;
else if (report.mid) trackID = type === "remote" ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid) : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);
else if (report.ssrc) {
if (!this.mediaSsrcHandler.findMidBySsrc(report.ssrc, type)) return;
trackID = type === "remote" ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid) : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);
}
if (!trackID) return;
var trackStats = this.track2stats.get(trackID);
if (!trackStats) {
var track = this.mediaTrackHandler.getTackById(trackID);
if (track !== void 0) {
var kind = track.kind === "audio" ? track.kind : "video";
trackStats = new MediaTrackStats(trackID, type, kind);
this.track2stats.set(trackID, trackStats);
} else return;
}
return trackStats;
}
findLocalVideoTrackStats(report) {
if (this.mediaTrackHandler.getLocalTracks("video").length === 0) return;
return this.findTrack2Stats(report, "local");
}
getTrack2stats() {
return this.track2stats;
}
findTransceiverByTrackId(trackID) {
return this.mediaTrackHandler.getTransceiverByTrackId(trackID);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/valueFormatter.js
var ValueFormatter = class {
static getNonNegativeValue(imput) {
var value = imput;
if (typeof value !== "number") value = Number(value);
if (isNaN(value)) return 0;
return Math.max(0, value);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/trackStatsBuilder.js
var TrackStatsBuilder = class TrackStatsBuilder {
static buildFramerateResolution(trackStats, now) {
var resolution = {
height: now.frameHeight,
width: now.frameWidth
};
var frameRate = now.framesPerSecond;
if (resolution.height && resolution.width) trackStats.setResolution(resolution);
trackStats.setFramerate(Math.round(frameRate || 0));
}
static calculateSimulcastFramerate(trackStats, now, before, layer) {
var frameRate = trackStats.getFramerate();
if (!frameRate) {
if (before) {
var timeMs = now.timestamp - before.timestamp;
if (timeMs > 0 && now.framesSent) frameRate = (now.framesSent - before.framesSent) / timeMs * 1e3;
}
if (!frameRate) return;
}
frameRate = layer ? Math.round(frameRate / layer) : 0;
trackStats.setFramerate(frameRate);
}
static buildCodec(report, trackStats, now) {
var codec = report === null || report === void 0 ? void 0 : report.get(now.codecId);
if (codec) {
/**
* The mime type has the following form: video/VP8 or audio/ISAC,
* so we what to keep just the type after the '/', audio and video
* keys will be added on the processing side.
*/
var codecShortType = codec.mimeType.split("/")[1];
if (codecShortType) trackStats.setCodec(codecShortType);
}
}
static buildBitrateReceived(trackStats, now, before) {
trackStats.setBitrate({
download: TrackStatsBuilder.calculateBitrate(now.bytesReceived, before.bytesReceived, now.timestamp, before.timestamp),
upload: 0
});
}
static buildBitrateSend(trackStats, now, before) {
trackStats.setBitrate({
download: 0,
upload: this.calculateBitrate(now.bytesSent, before.bytesSent, now.timestamp, before.timestamp)
});
}
static buildPacketsLost(trackStats, now, before) {
var key = now.type === "outbound-rtp" ? "packetsSent" : "packetsReceived";
var packetsNow = now[key];
if (!packetsNow || packetsNow < 0) packetsNow = 0;
var packetsBefore = ValueFormatter.getNonNegativeValue(before[key]);
var packetsDiff = Math.max(0, packetsNow - packetsBefore);
var packetsLostNow = ValueFormatter.getNonNegativeValue(now.packetsLost);
var packetsLostBefore = ValueFormatter.getNonNegativeValue(before.packetsLost);
var packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
trackStats.setLoss({
packetsTotal: packetsDiff + packetsLostDiff,
packetsLost: packetsLostDiff,
isDownloadStream: now.type !== "outbound-rtp"
});
}
static calculateBitrate(bytesNowAny, bytesBeforeAny, nowTimestamp, beforeTimestamp) {
var bytesNow = ValueFormatter.getNonNegativeValue(bytesNowAny);
var bytesBefore = ValueFormatter.getNonNegativeValue(bytesBeforeAny);
var bytesProcessed = Math.max(0, bytesNow - bytesBefore);
var timeMs = nowTimestamp - beforeTimestamp;
var bitrateKbps = 0;
if (timeMs > 0) bitrateKbps = Math.round(bytesProcessed * 8 / timeMs);
return bitrateKbps;
}
static setTrackStatsState(trackStats, transceiver) {
var _transceiver$sender;
if (transceiver === void 0) {
trackStats.alive = false;
return;
}
var track = trackStats.getType() === "remote" ? transceiver.receiver.track : transceiver === null || transceiver === void 0 || (_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 ? void 0 : _transceiver$sender.track;
if (track === void 0 || track === null) {
trackStats.alive = false;
return;
}
if (track.readyState === "ended") {
trackStats.alive = false;
return;
}
trackStats.muted = track.muted;
trackStats.enabled = track.enabled;
trackStats.alive = true;
}
static buildTrackSummary(trackStatsList) {
var videoTrackSummary = {
count: 0,
muted: 0,
maxJitter: 0,
maxPacketLoss: 0,
concealedAudio: 0,
totalAudio: 0
};
var audioTrackSummary = {
count: 0,
muted: 0,
maxJitter: 0,
maxPacketLoss: 0,
concealedAudio: 0,
totalAudio: 0
};
var remoteTrackList = trackStatsList.filter((t) => t.getType() === "remote");
var audioTrackList = remoteTrackList.filter((t) => t.kind === "audio");
remoteTrackList.forEach((stats) => {
var trackSummary = stats.kind === "video" ? videoTrackSummary : audioTrackSummary;
trackSummary.count++;
if (stats.alive && stats.muted) trackSummary.muted++;
if (trackSummary.maxJitter < stats.getJitter()) trackSummary.maxJitter = stats.getJitter();
if (trackSummary.maxPacketLoss < stats.getLoss().packetsLost) trackSummary.maxPacketLoss = stats.getLoss().packetsLost;
if (audioTrackList.length > 0) {
var _stats$getAudioConcea, _stats$getAudioConcea2;
trackSummary.concealedAudio += (_stats$getAudioConcea = stats.getAudioConcealment()) === null || _stats$getAudioConcea === void 0 ? void 0 : _stats$getAudioConcea.concealedAudio;
trackSummary.totalAudio += (_stats$getAudioConcea2 = stats.getAudioConcealment()) === null || _stats$getAudioConcea2 === void 0 ? void 0 : _stats$getAudioConcea2.totalAudioDuration;
}
});
return {
audioTrackSummary,
videoTrackSummary
};
}
static buildJitter(trackStats, statsReport) {
if (statsReport.type !== "inbound-rtp") return;
var jitterStr = statsReport === null || statsReport === void 0 ? void 0 : statsReport.jitter;
if (jitterStr !== void 0) {
var jitter = ValueFormatter.getNonNegativeValue(jitterStr);
trackStats.setJitter(Math.round(jitter * 1e3));
} else trackStats.setJitter(-1);
}
static buildAudioConcealment(trackStats, statsReport) {
if (statsReport.type !== "inbound-rtp") return;
var concealedAudioDuration = 1e3 * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesDuration) / (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesReceived) * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.concealedSamples);
var totalAudioDuration = 1e3 * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesDuration);
trackStats.setAudioConcealment(concealedAudioDuration, totalAudioDuration);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStatsReportBuilder.js
var ConnectionStatsReportBuilder = class ConnectionStatsReportBuilder {
static build(stats) {
var report = {};
var totalPackets = {
download: 0,
upload: 0
};
var lostPackets = {
download: 0,
upload: 0
};
var bitrateDownload = 0;
var bitrateUpload = 0;
var resolutions = {
local: /* @__PURE__ */ new Map(),
remote: /* @__PURE__ */ new Map()
};
var framerates = {
local: /* @__PURE__ */ new Map(),
remote: /* @__PURE__ */ new Map()
};
var codecs = {
local: /* @__PURE__ */ new Map(),
remote: /* @__PURE__ */ new Map()
};
var jitter = /* @__PURE__ */ new Map();
var audioConcealment = /* @__PURE__ */ new Map();
var audioBitrateDownload = 0;
var audioBitrateUpload = 0;
var videoBitrateDownload = 0;
var videoBitrateUpload = 0;
var totalConcealedAudio = 0;
var totalAudioDuration = 0;
for (var [trackId, trackStats] of stats) {
var loss = trackStats.getLoss();
var type = loss.isDownloadStream ? "download" : "upload";
totalPackets[type] += loss.packetsTotal;
lostPackets[type] += loss.packetsLost;
bitrateDownload += trackStats.getBitrate().download;
bitrateUpload += trackStats.getBitrate().upload;
if (trackStats.kind === "audio") {
var audioConcealmentForTrack = trackStats.getAudioConcealment();
totalConcealedAudio += audioConcealmentForTrack.concealedAudio;
totalAudioDuration += audioConcealmentForTrack.totalAudioDuration;
audioBitrateDownload += trackStats.getBitrate().download;
audioBitrateUpload += trackStats.getBitrate().upload;
} else {
videoBitrateDownload += trackStats.getBitrate().download;
videoBitrateUpload += trackStats.getBitrate().upload;
}
resolutions[trackStats.getType()].set(trackId, trackStats.getResolution());
framerates[trackStats.getType()].set(trackId, trackStats.getFramerate());
codecs[trackStats.getType()].set(trackId, trackStats.getCodec());
if (trackStats.getType() === "remote") {
jitter.set(trackId, trackStats.getJitter());
if (trackStats.kind === "audio") audioConcealment.set(trackId, trackStats.getAudioConcealment());
}
trackStats.resetBitrate();
}
report.bitrate = {
upload: bitrateUpload,
download: bitrateDownload
};
report.bitrate.audio = {
upload: audioBitrateUpload,
download: audioBitrateDownload
};
report.bitrate.video = {
upload: videoBitrateUpload,
download: videoBitrateDownload
};
report.packetLoss = {
total: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.download + lostPackets.upload, totalPackets.download + totalPackets.upload),
download: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.download, totalPackets.download),
upload: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.upload, totalPackets.upload)
};
report.audioConcealment = audioConcealment;
report.totalAudioConcealment = {
concealedAudio: totalConcealedAudio,
totalAudioDuration
};
report.framerate = framerates;
report.resolution = resolutions;
report.codec = codecs;
report.jitter = jitter;
return report;
}
static calculatePacketLoss(lostPackets, totalPackets) {
if (!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0) return 0;
return Math.round(lostPackets / totalPackets * 100);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/callFeedStatsReporter.js
var CallFeedStatsReporter = class CallFeedStatsReporter {
static buildCallFeedReport(callId, opponentMemberId, pc) {
var rtpTransceivers = pc.getTransceivers();
var transceiver = [];
var callFeeds = [];
rtpTransceivers.forEach((t) => {
var _t$sender;
var sender = (_t$sender = t.sender) !== null && _t$sender !== void 0 && _t$sender.track ? CallFeedStatsReporter.buildTrackStats(t.sender.track, "sender") : null;
var receiver = CallFeedStatsReporter.buildTrackStats(t.receiver.track, "receiver");
transceiver.push({
mid: t.mid == null ? "null" : t.mid,
direction: t.direction,
currentDirection: t.currentDirection == null ? "null" : t.currentDirection,
sender,
receiver
});
});
return {
callId,
opponentMemberId,
transceiver,
callFeeds
};
}
static buildTrackStats(track) {
var _track$getSettings, _track$getConstraints;
var label = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "--";
var settingDeviceId = (_track$getSettings = track.getSettings()) === null || _track$getSettings === void 0 ? void 0 : _track$getSettings.deviceId;
var constrainDeviceId = (_track$getConstraints = track.getConstraints()) === null || _track$getConstraints === void 0 ? void 0 : _track$getConstraints.deviceId;
return {
id: track.id,
kind: track.kind,
settingDeviceId: settingDeviceId !== null && settingDeviceId !== void 0 ? settingDeviceId : "unknown",
constrainDeviceId: constrainDeviceId !== null && constrainDeviceId !== void 0 ? constrainDeviceId : "unknown",
muted: track.muted,
enabled: track.enabled,
readyState: track.readyState,
label
};
}
static expandCallFeedReport(report, callFeeds) {
var prefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "unknown";
callFeeds.forEach((feed) => {
var audioTracks = feed.stream.getAudioTracks();
var videoTracks = feed.stream.getVideoTracks();
var audio = audioTracks.length > 0 ? CallFeedStatsReporter.buildTrackStats(feed.stream.getAudioTracks()[0], feed.purpose) : null;
var video = videoTracks.length > 0 ? CallFeedStatsReporter.buildTrackStats(feed.stream.getVideoTracks()[0], feed.purpose) : null;
var feedStats = {
stream: feed.stream.id,
type: feed.isLocal() ? "local" : "remote",
audio,
video,
purpose: feed.purpose,
prefix,
isVideoMuted: feed.isVideoMuted(),
isAudioMuted: feed.isAudioMuted()
};
report.callFeeds.push(feedStats);
});
return report;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/callStatsReportGatherer.js
function ownKeys$11(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;
}
function _objectSpread$11(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$11(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$11(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var CallStatsReportGatherer = class {
constructor(callId, opponentMemberId, pc, emitter) {
var isFocus = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
this.callId = callId;
this.opponentMemberId = opponentMemberId;
this.pc = pc;
this.emitter = emitter;
this.isFocus = isFocus;
(0, import_defineProperty.default)(this, "isActive", true);
(0, import_defineProperty.default)(this, "previousStatsReport", void 0);
(0, import_defineProperty.default)(this, "currentStatsReport", void 0);
(0, import_defineProperty.default)(this, "connectionStats", new ConnectionStats());
(0, import_defineProperty.default)(this, "trackStats", void 0);
pc.addEventListener("signalingstatechange", this.onSignalStateChange.bind(this));
this.trackStats = new MediaTrackStatsHandler(new MediaSsrcHandler(), new MediaTrackHandler(pc));
}
processStats(groupCallId, localUserId) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var summary = {
isFirstCollection: _this.previousStatsReport === void 0,
receivedMedia: 0,
receivedAudioMedia: 0,
receivedVideoMedia: 0,
audioTrackSummary: {
count: 0,
muted: 0,
maxPacketLoss: 0,
maxJitter: 0,
concealedAudio: 0,
totalAudio: 0
},
videoTrackSummary: {
count: 0,
muted: 0,
maxPacketLoss: 0,
maxJitter: 0,
concealedAudio: 0,
totalAudio: 0
}
};
if (_this.isActive) {
var statsPromise = _this.pc.getStats();
if (typeof (statsPromise === null || statsPromise === void 0 ? void 0 : statsPromise.then) === "function") return statsPromise.then((report) => {
var _this$connectionStats, _this$connectionStats2;
_this.currentStatsReport = typeof (report === null || report === void 0 ? void 0 : report.result) === "function" ? report.result() : report;
try {
_this.processStatsReport(groupCallId, localUserId);
} catch (error) {
_this.handleError(error);
return summary;
}
_this.previousStatsReport = _this.currentStatsReport;
summary.receivedMedia = _this.connectionStats.bitrate.download;
summary.receivedAudioMedia = ((_this$connectionStats = _this.connectionStats.bitrate.audio) === null || _this$connectionStats === void 0 ? void 0 : _this$connectionStats.download) || 0;
summary.receivedVideoMedia = ((_this$connectionStats2 = _this.connectionStats.bitrate.video) === null || _this$connectionStats2 === void 0 ? void 0 : _this$connectionStats2.download) || 0;
var trackSummary = TrackStatsBuilder.buildTrackSummary(Array.from(_this.trackStats.getTrack2stats().values()));
return _objectSpread$11(_objectSpread$11({}, summary), {}, {
audioTrackSummary: trackSummary.audioTrackSummary,
videoTrackSummary: trackSummary.videoTrackSummary
});
}).catch((error) => {
_this.handleError(error);
return summary;
});
_this.isActive = false;
}
return Promise.resolve(summary);
})();
}
processStatsReport(groupCallId, localUserId) {
var _this$currentStatsRep;
var byteSentStatsReport = /* @__PURE__ */ new Map();
byteSentStatsReport.callId = this.callId;
byteSentStatsReport.opponentMemberId = this.opponentMemberId;
(_this$currentStatsRep = this.currentStatsReport) === null || _this$currentStatsRep === void 0 || _this$currentStatsRep.forEach((now) => {
var before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;
if (now.type === "candidate-pair" && now.nominated && now.state === "succeeded") {
this.connectionStats.bandwidth = ConnectionStatsBuilder.buildBandwidthReport(now);
this.connectionStats.transport = TransportStatsBuilder.buildReport(this.currentStatsReport, now, this.connectionStats.transport, this.isFocus);
} else if (now.type === "inbound-rtp" || now.type === "outbound-rtp") {
var trackStats = this.trackStats.findTrack2Stats(now, now.type === "inbound-rtp" ? "remote" : "local");
if (!trackStats) return;
if (before) TrackStatsBuilder.buildPacketsLost(trackStats, now, before);
if (now.type === "inbound-rtp") {
TrackStatsBuilder.buildFramerateResolution(trackStats, now);
if (before) TrackStatsBuilder.buildBitrateReceived(trackStats, now, before);
var ts = this.trackStats.findTransceiverByTrackId(trackStats.trackId);
TrackStatsBuilder.setTrackStatsState(trackStats, ts);
TrackStatsBuilder.buildJitter(trackStats, now);
TrackStatsBuilder.buildAudioConcealment(trackStats, now);
} else if (before) {
byteSentStatsReport.set(trackStats.trackId, ValueFormatter.getNonNegativeValue(now.bytesSent));
TrackStatsBuilder.buildBitrateSend(trackStats, now, before);
}
TrackStatsBuilder.buildCodec(this.currentStatsReport, trackStats, now);
} else if (now.type === "track" && now.kind === "video" && !now.remoteSource) {
var _trackStats = this.trackStats.findLocalVideoTrackStats(now);
if (!_trackStats) return;
TrackStatsBuilder.buildFramerateResolution(_trackStats, now);
TrackStatsBuilder.calculateSimulcastFramerate(_trackStats, now, before, this.trackStats.mediaTrackHandler.getActiveSimulcastStreams());
}
});
this.emitter.emitByteSendReport(byteSentStatsReport);
this.emitter.emitCallFeedReport(CallFeedStatsReporter.buildCallFeedReport(this.callId, this.opponentMemberId, this.pc));
this.processAndEmitConnectionStatsReport();
}
setActive(isActive) {
this.isActive = isActive;
}
getActive() {
return this.isActive;
}
handleError(error) {
this.isActive = false;
logger$2.warn("CallStatsReportGatherer ".concat(this.callId, " processStatsReport fails and set to inactive ").concat(error));
}
processAndEmitConnectionStatsReport() {
var report = ConnectionStatsReportBuilder.build(this.trackStats.getTrack2stats());
report.callId = this.callId;
report.opponentMemberId = this.opponentMemberId;
this.connectionStats.bandwidth = report.bandwidth;
this.connectionStats.bitrate = report.bitrate;
this.connectionStats.packetLoss = report.packetLoss;
this.emitter.emitConnectionStatsReport(_objectSpread$11(_objectSpread$11({}, report), {}, { transport: this.connectionStats.transport }));
this.connectionStats.transport = [];
}
stopProcessingStats() {}
onSignalStateChange() {
if (this.pc.signalingState === "stable") {
if (this.pc.currentRemoteDescription) this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp, "remote");
if (this.pc.currentLocalDescription) this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp, "local");
}
}
setOpponentMemberId(id) {
this.opponentMemberId = id;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/statsReport.js
var StatsReport = /* @__PURE__ */ function(StatsReport) {
StatsReport["CONNECTION_STATS"] = "StatsReport.connection_stats";
StatsReport["CALL_FEED_REPORT"] = "StatsReport.call_feed_report";
StatsReport["BYTE_SENT_STATS"] = "StatsReport.byte_sent_stats";
StatsReport["SUMMARY_STATS"] = "StatsReport.summary_stats";
return StatsReport;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/statsReportEmitter.js
var StatsReportEmitter = class extends TypedEventEmitter {
emitByteSendReport(byteSentStats) {
this.emit(StatsReport.BYTE_SENT_STATS, byteSentStats);
}
emitConnectionStatsReport(report) {
this.emit(StatsReport.CONNECTION_STATS, report);
}
emitCallFeedReport(report) {
this.emit(StatsReport.CALL_FEED_REPORT, report);
}
emitSummaryStatsReport(report) {
this.emit(StatsReport.SUMMARY_STATS, report);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/summaryStatsReportGatherer.js
var SummaryStatsReportGatherer = class {
constructor(emitter) {
this.emitter = emitter;
}
build(allSummary) {
var summary = allSummary.filter((s) => !s.isFirstCollection);
var summaryTotalCount = summary.length;
var peerConnectionsCount = allSummary.length;
if (summaryTotalCount === 0) return;
var summaryCounter = {
receivedAudio: 0,
receivedVideo: 0,
receivedMedia: 0,
concealedAudio: 0,
totalAudio: 0
};
var maxJitter = 0;
var maxPacketLoss = 0;
summary.forEach((stats) => {
this.countTrackListReceivedMedia(summaryCounter, stats);
this.countConcealedAudio(summaryCounter, stats);
maxJitter = this.buildMaxJitter(maxJitter, stats);
maxPacketLoss = this.buildMaxPacketLoss(maxPacketLoss, stats);
});
var decimalPlaces = 5;
var report = {
percentageReceivedMedia: Number((summaryCounter.receivedMedia / summaryTotalCount).toFixed(decimalPlaces)),
percentageReceivedVideoMedia: Number((summaryCounter.receivedVideo / summaryTotalCount).toFixed(decimalPlaces)),
percentageReceivedAudioMedia: Number((summaryCounter.receivedAudio / summaryTotalCount).toFixed(decimalPlaces)),
maxJitter,
maxPacketLoss,
percentageConcealedAudio: Number(summaryCounter.totalAudio > 0 ? (summaryCounter.concealedAudio / summaryCounter.totalAudio).toFixed(decimalPlaces) : 0),
peerConnections: peerConnectionsCount
};
this.emitter.emitSummaryStatsReport(report);
}
static extendSummaryReport(report, callParticipants) {
var devices = [];
var users = [];
for (var userEntry of callParticipants) {
users.push(userEntry);
for (var device of userEntry[1]) devices.push(device);
}
report.opponentDevicesInCall = Math.max(0, devices.length - 1);
report.opponentUsersInCall = Math.max(0, users.length - 1);
report.diffDevicesToPeerConnections = Math.max(0, devices.length - 1) - report.peerConnections;
report.ratioPeerConnectionToDevices = Math.max(0, devices.length - 1) == 0 ? 0 : report.peerConnections / (devices.length - 1);
}
countTrackListReceivedMedia(counter, stats) {
var hasReceivedAudio = false;
var hasReceivedVideo = false;
if (stats.receivedAudioMedia > 0 || stats.audioTrackSummary.count === 0) {
counter.receivedAudio++;
hasReceivedAudio = true;
}
if (stats.receivedVideoMedia > 0 || stats.videoTrackSummary.count === 0) {
counter.receivedVideo++;
hasReceivedVideo = true;
} else if (stats.videoTrackSummary.muted > 0 && stats.videoTrackSummary.muted === stats.videoTrackSummary.count) {
counter.receivedVideo++;
hasReceivedVideo = true;
}
if (hasReceivedVideo && hasReceivedAudio) counter.receivedMedia++;
}
buildMaxJitter(maxJitter, stats) {
if (maxJitter < stats.videoTrackSummary.maxJitter) maxJitter = stats.videoTrackSummary.maxJitter;
if (maxJitter < stats.audioTrackSummary.maxJitter) maxJitter = stats.audioTrackSummary.maxJitter;
return maxJitter;
}
buildMaxPacketLoss(maxPacketLoss, stats) {
if (maxPacketLoss < stats.videoTrackSummary.maxPacketLoss) maxPacketLoss = stats.videoTrackSummary.maxPacketLoss;
if (maxPacketLoss < stats.audioTrackSummary.maxPacketLoss) maxPacketLoss = stats.audioTrackSummary.maxPacketLoss;
return maxPacketLoss;
}
countConcealedAudio(summaryCounter, stats) {
summaryCounter.concealedAudio += stats.audioTrackSummary.concealedAudio;
summaryCounter.totalAudio += stats.audioTrackSummary.totalAudio;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/stats/groupCallStats.js
var GroupCallStats = class {
constructor(groupCallId, userId) {
var interval = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1e4;
this.groupCallId = groupCallId;
this.userId = userId;
this.interval = interval;
(0, import_defineProperty.default)(this, "timer", void 0);
(0, import_defineProperty.default)(this, "gatherers", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "reports", new StatsReportEmitter());
(0, import_defineProperty.default)(this, "summaryStatsReportGatherer", new SummaryStatsReportGatherer(this.reports));
}
start() {
if (this.timer === void 0 && this.interval > 0) this.timer = setInterval(() => {
this.processStats();
}, this.interval);
}
stop() {
if (this.timer !== void 0) {
clearInterval(this.timer);
this.gatherers.forEach((c) => c.stopProcessingStats());
}
}
hasStatsReportGatherer(callId) {
return this.gatherers.has(callId);
}
addStatsReportGatherer(callId, opponentMemberId, peerConnection) {
if (this.hasStatsReportGatherer(callId)) return false;
this.gatherers.set(callId, new CallStatsReportGatherer(callId, opponentMemberId, peerConnection, this.reports));
return true;
}
removeStatsReportGatherer(callId) {
return this.gatherers.delete(callId);
}
getStatsReportGatherer(callId) {
return this.hasStatsReportGatherer(callId) ? this.gatherers.get(callId) : void 0;
}
updateOpponentMember(callId, opponentMember) {
var _this$getStatsReportG;
(_this$getStatsReportG = this.getStatsReportGatherer(callId)) === null || _this$getStatsReportG === void 0 || _this$getStatsReportG.setOpponentMemberId(opponentMember);
}
processStats() {
var summary = [];
this.gatherers.forEach((c) => {
summary.push(c.processStats(this.groupCallId, this.userId));
});
Promise.all(summary).then((s) => this.summaryStatsReportGatherer.build(s)).catch((err) => {
logger$2.error("Could not build summary stats report", err);
});
}
setInterval(interval) {
this.interval = interval;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/groupCall.js
function ownKeys$10(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;
}
function _objectSpread$10(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$10(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$10(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var GroupCallIntent = /* @__PURE__ */ function(GroupCallIntent) {
GroupCallIntent["Ring"] = "m.ring";
GroupCallIntent["Prompt"] = "m.prompt";
GroupCallIntent["Room"] = "m.room";
return GroupCallIntent;
}({});
var GroupCallType = /* @__PURE__ */ function(GroupCallType) {
GroupCallType["Video"] = "m.video";
GroupCallType["Voice"] = "m.voice";
return GroupCallType;
}({});
var GroupCallTerminationReason = /* @__PURE__ */ function(GroupCallTerminationReason) {
GroupCallTerminationReason["CallEnded"] = "call_ended";
return GroupCallTerminationReason;
}({});
/**
* Because event names are just strings, they do need
* to be unique over all event types of event emitter.
* Some objects could emit more then one set of events.
*/
var GroupCallEvent = /* @__PURE__ */ function(GroupCallEvent) {
GroupCallEvent["GroupCallStateChanged"] = "group_call_state_changed";
GroupCallEvent["ActiveSpeakerChanged"] = "active_speaker_changed";
GroupCallEvent["CallsChanged"] = "calls_changed";
GroupCallEvent["UserMediaFeedsChanged"] = "user_media_feeds_changed";
GroupCallEvent["ScreenshareFeedsChanged"] = "screenshare_feeds_changed";
GroupCallEvent["LocalScreenshareStateChanged"] = "local_screenshare_state_changed";
GroupCallEvent["LocalMuteStateChanged"] = "local_mute_state_changed";
GroupCallEvent["ParticipantsChanged"] = "participants_changed";
GroupCallEvent["Error"] = "group_call_error";
return GroupCallEvent;
}({});
var GroupCallStatsReportEvent = /* @__PURE__ */ function(GroupCallStatsReportEvent) {
GroupCallStatsReportEvent["ConnectionStats"] = "GroupCall.connection_stats";
GroupCallStatsReportEvent["ByteSentStats"] = "GroupCall.byte_sent_stats";
GroupCallStatsReportEvent["SummaryStats"] = "GroupCall.summary_stats";
GroupCallStatsReportEvent["CallFeedStats"] = "GroupCall.call_feed_stats";
return GroupCallStatsReportEvent;
}({});
/**
* The final report-events that get consumed by client.
*/
var GroupCallErrorCode = /* @__PURE__ */ function(GroupCallErrorCode) {
GroupCallErrorCode["NoUserMedia"] = "no_user_media";
GroupCallErrorCode["UnknownDevice"] = "unknown_device";
GroupCallErrorCode["PlaceCallFailed"] = "place_call_failed";
return GroupCallErrorCode;
}({});
var GroupCallError = class extends Error {
constructor(code, msg, err) {
if (err) {
super(msg + ": " + err);
(0, import_defineProperty.default)(this, "code", void 0);
} else {
super(msg);
(0, import_defineProperty.default)(this, "code", void 0);
}
this.code = code;
}
};
var GroupCallUnknownDeviceError = class extends GroupCallError {
constructor(userId) {
super(GroupCallErrorCode.UnknownDevice, "No device found for " + userId);
this.userId = userId;
}
};
var GroupCallState = /* @__PURE__ */ function(GroupCallState) {
GroupCallState["LocalCallFeedUninitialized"] = "local_call_feed_uninitialized";
GroupCallState["InitializingLocalCallFeed"] = "initializing_local_call_feed";
GroupCallState["LocalCallFeedInitialized"] = "local_call_feed_initialized";
GroupCallState["Entered"] = "entered";
GroupCallState["Ended"] = "ended";
return GroupCallState;
}({});
var DEVICE_TIMEOUT = 1e3 * 60 * 60;
function getCallUserId(call) {
var _call$getOpponentMemb;
return ((_call$getOpponentMemb = call.getOpponentMember()) === null || _call$getOpponentMemb === void 0 ? void 0 : _call$getOpponentMemb.userId) || call.invitee || null;
}
var GroupCall = class extends TypedEventEmitter {
constructor(client, room, type, isPtt, intent, groupCallId, dataChannelsEnabled, dataChannelOptions, isCallWithoutVideoAndAudio) {
var _room$currentState$ge, _room$currentState$ge2;
var useLivekit = arguments.length > 9 && arguments[9] !== void 0 ? arguments[9] : false;
var livekitServiceURL = arguments.length > 10 ? arguments[10] : void 0;
super();
this.client = client;
this.room = room;
this.type = type;
this.isPtt = isPtt;
this.intent = intent;
this.dataChannelsEnabled = dataChannelsEnabled;
this.dataChannelOptions = dataChannelOptions;
this.useLivekit = useLivekit;
(0, import_defineProperty.default)(this, "activeSpeakerInterval", 1e3);
(0, import_defineProperty.default)(this, "retryCallInterval", 5e3);
(0, import_defineProperty.default)(this, "participantTimeout", 1e3 * 15);
(0, import_defineProperty.default)(this, "pttMaxTransmitTime", 1e3 * 20);
(0, import_defineProperty.default)(this, "activeSpeaker", void 0);
(0, import_defineProperty.default)(this, "localCallFeed", void 0);
(0, import_defineProperty.default)(this, "localScreenshareFeed", void 0);
(0, import_defineProperty.default)(this, "localDesktopCapturerSourceId", void 0);
(0, import_defineProperty.default)(this, "userMediaFeeds", []);
(0, import_defineProperty.default)(this, "screenshareFeeds", []);
(0, import_defineProperty.default)(this, "groupCallId", void 0);
(0, import_defineProperty.default)(this, "allowCallWithoutVideoAndAudio", void 0);
(0, import_defineProperty.default)(this, "calls", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "callHandlers", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "activeSpeakerLoopInterval", void 0);
(0, import_defineProperty.default)(this, "retryCallLoopInterval", void 0);
(0, import_defineProperty.default)(this, "retryCallCounts", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "reEmitter", void 0);
(0, import_defineProperty.default)(this, "transmitTimer", null);
(0, import_defineProperty.default)(this, "participantsExpirationTimer", null);
(0, import_defineProperty.default)(this, "resendMemberStateTimer", null);
(0, import_defineProperty.default)(this, "initWithAudioMuted", false);
(0, import_defineProperty.default)(this, "initWithVideoMuted", false);
(0, import_defineProperty.default)(this, "initCallFeedPromise", void 0);
(0, import_defineProperty.default)(this, "_livekitServiceURL", void 0);
(0, import_defineProperty.default)(this, "stats", void 0);
/**
* Configure default webrtc stats collection interval in ms
* Disable collecting webrtc stats by setting interval to 0
*/
(0, import_defineProperty.default)(this, "statsCollectIntervalTime", 0);
(0, import_defineProperty.default)(this, "onConnectionStats", (report) => {
this.emit(GroupCallStatsReportEvent.ConnectionStats, { report });
});
(0, import_defineProperty.default)(this, "onByteSentStats", (report) => {
this.emit(GroupCallStatsReportEvent.ByteSentStats, { report });
});
(0, import_defineProperty.default)(this, "onSummaryStats", (report) => {
SummaryStatsReportGatherer.extendSummaryReport(report, this.participants);
this.emit(GroupCallStatsReportEvent.SummaryStats, { report });
});
(0, import_defineProperty.default)(this, "onCallFeedReport", (report) => {
if (this.localCallFeed) report = CallFeedStatsReporter.expandCallFeedReport(report, [this.localCallFeed], "from-local-feed");
var callFeeds = [];
this.forEachCall((call) => {
if (call.callId === report.callId) call.getFeeds().forEach((f) => callFeeds.push(f));
});
report = CallFeedStatsReporter.expandCallFeedReport(report, callFeeds, "from-call-feed");
this.emit(GroupCallStatsReportEvent.CallFeedStats, { report });
});
(0, import_defineProperty.default)(this, "_state", GroupCallState.LocalCallFeedUninitialized);
(0, import_defineProperty.default)(this, "_participants", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "_creationTs", null);
(0, import_defineProperty.default)(this, "_enteredViaAnotherSession", false);
(0, import_defineProperty.default)(this, "onIncomingCall", (newCall) => {
var _newCall$getOpponentM, _this$calls$get;
if (newCall.roomId !== this.room.roomId) return;
if (newCall.state !== CallState.Ringing) {
logger$2.warn("GroupCall ".concat(this.groupCallId, " onIncomingCall() incoming call no longer in ringing state - ignoring"));
return;
}
if (!newCall.groupCallId || newCall.groupCallId !== this.groupCallId) {
logger$2.log("GroupCall ".concat(this.groupCallId, " onIncomingCall() ignored because it doesn't match the current group call"));
newCall.reject();
return;
}
var opponentUserId = (_newCall$getOpponentM = newCall.getOpponentMember()) === null || _newCall$getOpponentM === void 0 ? void 0 : _newCall$getOpponentM.userId;
if (opponentUserId === void 0) {
logger$2.warn("GroupCall ".concat(this.groupCallId, " onIncomingCall() incoming call with no member - ignoring"));
return;
}
if (this.useLivekit) {
logger$2.info("Received incoming call whilst in signaling-only mode! Ignoring.");
return;
}
var deviceMap = (_this$calls$get = this.calls.get(opponentUserId)) !== null && _this$calls$get !== void 0 ? _this$calls$get : /* @__PURE__ */ new Map();
var prevCall = deviceMap.get(newCall.getOpponentDeviceId());
if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.callId) === newCall.callId) return;
logger$2.log("GroupCall ".concat(this.groupCallId, " onIncomingCall() incoming call (userId=").concat(opponentUserId, ", callId=").concat(newCall.callId, ")"));
if (prevCall) prevCall.hangup(CallErrorCode.Replaced, false);
deviceMap.set(newCall.getOpponentDeviceId(), newCall);
this.calls.set(opponentUserId, deviceMap);
this.initCall(newCall);
var feeds = this.getLocalFeeds().map((feed) => feed.clone());
if (!this.callExpected(newCall)) for (var feed of feeds) {
setTracksEnabled(feed.stream.getAudioTracks(), false);
setTracksEnabled(feed.stream.getVideoTracks(), false);
}
newCall.answerWithCallFeeds(feeds);
this.emit(GroupCallEvent.CallsChanged, this.calls);
});
(0, import_defineProperty.default)(this, "onRetryCallLoop", () => {
var needsRetry = false;
for (var [{ userId: _userId }, participantMap] of this.participants) {
var callMap = this.calls.get(_userId);
var retriesMap = this.retryCallCounts.get(_userId);
for (var [deviceId, participant] of participantMap) {
var _retriesMap$get, _retriesMap;
var call = callMap === null || callMap === void 0 ? void 0 : callMap.get(deviceId);
var retries = (_retriesMap$get = (_retriesMap = retriesMap) === null || _retriesMap === void 0 ? void 0 : _retriesMap.get(deviceId)) !== null && _retriesMap$get !== void 0 ? _retriesMap$get : 0;
if ((call === null || call === void 0 ? void 0 : call.getOpponentSessionId()) !== participant.sessionId && this.wantsOutgoingCall(_userId, deviceId) && retries < 3) {
if (retriesMap === void 0) {
retriesMap = /* @__PURE__ */ new Map();
this.retryCallCounts.set(_userId, retriesMap);
}
retriesMap.set(deviceId, retries + 1);
needsRetry = true;
}
}
}
if (needsRetry) this.placeOutgoingCalls();
});
(0, import_defineProperty.default)(this, "onCallFeedsChanged", (call) => {
var opponentMemberId = getCallUserId(call);
var opponentDeviceId = call.getOpponentDeviceId();
if (!opponentMemberId) throw new Error("Cannot change call feeds without user id");
var currentUserMediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);
var remoteUsermediaFeed = call.remoteUsermediaFeed;
var remoteFeedChanged = remoteUsermediaFeed !== currentUserMediaFeed;
var deviceMap = this.calls.get(opponentMemberId);
var currentCallForUserDevice = deviceMap === null || deviceMap === void 0 ? void 0 : deviceMap.get(opponentDeviceId);
if ((currentCallForUserDevice === null || currentCallForUserDevice === void 0 ? void 0 : currentCallForUserDevice.callId) !== call.callId) return;
if (remoteFeedChanged) {
if (!currentUserMediaFeed && remoteUsermediaFeed) this.addUserMediaFeed(remoteUsermediaFeed);
else if (currentUserMediaFeed && remoteUsermediaFeed) this.replaceUserMediaFeed(currentUserMediaFeed, remoteUsermediaFeed);
else if (currentUserMediaFeed && !remoteUsermediaFeed) this.removeUserMediaFeed(currentUserMediaFeed);
}
var currentScreenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);
var remoteScreensharingFeed = call.remoteScreensharingFeed;
if (remoteScreensharingFeed !== currentScreenshareFeed) {
if (!currentScreenshareFeed && remoteScreensharingFeed) this.addScreenshareFeed(remoteScreensharingFeed);
else if (currentScreenshareFeed && remoteScreensharingFeed) this.replaceScreenshareFeed(currentScreenshareFeed, remoteScreensharingFeed);
else if (currentScreenshareFeed && !remoteScreensharingFeed) this.removeScreenshareFeed(currentScreenshareFeed);
}
});
(0, import_defineProperty.default)(this, "onCallStateChanged", (call, state, _oldState) => {
var _call$getOpponentMemb2;
if (state === CallState.Ended) return;
var audioMuted = this.localCallFeed.isAudioMuted();
if (call.localUsermediaStream && call.isMicrophoneMuted() !== audioMuted) call.setMicrophoneMuted(audioMuted);
var videoMuted = this.localCallFeed.isVideoMuted();
if (call.localUsermediaStream && call.isLocalVideoMuted() !== videoMuted) call.setLocalVideoMuted(videoMuted);
var opponentUserId = (_call$getOpponentMemb2 = call.getOpponentMember()) === null || _call$getOpponentMemb2 === void 0 ? void 0 : _call$getOpponentMemb2.userId;
if (state === CallState.Connected && opponentUserId) {
var retriesMap = this.retryCallCounts.get(opponentUserId);
retriesMap === null || retriesMap === void 0 || retriesMap.delete(call.getOpponentDeviceId());
if ((retriesMap === null || retriesMap === void 0 ? void 0 : retriesMap.size) === 0) this.retryCallCounts.delete(opponentUserId);
}
});
(0, import_defineProperty.default)(this, "onCallHangup", (call) => {
var _call$getOpponentMemb3, _call$getOpponentMemb4;
if (call.hangupReason === CallErrorCode.Replaced) return;
var opponentUserId = (_call$getOpponentMemb3 = (_call$getOpponentMemb4 = call.getOpponentMember()) === null || _call$getOpponentMemb4 === void 0 ? void 0 : _call$getOpponentMemb4.userId) !== null && _call$getOpponentMemb3 !== void 0 ? _call$getOpponentMemb3 : this.room.getMember(call.invitee).userId;
var deviceMap = this.calls.get(opponentUserId);
if ((deviceMap === null || deviceMap === void 0 ? void 0 : deviceMap.get(call.getOpponentDeviceId())) === call) {
this.disposeCall(call, call.hangupReason);
deviceMap.delete(call.getOpponentDeviceId());
if (deviceMap.size === 0) this.calls.delete(opponentUserId);
this.emit(GroupCallEvent.CallsChanged, this.calls);
}
});
(0, import_defineProperty.default)(this, "onCallReplaced", (prevCall, newCall) => {
var opponentUserId = prevCall.getOpponentMember().userId;
var deviceMap = this.calls.get(opponentUserId);
if (deviceMap === void 0) {
deviceMap = /* @__PURE__ */ new Map();
this.calls.set(opponentUserId, deviceMap);
}
prevCall.hangup(CallErrorCode.Replaced, false);
this.initCall(newCall);
deviceMap.set(prevCall.getOpponentDeviceId(), newCall);
this.emit(GroupCallEvent.CallsChanged, this.calls);
});
(0, import_defineProperty.default)(this, "onActiveSpeakerLoop", () => {
var topAvg = void 0;
var nextActiveSpeaker = void 0;
for (var callFeed of this.userMediaFeeds) {
if (callFeed.isLocal() && this.userMediaFeeds.length > 1) continue;
var avg = callFeed.speakingVolumeSamples.reduce((acc, volume) => acc + Math.max(volume, -60)) / callFeed.speakingVolumeSamples.length;
if (!topAvg || avg > topAvg) {
topAvg = avg;
nextActiveSpeaker = callFeed;
}
}
if (nextActiveSpeaker && this.activeSpeaker !== nextActiveSpeaker && topAvg && topAvg > -60) {
this.activeSpeaker = nextActiveSpeaker;
this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);
}
});
(0, import_defineProperty.default)(this, "onRoomState", () => this.updateParticipants());
(0, import_defineProperty.default)(this, "onParticipantsChanged", () => {
this.forEachCall((call) => {
var expected = this.callExpected(call);
for (var feed of call.getLocalFeeds()) {
setTracksEnabled(feed.stream.getAudioTracks(), !feed.isAudioMuted() && expected);
setTracksEnabled(feed.stream.getVideoTracks(), !feed.isVideoMuted() && expected);
}
});
if (this.state === GroupCallState.Entered && !this.useLivekit) this.placeOutgoingCalls();
});
(0, import_defineProperty.default)(this, "onStateChanged", (newState, oldState) => {
if (newState === GroupCallState.Entered || oldState === GroupCallState.Entered || newState === GroupCallState.Ended) {
this.updateParticipants();
this.updateMemberState().catch((e) => logger$2.error("GroupCall ".concat(this.groupCallId, " onStateChanged() failed to update member state devices\""), e));
}
});
(0, import_defineProperty.default)(this, "onLocalFeedsChanged", () => {
if (this.state === GroupCallState.Entered) this.updateMemberState().catch((e) => logger$2.error("GroupCall ".concat(this.groupCallId, " onLocalFeedsChanged() failed to update member state feeds"), e));
});
this.reEmitter = new ReEmitter(this);
this.groupCallId = groupCallId !== null && groupCallId !== void 0 ? groupCallId : genCallID();
this._livekitServiceURL = livekitServiceURL;
this.creationTs = (_room$currentState$ge = (_room$currentState$ge2 = room.currentState.getStateEvents(EventType.GroupCallPrefix, this.groupCallId)) === null || _room$currentState$ge2 === void 0 ? void 0 : _room$currentState$ge2.getTs()) !== null && _room$currentState$ge !== void 0 ? _room$currentState$ge : null;
this.updateParticipants();
room.on(RoomStateEvent.Update, this.onRoomState);
this.on(GroupCallEvent.ParticipantsChanged, this.onParticipantsChanged);
this.on(GroupCallEvent.GroupCallStateChanged, this.onStateChanged);
this.on(GroupCallEvent.LocalScreenshareStateChanged, this.onLocalFeedsChanged);
this.allowCallWithoutVideoAndAudio = !!isCallWithoutVideoAndAudio;
}
create() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
_this.creationTs = Date.now();
_this.client.groupCallEventHandler.groupCalls.set(_this.room.roomId, _this);
_this.client.emit(GroupCallEventHandlerEvent.Outgoing, _this);
yield _this.sendCallStateEvent();
return _this;
})();
}
sendCallStateEvent() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var groupCallState = {
"m.intent": _this2.intent,
"m.type": _this2.type,
"io.element.ptt": _this2.isPtt,
"dataChannelsEnabled": _this2.dataChannelsEnabled,
"dataChannelOptions": _this2.dataChannelsEnabled ? _this2.dataChannelOptions : void 0
};
if (_this2.livekitServiceURL) groupCallState["io.element.livekit_service_url"] = _this2.livekitServiceURL;
yield _this2.client.sendStateEvent(_this2.room.roomId, EventType.GroupCallPrefix, groupCallState, _this2.groupCallId);
})();
}
get livekitServiceURL() {
return this._livekitServiceURL;
}
updateLivekitServiceURL(newURL) {
this._livekitServiceURL = newURL;
return this.sendCallStateEvent();
}
/**
* The group call's state.
*/
get state() {
return this._state;
}
set state(value) {
var prevValue = this._state;
if (value !== prevValue) {
this._state = value;
this.emit(GroupCallEvent.GroupCallStateChanged, value, prevValue);
}
}
/**
* The current participants in the call, as a map from members to device IDs
* to participant info.
*/
get participants() {
return this._participants;
}
set participants(value) {
var prevValue = this._participants;
var participantStateEqual = (x, y) => x.sessionId === y.sessionId && x.screensharing === y.screensharing;
var deviceMapsEqual = (x, y) => mapsEqual(x, y, participantStateEqual);
if (!mapsEqual(value, prevValue, deviceMapsEqual)) {
this._participants = value;
this.emit(GroupCallEvent.ParticipantsChanged, value);
}
}
/**
* The timestamp at which the call was created, or null if it has not yet
* been created.
*/
get creationTs() {
return this._creationTs;
}
set creationTs(value) {
this._creationTs = value;
}
/**
* Whether the local device has entered this call via another session, such
* as a widget.
*/
get enteredViaAnotherSession() {
return this._enteredViaAnotherSession;
}
set enteredViaAnotherSession(value) {
this._enteredViaAnotherSession = value;
this.updateParticipants();
}
/**
* Executes the given callback on all calls in this group call.
* @param f - The callback.
*/
forEachCall(f) {
for (var deviceMap of this.calls.values()) for (var call of deviceMap.values()) f(call);
}
getLocalFeeds() {
var feeds = [];
if (this.localCallFeed) feeds.push(this.localCallFeed);
if (this.localScreenshareFeed) feeds.push(this.localScreenshareFeed);
return feeds;
}
hasLocalParticipant() {
var _this$participants$ge, _this$participants$ge2;
return (_this$participants$ge = (_this$participants$ge2 = this.participants.get(this.room.getMember(this.client.getUserId()))) === null || _this$participants$ge2 === void 0 ? void 0 : _this$participants$ge2.has(this.client.getDeviceId())) !== null && _this$participants$ge !== void 0 ? _this$participants$ge : false;
}
/**
* Determines whether the given call is one that we were expecting to exist
* given our knowledge of who is participating in the group call.
*/
callExpected(call) {
var _this$participants$ge3;
var userId = getCallUserId(call);
var member = userId === null ? null : this.room.getMember(userId);
var deviceId = call.getOpponentDeviceId();
return member !== null && deviceId !== void 0 && ((_this$participants$ge3 = this.participants.get(member)) === null || _this$participants$ge3 === void 0 ? void 0 : _this$participants$ge3.get(deviceId)) !== void 0;
}
initLocalCallFeed() {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this3.useLivekit) {
logger$2.info("Livekit group call: not starting local call feed.");
return;
}
if (_this3.state !== GroupCallState.LocalCallFeedUninitialized) throw new Error("Cannot initialize local call feed in the \"".concat(_this3.state, "\" state."));
_this3.state = GroupCallState.InitializingLocalCallFeed;
if (_this3.initCallFeedPromise) return _this3.initCallFeedPromise;
try {
_this3.initCallFeedPromise = _this3.initLocalCallFeedInternal();
yield _this3.initCallFeedPromise;
} finally {
_this3.initCallFeedPromise = void 0;
}
})();
}
initLocalCallFeedInternal() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.log("GroupCall ".concat(_this4.groupCallId, " initLocalCallFeedInternal() running"));
var stream;
try {
stream = yield _this4.client.getMediaHandler().getUserMediaStream(true, _this4.type === GroupCallType.Video);
} catch (error) {
if (_this4.allowCallWithoutVideoAndAudio) stream = new MediaStream();
else {
_this4.state = GroupCallState.LocalCallFeedUninitialized;
throw error;
}
}
if (_this4._state !== GroupCallState.InitializingLocalCallFeed) {
_this4.client.getMediaHandler().stopUserMediaStream(stream);
throw new Error("Group call disposed while gathering media stream");
}
var callFeed = new CallFeed({
client: _this4.client,
roomId: _this4.room.roomId,
userId: _this4.client.getUserId(),
deviceId: _this4.client.getDeviceId(),
stream,
purpose: SDPStreamMetadataPurpose.Usermedia,
audioMuted: _this4.initWithAudioMuted || stream.getAudioTracks().length === 0 || _this4.isPtt,
videoMuted: _this4.initWithVideoMuted || stream.getVideoTracks().length === 0
});
setTracksEnabled(stream.getAudioTracks(), !callFeed.isAudioMuted());
setTracksEnabled(stream.getVideoTracks(), !callFeed.isVideoMuted());
_this4.localCallFeed = callFeed;
_this4.addUserMediaFeed(callFeed);
_this4.state = GroupCallState.LocalCallFeedInitialized;
})();
}
updateLocalUsermediaStream(stream) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this5.localCallFeed) {
var oldStream = _this5.localCallFeed.stream;
_this5.localCallFeed.setNewStream(stream);
var micShouldBeMuted = _this5.localCallFeed.isAudioMuted();
var vidShouldBeMuted = _this5.localCallFeed.isVideoMuted();
logger$2.log("GroupCall ".concat(_this5.groupCallId, " updateLocalUsermediaStream() (oldStreamId=").concat(oldStream.id, ", newStreamId=").concat(stream.id, ", micShouldBeMuted=").concat(micShouldBeMuted, ", vidShouldBeMuted=").concat(vidShouldBeMuted, ")"));
setTracksEnabled(stream.getAudioTracks(), !micShouldBeMuted);
setTracksEnabled(stream.getVideoTracks(), !vidShouldBeMuted);
_this5.client.getMediaHandler().stopUserMediaStream(oldStream);
}
})();
}
enter() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this6.state === GroupCallState.LocalCallFeedUninitialized) yield _this6.initLocalCallFeed();
else if (_this6.state !== GroupCallState.LocalCallFeedInitialized) throw new Error("Cannot enter call in the \"".concat(_this6.state, "\" state"));
logger$2.log("GroupCall ".concat(_this6.groupCallId, " enter() running"));
_this6.state = GroupCallState.Entered;
_this6.client.on(CallEventHandlerEvent.Incoming, _this6.onIncomingCall);
for (var call of _this6.client.callEventHandler.calls.values()) _this6.onIncomingCall(call);
if (!_this6.useLivekit) {
_this6.retryCallLoopInterval = setInterval(_this6.onRetryCallLoop, _this6.retryCallInterval);
_this6.activeSpeaker = void 0;
_this6.onActiveSpeakerLoop();
_this6.activeSpeakerLoopInterval = setInterval(_this6.onActiveSpeakerLoop, _this6.activeSpeakerInterval);
}
})();
}
dispose() {
var _this$stats;
if (this.localCallFeed) {
this.removeUserMediaFeed(this.localCallFeed);
this.localCallFeed = void 0;
}
if (this.localScreenshareFeed) {
this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream);
this.removeScreenshareFeed(this.localScreenshareFeed);
this.localScreenshareFeed = void 0;
this.localDesktopCapturerSourceId = void 0;
}
this.client.getMediaHandler().stopAllStreams();
if (this.transmitTimer !== null) {
clearTimeout(this.transmitTimer);
this.transmitTimer = null;
}
if (this.retryCallLoopInterval !== void 0) {
clearInterval(this.retryCallLoopInterval);
this.retryCallLoopInterval = void 0;
}
if (this.participantsExpirationTimer !== null) {
clearTimeout(this.participantsExpirationTimer);
this.participantsExpirationTimer = null;
}
if (this.state !== GroupCallState.Entered) return;
this.forEachCall((call) => call.hangup(CallErrorCode.UserHangup, false));
this.activeSpeaker = void 0;
clearInterval(this.activeSpeakerLoopInterval);
this.retryCallCounts.clear();
clearInterval(this.retryCallLoopInterval);
this.client.removeListener(CallEventHandlerEvent.Incoming, this.onIncomingCall);
(_this$stats = this.stats) === null || _this$stats === void 0 || _this$stats.stop();
}
leave() {
this.dispose();
this.state = GroupCallState.LocalCallFeedUninitialized;
}
terminate() {
var _arguments = arguments, _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var emitStateEvent = _arguments.length > 0 && _arguments[0] !== void 0 ? _arguments[0] : true;
_this7.dispose();
_this7.room.off(RoomStateEvent.Update, _this7.onRoomState);
_this7.client.groupCallEventHandler.groupCalls.delete(_this7.room.roomId);
_this7.client.emit(GroupCallEventHandlerEvent.Ended, _this7);
_this7.state = GroupCallState.Ended;
if (emitStateEvent) {
var existingStateEvent = _this7.room.currentState.getStateEvents(EventType.GroupCallPrefix, _this7.groupCallId);
yield _this7.client.sendStateEvent(_this7.room.roomId, EventType.GroupCallPrefix, _objectSpread$10(_objectSpread$10({}, existingStateEvent.getContent()), {}, { "m.terminated": GroupCallTerminationReason.CallEnded }), _this7.groupCallId);
}
})();
}
isLocalVideoMuted() {
if (this.localCallFeed) return this.localCallFeed.isVideoMuted();
return true;
}
isMicrophoneMuted() {
if (this.localCallFeed) return this.localCallFeed.isAudioMuted();
return true;
}
/**
* Sets the mute state of the local participants's microphone.
* @param muted - Whether to mute the microphone
* @returns Whether muting/unmuting was successful
*/
setMicrophoneMuted(muted) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!muted && !(yield _this8.client.getMediaHandler().hasAudioDevice())) return false;
var sendUpdatesBefore = !muted && _this8.isPtt;
if (_this8.isPtt) {
if (!muted && _this8.isMicrophoneMuted()) _this8.transmitTimer = setTimeout(() => {
_this8.setMicrophoneMuted(true);
}, _this8.pttMaxTransmitTime);
else if (muted && !_this8.isMicrophoneMuted()) {
if (_this8.transmitTimer !== null) clearTimeout(_this8.transmitTimer);
_this8.transmitTimer = null;
}
}
_this8.forEachCall((call) => {
var _call$localUsermediaF;
return (_call$localUsermediaF = call.localUsermediaFeed) === null || _call$localUsermediaF === void 0 ? void 0 : _call$localUsermediaF.setAudioVideoMuted(muted, null);
});
var sendUpdates = /* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* () {
var updates = [];
_this8.forEachCall((call) => updates.push(call.sendMetadataUpdate()));
yield Promise.all(updates).catch((e) => logger$2.info("GroupCall ".concat(_this8.groupCallId, " setMicrophoneMuted() failed to send some metadata updates"), e));
});
return function sendUpdates() {
return _ref.apply(this, arguments);
};
}();
if (sendUpdatesBefore) yield sendUpdates();
if (_this8.localCallFeed) {
logger$2.log("GroupCall ".concat(_this8.groupCallId, " setMicrophoneMuted() (streamId=").concat(_this8.localCallFeed.stream.id, ", muted=").concat(muted, ")"));
if (!(yield _this8.checkAudioPermissionIfNecessary(muted))) return false;
_this8.localCallFeed.setAudioVideoMuted(muted, null);
setTracksEnabled(_this8.localCallFeed.stream.getAudioTracks(), !muted);
} else {
logger$2.log("GroupCall ".concat(_this8.groupCallId, " setMicrophoneMuted() no stream muted (muted=").concat(muted, ")"));
_this8.initWithAudioMuted = muted;
}
_this8.forEachCall((call) => setTracksEnabled(call.localUsermediaFeed.stream.getAudioTracks(), !muted && _this8.callExpected(call)));
_this8.emit(GroupCallEvent.LocalMuteStateChanged, muted, _this8.isLocalVideoMuted());
if (!sendUpdatesBefore) yield sendUpdates();
return true;
})();
}
/**
* If we allow entering a call without a camera and without video, it can happen that the access rights to the
* devices have not yet been queried. If a stream does not yet have an audio track, we assume that the rights have
* not yet been checked.
*
* `this.client.getMediaHandler().getUserMediaStream` clones the current stream, so it only wanted to be called when
* not Audio Track exists.
* As such, this is a compromise, because, the access rights should always be queried before the call.
*/
checkAudioPermissionIfNecessary(muted) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
try {
if (!muted && _this9.localCallFeed && !_this9.localCallFeed.hasAudioTrack) {
var stream = yield _this9.client.getMediaHandler().getUserMediaStream(true, !_this9.localCallFeed.isVideoMuted());
if ((stream === null || stream === void 0 ? void 0 : stream.getTracks().length) === 0) {
/* istanbul ignore next */
logger$2.log("GroupCall ".concat(_this9.groupCallId, " setMicrophoneMuted() no device to receive local stream, muted=").concat(muted));
return false;
}
}
} catch (_unused) {
/* istanbul ignore next */
logger$2.log("GroupCall ".concat(_this9.groupCallId, " setMicrophoneMuted() no device or permission to receive local stream, muted=").concat(muted));
return false;
}
return true;
})();
}
/**
* Sets the mute state of the local participants's video.
* @param muted - Whether to mute the video
* @returns Whether muting/unmuting was successful
*/
setLocalVideoMuted(muted) {
var _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!muted && !(yield _this0.client.getMediaHandler().hasVideoDevice())) return false;
if (_this0.localCallFeed) {
/* istanbul ignore next */
logger$2.log("GroupCall ".concat(_this0.groupCallId, " setLocalVideoMuted() (stream=").concat(_this0.localCallFeed.stream.id, ", muted=").concat(muted, ")"));
try {
var stream = yield _this0.client.getMediaHandler().getUserMediaStream(true, !muted);
yield _this0.updateLocalUsermediaStream(stream);
_this0.localCallFeed.setAudioVideoMuted(null, muted);
setTracksEnabled(_this0.localCallFeed.stream.getVideoTracks(), !muted);
} catch (_unused2) {
/* istanbul ignore next */
logger$2.log("GroupCall ".concat(_this0.groupCallId, " setLocalVideoMuted() no device or permission to receive local stream, muted=").concat(muted));
return false;
}
} else {
logger$2.log("GroupCall ".concat(_this0.groupCallId, " setLocalVideoMuted() no stream muted (muted=").concat(muted, ")"));
_this0.initWithVideoMuted = muted;
}
var updates = [];
_this0.forEachCall((call) => updates.push(call.setLocalVideoMuted(muted)));
yield Promise.all(updates);
_this0.forEachCall((call) => setTracksEnabled(call.localUsermediaFeed.stream.getVideoTracks(), !muted && _this0.callExpected(call)));
_this0.emit(GroupCallEvent.LocalMuteStateChanged, _this0.isMicrophoneMuted(), muted);
return true;
})();
}
setScreensharingEnabled(enabled) {
var _arguments2 = arguments, _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
var opts = _arguments2.length > 1 && _arguments2[1] !== void 0 ? _arguments2[1] : {};
if (enabled === _this1.isScreensharing()) return enabled;
if (enabled) try {
logger$2.log("GroupCall ".concat(_this1.groupCallId, " setScreensharingEnabled() is asking for screensharing permissions"));
var stream = yield _this1.client.getMediaHandler().getScreensharingStream(opts);
var _loop = function* _loop(track) {
var onTrackEnded = () => {
_this1.setScreensharingEnabled(false);
track.removeEventListener("ended", onTrackEnded);
};
track.addEventListener("ended", onTrackEnded);
};
for (var track of stream.getTracks()) yield* _loop(track);
logger$2.log("GroupCall ".concat(_this1.groupCallId, " setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls"));
_this1.localDesktopCapturerSourceId = opts.desktopCapturerSourceId;
_this1.localScreenshareFeed = new CallFeed({
client: _this1.client,
roomId: _this1.room.roomId,
userId: _this1.client.getUserId(),
deviceId: _this1.client.getDeviceId(),
stream,
purpose: SDPStreamMetadataPurpose.Screenshare,
audioMuted: false,
videoMuted: false
});
_this1.addScreenshareFeed(_this1.localScreenshareFeed);
_this1.emit(GroupCallEvent.LocalScreenshareStateChanged, true, _this1.localScreenshareFeed, _this1.localDesktopCapturerSourceId);
_this1.forEachCall((call) => call.pushLocalFeed(_this1.localScreenshareFeed.clone()));
return true;
} catch (error) {
if (opts.throwOnFail) throw error;
logger$2.error("GroupCall ".concat(_this1.groupCallId, " setScreensharingEnabled() enabling screensharing error"), error);
_this1.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.NoUserMedia, "Failed to get screen-sharing stream: ", error));
return false;
}
else {
_this1.forEachCall((call) => {
if (call.localScreensharingFeed) call.removeLocalFeed(call.localScreensharingFeed);
});
_this1.client.getMediaHandler().stopScreensharingStream(_this1.localScreenshareFeed.stream);
_this1.removeScreenshareFeed(_this1.localScreenshareFeed);
_this1.localScreenshareFeed = void 0;
_this1.localDesktopCapturerSourceId = void 0;
_this1.emit(GroupCallEvent.LocalScreenshareStateChanged, false, void 0, void 0);
return false;
}
})();
}
isScreensharing() {
return !!this.localScreenshareFeed;
}
/**
* Determines whether a given participant expects us to call them (versus
* them calling us).
* @param userId - The participant's user ID.
* @param deviceId - The participant's device ID.
* @returns Whether we need to place an outgoing call to the participant.
*/
wantsOutgoingCall(userId, deviceId) {
var localUserId = this.client.getUserId();
var localDeviceId = this.client.getDeviceId();
return userId >= localUserId && (userId !== localUserId || deviceId > localDeviceId);
}
/**
* Places calls to all participants that we're responsible for calling.
*/
placeOutgoingCalls() {
var _this10 = this;
var callsChanged = false;
var _loop2 = function _loop2(_userId2) {
var _this10$calls$get;
var callMap = (_this10$calls$get = _this10.calls.get(_userId2)) !== null && _this10$calls$get !== void 0 ? _this10$calls$get : /* @__PURE__ */ new Map();
var _loop3 = function _loop3(deviceId) {
var prevCall = callMap.get(deviceId);
if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.getOpponentSessionId()) !== participant.sessionId && _this10.wantsOutgoingCall(_userId2, deviceId)) {
callsChanged = true;
if (prevCall !== void 0) {
logger$2.debug("GroupCall ".concat(_this10.groupCallId, " placeOutgoingCalls() replacing call (userId=").concat(_userId2, ", deviceId=").concat(deviceId, ", callId=").concat(prevCall.callId, ")"));
prevCall.hangup(CallErrorCode.NewSession, false);
}
var newCall = createNewMatrixCall(_this10.client, _this10.room.roomId, {
invitee: _userId2,
opponentDeviceId: deviceId,
opponentSessionId: participant.sessionId,
groupCallId: _this10.groupCallId
});
if (newCall === null) {
logger$2.error("GroupCall ".concat(_this10.groupCallId, " placeOutgoingCalls() failed to create call (userId=").concat(_userId2, ", device=").concat(deviceId, ")"));
callMap.delete(deviceId);
} else {
_this10.initCall(newCall);
callMap.set(deviceId, newCall);
logger$2.debug("GroupCall ".concat(_this10.groupCallId, " placeOutgoingCalls() placing call (userId=").concat(_userId2, ", deviceId=").concat(deviceId, ", sessionId=").concat(participant.sessionId, ")"));
newCall.placeCallWithCallFeeds(_this10.getLocalFeeds().map((feed) => feed.clone()), participant.screensharing).then(() => {
if (_this10.dataChannelsEnabled) newCall.createDataChannel("datachannel", _this10.dataChannelOptions);
}).catch((e) => {
logger$2.warn("GroupCall ".concat(_this10.groupCallId, " placeOutgoingCalls() failed to place call (userId=").concat(_userId2, ")"), e);
if (e instanceof CallError && e.code === GroupCallErrorCode.UnknownDevice) _this10.emit(GroupCallEvent.Error, e);
else _this10.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.PlaceCallFailed, "Failed to place call to ".concat(_userId2)));
newCall.hangup(CallErrorCode.SignallingFailed, false);
if (callMap.get(deviceId) === newCall) callMap.delete(deviceId);
});
}
}
};
for (var [deviceId, participant] of participantMap) _loop3(deviceId);
if (callMap.size > 0) _this10.calls.set(_userId2, callMap);
else _this10.calls.delete(_userId2);
};
for (var [{ userId: _userId2 }, participantMap] of this.participants) _loop2(_userId2);
if (callsChanged) this.emit(GroupCallEvent.CallsChanged, this.calls);
}
getMemberStateEvents(userId) {
return userId === void 0 ? this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix) : this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix, userId);
}
initCall(call) {
var opponentMemberId = getCallUserId(call);
if (!opponentMemberId) throw new Error("Cannot init call without user id");
var onCallFeedsChanged = () => this.onCallFeedsChanged(call);
var onCallStateChanged = (state, oldState) => this.onCallStateChanged(call, state, oldState);
var onCallHangup = this.onCallHangup;
var onCallReplaced = (newCall) => this.onCallReplaced(call, newCall);
var deviceMap = this.callHandlers.get(opponentMemberId);
if (deviceMap === void 0) {
deviceMap = /* @__PURE__ */ new Map();
this.callHandlers.set(opponentMemberId, deviceMap);
}
deviceMap.set(call.getOpponentDeviceId(), {
onCallFeedsChanged,
onCallStateChanged,
onCallHangup,
onCallReplaced
});
call.on(CallEvent.FeedsChanged, onCallFeedsChanged);
call.on(CallEvent.State, onCallStateChanged);
call.on(CallEvent.Hangup, onCallHangup);
call.on(CallEvent.Replaced, onCallReplaced);
call.isPtt = this.isPtt;
this.reEmitter.reEmit(call, Object.values(CallEvent));
call.initStats(this.getGroupCallStats());
onCallFeedsChanged();
}
disposeCall(call, hangupReason) {
var opponentMemberId = getCallUserId(call);
var opponentDeviceId = call.getOpponentDeviceId();
if (!opponentMemberId) throw new Error("Cannot dispose call without user id");
var deviceMap = this.callHandlers.get(opponentMemberId);
var { onCallFeedsChanged, onCallStateChanged, onCallHangup, onCallReplaced } = deviceMap.get(opponentDeviceId);
call.removeListener(CallEvent.FeedsChanged, onCallFeedsChanged);
call.removeListener(CallEvent.State, onCallStateChanged);
call.removeListener(CallEvent.Hangup, onCallHangup);
call.removeListener(CallEvent.Replaced, onCallReplaced);
deviceMap.delete(opponentMemberId);
if (deviceMap.size === 0) this.callHandlers.delete(opponentMemberId);
if (call.hangupReason === CallErrorCode.Replaced) return;
var usermediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);
if (usermediaFeed) this.removeUserMediaFeed(usermediaFeed);
var screenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);
if (screenshareFeed) this.removeScreenshareFeed(screenshareFeed);
}
getUserMediaFeed(userId, deviceId) {
return this.userMediaFeeds.find((f) => f.userId === userId && f.deviceId === deviceId);
}
addUserMediaFeed(callFeed) {
this.userMediaFeeds.push(callFeed);
callFeed.measureVolumeActivity(true);
this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);
}
replaceUserMediaFeed(existingFeed, replacementFeed) {
var feedIndex = this.userMediaFeeds.findIndex((f) => f.userId === existingFeed.userId && f.deviceId === existingFeed.deviceId);
if (feedIndex === -1) throw new Error("Couldn't find user media feed to replace");
this.userMediaFeeds.splice(feedIndex, 1, replacementFeed);
existingFeed.dispose();
replacementFeed.measureVolumeActivity(true);
this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);
}
removeUserMediaFeed(callFeed) {
var feedIndex = this.userMediaFeeds.findIndex((f) => f.userId === callFeed.userId && f.deviceId === callFeed.deviceId);
if (feedIndex === -1) throw new Error("Couldn't find user media feed to remove");
this.userMediaFeeds.splice(feedIndex, 1);
callFeed.dispose();
this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);
if (this.activeSpeaker === callFeed) {
this.activeSpeaker = this.userMediaFeeds[0];
this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);
}
}
getScreenshareFeed(userId, deviceId) {
return this.screenshareFeeds.find((f) => f.userId === userId && f.deviceId === deviceId);
}
addScreenshareFeed(callFeed) {
this.screenshareFeeds.push(callFeed);
this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);
}
replaceScreenshareFeed(existingFeed, replacementFeed) {
var feedIndex = this.screenshareFeeds.findIndex((f) => f.userId === existingFeed.userId && f.deviceId === existingFeed.deviceId);
if (feedIndex === -1) throw new Error("Couldn't find screenshare feed to replace");
this.screenshareFeeds.splice(feedIndex, 1, replacementFeed);
existingFeed.dispose();
this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);
}
removeScreenshareFeed(callFeed) {
var feedIndex = this.screenshareFeeds.findIndex((f) => f.userId === callFeed.userId && f.deviceId === callFeed.deviceId);
if (feedIndex === -1) throw new Error("Couldn't find screenshare feed to remove");
this.screenshareFeeds.splice(feedIndex, 1);
callFeed.dispose();
this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);
}
/**
* Recalculates and updates the participant map to match the room state.
*/
updateParticipants() {
var localMember = this.room.getMember(this.client.getSafeUserId());
if (!localMember) {
logger$2.warn("GroupCall ".concat(this.groupCallId, " updateParticipants() tried to update participants before local room member is available"));
return;
}
if (this.participantsExpirationTimer !== null) {
clearTimeout(this.participantsExpirationTimer);
this.participantsExpirationTimer = null;
}
if (this.state === GroupCallState.Ended) {
this.participants = /* @__PURE__ */ new Map();
return;
}
var participants = /* @__PURE__ */ new Map();
var now = Date.now();
var entered = this.state === GroupCallState.Entered || this.enteredViaAnotherSession;
var nextExpiration = Infinity;
for (var e of this.getMemberStateEvents()) {
var member = this.room.getMember(e.getStateKey());
var content = e.getContent();
var call = (Array.isArray(content["m.calls"]) ? content["m.calls"] : []).find((call) => call["m.call_id"] === this.groupCallId);
var validDevices = (Array.isArray(call === null || call === void 0 ? void 0 : call["m.devices"]) ? call["m.devices"] : []).filter((d) => typeof d.device_id === "string" && typeof d.session_id === "string" && typeof d.expires_ts === "number" && d.expires_ts > now && Array.isArray(d.feeds));
if (!entered && (member === null || member === void 0 ? void 0 : member.userId) === this.client.getUserId()) validDevices = validDevices.filter((d) => d.device_id !== this.client.getDeviceId());
if (validDevices.length > 0 && (member === null || member === void 0 ? void 0 : member.membership) === KnownMembership.Join) {
var deviceMap = /* @__PURE__ */ new Map();
participants.set(member, deviceMap);
for (var d of validDevices) {
deviceMap.set(d.device_id, {
sessionId: d.session_id,
screensharing: d.feeds.some((f) => f.purpose === SDPStreamMetadataPurpose.Screenshare)
});
if (d.expires_ts < nextExpiration) nextExpiration = d.expires_ts;
}
}
}
if (entered) {
var _deviceMap = participants.get(localMember);
if (_deviceMap === void 0) {
_deviceMap = /* @__PURE__ */ new Map();
participants.set(localMember, _deviceMap);
}
if (!_deviceMap.has(this.client.getDeviceId())) _deviceMap.set(this.client.getDeviceId(), {
sessionId: this.client.getSessionId(),
screensharing: this.getLocalFeeds().some((f) => f.purpose === SDPStreamMetadataPurpose.Screenshare)
});
}
this.participants = participants;
if (nextExpiration < Infinity) this.participantsExpirationTimer = setTimeout(() => this.updateParticipants(), nextExpiration - now);
}
/**
* Updates the local user's member state with the devices returned by the given function.
* @param fn - A function from the current devices to the new devices. If it
* returns null, the update will be skipped.
* @param keepAlive - Whether the request should outlive the window.
*/
updateDevices(fn) {
var _arguments3 = arguments, _this11 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _event$getContent;
var keepAlive = _arguments3.length > 1 && _arguments3[1] !== void 0 ? _arguments3[1] : false;
var now = Date.now();
var localUserId = _this11.client.getUserId();
var event = _this11.getMemberStateEvents(localUserId);
var content = (_event$getContent = event === null || event === void 0 ? void 0 : event.getContent()) !== null && _event$getContent !== void 0 ? _event$getContent : {};
var calls = Array.isArray(content["m.calls"]) ? content["m.calls"] : [];
var call = null;
var otherCalls = [];
for (var c of calls) if (c["m.call_id"] === _this11.groupCallId) call = c;
else otherCalls.push(c);
if (call === null) call = {};
var newDevices = fn((Array.isArray(call["m.devices"]) ? call["m.devices"] : []).filter((d) => typeof d.device_id === "string" && typeof d.session_id === "string" && typeof d.expires_ts === "number" && d.expires_ts > now && Array.isArray(d.feeds)));
if (newDevices === null) return;
var newCalls = [...otherCalls];
if (newDevices.length > 0) newCalls.push(_objectSpread$10(_objectSpread$10({}, call), {}, {
"m.call_id": _this11.groupCallId,
"m.devices": newDevices
}));
var newContent = { "m.calls": newCalls };
yield _this11.client.sendStateEvent(_this11.room.roomId, EventType.GroupCallMemberPrefix, newContent, localUserId, { keepAlive });
})();
}
addDeviceToMemberState() {
var _this12 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this12.updateDevices((devices) => [...devices.filter((d) => d.device_id !== _this12.client.getDeviceId()), {
device_id: _this12.client.getDeviceId(),
session_id: _this12.client.getSessionId(),
expires_ts: Date.now() + DEVICE_TIMEOUT,
feeds: _this12.getLocalFeeds().map((feed) => ({ purpose: feed.purpose }))
}]);
})();
}
updateMemberState() {
var _this13 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this13.resendMemberStateTimer !== null) {
clearInterval(_this13.resendMemberStateTimer);
_this13.resendMemberStateTimer = null;
}
if (_this13.state === GroupCallState.Entered) {
yield _this13.addDeviceToMemberState();
_this13.resendMemberStateTimer = setInterval(/* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
logger$2.log("GroupCall ".concat(_this13.groupCallId, " updateMemberState() resending call member state\""));
try {
yield _this13.addDeviceToMemberState();
} catch (e) {
logger$2.error("GroupCall ".concat(_this13.groupCallId, " updateMemberState() failed to resend call member state"), e);
}
}), DEVICE_TIMEOUT * 3 / 4);
} else yield _this13.updateDevices((devices) => devices.filter((d) => d.device_id !== _this13.client.getDeviceId()), true);
})();
}
/**
* Cleans up our member state by filtering out logged out devices, inactive
* devices, and our own device (if we know we haven't entered).
*/
cleanMemberState() {
var _this14 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { devices: myDevices } = yield _this14.client.getDevices();
var deviceMap = new Map(myDevices.map((d) => [d.device_id, d]));
yield _this14.updateDevices((devices) => {
var newDevices = devices.filter((d) => {
var device = deviceMap.get(d.device_id);
return (device === null || device === void 0 ? void 0 : device.last_seen_ts) !== void 0 && !(d.device_id === _this14.client.getDeviceId() && _this14.state !== GroupCallState.Entered && !_this14.enteredViaAnotherSession);
});
return newDevices.length === devices.length ? null : newDevices;
});
})();
}
getGroupCallStats() {
if (this.stats === void 0) {
var userID = this.client.getUserId() || "unknown";
this.stats = new GroupCallStats(this.groupCallId, userID, this.statsCollectIntervalTime);
this.stats.reports.on(StatsReport.CONNECTION_STATS, this.onConnectionStats);
this.stats.reports.on(StatsReport.BYTE_SENT_STATS, this.onByteSentStats);
this.stats.reports.on(StatsReport.SUMMARY_STATS, this.onSummaryStats);
this.stats.reports.on(StatsReport.CALL_FEED_REPORT, this.onCallFeedReport);
}
return this.stats;
}
setGroupCallStatsInterval(interval) {
this.statsCollectIntervalTime = interval;
if (this.stats !== void 0) {
this.stats.stop();
this.stats.setInterval(interval);
if (interval > 0) this.stats.start();
}
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/call.js
/**
* This is an internal module. See {@link createNewMatrixCall} for the public API.
*/
function ownKeys$9(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;
}
function _objectSpread$9(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$9(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var CallState = /* @__PURE__ */ function(CallState) {
CallState["Fledgling"] = "fledgling";
CallState["InviteSent"] = "invite_sent";
CallState["WaitLocalMedia"] = "wait_local_media";
CallState["CreateOffer"] = "create_offer";
CallState["CreateAnswer"] = "create_answer";
CallState["Connecting"] = "connecting";
CallState["Connected"] = "connected";
CallState["Ringing"] = "ringing";
CallState["Ended"] = "ended";
return CallState;
}({});
var CallType = /* @__PURE__ */ function(CallType) {
CallType["Voice"] = "voice";
CallType["Video"] = "video";
return CallType;
}({});
var CallDirection = /* @__PURE__ */ function(CallDirection) {
CallDirection["Inbound"] = "inbound";
CallDirection["Outbound"] = "outbound";
return CallDirection;
}({});
var CallParty = /* @__PURE__ */ function(CallParty) {
CallParty["Local"] = "local";
CallParty["Remote"] = "remote";
return CallParty;
}({});
var CallEvent = /* @__PURE__ */ function(CallEvent) {
CallEvent["Hangup"] = "hangup";
CallEvent["State"] = "state";
CallEvent["Error"] = "error";
CallEvent["Replaced"] = "replaced";
CallEvent["LocalHoldUnhold"] = "local_hold_unhold";
CallEvent["RemoteHoldUnhold"] = "remote_hold_unhold";
CallEvent["HoldUnhold"] = "hold_unhold";
CallEvent["FeedsChanged"] = "feeds_changed";
CallEvent["AssertedIdentityChanged"] = "asserted_identity_changed";
CallEvent["LengthChanged"] = "length_changed";
CallEvent["DataChannel"] = "datachannel";
CallEvent["SendVoipEvent"] = "send_voip_event";
CallEvent["PeerConnectionCreated"] = "peer_connection_created";
return CallEvent;
}({});
var CallErrorCode = /* @__PURE__ */ function(CallErrorCode) {
/** The user chose to end the call */
CallErrorCode["UserHangup"] = "user_hangup";
/** An error code when the local client failed to create an offer. */
CallErrorCode["LocalOfferFailed"] = "local_offer_failed";
/**
* An error code when there is no local mic/camera to use. This may be because
* the hardware isn't plugged in, or the user has explicitly denied access.
*/
CallErrorCode["NoUserMedia"] = "no_user_media";
/**
* Error code used when a call event failed to send
* because unknown devices were present in the room
*/
CallErrorCode["UnknownDevices"] = "unknown_devices";
/**
* Error code used when we fail to send the invite
* for some reason other than there being unknown devices
*/
CallErrorCode["SendInvite"] = "send_invite";
/**
* An answer could not be created
*/
CallErrorCode["CreateAnswer"] = "create_answer";
/**
* An offer could not be created
*/
CallErrorCode["CreateOffer"] = "create_offer";
/**
* Error code used when we fail to send the answer
* for some reason other than there being unknown devices
*/
CallErrorCode["SendAnswer"] = "send_answer";
/**
* The session description from the other side could not be set
*/
CallErrorCode["SetRemoteDescription"] = "set_remote_description";
/**
* The session description from this side could not be set
*/
CallErrorCode["SetLocalDescription"] = "set_local_description";
/**
* A different device answered the call
*/
CallErrorCode["AnsweredElsewhere"] = "answered_elsewhere";
/**
* No media connection could be established to the other party
*/
CallErrorCode["IceFailed"] = "ice_failed";
/**
* The invite timed out whilst waiting for an answer
*/
CallErrorCode["InviteTimeout"] = "invite_timeout";
/**
* The call was replaced by another call
*/
CallErrorCode["Replaced"] = "replaced";
/**
* Signalling for the call could not be sent (other than the initial invite)
*/
CallErrorCode["SignallingFailed"] = "signalling_timeout";
/**
* The remote party is busy
*/
CallErrorCode["UserBusy"] = "user_busy";
/**
* We transferred the call off to somewhere else
*/
CallErrorCode["Transferred"] = "transferred";
/**
* A call from the same user was found with a new session id
*/
CallErrorCode["NewSession"] = "new_session";
return CallErrorCode;
}({});
/**
* The version field that we set in m.call.* events
*/
var VOIP_PROTO_VERSION = "1";
/** The fallback ICE server to use for STUN or TURN protocols. */
var FALLBACK_ICE_SERVER = "stun:turn.matrix.org";
/** The length of time a call can be ringing for. */
var CALL_TIMEOUT_MS = 60 * 1e3;
/** The time after which we increment callLength */
var CALL_LENGTH_INTERVAL = 1e3;
/** The time after which we end the call, if ICE got disconnected */
var ICE_DISCONNECTED_TIMEOUT = 30 * 1e3;
/** The time after which we try a ICE restart, if ICE got disconnected */
var ICE_RECONNECTING_TIMEOUT = 2 * 1e3;
var CallError = class extends Error {
constructor(code, msg, err) {
super(msg + ": " + err);
(0, import_defineProperty.default)(this, "code", void 0);
this.code = code;
}
};
function genCallID() {
return Date.now().toString() + secureRandomString(16);
}
function getCodecParamMods(isPtt) {
return [{
mediaType: "audio",
codec: "opus",
enableDtx: true,
maxAverageBitrate: isPtt ? 12e3 : void 0
}];
}
/**
* These now all have the call object as an argument. Why? Well, to know which call a given event is
* about you have three options:
* 1. Use a closure as the callback that remembers what call it's listening to. This can be
* a pain because you need to pass the listener function again when you remove the listener,
* which might be somewhere else.
* 2. Use not-very-well-known fact that EventEmitter sets 'this' to the emitter object in the
* callback. This doesn't really play well with modern Typescript and eslint and doesn't work
* with our pattern of re-emitting events.
* 3. Pass the object in question as an argument to the callback.
*
* Now that we have group calls which have to deal with multiple call objects, this will
* become more important, and I think methods 1 and 2 are just going to cause issues.
*/
function getTransceiverKey(purpose, kind) {
return purpose + ":" + kind;
}
var MatrixCall = class extends TypedEventEmitter {
/**
* Construct a new Matrix Call.
* @param opts - Config options.
*/
constructor(opts) {
var _this, _opts$forceTURN;
super();
_this = this;
(0, import_defineProperty.default)(this, "roomId", void 0);
(0, import_defineProperty.default)(this, "callId", void 0);
(0, import_defineProperty.default)(this, "invitee", void 0);
(0, import_defineProperty.default)(this, "hangupParty", void 0);
(0, import_defineProperty.default)(this, "hangupReason", void 0);
(0, import_defineProperty.default)(this, "direction", void 0);
(0, import_defineProperty.default)(this, "ourPartyId", void 0);
(0, import_defineProperty.default)(this, "peerConn", void 0);
(0, import_defineProperty.default)(this, "toDeviceSeq", 0);
(0, import_defineProperty.default)(this, "isPtt", false);
(0, import_defineProperty.default)(this, "_state", CallState.Fledgling);
(0, import_defineProperty.default)(this, "client", void 0);
(0, import_defineProperty.default)(this, "forceTURN", void 0);
(0, import_defineProperty.default)(this, "turnServers", void 0);
(0, import_defineProperty.default)(this, "candidateSendQueue", []);
(0, import_defineProperty.default)(this, "candidateSendTries", 0);
(0, import_defineProperty.default)(this, "candidatesEnded", false);
(0, import_defineProperty.default)(this, "feeds", []);
(0, import_defineProperty.default)(this, "transceivers", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "inviteOrAnswerSent", false);
(0, import_defineProperty.default)(this, "waitForLocalAVStream", false);
(0, import_defineProperty.default)(this, "successor", void 0);
(0, import_defineProperty.default)(this, "opponentMember", void 0);
(0, import_defineProperty.default)(this, "opponentVersion", void 0);
(0, import_defineProperty.default)(this, "opponentPartyId", void 0);
(0, import_defineProperty.default)(this, "opponentCaps", void 0);
(0, import_defineProperty.default)(this, "iceDisconnectedTimeout", void 0);
(0, import_defineProperty.default)(this, "iceReconnectionTimeOut", void 0);
(0, import_defineProperty.default)(this, "inviteTimeout", void 0);
(0, import_defineProperty.default)(this, "removeTrackListeners", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "remoteOnHold", false);
(0, import_defineProperty.default)(this, "callStatsAtEnd", void 0);
(0, import_defineProperty.default)(this, "makingOffer", false);
(0, import_defineProperty.default)(this, "ignoreOffer", false);
(0, import_defineProperty.default)(this, "isSettingRemoteAnswerPending", false);
(0, import_defineProperty.default)(this, "responsePromiseChain", void 0);
(0, import_defineProperty.default)(this, "remoteCandidateBuffer", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "remoteAssertedIdentity", void 0);
(0, import_defineProperty.default)(this, "remoteSDPStreamMetadata", void 0);
(0, import_defineProperty.default)(this, "callLengthInterval", void 0);
(0, import_defineProperty.default)(this, "callStartTime", void 0);
(0, import_defineProperty.default)(this, "opponentDeviceId", void 0);
(0, import_defineProperty.default)(this, "hasOpponentDeviceInfo", void 0);
(0, import_defineProperty.default)(this, "opponentSessionId", void 0);
(0, import_defineProperty.default)(this, "groupCallId", void 0);
(0, import_defineProperty.default)(this, "stopVideoTrackTimer", void 0);
(0, import_defineProperty.default)(this, "isOnlyDataChannelAllowed", void 0);
(0, import_defineProperty.default)(this, "stats", void 0);
/**
* Internal
*/
(0, import_defineProperty.default)(this, "gotLocalIceCandidate", (event) => {
if (event.candidate) {
if (this.candidatesEnded) logger$2.warn("Call ".concat(this.callId, " gotLocalIceCandidate() got candidate after candidates have ended!"));
logger$2.debug("Call ".concat(this.callId, " got local ICE ").concat(event.candidate.sdpMid, " ").concat(event.candidate.candidate));
if (this.callHasEnded()) return;
if (event.candidate.candidate === "") this.queueCandidate(null);
else this.queueCandidate(event.candidate);
}
});
(0, import_defineProperty.default)(this, "onIceGatheringStateChange", (event) => {
var _this$peerConn;
logger$2.debug("Call ".concat(this.callId, " onIceGatheringStateChange() ice gathering state changed to ").concat(this.peerConn.iceGatheringState));
if (((_this$peerConn = this.peerConn) === null || _this$peerConn === void 0 ? void 0 : _this$peerConn.iceGatheringState) === "complete") {
this.queueCandidate(null);
logger$2.debug("Call ".concat(this.callId, " onIceGatheringStateChange() ice gathering state complete, set candidates have ended"));
}
});
(0, import_defineProperty.default)(this, "getLocalOfferFailed", (err) => {
logger$2.error("Call ".concat(this.callId, " getLocalOfferFailed() running"), err);
this.emit(CallEvent.Error, new CallError(CallErrorCode.LocalOfferFailed, "Failed to get local offer!", err), this);
this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);
});
(0, import_defineProperty.default)(this, "getUserMediaFailed", (err) => {
if (this.successor) {
this.successor.getUserMediaFailed(err);
return;
}
logger$2.warn("Call ".concat(this.callId, " getUserMediaFailed() failed to get user media - ending call"), err);
this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, "Couldn't start capturing media! Is your microphone set up and does this app have permission?", err), this);
this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);
});
(0, import_defineProperty.default)(this, "placeCallFailed", (err) => {
if (this.successor) {
this.successor.placeCallFailed(err);
return;
}
logger$2.warn("Call ".concat(this.callId, " placeCallWithCallFeeds() failed - ending call"), err);
this.emit(CallEvent.Error, new CallError(CallErrorCode.IceFailed, "Couldn't start call! Invalid ICE server configuration.", err), this);
this.terminate(CallParty.Local, CallErrorCode.IceFailed, false);
});
(0, import_defineProperty.default)(this, "onIceConnectionStateChanged", () => {
var _this$peerConn2, _this$peerConn3, _this$peerConn$iceCon, _this$peerConn4, _this$peerConn5, _this$peerConn8;
if (this.callHasEnded()) return;
logger$2.debug("Call ".concat(this.callId, " onIceConnectionStateChanged() running (state=").concat((_this$peerConn2 = this.peerConn) === null || _this$peerConn2 === void 0 ? void 0 : _this$peerConn2.iceConnectionState, ", conn=").concat((_this$peerConn3 = this.peerConn) === null || _this$peerConn3 === void 0 ? void 0 : _this$peerConn3.connectionState, ")"));
if (["connected", "completed"].includes((_this$peerConn$iceCon = (_this$peerConn4 = this.peerConn) === null || _this$peerConn4 === void 0 ? void 0 : _this$peerConn4.iceConnectionState) !== null && _this$peerConn$iceCon !== void 0 ? _this$peerConn$iceCon : "")) {
clearTimeout(this.iceDisconnectedTimeout);
this.iceDisconnectedTimeout = void 0;
if (this.iceReconnectionTimeOut) clearTimeout(this.iceReconnectionTimeOut);
this.state = CallState.Connected;
if (!this.callLengthInterval && !this.callStartTime) {
this.callStartTime = Date.now();
this.callLengthInterval = setInterval(() => {
this.emit(CallEvent.LengthChanged, Math.round((Date.now() - this.callStartTime) / 1e3), this);
}, CALL_LENGTH_INTERVAL);
}
} else if (((_this$peerConn5 = this.peerConn) === null || _this$peerConn5 === void 0 ? void 0 : _this$peerConn5.iceConnectionState) == "failed") {
var _this$peerConn6;
this.candidatesEnded = false;
if ((_this$peerConn6 = this.peerConn) !== null && _this$peerConn6 !== void 0 && _this$peerConn6.restartIce) {
var _this$peerConn7;
this.candidatesEnded = false;
logger$2.debug("Call ".concat(this.callId, " onIceConnectionStateChanged() ice restart (state=").concat((_this$peerConn7 = this.peerConn) === null || _this$peerConn7 === void 0 ? void 0 : _this$peerConn7.iceConnectionState, ")"));
this.peerConn.restartIce();
} else {
logger$2.info("Call ".concat(this.callId, " onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)"));
this.hangup(CallErrorCode.IceFailed, false);
}
} else if (((_this$peerConn8 = this.peerConn) === null || _this$peerConn8 === void 0 ? void 0 : _this$peerConn8.iceConnectionState) == "disconnected") {
this.candidatesEnded = false;
this.iceReconnectionTimeOut = setTimeout(() => {
var _this$peerConn9, _this$peerConn0, _this$peerConn1;
logger$2.info("Call ".concat(this.callId, " onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((_this$peerConn9 = this.peerConn) === null || _this$peerConn9 === void 0 ? void 0 : _this$peerConn9.iceConnectionState, ", conn=").concat((_this$peerConn0 = this.peerConn) === null || _this$peerConn0 === void 0 ? void 0 : _this$peerConn0.connectionState, ")"));
if ((_this$peerConn1 = this.peerConn) !== null && _this$peerConn1 !== void 0 && _this$peerConn1.restartIce) {
this.candidatesEnded = false;
this.peerConn.restartIce();
}
this.iceReconnectionTimeOut = void 0;
}, ICE_RECONNECTING_TIMEOUT);
this.iceDisconnectedTimeout = setTimeout(() => {
logger$2.info("Call ".concat(this.callId, " onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)"));
this.hangup(CallErrorCode.IceFailed, false);
}, ICE_DISCONNECTED_TIMEOUT);
this.state = CallState.Connecting;
}
if (this.isPtt && ["failed", "disconnected"].includes(this.peerConn.iceConnectionState)) for (var feed of this.getRemoteFeeds()) feed.setAudioVideoMuted(true, true);
});
(0, import_defineProperty.default)(this, "onSignallingStateChanged", () => {
var _this$peerConn10;
logger$2.debug("Call ".concat(this.callId, " onSignallingStateChanged() running (state=").concat((_this$peerConn10 = this.peerConn) === null || _this$peerConn10 === void 0 ? void 0 : _this$peerConn10.signalingState, ")"));
});
(0, import_defineProperty.default)(this, "onTrack", (ev) => {
if (ev.streams.length === 0) {
logger$2.warn("Call ".concat(this.callId, " onTrack() called with streamless track streamless (kind=").concat(ev.track.kind, ")"));
return;
}
var stream = ev.streams[0];
this.pushRemoteFeed(stream);
if (!this.removeTrackListeners.has(stream)) {
var onRemoveTrack = () => {
if (stream.getTracks().length === 0) {
logger$2.info("Call ".concat(this.callId, " onTrack() removing track (streamId=").concat(stream.id, ")"));
this.deleteFeedByStream(stream);
stream.removeEventListener("removetrack", onRemoveTrack);
this.removeTrackListeners.delete(stream);
}
};
stream.addEventListener("removetrack", onRemoveTrack);
this.removeTrackListeners.set(stream, onRemoveTrack);
}
});
(0, import_defineProperty.default)(this, "onDataChannel", (ev) => {
this.emit(CallEvent.DataChannel, ev.channel, this);
});
(0, import_defineProperty.default)(this, "onNegotiationNeeded", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
logger$2.info("Call ".concat(_this.callId, " onNegotiationNeeded() negotiation is needed!"));
if (_this.state !== CallState.CreateOffer && _this.opponentVersion === 0) {
logger$2.info("Call ".concat(_this.callId, " onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event"));
return;
}
_this.queueGotLocalOffer();
}));
(0, import_defineProperty.default)(this, "onHangupReceived", (msg) => {
logger$2.debug("Call ".concat(this.callId, " onHangupReceived() running"));
if (this.partyIdMatches(msg) || this.state === CallState.Ringing) this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
else logger$2.info("Call ".concat(this.callId, " onHangupReceived() ignoring message from party ID ").concat(msg.party_id, ": our partner is ").concat(this.opponentPartyId));
});
(0, import_defineProperty.default)(this, "onRejectReceived", (msg) => {
logger$2.debug("Call ".concat(this.callId, " onRejectReceived() running"));
if ([CallState.InviteSent, CallState.Ringing].includes(this.state) || this.state === CallState.Fledgling && this.direction === CallDirection.Inbound) this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);
else logger$2.debug("Call ".concat(this.callId, " onRejectReceived() called in wrong state (state=").concat(this.state, ")"));
});
(0, import_defineProperty.default)(this, "onAnsweredElsewhere", (msg) => {
logger$2.debug("Call ".concat(this.callId, " onAnsweredElsewhere() running"));
this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);
});
this.roomId = opts.roomId;
this.invitee = opts.invitee;
this.client = opts.client;
if (!this.client.deviceId) throw new Error("Client must have a device ID to start calls");
this.forceTURN = (_opts$forceTURN = opts.forceTURN) !== null && _opts$forceTURN !== void 0 ? _opts$forceTURN : false;
this.ourPartyId = this.client.deviceId;
this.opponentDeviceId = opts.opponentDeviceId;
this.opponentSessionId = opts.opponentSessionId;
this.groupCallId = opts.groupCallId;
this.turnServers = opts.turnServers || [];
if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) this.turnServers.push({ urls: [FALLBACK_ICE_SERVER] });
for (var server of this.turnServers) checkObjectHasKeys(server, ["urls"]);
this.callId = genCallID();
this.isOnlyDataChannelAllowed = this.client.isVoipWithNoMediaAllowed;
}
/**
* Place a voice call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
placeVoiceCall() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this2.placeCall(true, false);
})();
}
/**
* Place a video call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
placeVideoCall() {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this3.placeCall(true, true);
})();
}
/**
* Create a datachannel using this call's peer connection.
* @param label - A human readable label for this datachannel
* @param options - An object providing configuration options for the data channel.
*/
createDataChannel(label, options) {
var dataChannel = this.peerConn.createDataChannel(label, options);
this.emit(CallEvent.DataChannel, dataChannel, this);
return dataChannel;
}
getOpponentMember() {
return this.opponentMember;
}
getOpponentDeviceId() {
return this.opponentDeviceId;
}
getOpponentSessionId() {
return this.opponentSessionId;
}
opponentCanBeTransferred() {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.transferee"]);
}
opponentSupportsDTMF() {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.dtmf"]);
}
getRemoteAssertedIdentity() {
return this.remoteAssertedIdentity;
}
get state() {
return this._state;
}
set state(state) {
var oldState = this._state;
this._state = state;
this.emit(CallEvent.State, state, oldState, this);
}
get type() {
return this.hasUserMediaVideoSender || this.hasRemoteUserMediaVideoTrack ? CallType.Video : CallType.Voice;
}
get hasLocalUserMediaVideoTrack() {
var _this$localUsermediaS;
return !!((_this$localUsermediaS = this.localUsermediaStream) !== null && _this$localUsermediaS !== void 0 && _this$localUsermediaS.getVideoTracks().length);
}
get hasRemoteUserMediaVideoTrack() {
return this.getRemoteFeeds().some((feed) => {
var _feed$stream;
return feed.purpose === SDPStreamMetadataPurpose.Usermedia && ((_feed$stream = feed.stream) === null || _feed$stream === void 0 ? void 0 : _feed$stream.getVideoTracks().length);
});
}
get hasLocalUserMediaAudioTrack() {
var _this$localUsermediaS2;
return !!((_this$localUsermediaS2 = this.localUsermediaStream) !== null && _this$localUsermediaS2 !== void 0 && _this$localUsermediaS2.getAudioTracks().length);
}
get hasRemoteUserMediaAudioTrack() {
return this.getRemoteFeeds().some((feed) => {
var _feed$stream2;
return feed.purpose === SDPStreamMetadataPurpose.Usermedia && !!((_feed$stream2 = feed.stream) !== null && _feed$stream2 !== void 0 && _feed$stream2.getAudioTracks().length);
});
}
get hasUserMediaAudioSender() {
var _this$transceivers$ge;
return Boolean((_this$transceivers$ge = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, "audio"))) === null || _this$transceivers$ge === void 0 ? void 0 : _this$transceivers$ge.sender);
}
get hasUserMediaVideoSender() {
var _this$transceivers$ge2;
return Boolean((_this$transceivers$ge2 = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _this$transceivers$ge2 === void 0 ? void 0 : _this$transceivers$ge2.sender);
}
get localUsermediaFeed() {
return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);
}
get localScreensharingFeed() {
return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);
}
get localUsermediaStream() {
var _this$localUsermediaF;
return (_this$localUsermediaF = this.localUsermediaFeed) === null || _this$localUsermediaF === void 0 ? void 0 : _this$localUsermediaF.stream;
}
get localScreensharingStream() {
var _this$localScreenshar;
return (_this$localScreenshar = this.localScreensharingFeed) === null || _this$localScreenshar === void 0 ? void 0 : _this$localScreenshar.stream;
}
get remoteUsermediaFeed() {
return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);
}
get remoteScreensharingFeed() {
return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);
}
get remoteUsermediaStream() {
var _this$remoteUsermedia;
return (_this$remoteUsermedia = this.remoteUsermediaFeed) === null || _this$remoteUsermedia === void 0 ? void 0 : _this$remoteUsermedia.stream;
}
get remoteScreensharingStream() {
var _this$remoteScreensha;
return (_this$remoteScreensha = this.remoteScreensharingFeed) === null || _this$remoteScreensha === void 0 ? void 0 : _this$remoteScreensha.stream;
}
getFeedByStreamId(streamId) {
return this.getFeeds().find((feed) => feed.stream.id === streamId);
}
/**
* Returns an array of all CallFeeds
* @returns CallFeeds
*/
getFeeds() {
return this.feeds;
}
/**
* Returns an array of all local CallFeeds
* @returns local CallFeeds
*/
getLocalFeeds() {
return this.feeds.filter((feed) => feed.isLocal());
}
/**
* Returns an array of all remote CallFeeds
* @returns remote CallFeeds
*/
getRemoteFeeds() {
return this.feeds.filter((feed) => !feed.isLocal());
}
initOpponentCrypto() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this4$getOpponentMem;
if (!_this4.opponentDeviceId) return;
if (!_this4.client.getUseE2eForGroupCall()) return;
if (!_this4.client.getCrypto()) {
_this4.hasOpponentDeviceInfo = true;
return;
}
var userId = _this4.invitee || ((_this4$getOpponentMem = _this4.getOpponentMember()) === null || _this4$getOpponentMem === void 0 ? void 0 : _this4$getOpponentMem.userId);
if (!userId) throw new Error("Couldn't find opponent user ID to init crypto");
_this4.hasOpponentDeviceInfo = false;
throw new GroupCallUnknownDeviceError(userId);
})();
}
/**
* Generates and returns localSDPStreamMetadata
* @returns localSDPStreamMetadata
*/
getLocalSDPStreamMetadata() {
var updateStreamIds = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
var metadata = {};
for (var localFeed of this.getLocalFeeds()) {
if (updateStreamIds) localFeed.sdpMetadataStreamId = localFeed.stream.id;
metadata[localFeed.sdpMetadataStreamId] = {
purpose: localFeed.purpose,
audio_muted: localFeed.isAudioMuted(),
video_muted: localFeed.isVideoMuted()
};
}
return metadata;
}
/**
* Returns true if there are no incoming feeds,
* otherwise returns false
* @returns no incoming feeds
*/
noIncomingFeeds() {
return !this.feeds.some((feed) => !feed.isLocal());
}
pushRemoteFeed(stream) {
if (!this.opponentSupportsSDPStreamMetadata()) {
this.pushRemoteFeedWithoutMetadata(stream);
return;
}
var userId = this.getOpponentMember().userId;
var purpose = this.remoteSDPStreamMetadata[stream.id].purpose;
var audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted;
var videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted;
if (!purpose) {
logger$2.warn("Call ".concat(this.callId, " pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=").concat(stream.id, ")"));
return;
}
if (this.getFeedByStreamId(stream.id)) {
logger$2.warn("Call ".concat(this.callId, " pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")"));
return;
}
this.feeds.push(new CallFeed({
client: this.client,
call: this,
roomId: this.roomId,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose,
audioMuted,
videoMuted
}));
this.emit(CallEvent.FeedsChanged, this.feeds, this);
logger$2.info("Call ".concat(this.callId, " pushRemoteFeed() pushed stream (streamId=").concat(stream.id, ", active=").concat(stream.active, ", purpose=").concat(purpose, ")"));
}
/**
* This method is used ONLY if the other client doesn't support sending SDPStreamMetadata
*/
pushRemoteFeedWithoutMetadata(stream) {
var _this$feeds$find;
var userId = this.getOpponentMember().userId;
var purpose = SDPStreamMetadataPurpose.Usermedia;
var oldRemoteStream = (_this$feeds$find = this.feeds.find((feed) => !feed.isLocal())) === null || _this$feeds$find === void 0 ? void 0 : _this$feeds$find.stream;
if (oldRemoteStream && stream.id !== oldRemoteStream.id) {
logger$2.warn("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(stream.id, ")"));
return;
}
if (this.getFeedByStreamId(stream.id)) {
logger$2.warn("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")"));
return;
}
this.feeds.push(new CallFeed({
client: this.client,
call: this,
roomId: this.roomId,
audioMuted: false,
videoMuted: false,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose
}));
this.emit(CallEvent.FeedsChanged, this.feeds, this);
logger$2.info("Call ".concat(this.callId, " pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(stream.id, ", active=").concat(stream.active, ")"));
}
pushNewLocalFeed(stream, purpose) {
var addToPeerConnection = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
var userId = this.client.getUserId();
setTracksEnabled(stream.getAudioTracks(), true);
setTracksEnabled(stream.getVideoTracks(), true);
if (this.getFeedByStreamId(stream.id)) {
logger$2.warn("Call ".concat(this.callId, " pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(stream.id, ")"));
return;
}
this.pushLocalFeed(new CallFeed({
client: this.client,
roomId: this.roomId,
audioMuted: false,
videoMuted: false,
userId,
deviceId: this.getOpponentDeviceId(),
stream,
purpose
}), addToPeerConnection);
}
/**
* Pushes supplied feed to the call
* @param callFeed - to push
* @param addToPeerConnection - whether to add the tracks to the peer connection
*/
pushLocalFeed(callFeed) {
var _this5 = this;
var addToPeerConnection = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
if (this.feeds.some((feed) => callFeed.stream.id === feed.stream.id)) {
logger$2.info("Call ".concat(this.callId, " pushLocalFeed() ignoring duplicate local stream (streamId=").concat(callFeed.stream.id, ")"));
return;
}
this.feeds.push(callFeed);
if (addToPeerConnection) {
var _loop = function _loop() {
logger$2.info("Call ".concat(_this5.callId, " pushLocalFeed() adding track to peer connection (id=").concat(track.id, ", kind=").concat(track.kind, ", streamId=").concat(callFeed.stream.id, ", streamPurpose=").concat(callFeed.purpose, ", enabled=").concat(track.enabled, ")"));
var tKey = getTransceiverKey(callFeed.purpose, track.kind);
if (_this5.transceivers.has(tKey)) {
var transceiver = _this5.transceivers.get(tKey);
transceiver.sender.replaceTrack(track);
transceiver.direction = transceiver.direction === "inactive" ? "sendonly" : "sendrecv";
} else {
var newSender = _this5.peerConn.addTrack(track, callFeed.stream);
var newTransceiver = _this5.peerConn.getTransceivers().find((t) => t.sender === newSender);
if (newTransceiver) _this5.transceivers.set(tKey, newTransceiver);
else logger$2.warn("Call ".concat(_this5.callId, " pushLocalFeed() didn't find a matching transceiver after adding track!"));
}
};
for (var track of callFeed.stream.getTracks()) _loop();
}
logger$2.info("Call ".concat(this.callId, " pushLocalFeed() pushed stream (id=").concat(callFeed.stream.id, ", active=").concat(callFeed.stream.active, ", purpose=").concat(callFeed.purpose, ")"));
this.emit(CallEvent.FeedsChanged, this.feeds, this);
}
/**
* Removes local call feed from the call and its tracks from the peer
* connection
* @param callFeed - to remove
*/
removeLocalFeed(callFeed) {
for (var transceiverKey of [getTransceiverKey(callFeed.purpose, "audio"), getTransceiverKey(callFeed.purpose, "video")]) if (this.transceivers.has(transceiverKey)) {
var transceiver = this.transceivers.get(transceiverKey);
if (transceiver.sender) this.peerConn.removeTrack(transceiver.sender);
}
if (callFeed.purpose === SDPStreamMetadataPurpose.Screenshare) this.client.getMediaHandler().stopScreensharingStream(callFeed.stream);
this.deleteFeed(callFeed);
}
deleteAllFeeds() {
for (var feed of this.feeds) if (!feed.isLocal() || !this.groupCallId) feed.dispose();
this.feeds = [];
this.emit(CallEvent.FeedsChanged, this.feeds, this);
}
deleteFeedByStream(stream) {
var feed = this.getFeedByStreamId(stream.id);
if (!feed) {
logger$2.warn("Call ".concat(this.callId, " deleteFeedByStream() didn't find the feed to delete (streamId=").concat(stream.id, ")"));
return;
}
this.deleteFeed(feed);
}
deleteFeed(feed) {
feed.dispose();
this.feeds.splice(this.feeds.indexOf(feed), 1);
this.emit(CallEvent.FeedsChanged, this.feeds, this);
}
getCurrentCallStats() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this6.callHasEnded()) return _this6.callStatsAtEnd;
return _this6.collectCallStats();
})();
}
collectCallStats() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this7.peerConn) return;
var statsReport = yield _this7.peerConn.getStats();
var stats = [];
statsReport.forEach((item) => {
stats.push(item);
});
return stats;
})();
}
/**
* Configure this call from an invite event. Used by MatrixClient.
* @param event - The m.call.invite event
*/
initWithInvite(event) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this8$feeds$find;
var invite = event.getContent();
_this8.direction = CallDirection.Inbound;
if (!(yield _this8.client.checkTurnServers())) logger$2.warn("Call ".concat(_this8.callId, " initWithInvite() failed to get TURN credentials! Proceeding with call anyway..."));
var sdpStreamMetadata = SDPStreamMetadataKey.findIn(invite);
if (sdpStreamMetadata) _this8.updateRemoteSDPStreamMetadata(sdpStreamMetadata);
else logger$2.debug("Call ".concat(_this8.callId, " initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));
_this8.peerConn = _this8.createPeerConnection();
_this8.emit(CallEvent.PeerConnectionCreated, _this8.peerConn, _this8);
_this8.chooseOpponent(event);
yield _this8.initOpponentCrypto();
try {
yield _this8.peerConn.setRemoteDescription(invite.offer);
logger$2.debug("Call ".concat(_this8.callId, " initWithInvite() set remote description: ").concat(invite.offer.type));
yield _this8.addBufferedIceCandidates();
} catch (e) {
logger$2.debug("Call ".concat(_this8.callId, " initWithInvite() failed to set remote description"), e);
_this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
return;
}
var remoteStream = (_this8$feeds$find = _this8.feeds.find((feed) => !feed.isLocal())) === null || _this8$feeds$find === void 0 ? void 0 : _this8$feeds$find.stream;
if (!_this8.isOnlyDataChannelAllowed && (!remoteStream || remoteStream.getTracks().length === 0)) {
logger$2.error("Call ".concat(_this8.callId, " initWithInvite() no remote stream or no tracks after setting remote description!"));
_this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
return;
}
_this8.state = CallState.Ringing;
if (event.getLocalAge()) {
var ringingTimer = setTimeout(() => {
if (_this8.state == CallState.Ringing) {
var _this8$stats;
logger$2.debug("Call ".concat(_this8.callId, " initWithInvite() invite has expired. Hanging up."));
_this8.hangupParty = CallParty.Remote;
_this8.state = CallState.Ended;
_this8.stopAllMedia();
if (_this8.peerConn.signalingState != "closed") _this8.peerConn.close();
(_this8$stats = _this8.stats) === null || _this8$stats === void 0 || _this8$stats.removeStatsReportGatherer(_this8.callId);
_this8.emit(CallEvent.Hangup, _this8);
}
}, invite.lifetime - event.getLocalAge());
var onState = (state) => {
if (state !== CallState.Ringing) {
clearTimeout(ringingTimer);
_this8.off(CallEvent.State, onState);
}
};
_this8.on(CallEvent.State, onState);
}
})();
}
/**
* Configure this call from a hangup or reject event. Used by MatrixClient.
* @param event - The m.call.hangup event
*/
initWithHangup(event) {
this.state = CallState.Ended;
}
shouldAnswerWithMediaType(wantedValue, valueOfTheOtherSide, type) {
if (wantedValue && !valueOfTheOtherSide) {
logger$2.warn("Call ".concat(this.callId, " shouldAnswerWithMediaType() unable to answer with ").concat(type, " because the other side isn't sending it either."));
return false;
} else if (!isNullOrUndefined(wantedValue) && wantedValue !== valueOfTheOtherSide && !this.opponentSupportsSDPStreamMetadata()) {
logger$2.warn("Call ".concat(this.callId, " shouldAnswerWithMediaType() unable to answer with ").concat(type, "=").concat(wantedValue, " because the other side doesn't support it. Answering with ").concat(type, "=").concat(valueOfTheOtherSide, "."));
return valueOfTheOtherSide;
}
return wantedValue !== null && wantedValue !== void 0 ? wantedValue : valueOfTheOtherSide;
}
/**
* Answer a call.
*/
answer(audio, video) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this9.inviteOrAnswerSent) return;
if (audio === false && video === false) throw new Error("You CANNOT answer a call without media");
if (!_this9.localUsermediaStream && !_this9.waitForLocalAVStream) {
var prevState = _this9.state;
var answerWithAudio = _this9.shouldAnswerWithMediaType(audio, _this9.hasRemoteUserMediaAudioTrack, "audio");
var answerWithVideo = _this9.shouldAnswerWithMediaType(video, _this9.hasRemoteUserMediaVideoTrack, "video");
_this9.state = CallState.WaitLocalMedia;
_this9.waitForLocalAVStream = true;
try {
var _this9$client$getDevi;
var stream = yield _this9.client.getMediaHandler().getUserMediaStream(answerWithAudio, answerWithVideo);
_this9.waitForLocalAVStream = false;
var feeds = [new CallFeed({
client: _this9.client,
roomId: _this9.roomId,
userId: _this9.client.getUserId(),
deviceId: (_this9$client$getDevi = _this9.client.getDeviceId()) !== null && _this9$client$getDevi !== void 0 ? _this9$client$getDevi : void 0,
stream,
purpose: SDPStreamMetadataPurpose.Usermedia,
audioMuted: false,
videoMuted: false
})];
if (_this9.localScreensharingFeed) feeds.push(_this9.localScreensharingFeed);
_this9.answerWithCallFeeds(feeds);
} catch (e) {
if (answerWithVideo) {
logger$2.warn("Call ".concat(_this9.callId, " answer() failed to getUserMedia(), trying to getUserMedia() without video"));
_this9.state = prevState;
_this9.waitForLocalAVStream = false;
yield _this9.answer(answerWithAudio, false);
} else {
_this9.getUserMediaFailed(e);
return;
}
}
} else if (_this9.waitForLocalAVStream) _this9.state = CallState.WaitLocalMedia;
})();
}
answerWithCallFeeds(callFeeds) {
if (this.inviteOrAnswerSent) return;
this.queueGotCallFeedsForAnswer(callFeeds);
}
/**
* Replace this call with a new call, e.g. for glare resolution. Used by
* MatrixClient.
* @param newCall - The new call.
*/
replacedBy(newCall) {
logger$2.debug("Call ".concat(this.callId, " replacedBy() running (newCallId=").concat(newCall.callId, ")"));
if (this.state === CallState.WaitLocalMedia) {
logger$2.debug("Call ".concat(this.callId, " replacedBy() telling new call to wait for local media (newCallId=").concat(newCall.callId, ")"));
newCall.waitForLocalAVStream = true;
} else if ([CallState.CreateOffer, CallState.InviteSent].includes(this.state)) if (newCall.direction === CallDirection.Outbound) newCall.queueGotCallFeedsForAnswer([]);
else {
logger$2.debug("Call ".concat(this.callId, " replacedBy() handing local stream to new call(newCallId=").concat(newCall.callId, ")"));
newCall.queueGotCallFeedsForAnswer(this.getLocalFeeds().map((feed) => feed.clone()));
}
this.successor = newCall;
this.emit(CallEvent.Replaced, newCall, this);
this.hangup(CallErrorCode.Replaced, true);
}
/**
* Hangup a call.
* @param reason - The reason why the call is being hung up.
* @param suppressEvent - True to suppress emitting an event.
*/
hangup(reason, suppressEvent) {
if (this.callHasEnded()) return;
logger$2.debug("Call ".concat(this.callId, " hangup() ending call (reason=").concat(reason, ")"));
this.terminate(CallParty.Local, reason, !suppressEvent);
if ([CallState.Fledgling, CallState.WaitLocalMedia].includes(this.state)) return;
var content = {};
if (this.opponentVersion && this.opponentVersion !== 0 || reason !== CallErrorCode.UserHangup) content["reason"] = reason;
this.sendVoipEvent(EventType.CallHangup, content);
}
/**
* Reject a call
* This used to be done by calling hangup, but is a separate method and protocol
* event as of MSC2746.
*/
reject() {
if (this.state !== CallState.Ringing) throw Error("Call must be in 'ringing' state to reject!");
if (this.opponentVersion === 0) {
logger$2.info("Call ".concat(this.callId, " reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=").concat(this.opponentVersion, ")"));
this.hangup(CallErrorCode.UserHangup, true);
return;
}
logger$2.debug("Rejecting call: " + this.callId);
this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);
this.sendVoipEvent(EventType.CallReject, {});
}
/**
* Adds an audio and/or video track - upgrades the call
* @param audio - should add an audio track
* @param video - should add an video track
*/
upgradeCall(audio, video) {
var _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!audio && !video) return;
if (!_this0.opponentSupportsSDPStreamMetadata()) return;
try {
logger$2.debug("Call ".concat(_this0.callId, " upgradeCall() upgrading call (audio=").concat(audio, ", video=").concat(video, ")"));
var getAudio = audio || _this0.hasLocalUserMediaAudioTrack;
var getVideo = video || _this0.hasLocalUserMediaVideoTrack;
var stream = yield _this0.client.getMediaHandler().getUserMediaStream(getAudio, getVideo, false);
yield _this0.updateLocalUsermediaStream(stream, audio, video);
} catch (error) {
logger$2.error("Call ".concat(_this0.callId, " upgradeCall() failed to upgrade the call"), error);
_this0.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, "Failed to get camera access: ", error), _this0);
}
})();
}
/**
* Returns true if this.remoteSDPStreamMetadata is defined, otherwise returns false
* @returns can screenshare
*/
opponentSupportsSDPStreamMetadata() {
return Boolean(this.remoteSDPStreamMetadata);
}
/**
* If there is a screensharing stream returns true, otherwise returns false
* @returns is screensharing
*/
isScreensharing() {
return Boolean(this.localScreensharingStream);
}
/**
* Starts/stops screensharing
* @param enabled - the desired screensharing state
* @param opts - screen sharing options
* @returns new screensharing state
*/
setScreensharingEnabled(enabled, opts) {
var _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (enabled && _this1.isScreensharing()) {
logger$2.warn("Call ".concat(_this1.callId, " setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!"));
return true;
} else if (!enabled && !_this1.isScreensharing()) {
logger$2.warn("Call ".concat(_this1.callId, " setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!"));
return false;
}
if (!_this1.opponentSupportsSDPStreamMetadata()) return _this1.setScreensharingEnabledWithoutMetadataSupport(enabled, opts);
logger$2.debug("Call ".concat(_this1.callId, " setScreensharingEnabled() running (enabled=").concat(enabled, ")"));
if (enabled) try {
var stream = yield _this1.client.getMediaHandler().getScreensharingStream(opts);
if (!stream) return false;
_this1.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare);
return true;
} catch (err) {
logger$2.error("Call ".concat(_this1.callId, " setScreensharingEnabled() failed to get screen-sharing stream:"), err);
return false;
}
else {
for (var transceiver of [_this1.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, "audio")), _this1.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, "video"))]) if (transceiver && transceiver.sender) _this1.peerConn.removeTrack(transceiver.sender);
_this1.client.getMediaHandler().stopScreensharingStream(_this1.localScreensharingStream);
_this1.deleteFeedByStream(_this1.localScreensharingStream);
return false;
}
})();
}
/**
* Starts/stops screensharing
* Should be used ONLY if the opponent doesn't support SDPStreamMetadata
* @param enabled - the desired screensharing state
* @param opts - screen sharing options
* @returns new screensharing state
*/
setScreensharingEnabledWithoutMetadataSupport(enabled, opts) {
var _this10 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.debug("Call ".concat(_this10.callId, " setScreensharingEnabledWithoutMetadataSupport() running (enabled=").concat(enabled, ")"));
if (enabled) try {
var _this10$transceivers$;
var stream = yield _this10.client.getMediaHandler().getScreensharingStream(opts);
if (!stream) return false;
var track = stream.getTracks().find((track) => track.kind === "video");
var sender = (_this10$transceivers$ = _this10.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _this10$transceivers$ === void 0 ? void 0 : _this10$transceivers$.sender;
sender === null || sender === void 0 || sender.replaceTrack(track !== null && track !== void 0 ? track : null);
_this10.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare, false);
return true;
} catch (err) {
logger$2.error("Call ".concat(_this10.callId, " setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:"), err);
return false;
}
else {
var _this10$localUsermedi, _this10$transceivers$2;
var _track = (_this10$localUsermedi = _this10.localUsermediaStream) === null || _this10$localUsermedi === void 0 ? void 0 : _this10$localUsermedi.getTracks().find((track) => track.kind === "video");
var _sender = (_this10$transceivers$2 = _this10.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _this10$transceivers$2 === void 0 ? void 0 : _this10$transceivers$2.sender;
_sender === null || _sender === void 0 || _sender.replaceTrack(_track !== null && _track !== void 0 ? _track : null);
_this10.client.getMediaHandler().stopScreensharingStream(_this10.localScreensharingStream);
_this10.deleteFeedByStream(_this10.localScreensharingStream);
return false;
}
})();
}
/**
* Replaces/adds the tracks from the passed stream to the localUsermediaStream
* @param stream - to use a replacement for the local usermedia stream
*/
updateLocalUsermediaStream(stream) {
var _arguments = arguments, _this11 = this;
return (0, import_asyncToGenerator.default)(function* () {
var forceAudio = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : false;
var forceVideo = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : false;
var callFeed = _this11.localUsermediaFeed;
var audioEnabled = forceAudio || !callFeed.isAudioMuted() && !_this11.remoteOnHold;
var videoEnabled = forceVideo || !callFeed.isVideoMuted() && !_this11.remoteOnHold;
logger$2.log("Call ".concat(_this11.callId, " updateLocalUsermediaStream() running (streamId=").concat(stream.id, ", audio=").concat(audioEnabled, ", video=").concat(videoEnabled, ")"));
setTracksEnabled(stream.getAudioTracks(), audioEnabled);
setTracksEnabled(stream.getVideoTracks(), videoEnabled);
for (var track of _this11.localUsermediaStream.getTracks()) {
_this11.localUsermediaStream.removeTrack(track);
track.stop();
}
for (var _track2 of stream.getTracks()) _this11.localUsermediaStream.addTrack(_track2);
var _loop2 = function* _loop2() {
var tKey = getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, _track3.kind);
var transceiver = _this11.transceivers.get(tKey);
var oldSender = transceiver === null || transceiver === void 0 ? void 0 : transceiver.sender;
var added = false;
if (oldSender) try {
logger$2.info("Call ".concat(_this11.callId, " updateLocalUsermediaStream() replacing track (id=").concat(_track3.id, ", kind=").concat(_track3.kind, ", streamId=").concat(stream.id, ", streamPurpose=").concat(callFeed.purpose, ")"));
yield oldSender.replaceTrack(_track3);
transceiver.direction = transceiver.direction === "inactive" ? "sendonly" : "sendrecv";
added = true;
} catch (error) {
logger$2.warn("Call ".concat(_this11.callId, " updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead"), error);
}
if (!added) {
logger$2.info("Call ".concat(_this11.callId, " updateLocalUsermediaStream() adding track to peer connection (id=").concat(_track3.id, ", kind=").concat(_track3.kind, ", streamId=").concat(stream.id, ", streamPurpose=").concat(callFeed.purpose, ")"));
var newSender = _this11.peerConn.addTrack(_track3, _this11.localUsermediaStream);
var newTransceiver = _this11.peerConn.getTransceivers().find((t) => t.sender === newSender);
if (newTransceiver) _this11.transceivers.set(tKey, newTransceiver);
else logger$2.warn("Call ".concat(_this11.callId, " updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!"));
}
};
for (var _track3 of stream.getTracks()) yield* _loop2();
})();
}
/**
* Set whether our outbound video should be muted or not.
* @param muted - True to mute the outbound video.
* @returns the new mute state
*/
setLocalVideoMuted(muted) {
var _this12 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this12$localUsermedi2;
logger$2.log("Call ".concat(_this12.callId, " setLocalVideoMuted() running ").concat(muted));
if (!muted && _this12.stopVideoTrackTimer !== void 0) {
clearTimeout(_this12.stopVideoTrackTimer);
_this12.stopVideoTrackTimer = void 0;
}
if (!(yield _this12.client.getMediaHandler().hasVideoDevice())) return _this12.isLocalVideoMuted();
if (!_this12.hasUserMediaVideoSender && !muted) {
var _this12$localUsermedi;
(_this12$localUsermedi = _this12.localUsermediaFeed) === null || _this12$localUsermedi === void 0 || _this12$localUsermedi.setAudioVideoMuted(null, muted);
yield _this12.upgradeCall(false, true);
return _this12.isLocalVideoMuted();
}
if (!muted && _this12.localUsermediaStream.getVideoTracks().length === 0) {
var stream = yield _this12.client.getMediaHandler().getUserMediaStream(true, true);
yield _this12.updateLocalUsermediaStream(stream);
}
(_this12$localUsermedi2 = _this12.localUsermediaFeed) === null || _this12$localUsermedi2 === void 0 || _this12$localUsermedi2.setAudioVideoMuted(null, muted);
_this12.updateMuteStatus();
yield _this12.sendMetadataUpdate();
if (muted) _this12.stopVideoTrackTimer = setTimeout(() => {
for (var t of _this12.localUsermediaStream.getVideoTracks()) {
t.stop();
_this12.localUsermediaStream.removeTrack(t);
}
}, 120);
return _this12.isLocalVideoMuted();
})();
}
/**
* Check if local video is muted.
*
* If there are multiple video tracks, <i>all</i> of the tracks need to be muted
* for this to return true. This means if there are no video tracks, this will
* return true.
* @returns True if the local preview video is muted, else false
* (including if the call is not set up yet).
*/
isLocalVideoMuted() {
var _this$localUsermediaF2, _this$localUsermediaF3;
return (_this$localUsermediaF2 = (_this$localUsermediaF3 = this.localUsermediaFeed) === null || _this$localUsermediaF3 === void 0 ? void 0 : _this$localUsermediaF3.isVideoMuted()) !== null && _this$localUsermediaF2 !== void 0 ? _this$localUsermediaF2 : false;
}
/**
* Set whether the microphone should be muted or not.
* @param muted - True to mute the mic.
* @returns the new mute state
*/
setMicrophoneMuted(muted) {
var _this13 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this13$localUsermedi;
logger$2.log("Call ".concat(_this13.callId, " setMicrophoneMuted() running ").concat(muted));
if (!(yield _this13.client.getMediaHandler().hasAudioDevice())) return _this13.isMicrophoneMuted();
if (!muted && (!_this13.hasUserMediaAudioSender || !_this13.hasLocalUserMediaAudioTrack)) {
yield _this13.upgradeCall(true, false);
return _this13.isMicrophoneMuted();
}
(_this13$localUsermedi = _this13.localUsermediaFeed) === null || _this13$localUsermedi === void 0 || _this13$localUsermedi.setAudioVideoMuted(muted, null);
_this13.updateMuteStatus();
yield _this13.sendMetadataUpdate();
return _this13.isMicrophoneMuted();
})();
}
/**
* Check if the microphone is muted.
*
* If there are multiple audio tracks, <i>all</i> of the tracks need to be muted
* for this to return true. This means if there are no audio tracks, this will
* return true.
* @returns True if the mic is muted, else false (including if the call
* is not set up yet).
*/
isMicrophoneMuted() {
var _this$localUsermediaF4, _this$localUsermediaF5;
return (_this$localUsermediaF4 = (_this$localUsermediaF5 = this.localUsermediaFeed) === null || _this$localUsermediaF5 === void 0 ? void 0 : _this$localUsermediaF5.isAudioMuted()) !== null && _this$localUsermediaF4 !== void 0 ? _this$localUsermediaF4 : false;
}
/**
* @returns true if we have put the party on the other side of the call on hold
* (that is, we are signalling to them that we are not listening)
*/
isRemoteOnHold() {
return this.remoteOnHold;
}
setRemoteOnHold(onHold) {
if (this.isRemoteOnHold() === onHold) return;
this.remoteOnHold = onHold;
for (var transceiver of this.peerConn.getTransceivers()) transceiver.direction = onHold ? "sendonly" : "sendrecv";
this.updateMuteStatus();
this.sendMetadataUpdate();
this.emit(CallEvent.RemoteHoldUnhold, this.remoteOnHold, this);
}
/**
* Indicates whether we are 'on hold' to the remote party (ie. if true,
* they cannot hear us).
* @returns true if the other party has put us on hold
*/
isLocalOnHold() {
if (this.state !== CallState.Connected) return false;
var callOnHold = true;
for (var transceiver of this.peerConn.getTransceivers()) if (!["inactive", "recvonly"].includes(transceiver.currentDirection)) callOnHold = false;
return callOnHold;
}
/**
* Sends a DTMF digit to the other party
* @param digit - The digit (nb. string - '#' and '*' are dtmf too)
*/
sendDtmfDigit(digit) {
for (var sender of this.peerConn.getSenders()) {
var _sender$track;
if (((_sender$track = sender.track) === null || _sender$track === void 0 ? void 0 : _sender$track.kind) === "audio" && sender.dtmf) {
sender.dtmf.insertDTMF(digit);
return;
}
}
throw new Error("Unable to find a track to send DTMF on");
}
updateMuteStatus() {
var micShouldBeMuted = this.isMicrophoneMuted() || this.remoteOnHold;
var vidShouldBeMuted = this.isLocalVideoMuted() || this.remoteOnHold;
logger$2.log("Call ".concat(this.callId, " updateMuteStatus stream ").concat(this.localUsermediaStream.id, " micShouldBeMuted ").concat(micShouldBeMuted, " vidShouldBeMuted ").concat(vidShouldBeMuted));
setTracksEnabled(this.localUsermediaStream.getAudioTracks(), !micShouldBeMuted);
setTracksEnabled(this.localUsermediaStream.getVideoTracks(), !vidShouldBeMuted);
}
sendMetadataUpdate() {
var _this14 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this14.sendVoipEvent(EventType.CallSDPStreamMetadataChanged, { [SDPStreamMetadataKey.name]: _this14.getLocalSDPStreamMetadata() });
})();
}
gotCallFeedsForInvite(callFeeds) {
var requestScreenshareFeed = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
if (this.successor) {
this.successor.queueGotCallFeedsForAnswer(callFeeds);
return;
}
if (this.callHasEnded()) {
this.stopAllMedia();
return;
}
for (var feed of callFeeds) this.pushLocalFeed(feed);
if (requestScreenshareFeed) this.peerConn.addTransceiver("video", { direction: "recvonly" });
this.state = CallState.CreateOffer;
logger$2.debug("Call ".concat(this.callId, " gotUserMediaForInvite() run"));
}
sendAnswer() {
var _this15 = this;
return (0, import_asyncToGenerator.default)(function* () {
var answerContent = {
answer: {
sdp: _this15.peerConn.localDescription.sdp,
type: _this15.peerConn.localDescription.type
},
[SDPStreamMetadataKey.name]: _this15.getLocalSDPStreamMetadata(true)
};
answerContent.capabilities = {
"m.call.transferee": _this15.client.supportsCallTransfer,
"m.call.dtmf": false
};
var discardCount = _this15.discardDuplicateCandidates();
logger$2.info("Call ".concat(_this15.callId, " sendAnswer() discarding ").concat(discardCount, " candidates that will be sent in answer"));
try {
yield _this15.sendVoipEvent(EventType.CallAnswer, answerContent);
_this15.inviteOrAnswerSent = true;
} catch (error) {
_this15.state = CallState.Ringing;
if (error instanceof MatrixError && error.event) _this15.client.cancelPendingEvent(error.event);
var code = CallErrorCode.SendAnswer;
var message = "Failed to send answer";
if (error.name == "UnknownDeviceError") {
code = CallErrorCode.UnknownDevices;
message = "Unknown devices present in the room";
}
_this15.emit(CallEvent.Error, new CallError(code, message, error), _this15);
throw error;
}
_this15.sendCandidateQueue();
})();
}
queueGotCallFeedsForAnswer(callFeeds) {
if (this.responsePromiseChain) this.responsePromiseChain = this.responsePromiseChain.then(() => this.gotCallFeedsForAnswer(callFeeds));
else this.responsePromiseChain = this.gotCallFeedsForAnswer(callFeeds);
}
mungeSdp(description, mods) {
var sdp = (0, import_lib.parse)(description.sdp);
sdp.media.forEach((media) => {
var payloadTypeToCodecMap = /* @__PURE__ */ new Map();
var codecToPayloadTypeMap = /* @__PURE__ */ new Map();
for (var rtp of media.rtp) {
payloadTypeToCodecMap.set(rtp.payload, rtp.codec);
codecToPayloadTypeMap.set(rtp.codec, rtp.payload);
}
for (var mod of mods) {
if (mod.mediaType !== media.type) continue;
if (!codecToPayloadTypeMap.has(mod.codec)) {
logger$2.info("Call ".concat(this.callId, " mungeSdp() ignoring SDP modifications for ").concat(mod.codec, " as it's not present."));
continue;
}
var extraConfig = [];
if (mod.enableDtx !== void 0) extraConfig.push("usedtx=".concat(mod.enableDtx ? "1" : "0"));
if (mod.maxAverageBitrate !== void 0) extraConfig.push("maxaveragebitrate=".concat(mod.maxAverageBitrate));
var found = false;
for (var fmtp of media.fmtp) if (payloadTypeToCodecMap.get(fmtp.payload) === mod.codec) {
found = true;
fmtp.config += ";" + extraConfig.join(";");
}
if (!found) media.fmtp.push({
payload: codecToPayloadTypeMap.get(mod.codec),
config: extraConfig.join(";")
});
}
});
description.sdp = (0, import_lib.write)(sdp);
}
createOffer() {
var _this16 = this;
return (0, import_asyncToGenerator.default)(function* () {
var offer = yield _this16.peerConn.createOffer();
_this16.mungeSdp(offer, getCodecParamMods(_this16.isPtt));
return offer;
})();
}
createAnswer() {
var _this17 = this;
return (0, import_asyncToGenerator.default)(function* () {
var answer = yield _this17.peerConn.createAnswer();
_this17.mungeSdp(answer, getCodecParamMods(_this17.isPtt));
return answer;
})();
}
gotCallFeedsForAnswer(callFeeds) {
var _this18 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this18.callHasEnded()) return;
_this18.waitForLocalAVStream = false;
for (var feed of callFeeds) _this18.pushLocalFeed(feed);
_this18.state = CallState.CreateAnswer;
var answer;
try {
_this18.getRidOfRTXCodecs();
answer = yield _this18.createAnswer();
} catch (err) {
logger$2.debug("Call ".concat(_this18.callId, " gotCallFeedsForAnswer() failed to create answer: "), err);
_this18.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);
return;
}
try {
yield _this18.peerConn.setLocalDescription(answer);
if (_this18.callHasEnded()) return;
_this18.state = CallState.Connecting;
yield new Promise((resolve) => {
setTimeout(resolve, 200);
});
if (_this18.callHasEnded()) return;
_this18.sendAnswer();
} catch (err) {
logger$2.debug("Call ".concat(_this18.callId, " gotCallFeedsForAnswer() error setting local description!"), err);
_this18.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);
return;
}
})();
}
onRemoteIceCandidatesReceived(ev) {
var _this19 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this19.callHasEnded()) return;
var content = ev.getContent();
var candidates = content.candidates;
if (!candidates) {
logger$2.info("Call ".concat(_this19.callId, " onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!"));
return;
}
var fromPartyId = content.version === 0 ? null : content.party_id || null;
if (_this19.opponentPartyId === void 0) {
if (fromPartyId) {
logger$2.info("Call ".concat(_this19.callId, " onRemoteIceCandidatesReceived() buffering ").concat(candidates.length, " candidates until we pick an opponent"));
var bufferedCandidates = _this19.remoteCandidateBuffer.get(fromPartyId) || [];
bufferedCandidates.push(...candidates);
_this19.remoteCandidateBuffer.set(fromPartyId, bufferedCandidates);
}
return;
}
if (!_this19.partyIdMatches(content)) {
logger$2.info("Call ".concat(_this19.callId, " onRemoteIceCandidatesReceived() ignoring candidates from party ID ").concat(content.party_id, ": we have chosen party ID ").concat(_this19.opponentPartyId));
return;
}
yield _this19.addIceCandidates(candidates);
})();
}
/**
* Used by MatrixClient.
*/
onAnswerReceived(event) {
var _this20 = this;
return (0, import_asyncToGenerator.default)(function* () {
var content = event.getContent();
logger$2.debug("Call ".concat(_this20.callId, " onAnswerReceived() running (hangupParty=").concat(content.party_id, ")"));
if (_this20.callHasEnded()) {
logger$2.debug("Call ".concat(_this20.callId, " onAnswerReceived() ignoring answer because call has ended"));
return;
}
if (_this20.opponentPartyId !== void 0) {
logger$2.info("Call ".concat(_this20.callId, " onAnswerReceived() ignoring answer from party ID ").concat(content.party_id, ": we already have an answer/reject from ").concat(_this20.opponentPartyId));
return;
}
_this20.chooseOpponent(event);
yield _this20.addBufferedIceCandidates();
_this20.state = CallState.Connecting;
var sdpStreamMetadata = SDPStreamMetadataKey.findIn(content);
if (sdpStreamMetadata) _this20.updateRemoteSDPStreamMetadata(sdpStreamMetadata);
else logger$2.warn("Call ".concat(_this20.callId, " onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));
try {
_this20.isSettingRemoteAnswerPending = true;
yield _this20.peerConn.setRemoteDescription(content.answer);
_this20.isSettingRemoteAnswerPending = false;
logger$2.debug("Call ".concat(_this20.callId, " onAnswerReceived() set remote description: ").concat(content.answer.type));
} catch (e) {
_this20.isSettingRemoteAnswerPending = false;
logger$2.debug("Call ".concat(_this20.callId, " onAnswerReceived() failed to set remote description"), e);
_this20.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
return;
}
if (_this20.opponentPartyId !== null) try {
yield _this20.sendVoipEvent(EventType.CallSelectAnswer, { selected_party_id: _this20.opponentPartyId });
} catch (err) {
logger$2.warn("Call ".concat(_this20.callId, " onAnswerReceived() failed to send select_answer event"), err);
}
})();
}
onSelectAnswerReceived(event) {
var _this21 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this21.direction !== CallDirection.Inbound) {
logger$2.warn("Call ".concat(_this21.callId, " onSelectAnswerReceived() got select_answer for an outbound call: ignoring"));
return;
}
var selectedPartyId = event.getContent().selected_party_id;
if (selectedPartyId === void 0 || selectedPartyId === null) {
logger$2.warn("Call ".concat(_this21.callId, " onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring"));
return;
}
if (selectedPartyId !== _this21.ourPartyId) {
logger$2.info("Call ".concat(_this21.callId, " onSelectAnswerReceived() got select_answer for party ID ").concat(selectedPartyId, ": we are party ID ").concat(_this21.ourPartyId, "."));
yield _this21.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);
}
})();
}
onNegotiateReceived(event) {
var _this22 = this;
return (0, import_asyncToGenerator.default)(function* () {
var content = event.getContent();
var description = content.description;
if (!description || !description.sdp || !description.type) {
logger$2.info("Call ".concat(_this22.callId, " onNegotiateReceived() ignoring invalid m.call.negotiate event"));
return;
}
var polite = _this22.direction === CallDirection.Inbound;
var readyForOffer = !_this22.makingOffer && (_this22.peerConn.signalingState === "stable" || _this22.isSettingRemoteAnswerPending);
var offerCollision = description.type === "offer" && !readyForOffer;
_this22.ignoreOffer = !polite && offerCollision;
if (_this22.ignoreOffer) {
logger$2.info("Call ".concat(_this22.callId, " onNegotiateReceived() ignoring colliding negotiate event because we're impolite"));
return;
}
var prevLocalOnHold = _this22.isLocalOnHold();
var sdpStreamMetadata = SDPStreamMetadataKey.findIn(content);
if (sdpStreamMetadata) _this22.updateRemoteSDPStreamMetadata(sdpStreamMetadata);
else logger$2.warn("Call ".concat(_this22.callId, " onNegotiateReceived() received negotiation event without SDPStreamMetadata!"));
try {
_this22.isSettingRemoteAnswerPending = description.type == "answer";
yield _this22.peerConn.setRemoteDescription(description);
_this22.isSettingRemoteAnswerPending = false;
logger$2.debug("Call ".concat(_this22.callId, " onNegotiateReceived() set remote description: ").concat(description.type));
if (description.type === "offer") {
var _localDescription;
var answer;
try {
_this22.getRidOfRTXCodecs();
answer = yield _this22.createAnswer();
} catch (err) {
logger$2.debug("Call ".concat(_this22.callId, " onNegotiateReceived() failed to create answer: "), err);
_this22.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);
return;
}
yield _this22.peerConn.setLocalDescription(answer);
logger$2.debug("Call ".concat(_this22.callId, " onNegotiateReceived() create an answer"));
_this22.sendVoipEvent(EventType.CallNegotiate, {
lifetime: CALL_TIMEOUT_MS,
description: (_localDescription = _this22.peerConn.localDescription) === null || _localDescription === void 0 ? void 0 : _localDescription.toJSON(),
[SDPStreamMetadataKey.name]: _this22.getLocalSDPStreamMetadata(true)
});
}
} catch (err) {
_this22.isSettingRemoteAnswerPending = false;
logger$2.warn("Call ".concat(_this22.callId, " onNegotiateReceived() failed to complete negotiation"), err);
}
var newLocalOnHold = _this22.isLocalOnHold();
if (prevLocalOnHold !== newLocalOnHold) {
_this22.emit(CallEvent.LocalHoldUnhold, newLocalOnHold, _this22);
_this22.emit(CallEvent.HoldUnhold, newLocalOnHold);
}
})();
}
updateRemoteSDPStreamMetadata(metadata) {
this.remoteSDPStreamMetadata = recursivelyAssign(this.remoteSDPStreamMetadata || {}, metadata, true);
for (var feed of this.getRemoteFeeds()) {
var _streamId;
var streamId = feed.stream.id;
var _metadata = this.remoteSDPStreamMetadata[streamId];
feed.setAudioVideoMuted(_metadata === null || _metadata === void 0 ? void 0 : _metadata.audio_muted, _metadata === null || _metadata === void 0 ? void 0 : _metadata.video_muted);
feed.purpose = (_streamId = this.remoteSDPStreamMetadata[streamId]) === null || _streamId === void 0 ? void 0 : _streamId.purpose;
}
}
onSDPStreamMetadataChangedReceived(event) {
var content = event.getContent();
var metadata = SDPStreamMetadataKey.findIn(content);
if (metadata) this.updateRemoteSDPStreamMetadata(metadata);
}
onAssertedIdentityReceived(event) {
var _this23 = this;
return (0, import_asyncToGenerator.default)(function* () {
var content = event.getContent();
if (!content.asserted_identity) return;
_this23.remoteAssertedIdentity = {
id: content.asserted_identity.id,
displayName: content.asserted_identity.display_name
};
_this23.emit(CallEvent.AssertedIdentityChanged, _this23);
})();
}
callHasEnded() {
return this.state === CallState.Ended;
}
queueGotLocalOffer() {
if (this.responsePromiseChain) this.responsePromiseChain = this.responsePromiseChain.then(() => this.wrappedGotLocalOffer());
else this.responsePromiseChain = this.wrappedGotLocalOffer();
}
wrappedGotLocalOffer() {
var _this24 = this;
return (0, import_asyncToGenerator.default)(function* () {
_this24.makingOffer = true;
try {
yield _this24.gotLocalOffer();
} catch (e) {
_this24.getLocalOfferFailed(e);
return;
} finally {
_this24.makingOffer = false;
}
})();
}
gotLocalOffer() {
var _this25 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.debug("Call ".concat(_this25.callId, " gotLocalOffer() running"));
if (_this25.callHasEnded()) {
logger$2.debug("Call ".concat(_this25.callId, " gotLocalOffer() ignoring newly created offer because the call has ended\""));
return;
}
var offer;
try {
_this25.getRidOfRTXCodecs();
offer = yield _this25.createOffer();
} catch (err) {
logger$2.debug("Call ".concat(_this25.callId, " gotLocalOffer() failed to create offer: "), err);
_this25.terminate(CallParty.Local, CallErrorCode.CreateOffer, true);
return;
}
try {
yield _this25.peerConn.setLocalDescription(offer);
} catch (err) {
logger$2.debug("Call ".concat(_this25.callId, " gotLocalOffer() error setting local description!"), err);
_this25.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);
return;
}
if (_this25.peerConn.iceGatheringState === "gathering") yield new Promise((resolve) => {
setTimeout(resolve, 200);
});
if (_this25.callHasEnded()) return;
var eventType = _this25.state === CallState.CreateOffer ? EventType.CallInvite : EventType.CallNegotiate;
var content = { lifetime: CALL_TIMEOUT_MS };
if (eventType === EventType.CallInvite && _this25.invitee) content.invitee = _this25.invitee;
if (_this25.state === CallState.CreateOffer) {
var _localDescription2;
content.offer = (_localDescription2 = _this25.peerConn.localDescription) === null || _localDescription2 === void 0 ? void 0 : _localDescription2.toJSON();
} else {
var _localDescription3;
content.description = (_localDescription3 = _this25.peerConn.localDescription) === null || _localDescription3 === void 0 ? void 0 : _localDescription3.toJSON();
}
content.capabilities = {
"m.call.transferee": _this25.client.supportsCallTransfer,
"m.call.dtmf": false
};
content[SDPStreamMetadataKey.name] = _this25.getLocalSDPStreamMetadata(true);
var discardCount = _this25.discardDuplicateCandidates();
logger$2.info("Call ".concat(_this25.callId, " gotLocalOffer() discarding ").concat(discardCount, " candidates that will be sent in offer"));
try {
yield _this25.sendVoipEvent(eventType, content);
} catch (error) {
logger$2.error("Call ".concat(_this25.callId, " gotLocalOffer() failed to send invite"), error);
if (error instanceof MatrixError && error.event) _this25.client.cancelPendingEvent(error.event);
var code = CallErrorCode.SignallingFailed;
var message = "Signalling failed";
if (_this25.state === CallState.CreateOffer) {
code = CallErrorCode.SendInvite;
message = "Failed to send invite";
}
if (error.name == "UnknownDeviceError") {
code = CallErrorCode.UnknownDevices;
message = "Unknown devices present in the room";
}
_this25.emit(CallEvent.Error, new CallError(code, message, error), _this25);
_this25.terminate(CallParty.Local, code, false);
return;
}
_this25.sendCandidateQueue();
if (_this25.state === CallState.CreateOffer) {
_this25.inviteOrAnswerSent = true;
_this25.state = CallState.InviteSent;
_this25.inviteTimeout = setTimeout(() => {
_this25.inviteTimeout = void 0;
if (_this25.state === CallState.InviteSent) _this25.hangup(CallErrorCode.InviteTimeout, false);
}, CALL_TIMEOUT_MS);
}
})();
}
/**
* This method removes all video/rtx codecs from screensharing video
* transceivers. This is necessary since they can cause problems. Without
* this the following steps should produce an error:
* Chromium calls Firefox
* Firefox answers
* Firefox starts screen-sharing
* Chromium starts screen-sharing
* Call crashes for Chromium with:
* [96685:23:0518/162603.933321:ERROR:webrtc_video_engine.cc(3296)] RTX codec (PT=97) mapped to PT=96 which is not in the codec list.
* [96685:23:0518/162603.933377:ERROR:webrtc_video_engine.cc(1171)] GetChangedRecvParameters called without any video codecs.
* [96685:23:0518/162603.933430:ERROR:sdp_offer_answer.cc(4302)] Failed to set local video description recv parameters for m-section with mid='2'. (INVALID_PARAMETER)
*/
getRidOfRTXCodecs() {
if (!RTCRtpReceiver.getCapabilities || !RTCRtpSender.getCapabilities) return;
var screenshareVideoTransceiver = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, "video"));
if (!screenshareVideoTransceiver || !screenshareVideoTransceiver.setCodecPreferences) return;
var recvCodecs = RTCRtpReceiver.getCapabilities("video").codecs;
var sendCodecs = RTCRtpSender.getCapabilities("video").codecs;
var codecs = [];
for (var codec of [...recvCodecs, ...sendCodecs]) if (codec.mimeType !== "video/rtx") {
codecs.push(codec);
try {
screenshareVideoTransceiver.setCodecPreferences(codecs);
} catch (e) {
logger$2.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences", codec, e);
codecs.pop();
}
}
}
/**
* @internal
*/
sendVoipEvent(eventType, content) {
var _this26 = this;
return (0, import_asyncToGenerator.default)(function* () {
var realContent = _objectSpread$9(_objectSpread$9({}, content), {}, {
version: VOIP_PROTO_VERSION,
call_id: _this26.callId,
party_id: _this26.ourPartyId,
conf_id: _this26.groupCallId
});
if (_this26.opponentDeviceId) {
var _this26$getOpponentMe;
var toDeviceSeq = _this26.toDeviceSeq++;
var _content = _objectSpread$9(_objectSpread$9({}, realContent), {}, {
device_id: _this26.client.deviceId,
sender_session_id: _this26.client.getSessionId(),
dest_session_id: _this26.opponentSessionId,
seq: toDeviceSeq,
[ToDeviceMessageId]: v4()
});
_this26.emit(CallEvent.SendVoipEvent, {
type: "toDevice",
eventType,
userId: _this26.invitee || ((_this26$getOpponentMe = _this26.getOpponentMember()) === null || _this26$getOpponentMe === void 0 ? void 0 : _this26$getOpponentMe.userId),
opponentDeviceId: _this26.opponentDeviceId,
content: _content
}, _this26);
var userId = _this26.invitee || _this26.getOpponentMember().userId;
if (_this26.client.getUseE2eForGroupCall()) {
if (!_this26.hasOpponentDeviceInfo) {
logger$2.warn("Call ".concat(_this26.callId, " sendVoipEvent() failed: we do not have opponentDeviceInfo"));
return;
}
throw new Error("Unimplemented");
} else yield _this26.client.sendToDevice(eventType, new Map([[userId, new Map([[_this26.opponentDeviceId, _content]])]]));
} else {
var _this26$getOpponentMe2;
_this26.emit(CallEvent.SendVoipEvent, {
type: "sendEvent",
eventType,
roomId: _this26.roomId,
content: realContent,
userId: _this26.invitee || ((_this26$getOpponentMe2 = _this26.getOpponentMember()) === null || _this26$getOpponentMe2 === void 0 ? void 0 : _this26$getOpponentMe2.userId)
}, _this26);
yield _this26.client.sendEvent(_this26.roomId, eventType, realContent);
}
})();
}
/**
* Queue a candidate to be sent
* @param content - The candidate to queue up, or null if candidates have finished being generated
* and end-of-candidates should be signalled
*/
queueCandidate(content) {
if (content) this.candidateSendQueue.push(content);
else this.candidatesEnded = true;
if (this.state === CallState.Ringing || !this.inviteOrAnswerSent) return;
var delay = this.direction === CallDirection.Inbound ? 500 : 2e3;
if (this.candidateSendTries === 0) setTimeout(() => {
this.sendCandidateQueue();
}, delay);
}
discardDuplicateCandidates() {
var discardCount = 0;
var newQueue = [];
for (var i = 0; i < this.candidateSendQueue.length; i++) {
var candidate = this.candidateSendQueue[i];
if (candidate.candidate === "") newQueue.push(candidate);
else discardCount++;
}
this.candidateSendQueue = newQueue;
return discardCount;
}
transfer(targetUserId) {
var _this27 = this;
return (0, import_asyncToGenerator.default)(function* () {
var profileInfo = yield _this27.client.getProfileInfo(targetUserId);
var replacementId = genCallID();
var body = {
replacement_id: genCallID(),
target_user: {
id: targetUserId,
display_name: profileInfo.displayname,
avatar_url: profileInfo.avatar_url
},
create_call: replacementId
};
yield _this27.sendVoipEvent(EventType.CallReplaces, body);
yield _this27.terminate(CallParty.Local, CallErrorCode.Transferred, true);
})();
}
transferToCall(transferTargetCall) {
var _this28 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _transferTargetCall$g, _this28$getOpponentMe;
var targetUserId = (_transferTargetCall$g = transferTargetCall.getOpponentMember()) === null || _transferTargetCall$g === void 0 ? void 0 : _transferTargetCall$g.userId;
var targetProfileInfo = targetUserId ? yield _this28.client.getProfileInfo(targetUserId) : void 0;
var opponentUserId = (_this28$getOpponentMe = _this28.getOpponentMember()) === null || _this28$getOpponentMe === void 0 ? void 0 : _this28$getOpponentMe.userId;
var transfereeProfileInfo = opponentUserId ? yield _this28.client.getProfileInfo(opponentUserId) : void 0;
var newCallId = genCallID();
var bodyToTransferTarget = {
replacement_id: genCallID(),
target_user: {
id: opponentUserId,
display_name: transfereeProfileInfo === null || transfereeProfileInfo === void 0 ? void 0 : transfereeProfileInfo.displayname,
avatar_url: transfereeProfileInfo === null || transfereeProfileInfo === void 0 ? void 0 : transfereeProfileInfo.avatar_url
},
await_call: newCallId
};
yield transferTargetCall.sendVoipEvent(EventType.CallReplaces, bodyToTransferTarget);
var bodyToTransferee = {
replacement_id: genCallID(),
target_user: {
id: targetUserId,
display_name: targetProfileInfo === null || targetProfileInfo === void 0 ? void 0 : targetProfileInfo.displayname,
avatar_url: targetProfileInfo === null || targetProfileInfo === void 0 ? void 0 : targetProfileInfo.avatar_url
},
create_call: newCallId
};
yield _this28.sendVoipEvent(EventType.CallReplaces, bodyToTransferee);
yield _this28.terminate(CallParty.Local, CallErrorCode.Transferred, true);
yield transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transferred, true);
})();
}
terminate(hangupParty, hangupReason, shouldEmit) {
var _this29 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this29$stats;
if (_this29.callHasEnded()) return;
_this29.hangupParty = hangupParty;
_this29.hangupReason = hangupReason;
_this29.state = CallState.Ended;
if (_this29.inviteTimeout) {
clearTimeout(_this29.inviteTimeout);
_this29.inviteTimeout = void 0;
}
if (_this29.iceDisconnectedTimeout !== void 0) {
clearTimeout(_this29.iceDisconnectedTimeout);
_this29.iceDisconnectedTimeout = void 0;
}
if (_this29.callLengthInterval) {
clearInterval(_this29.callLengthInterval);
_this29.callLengthInterval = void 0;
}
if (_this29.stopVideoTrackTimer !== void 0) {
clearTimeout(_this29.stopVideoTrackTimer);
_this29.stopVideoTrackTimer = void 0;
}
for (var [stream, listener] of _this29.removeTrackListeners) stream.removeEventListener("removetrack", listener);
_this29.removeTrackListeners.clear();
_this29.callStatsAtEnd = yield _this29.collectCallStats();
_this29.stopAllMedia();
_this29.deleteAllFeeds();
if (_this29.peerConn && _this29.peerConn.signalingState !== "closed") _this29.peerConn.close();
(_this29$stats = _this29.stats) === null || _this29$stats === void 0 || _this29$stats.removeStatsReportGatherer(_this29.callId);
if (shouldEmit) _this29.emit(CallEvent.Hangup, _this29);
_this29.client.callEventHandler.calls.delete(_this29.callId);
})();
}
stopAllMedia() {
logger$2.debug("Call ".concat(this.callId, " stopAllMedia() running"));
for (var feed of this.feeds) if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Usermedia) this.client.getMediaHandler().stopUserMediaStream(feed.stream);
else if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Screenshare) this.client.getMediaHandler().stopScreensharingStream(feed.stream);
else if (!feed.isLocal()) {
logger$2.debug("Call ".concat(this.callId, " stopAllMedia() stopping stream (streamId=").concat(feed.stream.id, ")"));
for (var track of feed.stream.getTracks()) track.stop();
}
}
checkForErrorListener() {
if (this.listeners(EventEmitterEvents.Error).length === 0) throw new Error("You MUST attach an error listener using call.on('error', function() {})");
}
sendCandidateQueue() {
var _this30 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this30.candidateSendQueue.length === 0 || _this30.callHasEnded()) return;
var candidates = _this30.candidateSendQueue;
_this30.candidateSendQueue = [];
++_this30.candidateSendTries;
var content = { candidates: candidates.map((candidate) => candidate.toJSON()) };
if (_this30.candidatesEnded) content.candidates.push({ candidate: "" });
logger$2.debug("Call ".concat(_this30.callId, " sendCandidateQueue() attempting to send ").concat(candidates.length, " candidates"));
try {
yield _this30.sendVoipEvent(EventType.CallCandidates, content);
_this30.candidateSendTries = 0;
_this30.sendCandidateQueue();
} catch (error) {
if (error instanceof MatrixError && error.event) _this30.client.cancelPendingEvent(error.event);
_this30.candidateSendQueue.push(...candidates);
if (_this30.candidateSendTries > 5) {
logger$2.debug("Call ".concat(_this30.callId, " sendCandidateQueue() failed to send candidates on attempt ").concat(_this30.candidateSendTries, ". Giving up on this call."), error);
var code = CallErrorCode.SignallingFailed;
_this30.emit(CallEvent.Error, new CallError(code, "Signalling failed", error), _this30);
_this30.hangup(code, false);
return;
}
var delayMs = 500 * Math.pow(2, _this30.candidateSendTries);
++_this30.candidateSendTries;
logger$2.debug("Call ".concat(_this30.callId, " sendCandidateQueue() failed to send candidates. Retrying in ").concat(delayMs, "ms"), error);
setTimeout(() => {
_this30.sendCandidateQueue();
}, delayMs);
}
})();
}
/**
* Place a call to this room.
* @throws if you have not specified a listener for 'error' events.
* @throws if have passed audio=false.
*/
placeCall(audio, video) {
var _this31 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!audio) throw new Error("You CANNOT start a call without audio");
_this31.state = CallState.WaitLocalMedia;
var callFeed;
try {
var _this31$client$getDev;
var stream = yield _this31.client.getMediaHandler().getUserMediaStream(audio, video);
setTracksEnabled(stream.getAudioTracks(), true);
setTracksEnabled(stream.getVideoTracks(), true);
callFeed = new CallFeed({
client: _this31.client,
roomId: _this31.roomId,
userId: _this31.client.getUserId(),
deviceId: (_this31$client$getDev = _this31.client.getDeviceId()) !== null && _this31$client$getDev !== void 0 ? _this31$client$getDev : void 0,
stream,
purpose: SDPStreamMetadataPurpose.Usermedia,
audioMuted: false,
videoMuted: false
});
} catch (e) {
_this31.getUserMediaFailed(e);
return;
}
try {
yield _this31.placeCallWithCallFeeds([callFeed]);
} catch (e) {
_this31.placeCallFailed(e);
return;
}
})();
}
/**
* Place a call to this room with call feed.
* @param callFeeds - to use
* @throws if you have not specified a listener for 'error' events.
* @throws if have passed audio=false.
*/
placeCallWithCallFeeds(callFeeds) {
var _arguments2 = arguments, _this32 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestScreenshareFeed = _arguments2.length > 1 && _arguments2[1] !== void 0 ? _arguments2[1] : false;
_this32.checkForErrorListener();
_this32.direction = CallDirection.Outbound;
yield _this32.initOpponentCrypto();
_this32.client.callEventHandler.calls.set(_this32.callId, _this32);
if (!(yield _this32.client.checkTurnServers())) logger$2.warn("Call ".concat(_this32.callId, " placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway..."));
_this32.peerConn = _this32.createPeerConnection();
_this32.emit(CallEvent.PeerConnectionCreated, _this32.peerConn, _this32);
_this32.gotCallFeedsForInvite(callFeeds, requestScreenshareFeed);
})();
}
createPeerConnection() {
var _this$stats;
var pc = new window.RTCPeerConnection({
iceTransportPolicy: this.forceTURN ? "relay" : void 0,
iceServers: this.turnServers.length ? this.turnServers : void 0,
iceCandidatePoolSize: this.client.iceCandidatePoolSize,
bundlePolicy: "max-bundle"
});
pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChanged);
pc.addEventListener("signalingstatechange", this.onSignallingStateChanged);
pc.addEventListener("icecandidate", this.gotLocalIceCandidate);
pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
pc.addEventListener("track", this.onTrack);
pc.addEventListener("negotiationneeded", this.onNegotiationNeeded);
pc.addEventListener("datachannel", this.onDataChannel);
var opponentMember = this.getOpponentMember();
var opponentMemberId = opponentMember ? opponentMember.userId : "unknown";
(_this$stats = this.stats) === null || _this$stats === void 0 || _this$stats.addStatsReportGatherer(this.callId, opponentMemberId, pc);
return pc;
}
partyIdMatches(msg) {
return (msg.version === 0 ? null : msg.party_id || null) === this.opponentPartyId;
}
chooseOpponent(ev) {
var _getMember;
var msg = ev.getContent();
logger$2.debug("Call ".concat(this.callId, " chooseOpponent() running (partyId=").concat(msg.party_id, ")"));
this.opponentVersion = msg.version;
if (this.opponentVersion === 0) this.opponentPartyId = null;
else this.opponentPartyId = msg.party_id || null;
this.opponentCaps = msg.capabilities || {};
this.opponentMember = (_getMember = this.client.getRoom(this.roomId).getMember(ev.getSender())) !== null && _getMember !== void 0 ? _getMember : void 0;
if (this.opponentMember) {
var _this$stats2;
(_this$stats2 = this.stats) === null || _this$stats2 === void 0 || _this$stats2.updateOpponentMember(this.callId, this.opponentMember.userId);
}
}
addBufferedIceCandidates() {
var _this33 = this;
return (0, import_asyncToGenerator.default)(function* () {
var bufferedCandidates = _this33.remoteCandidateBuffer.get(_this33.opponentPartyId);
if (bufferedCandidates) {
logger$2.info("Call ".concat(_this33.callId, " addBufferedIceCandidates() adding ").concat(bufferedCandidates.length, " buffered candidates for opponent ").concat(_this33.opponentPartyId));
yield _this33.addIceCandidates(bufferedCandidates);
}
_this33.remoteCandidateBuffer.clear();
})();
}
addIceCandidates(candidates) {
var _this34 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var candidate of candidates) {
if ((candidate.sdpMid === null || candidate.sdpMid === void 0) && (candidate.sdpMLineIndex === null || candidate.sdpMLineIndex === void 0)) logger$2.debug("Call ".concat(_this34.callId, " addIceCandidates() got remote ICE end-of-candidates"));
else logger$2.debug("Call ".concat(_this34.callId, " addIceCandidates() got remote ICE candidate (sdpMid=").concat(candidate.sdpMid, ", candidate=").concat(candidate.candidate, ")"));
try {
yield _this34.peerConn.addIceCandidate(candidate);
} catch (err) {
if (!_this34.ignoreOffer) logger$2.info("Call ".concat(_this34.callId, " addIceCandidates() failed to add remote ICE candidate"), err);
else logger$2.debug("Call ".concat(_this34.callId, " addIceCandidates() failed to add remote ICE candidate because ignoring offer"), err);
}
}
})();
}
get hasPeerConnection() {
return Boolean(this.peerConn);
}
initStats(stats) {
arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
this.stats = stats;
this.stats.start();
}
};
function setTracksEnabled(tracks, enabled) {
for (var track of tracks) track.enabled = enabled;
}
function supportsMatrixCall() {
if (typeof window === "undefined" || typeof document === "undefined") return false;
try {
var _ref2, _ref3, _window$RTCPeerConnec;
if (!Boolean((_ref2 = (_ref3 = (_window$RTCPeerConnec = window.RTCPeerConnection) !== null && _window$RTCPeerConnec !== void 0 ? _window$RTCPeerConnec : window.RTCSessionDescription) !== null && _ref3 !== void 0 ? _ref3 : window.RTCIceCandidate) !== null && _ref2 !== void 0 ? _ref2 : navigator.mediaDevices)) {
logger$2.error("WebRTC is not supported in this browser / environment");
return false;
}
} catch (e) {
logger$2.error("Exception thrown when trying to access WebRTC", e);
return false;
}
return true;
}
/**
* DEPRECATED
* Use client.createCall()
*
* Create a new Matrix call for the browser.
* @param client - The client instance to use.
* @param roomId - The room the call is in.
* @param options - DEPRECATED optional options map.
* @returns the call or null if the browser doesn't support calling.
*/
function createNewMatrixCall(client, roomId, options) {
if (!supportsMatrixCall()) return null;
var optionsForceTURN = options ? options.forceTURN : false;
var call = new MatrixCall({
client,
roomId,
invitee: options === null || options === void 0 ? void 0 : options.invitee,
turnServers: client.getTurnServers(),
forceTURN: client.forceTURN || optionsForceTURN,
opponentDeviceId: options === null || options === void 0 ? void 0 : options.opponentDeviceId,
opponentSessionId: options === null || options === void 0 ? void 0 : options.opponentSessionId,
groupCallId: options === null || options === void 0 ? void 0 : options.groupCallId
});
client.reEmitter.reEmit(call, Object.values(CallEvent));
return call;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/PushRules.js
var PushRuleActionName = /* @__PURE__ */ function(PushRuleActionName) {
PushRuleActionName["DontNotify"] = "dont_notify";
PushRuleActionName["Notify"] = "notify";
PushRuleActionName["Coalesce"] = "coalesce";
return PushRuleActionName;
}({});
var TweakName = /* @__PURE__ */ function(TweakName) {
TweakName["Highlight"] = "highlight";
TweakName["Sound"] = "sound";
return TweakName;
}({});
var ConditionKind = /* @__PURE__ */ function(ConditionKind) {
ConditionKind["EventMatch"] = "event_match";
ConditionKind["EventPropertyIs"] = "event_property_is";
ConditionKind["EventPropertyContains"] = "event_property_contains";
ConditionKind["ContainsDisplayName"] = "contains_display_name";
ConditionKind["RoomMemberCount"] = "room_member_count";
ConditionKind["SenderNotificationPermission"] = "sender_notification_permission";
ConditionKind["CallStarted"] = "call_started";
ConditionKind["CallStartedPrefix"] = "org.matrix.msc3914.call_started";
return ConditionKind;
}({});
var PushRuleKind = /* @__PURE__ */ function(PushRuleKind) {
PushRuleKind["Override"] = "override";
PushRuleKind["ContentSpecific"] = "content";
PushRuleKind["RoomSpecific"] = "room";
PushRuleKind["SenderSpecific"] = "sender";
PushRuleKind["Underride"] = "underride";
return PushRuleKind;
}({});
var RuleId = /* @__PURE__ */ function(RuleId) {
RuleId["Master"] = ".m.rule.master";
RuleId["IsUserMention"] = ".m.rule.is_user_mention";
RuleId["IsRoomMention"] = ".m.rule.is_room_mention";
RuleId["ContainsDisplayName"] = ".m.rule.contains_display_name";
RuleId["ContainsUserName"] = ".m.rule.contains_user_name";
RuleId["AtRoomNotification"] = ".m.rule.roomnotif";
RuleId["DM"] = ".m.rule.room_one_to_one";
RuleId["EncryptedDM"] = ".m.rule.encrypted_room_one_to_one";
RuleId["Message"] = ".m.rule.message";
RuleId["EncryptedMessage"] = ".m.rule.encrypted";
RuleId["InviteToSelf"] = ".m.rule.invite_for_me";
RuleId["MemberEvent"] = ".m.rule.member_event";
RuleId["IncomingCall"] = ".m.rule.call";
RuleId["SuppressNotices"] = ".m.rule.suppress_notices";
RuleId["Tombstone"] = ".m.rule.tombstone";
RuleId["PollStart"] = ".m.rule.poll_start";
RuleId["PollStartUnstable"] = ".org.matrix.msc3930.rule.poll_start";
RuleId["PollEnd"] = ".m.rule.poll_end";
RuleId["PollEndUnstable"] = ".org.matrix.msc3930.rule.poll_end";
RuleId["PollStartOneToOne"] = ".m.rule.poll_start_one_to_one";
RuleId["PollStartOneToOneUnstable"] = ".org.matrix.msc3930.rule.poll_start_one_to_one";
RuleId["PollEndOneToOne"] = ".m.rule.poll_end_one_to_one";
RuleId["PollEndOneToOneUnstable"] = ".org.matrix.msc3930.rule.poll_end_one_to_one";
return RuleId;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/pushprocessor.js
function ownKeys$8(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;
}
function _objectSpread$8(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$8(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var RULEKINDS_IN_ORDER = [
PushRuleKind.Override,
PushRuleKind.ContentSpecific,
PushRuleKind.RoomSpecific,
PushRuleKind.SenderSpecific,
PushRuleKind.Underride
];
var DEFAULT_OVERRIDE_RULES = {
".m.rule.is_room_mention": {
rule_id: ".m.rule.is_room_mention",
default: true,
enabled: true,
conditions: [{
kind: ConditionKind.EventPropertyIs,
key: "content.m\\.mentions.room",
value: true
}, {
kind: ConditionKind.SenderNotificationPermission,
key: "room"
}],
actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Highlight }]
},
".m.rule.reaction": {
rule_id: ".m.rule.reaction",
default: true,
enabled: true,
conditions: [{
kind: ConditionKind.EventMatch,
key: "type",
pattern: "m.reaction"
}],
actions: [PushRuleActionName.DontNotify]
},
".org.matrix.msc3786.rule.room.server_acl": {
rule_id: ".org.matrix.msc3786.rule.room.server_acl",
default: true,
enabled: true,
conditions: [{
kind: ConditionKind.EventMatch,
key: "type",
pattern: EventType.RoomServerAcl
}, {
kind: ConditionKind.EventMatch,
key: "state_key",
pattern: ""
}],
actions: []
}
};
var UserDefinedRules = Symbol("UserDefinedRules");
var EXPECTED_DEFAULT_OVERRIDE_RULE_IDS = [
RuleId.Master,
UserDefinedRules,
RuleId.SuppressNotices,
RuleId.InviteToSelf,
RuleId.MemberEvent,
RuleId.IsUserMention,
RuleId.ContainsDisplayName,
RuleId.IsRoomMention,
RuleId.AtRoomNotification,
RuleId.Tombstone,
".m.rule.reaction",
".m.rule.room.server_acl",
".org.matrix.msc3786.rule.room.server_acl",
".m.rule.suppress_edits"
];
var DEFAULT_UNDERRIDE_RULES = { ".org.matrix.msc3914.rule.room.call": {
rule_id: ".org.matrix.msc3914.rule.room.call",
default: true,
enabled: true,
conditions: [{
kind: ConditionKind.EventMatch,
key: "type",
pattern: "org.matrix.msc3401.call"
}, { kind: ConditionKind.CallStarted }],
actions: [PushRuleActionName.Notify, {
set_tweak: TweakName.Sound,
value: "default"
}]
} };
var EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS = [
UserDefinedRules,
RuleId.IncomingCall,
".org.matrix.msc3914.rule.room.call",
RuleId.EncryptedDM,
RuleId.DM,
RuleId.Message,
RuleId.EncryptedMessage
];
/**
* Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.
*
* @param logger - A `Logger` to write log messages to.
* @param kind - the kind of push rule set being merged.
* @param incomingRules - the existing set of known push rules for the user.
* @param defaultRules - a lookup table for the default definitions of push rules.
* @param orderedRuleIds - the IDs of the expected push rules, in order.
*
* @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.
*/
function mergeRulesWithDefaults(logger, kind, incomingRules, defaultRules, orderedRuleIds) {
var incomingDefaultRules = incomingRules.filter((rule) => rule.default);
var incomingCustomRules = incomingRules.filter((rule) => !rule.default);
function insertDefaultPushRule(ruleId) {
if (ruleId === UserDefinedRules) newRules.push(...incomingCustomRules);
else if (ruleId in defaultRules) {
logger.warn("Adding default global ".concat(kind, " push rule ").concat(ruleId));
newRules.push(defaultRules[ruleId]);
} else logger.warn("Missing default global ".concat(kind, " push rule ").concat(ruleId));
}
var nextExpectedRuleIdIndex = 0;
var newRules = [];
for (var rule of incomingDefaultRules) {
var ruleIndex = orderedRuleIds.indexOf(rule.rule_id);
if (ruleIndex === -1) {
newRules.push(rule);
continue;
}
while (ruleIndex > nextExpectedRuleIdIndex) {
var defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];
insertDefaultPushRule(defaultRuleId);
nextExpectedRuleIdIndex += 1;
}
newRules.push(rule);
nextExpectedRuleIdIndex += 1;
}
for (var ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) insertDefaultPushRule(ruleId);
return newRules;
}
var PushProcessor = class PushProcessor {
/**
* Construct a Push Processor.
* @param client - The Matrix client object to use
*/
constructor(client) {
this.client = client;
/**
* Maps the original key from the push rules to a list of property names
* after unescaping.
*/
(0, import_defineProperty.default)(this, "parsedKeys", /* @__PURE__ */ new Map());
}
/**
* Convert a list of actions into a object with the actions as keys and their values
* @example
* eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`
* becomes `{ notify: true, tweaks: { sound: 'default' } }`
* @param actionList - The actions list
*
* @returns A object with key 'notify' (true or false) and an object of actions
*/
static actionListToActionsObject(actionList) {
var actionObj = {
notify: false,
tweaks: {}
};
for (var action of actionList) if (action === PushRuleActionName.Notify) actionObj.notify = true;
else if (typeof action === "object") {
if (action.value === void 0) action.value = true;
actionObj.tweaks[action.set_tweak] = action.value;
}
return actionObj;
}
/**
* Rewrites conditions on a client's push rules to match the defaults
* where applicable. Useful for upgrading push rules to more strict
* conditions when the server is falling behind on defaults.
*
* @param logger - A `Logger` to write log messages to.
* @param incomingRules - The client's existing push rules
* @param userId - The Matrix ID of the client.
* @returns The rewritten rules
*/
static rewriteDefaultRules(logger, incomingRules) {
arguments.length > 2 && arguments[2] !== void 0 && arguments[2];
var newRules = JSON.parse(JSON.stringify(incomingRules));
if (!newRules) newRules = {};
if (!newRules.global) newRules.global = {};
if (!newRules.global.override) newRules.global.override = [];
if (!newRules.global.underride) newRules.global.underride = [];
newRules.global.override = mergeRulesWithDefaults(logger, PushRuleKind.Override, newRules.global.override, DEFAULT_OVERRIDE_RULES, EXPECTED_DEFAULT_OVERRIDE_RULE_IDS);
newRules.global.underride = mergeRulesWithDefaults(logger, PushRuleKind.Underride, newRules.global.underride, DEFAULT_UNDERRIDE_RULES, EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS);
return newRules;
}
/**
* Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.
* No cache invalidation is present currently,
* as this will be inherently bounded to the size of the user's own push rules.
* @param pattern - the glob pattern to convert to a RegExp
* @param alignToWordBoundary - whether to align the pattern to word boundaries,
* as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern
* @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive
*/
static getPushRuleGlobRegex(pattern) {
var alignToWordBoundary = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var flags = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "i";
var [prefix, suffix] = alignToWordBoundary ? ["(?<=^|\\W)", "(?=\\W|$)"] : ["^", "$"];
var cacheKey = "".concat(alignToWordBoundary, "-").concat(flags, "-").concat(pattern);
if (!PushProcessor.cachedGlobToRegex[cacheKey]) PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(prefix + "(" + globToRegexp(pattern) + ")" + suffix, flags);
return PushProcessor.cachedGlobToRegex[cacheKey];
}
/**
* Pre-caches the parsed keys for push rules and cleans out any obsolete cache
* entries. Should be called after push rules are updated.
* @param newRules - The new push rules.
*/
updateCachedPushRuleKeys(newRules) {
if (!newRules) newRules = {};
if (!newRules.global) newRules.global = {};
if (!newRules.global.override) newRules.global.override = [];
if (!newRules.global.room) newRules.global.room = [];
if (!newRules.global.sender) newRules.global.sender = [];
if (!newRules.global.underride) newRules.global.underride = [];
var toRemoveKeys = new Set(this.parsedKeys.keys());
for (var ruleset of [
newRules.global.override,
newRules.global.room,
newRules.global.sender,
newRules.global.underride
]) for (var rule of ruleset) {
if (!rule.conditions) continue;
for (var condition of rule.conditions) {
if (condition.kind !== ConditionKind.EventMatch) continue;
toRemoveKeys.delete(condition.key);
this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));
}
}
toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));
}
matchingRuleFromKindSet(ev, kindset) {
for (var kind of RULEKINDS_IN_ORDER) {
var ruleset = kindset[kind];
if (!ruleset) continue;
for (var rule of ruleset) {
if (!rule.enabled) continue;
var rawrule = this.templateRuleToRaw(kind, rule);
if (!rawrule) continue;
if (this.ruleMatchesEvent(rawrule, ev)) return _objectSpread$8(_objectSpread$8({}, rule), {}, { kind });
}
}
return null;
}
templateRuleToRaw(kind, tprule) {
var rawrule = {
rule_id: tprule.rule_id,
actions: tprule.actions,
conditions: []
};
switch (kind) {
case PushRuleKind.Underride:
case PushRuleKind.Override:
rawrule.conditions = tprule.conditions;
break;
case PushRuleKind.RoomSpecific:
if (!tprule.rule_id) return null;
rawrule.conditions.push({
kind: ConditionKind.EventMatch,
key: "room_id",
value: tprule.rule_id
});
break;
case PushRuleKind.SenderSpecific:
if (!tprule.rule_id) return null;
rawrule.conditions.push({
kind: ConditionKind.EventMatch,
key: "user_id",
value: tprule.rule_id
});
break;
case PushRuleKind.ContentSpecific:
if (!tprule.pattern) return null;
rawrule.conditions.push({
kind: ConditionKind.EventMatch,
key: "content.body",
pattern: tprule.pattern
});
break;
}
return rawrule;
}
eventFulfillsCondition(cond, ev) {
switch (cond.kind) {
case ConditionKind.EventMatch: return this.eventFulfillsEventMatchCondition(cond, ev);
case ConditionKind.EventPropertyIs: return this.eventFulfillsEventPropertyIsCondition(cond, ev);
case ConditionKind.EventPropertyContains: return this.eventFulfillsEventPropertyContains(cond, ev);
case ConditionKind.ContainsDisplayName: return this.eventFulfillsDisplayNameCondition(cond, ev);
case ConditionKind.RoomMemberCount: return this.eventFulfillsRoomMemberCountCondition(cond, ev);
case ConditionKind.SenderNotificationPermission: return this.eventFulfillsSenderNotifPermCondition(cond, ev);
case ConditionKind.CallStarted:
case ConditionKind.CallStartedPrefix: return this.eventFulfillsCallStartedCondition(cond, ev);
}
return false;
}
eventFulfillsSenderNotifPermCondition(cond, ev) {
var notifLevelKey = cond["key"];
if (!notifLevelKey) return false;
var room = this.client.getRoom(ev.getRoomId());
if (!(room !== null && room !== void 0 && room.currentState)) return false;
return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender());
}
eventFulfillsRoomMemberCountCondition(cond, ev) {
if (!cond.is) return false;
var room = this.client.getRoom(ev.getRoomId());
if (!room || !room.currentState || !room.currentState.members) return false;
var memberCount = room.currentState.getJoinedMemberCount();
var m = cond.is.match(/^([=<>]*)(\d*)$/);
if (!m) return false;
var ineq = m[1];
var rhs = parseInt(m[2]);
if (isNaN(rhs)) return false;
switch (ineq) {
case "":
case "==": return memberCount == rhs;
case "<": return memberCount < rhs;
case ">": return memberCount > rhs;
case "<=": return memberCount <= rhs;
case ">=": return memberCount >= rhs;
default: return false;
}
}
eventFulfillsDisplayNameCondition(cond, ev) {
var _room$currentState;
var content = ev.getContent();
if (ev.isEncrypted() && ev.getClearContent()) content = ev.getClearContent();
if (!content || !content.body || typeof content.body != "string") return false;
var room = this.client.getRoom(ev.getRoomId());
var member = room === null || room === void 0 || (_room$currentState = room.currentState) === null || _room$currentState === void 0 ? void 0 : _room$currentState.getMember(this.client.credentials.userId);
if (!member) return false;
var displayName = member.name;
var pat = new RegExp("(^|\\W)" + escapeRegExp(displayName) + "(\\W|$)", "i");
return content.body.search(pat) > -1;
}
/**
* Check whether the given event matches the push rule condition by fetching
* the property from the event and comparing against the condition's glob-based
* pattern.
* @param cond - The push rule condition to check for a match.
* @param ev - The event to check for a match.
*/
eventFulfillsEventMatchCondition(cond, ev) {
if (!cond.key) return false;
var val = this.valueForDottedKey(cond.key, ev);
if (typeof val !== "string") return false;
if (cond.value) return cond.value === val;
if (typeof cond.pattern !== "string") return false;
var regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === "content.body");
return !!val.match(regex);
}
/**
* Check whether the given event matches the push rule condition by fetching
* the property from the event and comparing exactly against the condition's
* value.
* @param cond - The push rule condition to check for a match.
* @param ev - The event to check for a match.
*/
eventFulfillsEventPropertyIsCondition(cond, ev) {
if (!cond.key || cond.value === void 0) return false;
return cond.value === this.valueForDottedKey(cond.key, ev);
}
/**
* Check whether the given event matches the push rule condition by fetching
* the property from the event and comparing exactly against the condition's
* value.
* @param cond - The push rule condition to check for a match.
* @param ev - The event to check for a match.
*/
eventFulfillsEventPropertyContains(cond, ev) {
if (!cond.key || cond.value === void 0) return false;
var val = this.valueForDottedKey(cond.key, ev);
if (!Array.isArray(val)) return false;
return val.includes(cond.value);
}
eventFulfillsCallStartedCondition(_cond, ev) {
return ["m.ring", "m.prompt"].includes(ev.getContent()["m.intent"]) && !("m.terminated" in ev.getContent()) && (ev.getPrevContent()["m.terminated"] !== ev.getContent()["m.terminated"] || deepCompare(ev.getPrevContent(), {}));
}
/**
* Parse the key into the separate fields to search by splitting on
* unescaped ".", and then removing any escape characters.
*
* @param str - The key of the push rule condition: a dotted field.
* @returns The unescaped parts to fetch.
* @internal
*/
static partsForDottedKey(str) {
var result = [];
var part = "";
var escaped = false;
for (var c of str) {
if (escaped) {
if (c === "\\" || c === ".") part += c;
else part += "\\" + c;
escaped = false;
continue;
}
if (c == ".") {
result.push(part);
part = "";
} else if (c == "\\") escaped = true;
else part += c;
}
if (escaped) part += "\\";
result.push(part);
return result;
}
/**
* For a dotted field and event, fetch the value at that position, if one
* exists.
*
* @param key - The key of the push rule condition: a dotted field to fetch.
* @param ev - The matrix event to fetch the field from.
* @returns The value at the dotted path given by key.
*/
valueForDottedKey(key, ev) {
var parts = this.parsedKeys.get(key);
if (parts === void 0) {
parts = PushProcessor.partsForDottedKey(key);
this.parsedKeys.set(key, parts);
}
var val;
var firstPart = parts[0];
var currentIndex = 0;
if (firstPart === "content") {
val = ev.getContent();
++currentIndex;
} else if (firstPart === "type") {
val = ev.getType();
++currentIndex;
} else val = ev.event;
for (; currentIndex < parts.length; ++currentIndex) {
if (isNullOrUndefined(val)) return;
var thisPart = parts[currentIndex];
val = val[thisPart];
}
return val;
}
matchingRuleForEventWithRulesets(ev, rulesets) {
if (!rulesets) return null;
if (ev.getSender() === this.client.getSafeUserId()) return null;
return this.matchingRuleFromKindSet(ev, rulesets.global);
}
pushActionsForEventAndRulesets(ev, rulesets) {
var rule = this.matchingRuleForEventWithRulesets(ev, rulesets);
if (!rule) return {};
var actionObj = PushProcessor.actionListToActionsObject(rule.actions);
if (actionObj.tweaks.highlight === void 0) actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;
return {
actions: actionObj,
rule
};
}
ruleMatchesEvent(rule, ev) {
var _rule$conditions;
if (this.client.supportsIntentionalMentions() && ev.getContent()["m.mentions"] !== void 0 && (rule.rule_id === RuleId.ContainsUserName || rule.rule_id === RuleId.ContainsDisplayName || rule.rule_id === RuleId.AtRoomNotification)) return false;
return !((_rule$conditions = rule.conditions) !== null && _rule$conditions !== void 0 && _rule$conditions.some((cond) => !this.eventFulfillsCondition(cond, ev)));
}
/**
* Get the user's push actions for the given event
*/
actionsForEvent(ev) {
var { actions } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);
return actions || {};
}
actionsAndRuleForEvent(ev) {
return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);
}
/**
* Get one of the users push rules by its ID
*
* @param ruleId - The ID of the rule to search for
* @returns The push rule, or null if no such rule was found
*/
getPushRuleById(ruleId) {
var _result$rule;
var result = this.getPushRuleAndKindById(ruleId);
return (_result$rule = result === null || result === void 0 ? void 0 : result.rule) !== null && _result$rule !== void 0 ? _result$rule : null;
}
/**
* Get one of the users push rules by its ID
*
* @param ruleId - The ID of the rule to search for
* @returns rule The push rule, or null if no such rule was found
* @returns kind - The PushRuleKind of the rule to search for
*/
getPushRuleAndKindById(ruleId) {
for (var scope of ["global"]) {
var _this$client$pushRule;
if (((_this$client$pushRule = this.client.pushRules) === null || _this$client$pushRule === void 0 ? void 0 : _this$client$pushRule[scope]) === void 0) continue;
for (var kind of RULEKINDS_IN_ORDER) {
if (this.client.pushRules[scope][kind] === void 0) continue;
for (var rule of this.client.pushRules[scope][kind]) if (rule.rule_id === ruleId) return {
rule,
kind
};
}
}
return null;
}
};
(0, import_defineProperty.default)(PushProcessor, "cachedGlobToRegex", {});
//#endregion
//#region node_modules/matrix-js-sdk/lib/version-support.js
/**
* A list of the spec versions which the js-sdk is compatible with.
*
* In practice, this means: when we connect to a server, it must declare support for one of the versions in this list.
*
* Note that it does not *necessarily* mean that the js-sdk has good support for all the features in the listed spec
* versions; only that we should be able to provide a base level of functionality with a server that offers support for
* any of the listed versions.
*/
var SUPPORTED_MATRIX_VERSIONS = [
"v1.1",
"v1.2",
"v1.3",
"v1.4",
"v1.5",
"v1.6",
"v1.7",
"v1.8",
"v1.9",
"v1.10",
"v1.11",
"v1.12",
"v1.13"
];
SUPPORTED_MATRIX_VERSIONS[0];
SUPPORTED_MATRIX_VERSIONS[SUPPORTED_MATRIX_VERSIONS.length - 1];
//#endregion
//#region node_modules/matrix-js-sdk/lib/autodiscovery.js
var AutoDiscoveryAction = /* @__PURE__ */ function(AutoDiscoveryAction) {
AutoDiscoveryAction["SUCCESS"] = "SUCCESS";
AutoDiscoveryAction["IGNORE"] = "IGNORE";
AutoDiscoveryAction["PROMPT"] = "PROMPT";
AutoDiscoveryAction["FAIL_PROMPT"] = "FAIL_PROMPT";
AutoDiscoveryAction["FAIL_ERROR"] = "FAIL_ERROR";
return AutoDiscoveryAction;
}({});
var AutoDiscoveryError = /* @__PURE__ */ function(AutoDiscoveryError) {
AutoDiscoveryError["Invalid"] = "Invalid homeserver discovery response";
AutoDiscoveryError["GenericFailure"] = "Failed to get autodiscovery configuration from server";
AutoDiscoveryError["InvalidHsBaseUrl"] = "Invalid base_url for m.homeserver";
AutoDiscoveryError["InvalidHomeserver"] = "Homeserver URL does not appear to be a valid Matrix homeserver";
AutoDiscoveryError["InvalidIsBaseUrl"] = "Invalid base_url for m.identity_server";
AutoDiscoveryError["InvalidIdentityServer"] = "Identity server URL does not appear to be a valid identity server";
AutoDiscoveryError["InvalidIs"] = "Invalid identity server discovery response";
AutoDiscoveryError["MissingWellknown"] = "No .well-known JSON file found";
AutoDiscoveryError["InvalidJson"] = "Invalid JSON";
AutoDiscoveryError["UnsupportedHomeserverSpecVersion"] = "The homeserver does not meet the version requirements";
return AutoDiscoveryError;
}({});
/**
* Utilities for automatically discovery resources, such as homeservers
* for users to log in to.
*/
var AutoDiscovery = class AutoDiscovery {
/**
* Validates and verifies client configuration information for purposes
* of logging in. Such information includes the homeserver URL
* and identity server URL the client would want. Additional details
* may also be included, and will be transparently brought into the
* response object unaltered.
* @param wellknown - The configuration object itself, as returned
* by the .well-known auto-discovery endpoint.
* @returns Promise which resolves to the verified
* configuration, which may include error states. Rejects on unexpected
* failure, not when verification fails.
*/
static fromDiscoveryConfig(wellknown) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var _hsVersions$raw;
var clientConfig = {
"m.homeserver": {
state: AutoDiscovery.FAIL_ERROR,
error: AutoDiscovery.ERROR_INVALID,
base_url: null
},
"m.identity_server": {
state: AutoDiscovery.PROMPT,
error: null,
base_url: null
}
};
if (!(wellknown !== null && wellknown !== void 0 && wellknown["m.homeserver"])) {
logger$2.error("No m.homeserver key in config");
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID;
return Promise.resolve(clientConfig);
}
if (!wellknown["m.homeserver"]["base_url"]) {
logger$2.error("No m.homeserver base_url in config");
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
return Promise.resolve(clientConfig);
}
var hsUrl = _this.sanitizeWellKnownUrl(wellknown["m.homeserver"]["base_url"]);
if (!hsUrl) {
logger$2.error("Invalid base_url for m.homeserver");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
return Promise.resolve(clientConfig);
}
var hsVersions = yield _this.fetchWellKnownObject("".concat(hsUrl, "/_matrix/client/versions"));
if (!hsVersions || !Array.isArray((_hsVersions$raw = hsVersions.raw) === null || _hsVersions$raw === void 0 ? void 0 : _hsVersions$raw["versions"])) {
logger$2.error("Invalid /versions response");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;
clientConfig["m.homeserver"].base_url = hsUrl;
return Promise.resolve(clientConfig);
}
var hsVersionSet = new Set(hsVersions.raw["versions"]);
var supportedVersionFound = false;
for (var version of SUPPORTED_MATRIX_VERSIONS) if (hsVersionSet.has(version)) {
supportedVersionFound = true;
break;
}
if (!supportedVersionFound) {
logger$2.error("Homeserver does not meet version requirements");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;
clientConfig["m.homeserver"].base_url = hsUrl;
return Promise.resolve(clientConfig);
}
clientConfig["m.homeserver"] = {
state: AutoDiscovery.SUCCESS,
error: null,
base_url: hsUrl
};
var isUrl = "";
if (wellknown["m.identity_server"]) {
var failingClientConfig = {
"m.homeserver": clientConfig["m.homeserver"],
"m.identity_server": {
state: AutoDiscovery.FAIL_PROMPT,
error: AutoDiscovery.ERROR_INVALID_IS,
base_url: null
}
};
isUrl = _this.sanitizeWellKnownUrl(wellknown["m.identity_server"]["base_url"]);
if (!isUrl) {
logger$2.error("Invalid base_url for m.identity_server");
failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;
return Promise.resolve(failingClientConfig);
}
var isResponse = yield _this.fetchWellKnownObject("".concat(isUrl, "/_matrix/identity/v2"));
if (!(isResponse !== null && isResponse !== void 0 && isResponse.raw) || isResponse.action !== AutoDiscoveryAction.SUCCESS) {
logger$2.error("Invalid /v2 response");
failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;
failingClientConfig["m.identity_server"].base_url = isUrl;
return Promise.resolve(failingClientConfig);
}
}
if (isUrl && isUrl.toString().length > 0) clientConfig["m.identity_server"] = {
state: AutoDiscovery.SUCCESS,
error: null,
base_url: isUrl
};
Object.keys(wellknown).forEach((k) => {
if (k === "m.homeserver" || k === "m.identity_server") {
var notProps = [
"error",
"state",
"base_url"
];
for (var prop of Object.keys(wellknown[k])) {
if (notProps.includes(prop)) continue;
clientConfig[k][prop] = wellknown[k][prop];
}
} else clientConfig[k] = wellknown[k];
});
return Promise.resolve(clientConfig);
})();
}
/**
* Attempts to automatically discover client configuration information
* prior to logging in. Such information includes the homeserver URL
* and identity server URL the client would want. Additional details
* may also be discovered, and will be transparently included in the
* response object unaltered.
* @param domain - The homeserver domain to perform discovery
* on. For example, "matrix.org".
* @returns Promise which resolves to the discovered
* configuration, which may include error states. Rejects on unexpected
* failure, not when discovery fails.
*/
static findClientConfig(domain) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!domain || typeof domain !== "string" || domain.length === 0) throw new Error("'domain' must be a string of non-zero length");
var clientConfig = {
"m.homeserver": {
state: AutoDiscovery.FAIL_ERROR,
error: AutoDiscovery.ERROR_INVALID,
base_url: null
},
"m.identity_server": {
state: AutoDiscovery.PROMPT,
error: null,
base_url: null
}
};
var domainWithProtocol = domain.includes("://") ? domain : "https://".concat(domain);
var wellknown = yield _this2.fetchWellKnownObject("".concat(domainWithProtocol, "/.well-known/matrix/client"));
if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {
logger$2.error("No response or error when parsing .well-known");
if (wellknown.reason) logger$2.error(wellknown.reason);
if (wellknown.action === AutoDiscoveryAction.IGNORE) clientConfig["m.homeserver"] = {
state: AutoDiscovery.PROMPT,
error: null,
base_url: null
};
else {
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID;
}
return Promise.resolve(clientConfig);
}
return AutoDiscovery.fromDiscoveryConfig(wellknown.raw);
})();
}
/**
* Gets the raw discovery client configuration for the given domain name.
* Should only be used if there's no validation to be done on the resulting
* object, otherwise use findClientConfig().
* @param domain - The domain to get the client config for.
* @returns Promise which resolves to the domain's client config. Can
* be an empty object.
*/
static getRawClientConfig(domain) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _response$raw;
if (!domain || typeof domain !== "string" || domain.length === 0) throw new Error("'domain' must be a string of non-zero length");
var response = yield _this3.fetchWellKnownObject("https://".concat(domain, "/.well-known/matrix/client"));
if (!response) return {};
return (_response$raw = response.raw) !== null && _response$raw !== void 0 ? _response$raw : {};
})();
}
/**
* Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and
* is suitable for the requirements laid out by .well-known auto discovery.
* If valid, the URL will also be stripped of any trailing slashes.
* @param url - The potentially invalid URL to sanitize.
* @returns The sanitized URL or a falsey value if the URL is invalid.
* @internal
*/
static sanitizeWellKnownUrl(url) {
if (!url) return false;
try {
var _parsed;
var parsed;
try {
parsed = new URL(url);
} catch (e) {
logger$2.error("Could not parse url", e);
}
if (!((_parsed = parsed) !== null && _parsed !== void 0 && _parsed.hostname)) return false;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
var port = parsed.port ? ":".concat(parsed.port) : "";
var path = parsed.pathname ? parsed.pathname : "";
var saferUrl = "".concat(parsed.protocol, "//").concat(parsed.hostname).concat(port).concat(path);
if (saferUrl.endsWith("/")) saferUrl = saferUrl.substring(0, saferUrl.length - 1);
return saferUrl;
} catch (e) {
logger$2.error(e);
return false;
}
}
static fetch(resource, options) {
if (this.fetchFn) return this.fetchFn(resource, options);
return globalThis.fetch(resource, options);
}
static setFetchFn(fetchFn) {
AutoDiscovery.fetchFn = fetchFn;
}
/**
* Fetches a JSON object from a given URL, as expected by all .well-known
* related lookups. If the server gives a 404 then the `action` will be
* IGNORE. If the server returns something that isn't JSON, the `action`
* will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.
*
* The returned object will be a result of the call in object form with
* the following properties:
* raw: The JSON object returned by the server.
* action: One of SUCCESS, IGNORE, or FAIL_PROMPT.
* reason: Relatively human-readable description of what went wrong.
* error: The actual Error, if one exists.
* @param url - The URL to fetch a JSON object from.
* @returns Promise which resolves to the returned state.
* @internal
*/
static fetchWellKnownObject(url) {
return (0, import_asyncToGenerator.default)(function* () {
var response;
try {
response = yield AutoDiscovery.fetch(url, {
method: Method.Get,
signal: timeoutSignal(5e3)
});
if (response.status === 404) return {
raw: {},
action: AutoDiscoveryAction.IGNORE,
reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN
};
if (response.status !== 200) return {
raw: {},
action: AutoDiscoveryAction.FAIL_PROMPT,
reason: "General failure"
};
} catch (err) {
var error = err;
var reason = "";
if (typeof error === "object") reason = error === null || error === void 0 ? void 0 : error.message;
return {
error,
raw: {},
action: AutoDiscoveryAction.FAIL_PROMPT,
reason: reason || "General failure"
};
}
try {
return {
raw: yield response.json(),
action: AutoDiscoveryAction.SUCCESS
};
} catch (err) {
var _error = err;
return {
error: _error,
raw: {},
action: AutoDiscoveryAction.FAIL_PROMPT,
reason: (_error === null || _error === void 0 ? void 0 : _error.name) === "SyntaxError" ? AutoDiscovery.ERROR_INVALID_JSON : AutoDiscovery.ERROR_INVALID
};
}
})();
}
};
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID", AutoDiscoveryError.Invalid);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_GENERIC_FAILURE", AutoDiscoveryError.GenericFailure);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_HS_BASE_URL", AutoDiscoveryError.InvalidHsBaseUrl);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_HOMESERVER", AutoDiscoveryError.InvalidHomeserver);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_IS_BASE_URL", AutoDiscoveryError.InvalidIsBaseUrl);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_IDENTITY_SERVER", AutoDiscoveryError.InvalidIdentityServer);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_IS", AutoDiscoveryError.InvalidIs);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_MISSING_WELLKNOWN", AutoDiscoveryError.MissingWellknown);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_INVALID_JSON", AutoDiscoveryError.InvalidJson);
(0, import_defineProperty.default)(AutoDiscovery, "ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION", AutoDiscoveryError.UnsupportedHomeserverSpecVersion);
(0, import_defineProperty.default)(AutoDiscovery, "ALL_ERRORS", Object.keys(AutoDiscoveryError));
/**
* The auto discovery failed. The client is expected to communicate
* the error to the user and refuse logging in.
*/
(0, import_defineProperty.default)(AutoDiscovery, "FAIL_ERROR", AutoDiscoveryAction.FAIL_ERROR);
/**
* The auto discovery failed, however the client may still recover
* from the problem. The client is recommended to that the same
* action it would for PROMPT while also warning the user about
* what went wrong. The client may also treat this the same as
* a FAIL_ERROR state.
*/
(0, import_defineProperty.default)(AutoDiscovery, "FAIL_PROMPT", AutoDiscoveryAction.FAIL_PROMPT);
/**
* The auto discovery didn't fail but did not find anything of
* interest. The client is expected to prompt the user for more
* information, or fail if it prefers.
*/
(0, import_defineProperty.default)(AutoDiscovery, "PROMPT", AutoDiscoveryAction.PROMPT);
/**
* The auto discovery was successful.
*/
(0, import_defineProperty.default)(AutoDiscovery, "SUCCESS", AutoDiscoveryAction.SUCCESS);
(0, import_defineProperty.default)(AutoDiscovery, "fetchFn", void 0);
//#endregion
//#region node_modules/matrix-js-sdk/lib/service-types.js
var SERVICE_TYPES = /* @__PURE__ */ function(SERVICE_TYPES) {
SERVICE_TYPES["IS"] = "SERVICE_TYPE_IS";
SERVICE_TYPES["IM"] = "SERVICE_TYPE_IM";
return SERVICE_TYPES;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/event-context.js
var EventContext = class {
/**
* Construct a new EventContext
*
* An eventcontext is used for circumstances such as search results, when we
* have a particular event of interest, and a bunch of events before and after
* it.
*
* It also stores pagination tokens for going backwards and forwards in the
* timeline.
*
* @param ourEvent - the event at the centre of this context
*/
constructor(ourEvent) {
this.ourEvent = ourEvent;
(0, import_defineProperty.default)(this, "timeline", void 0);
(0, import_defineProperty.default)(this, "ourEventIndex", 0);
(0, import_defineProperty.default)(this, "paginateTokens", {
[Direction.Backward]: null,
[Direction.Forward]: null
});
this.timeline = [ourEvent];
}
/**
* Get the main event of interest
*
* This is a convenience function for getTimeline()[getOurEventIndex()].
*
* @returns The event at the centre of this context.
*/
getEvent() {
return this.timeline[this.ourEventIndex];
}
/**
* Get the list of events in this context
*
* @returns An array of MatrixEvents
*/
getTimeline() {
return this.timeline;
}
/**
* Get the index in the timeline of our event
*/
getOurEventIndex() {
return this.ourEventIndex;
}
/**
* Get a pagination token.
*
* @param backwards - true to get the pagination token for going
*/
getPaginateToken() {
var backwards = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
return this.paginateTokens[backwards ? Direction.Backward : Direction.Forward];
}
/**
* Set a pagination token.
*
* Generally this will be used only by the matrix js sdk.
*
* @param token - pagination token
* @param backwards - true to set the pagination token for going
* backwards in time
*/
setPaginateToken(token) {
var backwards = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
this.paginateTokens[backwards ? Direction.Backward : Direction.Forward] = token !== null && token !== void 0 ? token : null;
}
/**
* Add more events to the timeline
*
* @param events - new events, in timeline order
* @param atStart - true to insert new events at the start
*/
addEvents(events) {
if (arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false) {
this.timeline = events.concat(this.timeline);
this.ourEventIndex += events.length;
} else this.timeline = this.timeline.concat(events);
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/search-result.js
var SearchResult = class SearchResult {
/**
* Create a SearchResponse from the response to /search
*/
static fromJson(jsonObj, eventMapper) {
var jsonContext = jsonObj.context || {};
var eventsBefore = (jsonContext.events_before || []).map(eventMapper);
var eventsAfter = (jsonContext.events_after || []).map(eventMapper);
var context = new EventContext(eventMapper(jsonObj.result));
var threadRootId = context.ourEvent.threadRootId;
eventsBefore = eventsBefore.filter((e) => e.threadRootId === threadRootId);
eventsAfter = eventsAfter.filter((e) => e.threadRootId === threadRootId);
context.setPaginateToken(jsonContext.start, true);
context.addEvents(eventsBefore, true);
context.addEvents(eventsAfter, false);
context.setPaginateToken(jsonContext.end, false);
return new SearchResult(jsonObj.rank, context);
}
/**
* Construct a new SearchResult
*
* @param rank - where this SearchResult ranks in the results
* @param context - the matching event and its
* context
*/
constructor(rank, context) {
this.rank = rank;
this.context = context;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/requests.js
/** Options object for {@link MatrixClient.invite}. */
function isSendDelayedEventRequestOpts(opts) {
if ("parent_delay_id" in opts && typeof opts.parent_delay_id !== "string") return false;
if ("delay" in opts && typeof opts.delay !== "number") return true;
return "delay" in opts || "parent_delay_id" in opts;
}
var UpdateDelayedEventAction = /* @__PURE__ */ function(UpdateDelayedEventAction) {
UpdateDelayedEventAction["Cancel"] = "cancel";
UpdateDelayedEventAction["Restart"] = "restart";
UpdateDelayedEventAction["Send"] = "send";
return UpdateDelayedEventAction;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/partials.js
var Preset = /* @__PURE__ */ function(Preset) {
Preset["PrivateChat"] = "private_chat";
Preset["TrustedPrivateChat"] = "trusted_private_chat";
Preset["PublicChat"] = "public_chat";
return Preset;
}({});
var JoinRule = /* @__PURE__ */ function(JoinRule) {
JoinRule["Public"] = "public";
JoinRule["Invite"] = "invite";
/**
* @deprecated Reserved keyword. Should not be used. Not yet implemented.
*/
JoinRule["Private"] = "private";
JoinRule["Knock"] = "knock";
JoinRule["Restricted"] = "restricted";
return JoinRule;
}({});
var GuestAccess = /* @__PURE__ */ function(GuestAccess) {
GuestAccess["CanJoin"] = "can_join";
GuestAccess["Forbidden"] = "forbidden";
return GuestAccess;
}({});
var HistoryVisibility = /* @__PURE__ */ function(HistoryVisibility) {
HistoryVisibility["Invited"] = "invited";
HistoryVisibility["Joined"] = "joined";
HistoryVisibility["Shared"] = "shared";
HistoryVisibility["WorldReadable"] = "world_readable";
return HistoryVisibility;
}({});
/**
* A policy name & url in a specific internationalisation
* @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms_response-200_internationalised-policy
*/
/**
* A versioned policy with internationalised variants
* @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms_response-200_policy-object
*/
/**
* Response from the Terms API for Identity servers
* @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/event-mapper.js
function ownKeys$7(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;
}
function _objectSpread$7(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$7(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function eventMapperFor(client, options) {
var preventReEmit = Boolean(options.preventReEmit);
var decrypt = options.decrypt !== false;
function mapper(plainOldJsObject) {
var room = client.getRoom(plainOldJsObject.room_id);
var event;
if (room && plainOldJsObject.state_key === void 0) event = room.findEventById(plainOldJsObject.event_id);
if (!event || event.status) event = new MatrixEvent(plainOldJsObject);
else {
event.setUnsigned(_objectSpread$7(_objectSpread$7({}, event.getUnsigned()), plainOldJsObject.unsigned));
preventReEmit = true;
}
var bundledEdit = event.getServerAggregatedRelation(RelationType.Replace);
if (bundledEdit !== null && bundledEdit !== void 0 && bundledEdit.content) {
var replacement = mapper(bundledEdit);
event.makeReplaced(replacement);
}
var thread = room === null || room === void 0 ? void 0 : room.findThreadForEvent(event);
if (thread) event.setThread(thread);
if (event.isEncrypted()) {
if (!preventReEmit) client.reEmitter.reEmit(event, [MatrixEventEvent.Decrypted]);
if (decrypt) client.decryptEventIfNeeded(event);
}
if (!preventReEmit) {
client.reEmitter.reEmit(event, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);
room === null || room === void 0 || room.reEmitter.reEmit(event, [MatrixEventEvent.BeforeRedaction]);
}
return event;
}
return mapper;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/MSC3089Branch.js
function ownKeys$6(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;
}
function _objectSpread$6(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$6(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference
* to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes
* without notice.
*/
var MSC3089Branch = class {
constructor(client, indexEvent, directory) {
this.client = client;
this.indexEvent = indexEvent;
this.directory = directory;
}
/**
* The file ID.
*/
get id() {
var stateKey = this.indexEvent.getStateKey();
if (!stateKey) throw new Error("State key not found for branch");
return stateKey;
}
/**
* Whether this branch is active/valid.
*/
get isActive() {
return this.indexEvent.getContent()["active"] === true;
}
/**
* Version for the file, one-indexed.
*/
get version() {
var _this$indexEvent$getC;
return (_this$indexEvent$getC = this.indexEvent.getContent()["version"]) !== null && _this$indexEvent$getC !== void 0 ? _this$indexEvent$getC : 1;
}
get roomId() {
return this.indexEvent.getRoomId();
}
/**
* Deletes the file from the tree, including all prior edits/versions.
* @returns Promise which resolves when complete.
*/
delete() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this.client.sendStateEvent(_this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, _this.id);
yield _this.client.redactEvent(_this.roomId, _this.id);
var nextVersion = (yield _this.getVersionHistory())[1];
if (nextVersion) yield nextVersion.delete();
})();
}
/**
* Gets the name for this file.
* @returns The name, or "Unnamed File" if unknown.
*/
getName() {
return this.indexEvent.getContent()["name"] || "Unnamed File";
}
/**
* Sets the name for this file.
* @param name - The new name for this file.
* @returns Promise which resolves when complete.
*/
setName(name) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this2.client.sendStateEvent(_this2.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread$6(_objectSpread$6({}, _this2.indexEvent.getContent()), {}, { name }), _this2.id);
})();
}
/**
* Gets whether or not a file is locked.
* @returns True if locked, false otherwise.
*/
isLocked() {
return this.indexEvent.getContent()["locked"] || false;
}
/**
* Sets a file as locked or unlocked.
* @param locked - True to lock the file, false otherwise.
* @returns Promise which resolves when complete.
*/
setLocked(locked) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this3.client.sendStateEvent(_this3.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread$6(_objectSpread$6({}, _this3.indexEvent.getContent()), {}, { locked }), _this3.id);
})();
}
/**
* Gets information about the file needed to download it.
* @returns Information about the file.
*/
getFileInfo() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var file = (yield _this4.getFileEvent()).getOriginalContent()["file"];
var httpUrl = _this4.client.mxcUrlToHttp(file["url"]);
if (!httpUrl) throw new Error("No HTTP URL available for ".concat(file["url"]));
return {
info: file,
httpUrl
};
})();
}
/**
* Gets the event the file points to.
* @returns Promise which resolves to the file's event.
*/
getFileEvent() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var room = _this5.client.getRoom(_this5.roomId);
if (!room) throw new Error("Unknown room");
var event = room.getUnfilteredTimelineSet().findEventById(_this5.id);
while (!event && room.getLiveTimeline().getState(EventTimeline.BACKWARDS).paginationToken) {
yield _this5.client.scrollback(room, 100);
event = room.getUnfilteredTimelineSet().findEventById(_this5.id);
}
if (!event) throw new Error("Failed to find event");
yield _this5.client.decryptEventIfNeeded(event);
return event;
})();
}
/**
* Creates a new version of this file with contents in a type that is compatible with MatrixClient.uploadContent().
* @param name - The name of the file.
* @param encryptedContents - The encrypted contents.
* @param info - The encrypted file information.
* @param additionalContent - Optional event content fields to include in the message.
* @returns Promise which resolves to the file event's sent response.
*/
createNewVersion(name, encryptedContents, info, additionalContent) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var fileEventResponse = yield _this6.directory.createFile(name, encryptedContents, info, _objectSpread$6(_objectSpread$6({}, additionalContent !== null && additionalContent !== void 0 ? additionalContent : {}), {}, {
"m.new_content": true,
"m.relates_to": {
rel_type: RelationType.Replace,
event_id: _this6.id
}
}));
yield _this6.client.sendStateEvent(_this6.roomId, UNSTABLE_MSC3089_BRANCH.name, {
active: true,
name,
version: _this6.version + 1
}, fileEventResponse["event_id"]);
yield _this6.client.sendStateEvent(_this6.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread$6(_objectSpread$6({}, _this6.indexEvent.getContent()), {}, { active: false }), _this6.id);
return fileEventResponse;
})();
}
/**
* Gets the file's version history, starting at this file.
* @returns Promise which resolves to the file's version history, with the
* first element being the current version and the last element being the first version.
*/
getVersionHistory() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var fileHistory = [];
fileHistory.push(_this7);
var room = _this7.client.getRoom(_this7.roomId);
if (!room) throw new Error("Invalid or unknown room");
var timelineEvents = [...room.getLiveTimeline().getEvents()].reverse();
var childEvent;
var parentEvent = yield _this7.getFileEvent();
do {
childEvent = timelineEvents.find((e) => e.replacingEventId() === parentEvent.getId());
if (childEvent) {
var branch = _this7.directory.getFile(childEvent.getId());
if (branch) {
fileHistory.push(branch);
parentEvent = childEvent;
} else break;
}
} while (childEvent);
return fileHistory;
})();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/MSC3089TreeSpace.js
function ownKeys$5(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;
}
function _objectSpread$5(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$5(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* The recommended defaults for a tree space's power levels. Note that this
* is UNSTABLE and subject to breaking changes without notice.
*/
var DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {
invite: 100,
kick: 100,
ban: 100,
redact: 50,
state_default: 50,
events_default: 50,
users_default: 0,
events: {
[EventType.RoomPowerLevels]: 100,
[EventType.RoomHistoryVisibility]: 100,
[EventType.RoomTombstone]: 100,
[EventType.RoomEncryption]: 100,
[EventType.RoomName]: 50,
[EventType.RoomMessage]: 50,
[EventType.RoomMessageEncrypted]: 50,
[EventType.Sticker]: 50
},
users: {}
};
/**
* Ease-of-use representation for power levels represented as simple roles.
* Note that this is UNSTABLE and subject to breaking changes without notice.
*/
var TreePermissions = /* @__PURE__ */ function(TreePermissions) {
TreePermissions["Viewer"] = "viewer";
TreePermissions["Editor"] = "editor";
TreePermissions["Owner"] = "owner";
return TreePermissions;
}({});
/**
* Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)
* file tree Space. Note that this is UNSTABLE and subject to breaking changes
* without notice.
*/
var MSC3089TreeSpace = class {
constructor(client, roomId) {
this.client = client;
this.roomId = roomId;
(0, import_defineProperty.default)(this, "room", void 0);
this.room = this.client.getRoom(this.roomId);
if (!this.room) throw new Error("Unknown room");
}
/**
* Syntactic sugar for room ID of the Space.
*/
get id() {
return this.roomId;
}
/**
* Whether or not this is a top level space.
*/
get isTopLevel() {
var parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);
if (!(parentEvents !== null && parentEvents !== void 0 && parentEvents.length)) return true;
return parentEvents.every((e) => {
var _e$getContent;
return !((_e$getContent = e.getContent()) !== null && _e$getContent !== void 0 && _e$getContent["via"]);
});
}
/**
* Sets the name of the tree space.
* @param name - The new name for the space.
* @returns Promise which resolves when complete.
*/
setName(name) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this.client.sendStateEvent(_this.roomId, EventType.RoomName, { name }, "");
})();
}
/**
* Invites a user to the tree space. They will be given the default Viewer
* permission level unless specified elsewhere.
* @param userId - The user ID to invite.
* @param andSubspaces - True (default) to invite the user to all
* directories/subspaces too, recursively.
* @returns Promise which resolves when complete.
*/
invite(userId) {
var _arguments = arguments, _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var andSubspaces = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : true;
var promises = [_this2.retryInvite(userId)];
if (andSubspaces) promises.push(..._this2.getDirectories().map((d) => d.invite(userId, andSubspaces)));
yield Promise.all(promises);
})();
}
retryInvite(userId) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield simpleRetryOperation(() => _this3.client.invite(_this3.roomId, userId), (e) => {
if (e instanceof MatrixError && e.errcode === "M_FORBIDDEN") return false;
return true;
});
})();
}
/**
* Sets the permissions of a user to the given role. Note that if setting a user
* to Owner then they will NOT be able to be demoted. If the user does not have
* permission to change the power level of the target, an error will be thrown.
* @param userId - The user ID to change the role of.
* @param role - The role to assign.
* @returns Promise which resolves when complete.
*/
setPermissions(userId, role) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _pls$events;
var currentPls = _this4.room.currentState.getStateEvents(EventType.RoomPowerLevels, "");
if (Array.isArray(currentPls)) throw new Error("Unexpected return type for power levels");
var pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {};
var viewLevel = pls["users_default"] || 0;
var editLevel = pls["events_default"] || 50;
var adminLevel = ((_pls$events = pls["events"]) === null || _pls$events === void 0 ? void 0 : _pls$events[EventType.RoomPowerLevels]) || 100;
var users = pls["users"] || {};
switch (role) {
case TreePermissions.Viewer:
users[userId] = viewLevel;
break;
case TreePermissions.Editor:
users[userId] = editLevel;
break;
case TreePermissions.Owner:
users[userId] = adminLevel;
break;
default: throw new Error("Invalid role: " + role);
}
pls["users"] = users;
yield _this4.client.sendStateEvent(_this4.roomId, EventType.RoomPowerLevels, pls, "");
})();
}
/**
* Gets the current permissions of a user. Note that any users missing explicit permissions (or not
* in the space) will be considered Viewers. Appropriate membership checks need to be performed
* elsewhere.
* @param userId - The user ID to check permissions of.
* @returns The permissions for the user, defaulting to Viewer.
*/
getPermissions(userId) {
var _pls$events2, _pls$users;
var currentPls = this.room.currentState.getStateEvents(EventType.RoomPowerLevels, "");
if (Array.isArray(currentPls)) throw new Error("Unexpected return type for power levels");
var pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {};
var viewLevel = pls["users_default"] || 0;
var editLevel = pls["events_default"] || 50;
var adminLevel = ((_pls$events2 = pls["events"]) === null || _pls$events2 === void 0 ? void 0 : _pls$events2[EventType.RoomPowerLevels]) || 100;
var userLevel = ((_pls$users = pls["users"]) === null || _pls$users === void 0 ? void 0 : _pls$users[userId]) || viewLevel;
if (userLevel >= adminLevel) return TreePermissions.Owner;
if (userLevel >= editLevel) return TreePermissions.Editor;
return TreePermissions.Viewer;
}
/**
* Creates a directory under this tree space, represented as another tree space.
* @param name - The name for the directory.
* @returns Promise which resolves to the created directory.
*/
createDirectory(name) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var directory = yield _this5.client.unstableCreateFileTree(name);
yield _this5.client.sendStateEvent(_this5.roomId, EventType.SpaceChild, { via: [_this5.client.getDomain()] }, directory.roomId);
yield _this5.client.sendStateEvent(directory.roomId, EventType.SpaceParent, { via: [_this5.client.getDomain()] }, _this5.roomId);
return directory;
})();
}
/**
* Gets a list of all known immediate subdirectories to this tree space.
* @returns The tree spaces (directories). May be empty, but not null.
*/
getDirectories() {
var trees = [];
for (var child of this.room.currentState.getStateEvents(EventType.SpaceChild)) try {
var stateKey = child.getStateKey();
if (stateKey) {
var tree = this.client.unstableGetFileTreeSpace(stateKey);
if (tree) trees.push(tree);
}
} catch (e) {
logger$2.warn("Unable to create tree space instance for listing. Are we joined?", e);
}
return trees;
}
/**
* Gets a subdirectory of a given ID under this tree space. Note that this will not recurse
* into children and instead only look one level deep.
* @param roomId - The room ID (directory ID) to find.
* @returns The directory, or undefined if not found.
*/
getDirectory(roomId) {
return this.getDirectories().find((r) => r.roomId === roomId);
}
/**
* Deletes the tree, kicking all members and deleting **all subdirectories**.
* @returns Promise which resolves when complete.
*/
delete() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var dir of _this6.getDirectories()) yield dir.delete();
var kickMemberships = [
KnownMembership.Invite,
KnownMembership.Knock,
KnownMembership.Join
];
for (var member of _this6.room.currentState.getStateEvents(EventType.RoomMember)) if (member.getStateKey() !== _this6.client.getUserId() && kickMemberships.includes(member.getContent().membership)) {
var stateKey = member.getStateKey();
if (!stateKey) throw new Error("State key not found for branch");
yield _this6.client.kick(_this6.roomId, stateKey, "Room deleted");
}
yield _this6.client.leave(_this6.roomId);
})();
}
getOrderedChildren(children) {
var ordered = children.map((c) => ({
roomId: c.getStateKey(),
order: c.getContent()["order"]
})).filter((c) => c.roomId);
ordered.sort((a, b) => {
if (a.order && !b.order) return -1;
else if (!a.order && b.order) return 1;
else if (!a.order && !b.order) {
var _roomA$currentState$g, _roomA$currentState$g2, _roomB$currentState$g, _roomB$currentState$g2;
var roomA = this.client.getRoom(a.roomId);
var roomB = this.client.getRoom(b.roomId);
if (!roomA || !roomB) return lexicographicCompare(a.roomId, b.roomId);
var createTsA = (_roomA$currentState$g = (_roomA$currentState$g2 = roomA.currentState.getStateEvents(EventType.RoomCreate, "")) === null || _roomA$currentState$g2 === void 0 ? void 0 : _roomA$currentState$g2.getTs()) !== null && _roomA$currentState$g !== void 0 ? _roomA$currentState$g : 0;
var createTsB = (_roomB$currentState$g = (_roomB$currentState$g2 = roomB.currentState.getStateEvents(EventType.RoomCreate, "")) === null || _roomB$currentState$g2 === void 0 ? void 0 : _roomB$currentState$g2.getTs()) !== null && _roomB$currentState$g !== void 0 ? _roomB$currentState$g : 0;
if (createTsA === createTsB) return lexicographicCompare(a.roomId, b.roomId);
return createTsA - createTsB;
} else return lexicographicCompare(a.order, b.order);
});
return ordered;
}
getParentRoom() {
var parent = this.room.currentState.getStateEvents(EventType.SpaceParent)[0];
if (!parent) throw new Error("Expected to have a parent in a non-top level space");
var stateKey = parent.getStateKey();
if (!stateKey) throw new Error("No state key found for parent");
var parentRoom = this.client.getRoom(stateKey);
if (!parentRoom) throw new Error("Unable to locate room for parent");
return parentRoom;
}
/**
* Gets the current order index for this directory. Note that if this is the top level space
* then -1 will be returned.
* @returns The order index of this space.
*/
getOrder() {
if (this.isTopLevel) return -1;
var children = this.getParentRoom().currentState.getStateEvents(EventType.SpaceChild);
return this.getOrderedChildren(children).findIndex((c) => c.roomId === this.roomId);
}
/**
* Sets the order index for this directory within its parent. Note that if this is a top level
* space then an error will be thrown. -1 can be used to move the child to the start, and numbers
* larger than the number of children can be used to move the child to the end.
* @param index - The new order index for this space.
* @returns Promise which resolves when complete.
* @throws Throws if this is a top level space.
*/
setOrder(index) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _currentChild$getCont2;
if (_this7.isTopLevel) throw new Error("Cannot set order of top level spaces currently");
var parentRoom = _this7.getParentRoom();
var children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);
var ordered = _this7.getOrderedChildren(children);
index = Math.max(Math.min(index, ordered.length - 1), 0);
var movingUp = _this7.getOrder() < index;
if (movingUp && index === ordered.length - 1) index--;
else if (!movingUp && index === 0) index++;
var prev = ordered[movingUp ? index : index - 1];
var next = ordered[movingUp ? index + 1 : index];
var newOrder = DEFAULT_ALPHABET[0];
var ensureBeforeIsSane = false;
if (!prev) {
if (next !== null && next !== void 0 && next.order) newOrder = prevString(next.order);
} else if (index === ordered.length - 1) {
if (next !== null && next !== void 0 && next.order) newOrder = nextString(next.order);
} else {
var startOrder = prev === null || prev === void 0 ? void 0 : prev.order;
var endOrder = next === null || next === void 0 ? void 0 : next.order;
if (startOrder && endOrder) if (startOrder === endOrder) newOrder = nextString(startOrder);
else newOrder = averageBetweenStrings(startOrder, endOrder);
else if (startOrder) newOrder = nextString(startOrder);
else if (endOrder) newOrder = prevString(endOrder);
else ensureBeforeIsSane = true;
}
if (ensureBeforeIsSane) {
var lastOrder;
for (var i = 0; i <= index; i++) {
var target = ordered[i];
if (i === 0) lastOrder = target.order;
if (!target.order) {
var _currentChild$getCont;
lastOrder = lastOrder ? nextString(lastOrder) : DEFAULT_ALPHABET[0];
var _currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, target.roomId);
var _content = (_currentChild$getCont = _currentChild === null || _currentChild === void 0 ? void 0 : _currentChild.getContent()) !== null && _currentChild$getCont !== void 0 ? _currentChild$getCont : { via: [_this7.client.getDomain()] };
yield _this7.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, _objectSpread$5(_objectSpread$5({}, _content), {}, { order: lastOrder }), target.roomId);
} else lastOrder = target.order;
}
if (lastOrder) newOrder = nextString(lastOrder);
}
var currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, _this7.roomId);
var content = (_currentChild$getCont2 = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _currentChild$getCont2 !== void 0 ? _currentChild$getCont2 : { via: [_this7.client.getDomain()] };
yield _this7.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, _objectSpread$5(_objectSpread$5({}, content), {}, { order: newOrder }), _this7.roomId);
})();
}
/**
* Creates (uploads) a new file to this tree. The file must have already been encrypted for the room.
* The file contents are in a type that is compatible with MatrixClient.uploadContent().
* @param name - The name of the file.
* @param encryptedContents - The encrypted contents.
* @param info - The encrypted file information.
* @param additionalContent - Optional event content fields to include in the message.
* @returns Promise which resolves to the file event's sent response.
*/
createFile(name, encryptedContents, info, additionalContent) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { content_uri: mxc } = yield _this8.client.uploadContent(encryptedContents, { includeFilename: false });
info.url = mxc;
var fileContent = {
msgtype: MsgType.File,
body: name,
url: mxc,
file: info
};
additionalContent = additionalContent !== null && additionalContent !== void 0 ? additionalContent : {};
if (additionalContent["m.new_content"]) additionalContent["m.new_content"] = fileContent;
var res = yield _this8.client.sendMessage(_this8.roomId, _objectSpread$5(_objectSpread$5(_objectSpread$5({}, additionalContent), fileContent), {}, { [UNSTABLE_MSC3089_LEAF.name]: {} }));
yield _this8.client.sendStateEvent(_this8.roomId, UNSTABLE_MSC3089_BRANCH.name, {
active: true,
name
}, res["event_id"]);
return res;
})();
}
/**
* Retrieves a file from the tree.
* @param fileEventId - The event ID of the file.
* @returns The file, or null if not found.
*/
getFile(fileEventId) {
var branch = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name, fileEventId);
return branch ? new MSC3089Branch(this.client, branch, this) : null;
}
/**
* Gets an array of all known files for the tree.
* @returns The known files. May be empty, but not null.
*/
listFiles() {
return this.listAllFiles().filter((b) => b.isActive);
}
/**
* Gets an array of all known files for the tree, including inactive/invalid ones.
* @returns The known files. May be empty, but not null.
*/
listAllFiles() {
var _this$room$currentSta;
return ((_this$room$currentSta = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name)) !== null && _this$room$currentSta !== void 0 ? _this$room$currentSta : []).map((e) => new MSC3089Branch(this.client, e, this));
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/search.js
var SearchOrderBy = /* @__PURE__ */ function(SearchOrderBy) {
SearchOrderBy["Recent"] = "recent";
SearchOrderBy["Rank"] = "rank";
return SearchOrderBy;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/webrtc/mediaHandler.js
var MediaHandlerEvent = /* @__PURE__ */ function(MediaHandlerEvent) {
MediaHandlerEvent["LocalStreamsChanged"] = "local_streams_changed";
return MediaHandlerEvent;
}({});
var MediaHandler = class extends TypedEventEmitter {
constructor(client) {
super();
this.client = client;
(0, import_defineProperty.default)(this, "audioInput", void 0);
(0, import_defineProperty.default)(this, "audioSettings", void 0);
(0, import_defineProperty.default)(this, "videoInput", void 0);
(0, import_defineProperty.default)(this, "localUserMediaStream", void 0);
(0, import_defineProperty.default)(this, "userMediaStreams", []);
(0, import_defineProperty.default)(this, "screensharingStreams", []);
(0, import_defineProperty.default)(this, "getMediaStreamPromise", void 0);
}
restoreMediaSettings(audioInput, videoInput) {
this.audioInput = audioInput;
this.videoInput = videoInput;
}
/**
* Set an audio input device to use for MatrixCalls
* @param deviceId - the identifier for the device
* undefined treated as unset
*/
setAudioInput(deviceId) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.info("MediaHandler setAudioInput() running (deviceId=".concat(deviceId, ")"));
if (_this.audioInput === deviceId) return;
_this.audioInput = deviceId;
yield _this.updateLocalUsermediaStreams();
})();
}
/**
* Set audio settings for MatrixCalls
* @param opts - audio options to set
*/
setAudioSettings(opts) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.info("MediaHandler setAudioSettings() running (opts=".concat(JSON.stringify(opts), ")"));
_this2.audioSettings = Object.assign({}, opts);
yield _this2.updateLocalUsermediaStreams();
})();
}
/**
* Set a video input device to use for MatrixCalls
* @param deviceId - the identifier for the device
* undefined treated as unset
*/
setVideoInput(deviceId) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.info("MediaHandler setVideoInput() running (deviceId=".concat(deviceId, ")"));
if (_this3.videoInput === deviceId) return;
_this3.videoInput = deviceId;
yield _this3.updateLocalUsermediaStreams();
})();
}
/**
* Set media input devices to use for MatrixCalls
* @param audioInput - the identifier for the audio device
* @param videoInput - the identifier for the video device
* undefined treated as unset
*/
setMediaInputs(audioInput, videoInput) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
logger$2.log("MediaHandler setMediaInputs() running (audioInput: ".concat(audioInput, " videoInput: ").concat(videoInput, ")"));
_this4.audioInput = audioInput;
_this4.videoInput = videoInput;
yield _this4.updateLocalUsermediaStreams();
})();
}
updateLocalUsermediaStreams() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this5.userMediaStreams.length === 0) return;
var callMediaStreamParams = /* @__PURE__ */ new Map();
for (var call of _this5.client.callEventHandler.calls.values()) callMediaStreamParams.set(call.callId, {
audio: call.hasLocalUserMediaAudioTrack,
video: call.hasLocalUserMediaVideoTrack
});
for (var stream of _this5.userMediaStreams) {
logger$2.log("MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=".concat(stream.id, ")"));
for (var track of stream.getTracks()) track.stop();
}
_this5.userMediaStreams = [];
_this5.localUserMediaStream = void 0;
for (var _call of _this5.client.callEventHandler.calls.values()) {
if (_call.callHasEnded() || !callMediaStreamParams.has(_call.callId)) continue;
var { audio, video } = callMediaStreamParams.get(_call.callId);
logger$2.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=".concat(_call.callId, ")"));
var _stream = yield _this5.getUserMediaStream(audio, video);
if (_call.callHasEnded()) continue;
yield _call.updateLocalUsermediaStream(_stream);
}
for (var groupCall of _this5.client.groupCallEventHandler.groupCalls.values()) {
if (!groupCall.localCallFeed) continue;
logger$2.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=".concat(groupCall.groupCallId, ")"));
var _stream2 = yield _this5.getUserMediaStream(true, groupCall.type === GroupCallType.Video);
if (groupCall.state === GroupCallState.Ended) continue;
yield groupCall.updateLocalUsermediaStream(_stream2);
}
_this5.emit(MediaHandlerEvent.LocalStreamsChanged);
})();
}
hasAudioDevice() {
return (0, import_asyncToGenerator.default)(function* () {
try {
return (yield navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === "audioinput").length > 0;
} catch (err) {
logger$2.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error", err);
return false;
}
})();
}
hasVideoDevice() {
return (0, import_asyncToGenerator.default)(function* () {
try {
return (yield navigator.mediaDevices.enumerateDevices()).filter((device) => device.kind === "videoinput").length > 0;
} catch (err) {
logger$2.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error", err);
return false;
}
})();
}
/**
* @param audio - should have an audio track
* @param video - should have a video track
* @param reusable - is allowed to be reused by the MediaHandler
* @returns based on passed parameters
*/
getUserMediaStream(audio, video) {
var _arguments = arguments, _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var reusable = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : true;
if (_this6.getMediaStreamPromise) _this6.getMediaStreamPromise = _this6.getMediaStreamPromise.then(() => {
return _this6.getUserMediaStreamInternal(audio, video, reusable);
});
else _this6.getMediaStreamPromise = _this6.getUserMediaStreamInternal(audio, video, reusable);
return _this6.getMediaStreamPromise;
})();
}
getUserMediaStreamInternal(audio, video, reusable) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var shouldRequestAudio = audio && (yield _this7.hasAudioDevice());
var shouldRequestVideo = video && (yield _this7.hasVideoDevice());
var stream;
var canReuseStream = true;
if (_this7.localUserMediaStream) {
var _this7$localUserMedia, _this7$localUserMedia2;
if (shouldRequestAudio !== _this7.localUserMediaStream.getAudioTracks().length > 0) canReuseStream = false;
if (shouldRequestVideo !== _this7.localUserMediaStream.getVideoTracks().length > 0) canReuseStream = false;
if (shouldRequestAudio && ((_this7$localUserMedia = _this7.localUserMediaStream.getAudioTracks()[0]) === null || _this7$localUserMedia === void 0 || (_this7$localUserMedia = _this7$localUserMedia.getSettings()) === null || _this7$localUserMedia === void 0 ? void 0 : _this7$localUserMedia.deviceId) !== _this7.audioInput) canReuseStream = false;
if (shouldRequestVideo && ((_this7$localUserMedia2 = _this7.localUserMediaStream.getVideoTracks()[0]) === null || _this7$localUserMedia2 === void 0 || (_this7$localUserMedia2 = _this7$localUserMedia2.getSettings()) === null || _this7$localUserMedia2 === void 0 ? void 0 : _this7$localUserMedia2.deviceId) !== _this7.videoInput) canReuseStream = false;
} else canReuseStream = false;
if (!canReuseStream) {
var constraints;
try {
constraints = _this7.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo, true);
stream = yield navigator.mediaDevices.getUserMedia(constraints);
} catch (e) {
logger$2.warn("MediaHandler getUserMediaStreamInternal() error (e=".concat(e, "), retrying without exact deviceId"));
constraints = _this7.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo, false);
stream = yield navigator.mediaDevices.getUserMedia(constraints);
}
logger$2.log("MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=".concat(stream.id, ", shouldRequestAudio=").concat(shouldRequestAudio, ", shouldRequestVideo=").concat(shouldRequestVideo, ", constraints=").concat(JSON.stringify(constraints), ")"));
for (var track of stream.getTracks()) {
var settings = track.getSettings();
if (track.kind === "audio") _this7.audioInput = settings.deviceId;
else if (track.kind === "video") _this7.videoInput = settings.deviceId;
}
if (reusable) _this7.localUserMediaStream = stream;
} else {
var _this7$localUserMedia3;
stream = _this7.localUserMediaStream.clone();
logger$2.log("MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=".concat((_this7$localUserMedia3 = _this7.localUserMediaStream) === null || _this7$localUserMedia3 === void 0 ? void 0 : _this7$localUserMedia3.id, " newStreamId=").concat(stream.id, " shouldRequestAudio=").concat(shouldRequestAudio, " shouldRequestVideo=").concat(shouldRequestVideo, ")"));
if (!shouldRequestAudio) for (var _track of stream.getAudioTracks()) stream.removeTrack(_track);
if (!shouldRequestVideo) for (var _track2 of stream.getVideoTracks()) stream.removeTrack(_track2);
}
if (reusable) _this7.userMediaStreams.push(stream);
_this7.emit(MediaHandlerEvent.LocalStreamsChanged);
return stream;
})();
}
/**
* Stops all tracks on the provided usermedia stream
*/
stopUserMediaStream(mediaStream) {
logger$2.log("MediaHandler stopUserMediaStream() stopping (streamId=".concat(mediaStream.id, ")"));
for (var track of mediaStream.getTracks()) track.stop();
var index = this.userMediaStreams.indexOf(mediaStream);
if (index !== -1) {
logger$2.debug("MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=".concat(mediaStream.id, ")"), mediaStream.id);
this.userMediaStreams.splice(index, 1);
}
this.emit(MediaHandlerEvent.LocalStreamsChanged);
if (this.localUserMediaStream === mediaStream) this.localUserMediaStream = void 0;
else for (var _track3 of mediaStream.getTracks()) {
var _this$localUserMediaS;
if ((_this$localUserMediaS = this.localUserMediaStream) !== null && _this$localUserMediaS !== void 0 && _this$localUserMediaS.getTrackById(_track3.id)) {
this.stopUserMediaStream(this.localUserMediaStream);
break;
}
}
}
/**
* @param opts - screensharing stream options
* @param reusable - is allowed to be reused by the MediaHandler
* @returns based on passed parameters
*/
getScreensharingStream() {
var _arguments2 = arguments, _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var opts = _arguments2.length > 0 && _arguments2[0] !== void 0 ? _arguments2[0] : {};
var reusable = _arguments2.length > 1 && _arguments2[1] !== void 0 ? _arguments2[1] : true;
var stream;
if (_this8.screensharingStreams.length === 0) {
var screenshareConstraints = _this8.getScreenshareContraints(opts);
if (opts.desktopCapturerSourceId) {
logger$2.debug("MediaHandler getScreensharingStream() calling getUserMedia() (opts=".concat(JSON.stringify(opts), ")"));
stream = yield navigator.mediaDevices.getUserMedia(screenshareConstraints);
} else {
logger$2.debug("MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=".concat(JSON.stringify(opts), ")"));
stream = yield navigator.mediaDevices.getDisplayMedia(screenshareConstraints);
}
} else {
var matchingStream = _this8.screensharingStreams[_this8.screensharingStreams.length - 1];
logger$2.log("MediaHandler getScreensharingStream() cloning (streamId=".concat(matchingStream.id, ")"));
stream = matchingStream.clone();
}
if (reusable) _this8.screensharingStreams.push(stream);
_this8.emit(MediaHandlerEvent.LocalStreamsChanged);
return stream;
})();
}
/**
* Stops all tracks on the provided screensharing stream
*/
stopScreensharingStream(mediaStream) {
logger$2.debug("MediaHandler stopScreensharingStream() stopping stream (streamId=".concat(mediaStream.id, ")"));
for (var track of mediaStream.getTracks()) track.stop();
var index = this.screensharingStreams.indexOf(mediaStream);
if (index !== -1) {
logger$2.debug("MediaHandler stopScreensharingStream() splicing stream out (streamId=".concat(mediaStream.id, ")"));
this.screensharingStreams.splice(index, 1);
}
this.emit(MediaHandlerEvent.LocalStreamsChanged);
}
/**
* Stops all local media tracks
*/
stopAllStreams() {
for (var stream of this.userMediaStreams) {
logger$2.log("MediaHandler stopAllStreams() stopping (streamId=".concat(stream.id, ")"));
for (var track of stream.getTracks()) track.stop();
}
for (var _stream3 of this.screensharingStreams) for (var _track4 of _stream3.getTracks()) _track4.stop();
this.userMediaStreams = [];
this.screensharingStreams = [];
this.localUserMediaStream = void 0;
this.emit(MediaHandlerEvent.LocalStreamsChanged);
}
getUserMediaContraints(audio, video, exactDeviceId) {
var isWebkit = !!navigator.webkitGetUserMedia;
var deviceIdKey = exactDeviceId ? "exact" : "ideal";
var audioConstraints = {};
if (this.audioInput) audioConstraints.deviceId = { [deviceIdKey]: this.audioInput };
if (this.audioSettings) {
audioConstraints.autoGainControl = { ideal: this.audioSettings.autoGainControl };
audioConstraints.echoCancellation = { ideal: this.audioSettings.echoCancellation };
audioConstraints.noiseSuppression = { ideal: this.audioSettings.noiseSuppression };
}
var videoConstraints = {
width: isWebkit ? { exact: 640 } : { ideal: 640 },
height: isWebkit ? { exact: 360 } : { ideal: 360 }
};
if (this.videoInput) videoConstraints.deviceId = { [deviceIdKey]: this.videoInput };
return {
audio: audio ? audioConstraints : false,
video: video ? videoConstraints : false
};
}
getScreenshareContraints(opts) {
var { desktopCapturerSourceId, audio } = opts;
if (desktopCapturerSourceId) return {
audio: audio !== null && audio !== void 0 ? audio : false,
video: { mandatory: {
chromeMediaSource: "desktop",
chromeMediaSourceId: desktopCapturerSourceId
} }
};
else return {
audio: audio !== null && audio !== void 0 ? audio : false,
video: true
};
}
};
/**
* Represents a subscription to a room or set of rooms. Controls which events are returned.
*/
/**
* Controls which rooms are returned in a given list.
*/
/**
* Represents a list subscription.
*/
/**
* A complete Sliding Sync request.
*/
/**
* New format of hero introduced in MSC4186 with display name and avatar URL
* in addition to just user_id (as it is on the wire, with underscores)
* as opposed to Hero in room-summary.ts which has fields in camelCase
* (and also a flag to note what format the hero came from).
*/
/**
* A complete Sliding Sync response
*/
var SlidingSyncState = /* @__PURE__ */ function(SlidingSyncState) {
/**
* Fired by SlidingSyncEvent.Lifecycle event immediately before processing the response.
*/
SlidingSyncState["RequestFinished"] = "FINISHED";
/**
* Fired by SlidingSyncEvent.Lifecycle event immediately after all room data listeners have been
* invoked, but before list listeners.
*/
SlidingSyncState["Complete"] = "COMPLETE";
return SlidingSyncState;
}({});
/**
* When onResponse extensions should be invoked: before or after processing the main response.
*/
var ExtensionState = /* @__PURE__ */ function(ExtensionState) {
ExtensionState["PreProcess"] = "ExtState.PreProcess";
ExtensionState["PostProcess"] = "ExtState.PostProcess";
return ExtensionState;
}({});
/**
* An interface that must be satisfied to register extensions
*/
/**
* Events which can be fired by the SlidingSync class. These are designed to provide different levels
* of information when processing sync responses.
* - RoomData: concerns rooms, useful for SlidingSyncSdk to update its knowledge of rooms.
* - Lifecycle: concerns callbacks at various well-defined points in the sync process.
* Specifically, the order of event invocation is:
* - Lifecycle (state=RequestFinished)
* - RoomData (N times)
* - Lifecycle (state=Complete)
*/
var SlidingSyncEvent = /* @__PURE__ */ function(SlidingSyncEvent) {
/**
* This event fires when there are updates for a room. Fired as and when rooms are encountered
* in the response.
*/
SlidingSyncEvent["RoomData"] = "SlidingSync.RoomData";
/**
* This event fires at various points in the /sync loop lifecycle.
* - SlidingSyncState.RequestFinished: Fires after we receive a valid response but before the
* response has been processed. Perform any pre-process steps here. If there was a problem syncing,
* `err` will be set (e.g network errors).
* - SlidingSyncState.Complete: Fires after the response has been processed.
*/
SlidingSyncEvent["Lifecycle"] = "SlidingSync.Lifecycle";
return SlidingSyncEvent;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/sliding-sync-sdk.js
var FAILED_SYNC_ERROR_THRESHOLD = 3;
var ExtensionE2EE = class {
constructor(crypto) {
this.crypto = crypto;
}
name() {
return "e2ee";
}
when() {
return ExtensionState.PreProcess;
}
onRequest(isInitial) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (isInitial) {
logger$2.log("ExtensionE2EE: invalidating all device lists due to missing 'pos'");
yield _this.crypto.markAllTrackedUsersAsDirty();
}
return { enabled: true };
})();
}
onResponse(data) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (data.device_lists) yield _this2.crypto.processDeviceLists(data.device_lists);
yield _this2.crypto.processKeyCounts(data.device_one_time_keys_count, data["device_unused_fallback_key_types"] || data["org.matrix.msc2732.device_unused_fallback_key_types"]);
_this2.crypto.onSyncCompleted({});
})();
}
};
var ExtensionToDevice = class {
constructor(client, cryptoCallbacks) {
this.client = client;
this.cryptoCallbacks = cryptoCallbacks;
(0, import_defineProperty.default)(this, "nextBatch", null);
}
name() {
return "to_device";
}
when() {
return ExtensionState.PreProcess;
}
onRequest(isInitial) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
return {
since: _this3.nextBatch !== null ? _this3.nextBatch : void 0,
limit: 100,
enabled: true
};
})();
}
onResponse(data) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var events = data["events"] || [];
var receivedToDeviceMessages;
if (_this4.cryptoCallbacks) receivedToDeviceMessages = yield _this4.cryptoCallbacks.preprocessToDeviceMessages(events);
else receivedToDeviceMessages = events.map((rawEvent) => ({
message: rawEvent,
encryptionInfo: null
}));
processToDeviceMessages(receivedToDeviceMessages, _this4.client);
_this4.nextBatch = data.next_batch;
})();
}
};
var ExtensionAccountData = class {
constructor(client) {
this.client = client;
}
name() {
return "account_data";
}
when() {
return ExtensionState.PostProcess;
}
onRequest(isInitial) {
return (0, import_asyncToGenerator.default)(function* () {
return { enabled: true };
})();
}
onResponse(data) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (data.global && data.global.length > 0) _this5.processGlobalAccountData(data.global);
for (var roomId in data.rooms) {
var accountDataEvents = mapEvents(_this5.client, roomId, data.rooms[roomId]);
var room = _this5.client.getRoom(roomId);
if (!room) {
logger$2.warn("got account data for room but room doesn't exist on client:", roomId);
continue;
}
room.addAccountData(accountDataEvents);
accountDataEvents.forEach((e) => {
_this5.client.emit(ClientEvent.Event, e);
});
}
})();
}
processGlobalAccountData(globalAccountData) {
var events = mapEvents(this.client, void 0, globalAccountData);
var prevEventsMap = events.reduce((m, c) => {
m[c.getType()] = this.client.store.getAccountData(c.getType());
return m;
}, {});
this.client.store.storeAccountDataEvents(events);
events.forEach((accountDataEvent) => {
if (accountDataEvent.getType() === EventType.PushRules) {
var rules = accountDataEvent.getContent();
this.client.setPushRules(rules);
}
var prevEvent = prevEventsMap[accountDataEvent.getType()];
this.client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);
return accountDataEvent;
});
}
};
var ExtensionTyping = class {
constructor(client) {
this.client = client;
}
name() {
return "typing";
}
when() {
return ExtensionState.PostProcess;
}
onRequest(isInitial) {
return (0, import_asyncToGenerator.default)(function* () {
return { enabled: true };
})();
}
onResponse(data) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(data !== null && data !== void 0 && data.rooms)) return;
for (var roomId in data.rooms) processEphemeralEvents(_this6.client, roomId, [data.rooms[roomId]]);
})();
}
};
var ExtensionReceipts = class {
constructor(client) {
this.client = client;
}
name() {
return "receipts";
}
when() {
return ExtensionState.PostProcess;
}
onRequest(isInitial) {
return (0, import_asyncToGenerator.default)(function* () {
return { enabled: true };
})();
}
onResponse(data) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(data !== null && data !== void 0 && data.rooms)) return;
for (var roomId in data.rooms) processEphemeralEvents(_this7.client, roomId, [data.rooms[roomId]]);
})();
}
};
/**
* A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual
* sliding sync API, see sliding-sync.ts or the class SlidingSync.
*/
var SlidingSyncSdk = class {
constructor(slidingSync, client, opts, syncOpts) {
this.slidingSync = slidingSync;
this.client = client;
(0, import_defineProperty.default)(this, "opts", void 0);
(0, import_defineProperty.default)(this, "syncOpts", void 0);
(0, import_defineProperty.default)(this, "syncState", null);
(0, import_defineProperty.default)(this, "syncStateData", void 0);
(0, import_defineProperty.default)(this, "lastPos", null);
(0, import_defineProperty.default)(this, "failCount", 0);
(0, import_defineProperty.default)(this, "notifEvents", []);
this.opts = defaultClientOpts(opts);
this.syncOpts = defaultSyncApiOpts(syncOpts);
if (client.getNotifTimelineSet()) client.reEmitter.reEmit(client.getNotifTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);
this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));
this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));
var extensions = [
new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks),
new ExtensionAccountData(this.client),
new ExtensionTyping(this.client),
new ExtensionReceipts(this.client)
];
if (this.syncOpts.cryptoCallbacks) extensions.push(new ExtensionE2EE(this.syncOpts.cryptoCallbacks));
extensions.forEach((ext) => {
this.slidingSync.registerExtension(ext);
});
}
onRoomData(roomId, roomData) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var room = _this8.client.store.getRoom(roomId);
if (!room) {
if (!roomData.initial) {
_this8.syncOpts.logger.debug("initial flag not set but no stored room exists for room ", roomId, roomData);
return;
}
room = _createAndReEmitRoom(_this8.client, roomId, _this8.opts);
}
yield _this8.processRoomData(_this8.client, room, roomData);
})();
}
onLifecycle(state, resp, err) {
if (err) this.syncOpts.logger.debug("onLifecycle", state, err);
switch (state) {
case SlidingSyncState.Complete:
this.purgeNotifications();
if (!resp) break;
if (!this.lastPos) this.updateSyncState(SyncState.Prepared, {
oldSyncToken: void 0,
nextSyncToken: resp.pos,
catchingUp: false,
fromCache: false
});
this.updateSyncState(SyncState.Syncing, {
oldSyncToken: this.lastPos,
nextSyncToken: resp.pos,
catchingUp: false,
fromCache: false
});
this.lastPos = resp.pos;
break;
case SlidingSyncState.RequestFinished:
if (err) {
this.failCount += 1;
this.updateSyncState(this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting, { error: new MatrixError(err) });
if (this.shouldAbortSync(new MatrixError(err))) return;
} else {
this.failCount = 0;
this.syncOpts.logger.debug("SlidingSyncState.RequestFinished with ".concat(Object.keys((resp === null || resp === void 0 ? void 0 : resp.rooms) || []).length, " rooms"));
}
break;
}
}
/**
* Sync rooms the user has left.
* @returns Resolved when they've been added to the store.
*/
syncLeftRooms() {
return (0, import_asyncToGenerator.default)(function* () {
return [];
})();
}
/**
* Peek into a room. This will result in the room in question being synced so it
* is accessible via getRooms(). Live updates for the room will be provided.
* @param roomId - The room ID to peek into.
* @returns A promise which resolves once the room has been added to the
* store.
*/
peek(roomId) {
return (0, import_asyncToGenerator.default)(function* () {
return null;
})();
}
/**
* Stop polling for updates in the peeked room. NOPs if there is no room being
* peeked.
*/
stopPeeking() {}
/**
* Specify the set_presence value to be used for subsequent calls to the Sync API.
* @param presence - the presence to specify to set_presence of sync calls
*/
setPresence(presence) {}
/**
* Returns the current state of this sync object
* @see MatrixClient#event:"sync"
*/
getSyncState() {
return this.syncState;
}
/**
* Returns the additional data object associated with
* the current sync state, or null if there is no
* such data.
* Sync errors, if available, are put in the 'error' key of
* this object.
*/
getSyncStateData() {
var _this$syncStateData;
return (_this$syncStateData = this.syncStateData) !== null && _this$syncStateData !== void 0 ? _this$syncStateData : null;
}
createRoom(roomId) {
var { timelineSupport } = this.client;
var room = new Room(roomId, this.client, this.client.getUserId(), {
lazyLoadMembers: this.opts.lazyLoadMembers,
pendingEventOrdering: this.opts.pendingEventOrdering,
timelineSupport
});
this.client.reEmitter.reEmit(room, [
RoomEvent.Name,
RoomEvent.Redaction,
RoomEvent.RedactionCancelled,
RoomEvent.Receipt,
RoomEvent.Tags,
RoomEvent.LocalEchoUpdated,
RoomEvent.AccountData,
RoomEvent.MyMembership,
RoomEvent.Timeline,
RoomEvent.TimelineReset
]);
this.registerStateListeners(room);
return room;
}
registerStateListeners(room) {
this.client.reEmitter.reEmit(room.currentState, [
RoomStateEvent.Events,
RoomStateEvent.Members,
RoomStateEvent.NewMember,
RoomStateEvent.Update
]);
room.currentState.on(RoomStateEvent.NewMember, (event, state, member) => {
var _this$client$getUser;
member.user = (_this$client$getUser = this.client.getUser(member.userId)) !== null && _this$client$getUser !== void 0 ? _this$client$getUser : void 0;
this.client.reEmitter.reEmit(member, [
RoomMemberEvent.Name,
RoomMemberEvent.Typing,
RoomMemberEvent.PowerLevel,
RoomMemberEvent.Membership
]);
});
}
shouldAbortSync(error) {
if (error.errcode === "M_UNKNOWN_TOKEN") {
this.syncOpts.logger.warn("Token no longer valid - assuming logout");
this.stop();
this.updateSyncState(SyncState.Error, { error });
return true;
}
return false;
}
processRoomData(client, room, roomData) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
roomData = ensureNameEvent(client, room.roomId, roomData);
var stateEvents = mapEvents(_this9.client, room.roomId, roomData.required_state);
var timelineEvents = mapEvents(_this9.client, room.roomId, roomData.timeline, false);
var ephemeralEvents = [];
if (roomData.limited || roomData.initial) {
var knownEvents = /* @__PURE__ */ new Set();
room.getLiveTimeline().getEvents().forEach((e) => {
knownEvents.add(e.getId());
});
var oldEvents = [];
var newEvents = [];
var seenKnownEvent = false;
for (var i = timelineEvents.length - 1; i >= 0; i--) {
var recvEvent = timelineEvents[i];
if (knownEvents.has(recvEvent.getId())) {
seenKnownEvent = true;
continue;
}
if (seenKnownEvent) oldEvents.push(recvEvent);
else newEvents.unshift(recvEvent);
}
timelineEvents = newEvents;
if (oldEvents.length > 0) room.addEventsToTimeline(oldEvents, true, false, room.getLiveTimeline(), roomData.prev_batch);
}
var encrypted = room.hasEncryptionStateEvent();
if (roomData.notification_count != null) room.setUnreadNotificationCount(NotificationCountType.Total, roomData.notification_count);
if (roomData.highlight_count != null) {
if (!encrypted || encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) room.setUnreadNotificationCount(NotificationCountType.Highlight, roomData.highlight_count);
}
if (roomData.bump_stamp) room.setBumpStamp(roomData.bump_stamp);
if (Number.isInteger(roomData.invited_count)) room.currentState.setInvitedMemberCount(roomData.invited_count);
if (Number.isInteger(roomData.joined_count)) room.currentState.setJoinedMemberCount(roomData.joined_count);
if (roomData.invite_state) {
var inviteStateEvents = mapEvents(_this9.client, room.roomId, roomData.invite_state);
yield _this9.injectRoomEvents(room, inviteStateEvents);
if (roomData.initial) {
room.recalculate();
_this9.client.store.storeRoom(room);
_this9.client.emit(ClientEvent.Room, room);
}
inviteStateEvents.forEach((e) => {
_this9.client.emit(ClientEvent.Event, e);
});
return;
}
if (roomData.limited) {
var _roomData$prev_batch;
room.getLiveTimeline().setPaginationToken((_roomData$prev_batch = roomData.prev_batch) !== null && _roomData$prev_batch !== void 0 ? _roomData$prev_batch : null, EventTimeline.BACKWARDS);
}
yield _this9.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live);
room.addEphemeralEvents(ephemeralEvents);
room.updateMyMembership(KnownMembership.Join);
room.setMSC4186SummaryData(roomData.heroes, roomData.joined_count, roomData.invited_count);
room.recalculate();
if (roomData.initial) {
client.store.storeRoom(room);
client.emit(ClientEvent.Room, room);
}
_this9.addNotifications(timelineEvents);
var processRoomEvent = /* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (e) {
client.emit(ClientEvent.Event, e);
if (e.isState() && e.getType() == EventType.RoomEncryption && _this9.syncOpts.cryptoCallbacks) yield _this9.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);
});
return function processRoomEvent(_x) {
return _ref.apply(this, arguments);
};
}();
yield promiseMapSeries(stateEvents, processRoomEvent);
yield promiseMapSeries(timelineEvents, processRoomEvent);
ephemeralEvents.forEach(function(e) {
client.emit(ClientEvent.Event, e);
});
room.decryptCriticalEvents();
})();
}
/**
* Injects events into a room's model.
* @param stateEventList - A list of state events. This is the state
* at the *END* of the timeline list if it is supplied.
* @param timelineEventList - A list of timeline events. Lower index
* is earlier in time. Higher index is later.
* @param numLive - the number of events in timelineEventList which just happened,
* supplied from the server.
*/
injectRoomEvents(room, stateEventList) {
var _arguments = arguments, _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
var timelineEventList = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : [];
var numLive = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : 0;
var liveTimeline = room.getLiveTimeline();
var timelineWasEmpty = liveTimeline.getEvents().length == 0;
if (timelineWasEmpty) {
for (var ev of stateEventList) _this0.client.getPushActionsForEvent(ev);
liveTimeline.initialiseState(stateEventList);
}
if (!timelineWasEmpty) {
room.oldState.setStateEvents(stateEventList);
room.currentState.setStateEvents(stateEventList);
}
var liveTimelineEvents = [];
if (numLive > 0) {
liveTimelineEvents = timelineEventList.slice(-1 * numLive);
timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length);
}
yield room.addLiveEvents(timelineEventList, {
fromCache: true,
addToState: false
});
if (liveTimelineEvents.length > 0) yield room.addLiveEvents(liveTimelineEvents, {
fromCache: false,
addToState: false
});
room.recalculate();
_this0.resolveInvites(room);
})();
}
resolveInvites(room) {
if (!room || !this.opts.resolveInvitesToProfiles) return;
var client = this.client;
room.getMembersWithMembership(KnownMembership.Invite).forEach(function(member) {
if (member.requestedProfileInfo) return;
member.requestedProfileInfo = true;
var user = client.getUser(member.userId);
var promise;
if (user) promise = Promise.resolve({
avatar_url: user.avatarUrl,
displayname: user.displayName
});
else promise = client.getProfileInfo(member.userId);
promise.then(function(info) {
var inviteEvent = member.events.member;
if (inviteEvent.getContent().membership !== KnownMembership.Invite) return;
inviteEvent.getContent().avatar_url = info.avatar_url;
inviteEvent.getContent().displayname = info.displayname;
member.setMembershipEvent(inviteEvent, room.currentState);
}, function(_err) {});
});
}
retryImmediately() {
return true;
}
/**
* Main entry point. Blocks until stop() is called.
*/
sync() {
var _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
_this1.syncOpts.logger.debug("Sliding sync init loop");
while (!_this1.client.isGuest()) try {
_this1.syncOpts.logger.debug("Getting push rules...");
var result = yield _this1.client.getPushRules();
_this1.syncOpts.logger.debug("Got push rules");
_this1.client.pushRules = result;
break;
} catch (err) {
_this1.syncOpts.logger.error("Getting push rules failed", err);
if (_this1.shouldAbortSync(err)) return;
}
yield _this1.slidingSync.start();
})();
}
/**
* Stops the sync object from syncing.
*/
stop() {
this.syncOpts.logger.debug("SyncApi.stop");
this.slidingSync.stop();
}
/**
* Sets the sync state and emits an event to say so
* @param newState - The new state string
* @param data - Object of additional data to emit in the event
*/
updateSyncState(newState, data) {
var old = this.syncState;
this.syncState = newState;
this.syncStateData = data;
this.client.emit(ClientEvent.Sync, this.syncState, old, data);
}
/**
* Takes a list of timelineEvents and adds and adds to notifEvents
* as appropriate.
* This must be called after the room the events belong to has been stored.
*
* @param timelineEventList - A list of timeline events. Lower index
* is earlier in time. Higher index is later.
*/
addNotifications(timelineEventList) {
if (!this.client.getNotifTimelineSet()) return;
for (var timelineEvent of timelineEventList) {
var pushActions = this.client.getPushActionsForEvent(timelineEvent);
if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) this.notifEvents.push(timelineEvent);
}
}
/**
* Purge any events in the notifEvents array. Used after a /sync has been complete.
* This should not be called at a per-room scope (e.g in onRoomData) because otherwise the ordering
* will be messed up e.g room A gets a bing, room B gets a newer bing, but both in the same /sync
* response. If we purge at a per-room scope then we could process room B before room A leading to
* room B appearing earlier in the notifications timeline, even though it has the higher origin_server_ts.
*/
purgeNotifications() {
this.notifEvents.sort(function(a, b) {
return a.getTs() - b.getTs();
});
this.notifEvents.forEach((event) => {
var _this$client$getNotif;
(_this$client$getNotif = this.client.getNotifTimelineSet()) === null || _this$client$getNotif === void 0 || _this$client$getNotif.addLiveEvent(event, { addToState: false });
});
this.notifEvents = [];
}
};
function ensureNameEvent(client, roomId, roomData) {
if (!roomData.name) return roomData;
for (var stateEvent of roomData.required_state) if (stateEvent.type === EventType.RoomName && stateEvent.state_key === "") {
stateEvent.content = { name: roomData.name };
return roomData;
}
roomData.required_state.push({
event_id: "$fake-sliding-sync-name-event-" + roomId,
state_key: "",
type: EventType.RoomName,
content: { name: roomData.name },
sender: client.getUserId(),
origin_server_ts: (/* @__PURE__ */ new Date()).getTime()
});
return roomData;
}
function mapEvents(client, roomId, events) {
var decrypt = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : true;
var mapper = client.getEventMapper({ decrypt });
return events.map(function(e) {
e.room_id = roomId;
return mapper(e);
});
}
function processEphemeralEvents(client, roomId, ephEvents) {
var ephemeralEvents = mapEvents(client, roomId, ephEvents);
var room = client.getRoom(roomId);
if (!room) {
logger$2.warn("got ephemeral events for room but room doesn't exist on client:", roomId);
return;
}
room.addEphemeralEvents(ephemeralEvents);
ephemeralEvents.forEach((e) => {
client.emit(ClientEvent.Event, e);
});
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/@types/beacon.js
/**
* Beacon info and beacon event types as described in MSC3672
* https://github.com/matrix-org/matrix-spec-proposals/pull/3672
*/
/**
* Beacon info events are state events.
* We have two requirements for these events:
* 1. they can only be written by their owner
* 2. a user can have an arbitrary number of beacon_info events
*
* 1. is achieved by setting the state_key to the owners mxid.
* Event keys in room state are a combination of `type` + `state_key`.
* To achieve an arbitrary number of only owner-writable state events
* we introduce a variable suffix to the event type
*
* @example
* ```
* {
* "type": "m.beacon_info.@matthew:matrix.org.1",
* "state_key": "@matthew:matrix.org",
* "content": {
* "m.beacon_info": {
* "description": "The Matthew Tracker",
* "timeout": 86400000,
* },
* // more content as described below
* }
* },
* {
* "type": "m.beacon_info.@matthew:matrix.org.2",
* "state_key": "@matthew:matrix.org",
* "content": {
* "m.beacon_info": {
* "description": "Another different Matthew tracker",
* "timeout": 400000,
* },
* // more content as described below
* }
* }
* ```
*/
/**
* Non-variable type for m.beacon_info event content
*/
var M_BEACON_INFO = new UnstableValue$3("m.beacon_info", "org.matrix.msc3672.beacon_info");
var M_BEACON = new UnstableValue$3("m.beacon", "org.matrix.msc3672.beacon");
/**
* m.beacon_info Event example from the spec
* https://github.com/matrix-org/matrix-spec-proposals/pull/3672
* @example
* ```
* {
* "type": "m.beacon_info",
* "state_key": "@matthew:matrix.org",
* "content": {
* "m.beacon_info": {
* "description": "The Matthew Tracker", // same as an `m.location` description
* "timeout": 86400000, // how long from the last event until we consider the beacon inactive in milliseconds
* },
* "m.ts": 1436829458432, // creation timestamp of the beacon on the client
* "m.asset": {
* "type": "m.self" // the type of asset being tracked as per MSC3488
* }
* }
* }
* ```
*/
/**
* m.beacon_info.* event content
*/
/**
* m.beacon event example
* https://github.com/matrix-org/matrix-spec-proposals/pull/3672
* @example
* ```
* {
* "type": "m.beacon",
* "sender": "@matthew:matrix.org",
* "content": {
* "m.relates_to": { // from MSC2674: https://github.com/matrix-org/matrix-doc/pull/2674
* "rel_type": "m.reference", // from MSC3267: https://github.com/matrix-org/matrix-doc/pull/3267
* "event_id": "$beacon_info"
* },
* "m.location": {
* "uri": "geo:51.5008,0.1247;u=35",
* "description": "Arbitrary beacon information"
* },
* "m.ts": 1636829458432,
* }
* }
* ```
*/
/**
* Content of an m.beacon event
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/scheduler.js
/**
* This is an internal module which manages queuing, scheduling and retrying
* of requests.
*/
var DEBUG = false;
/**
* The function to invoke to process (send) events in the queue.
* @param event - The event to send.
* @returns Resolved/rejected depending on the outcome of the request.
*/
var MatrixScheduler = class MatrixScheduler {
/**
* Default retry algorithm for the matrix scheduler. Retries events up to 4 times with exponential backoff.
* @param attempts - Number of attempts that have been made, including the one that just failed (ie. starting at 1)
* @see retryAlgorithm
*/
static RETRY_BACKOFF_RATELIMIT(event, attempts, err) {
return calculateRetryBackoff(err, attempts, false);
}
/**
* Queues `m.room.message` events and lets other events continue
* concurrently.
* @see queueAlgorithm
*/
static QUEUE_MESSAGES(event) {
if (event.getType() === EventType.RoomMessage || event.hasAssociation()) return "message";
return null;
}
/**
* Construct a scheduler for Matrix. Requires
* {@link MatrixScheduler#setProcessFunction} to be provided
* with a way of processing events.
* @param retryAlgorithm - Optional. The retry
* algorithm to apply when determining when to try to send an event again.
* Defaults to {@link MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.
* @param queueAlgorithm - Optional. The queuing
* algorithm to apply when determining which events should be sent before the
* given event. Defaults to {@link MatrixScheduler.QUEUE_MESSAGES}.
*/
constructor() {
var retryAlgorithm = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : MatrixScheduler.RETRY_BACKOFF_RATELIMIT;
var queueAlgorithm = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : MatrixScheduler.QUEUE_MESSAGES;
this.retryAlgorithm = retryAlgorithm;
this.queueAlgorithm = queueAlgorithm;
(0, import_defineProperty.default)(this, "queues", {});
(0, import_defineProperty.default)(this, "activeQueues", []);
(0, import_defineProperty.default)(this, "procFn", null);
(0, import_defineProperty.default)(this, "processQueue", (queueName) => {
var obj = this.peekNextEvent(queueName);
if (!obj) {
this.disableQueue(queueName);
return;
}
debuglog("Queue '%s' has %s pending events", queueName, this.queues[queueName].length);
Promise.resolve().then(() => {
return this.procFn(obj.event);
}).then((res) => {
this.removeNextEvent(queueName);
debuglog("Queue '%s' sent event %s", queueName, obj.event.getId());
obj.resolvers.resolve(res);
this.processQueue(queueName);
}, (err) => {
obj.attempts += 1;
var waitTimeMs = this.retryAlgorithm(obj.event, obj.attempts, err);
debuglog("retry(%s) err=%s event_id=%s waitTime=%s", obj.attempts, err, obj.event.getId(), waitTimeMs);
if (waitTimeMs === -1) {
logger$2.info("Queue '%s' giving up on event %s", queueName, obj.event.getId());
this.clearQueue(queueName, err);
} else setTimeout(this.processQueue, waitTimeMs, queueName);
});
});
}
/**
* Retrieve a queue based on an event. The event provided does not need to be in
* the queue.
* @param event - An event to get the queue for.
* @returns A shallow copy of events in the queue or null.
* Modifying this array will not modify the list itself. Modifying events in
* this array <i>will</i> modify the underlying event in the queue.
* @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.
*/
getQueueForEvent(event) {
var name = this.queueAlgorithm(event);
if (!name || !this.queues[name]) return null;
return this.queues[name].map(function(obj) {
return obj.event;
});
}
/**
* Remove this event from the queue. The event is equal to another event if they
* have the same ID returned from event.getId().
* @param event - The event to remove.
* @returns True if this event was removed.
*/
removeEventFromQueue(event) {
var name = this.queueAlgorithm(event);
if (!name || !this.queues[name]) return false;
var removed = false;
removeElement(this.queues[name], (element) => {
if (element.event.getId() === event.getId()) {
removed = true;
return true;
}
return false;
});
return removed;
}
/**
* Set the process function. Required for events in the queue to be processed.
* If set after events have been added to the queue, this will immediately start
* processing them.
* @param fn - The function that can process events
* in the queue.
*/
setProcessFunction(fn) {
this.procFn = fn;
this.startProcessingQueues();
}
/**
* Queue an event if it is required and start processing queues.
* @param event - The event that may be queued.
* @returns A promise if the event was queued, which will be
* resolved or rejected in due time, else null.
*/
queueEvent(event) {
var queueName = this.queueAlgorithm(event);
if (!queueName) return null;
if (!this.queues[queueName]) this.queues[queueName] = [];
var eventResolvers = Promise.withResolvers();
this.queues[queueName].push({
event,
resolvers: eventResolvers,
attempts: 0
});
debuglog("Queue algorithm dumped event %s into queue '%s'", event.getId(), queueName);
this.startProcessingQueues();
return eventResolvers.promise;
}
startProcessingQueues() {
if (!this.procFn) return;
Object.keys(this.queues).filter((queueName) => {
return this.activeQueues.indexOf(queueName) === -1 && this.queues[queueName].length > 0;
}).forEach((queueName) => {
this.activeQueues.push(queueName);
debuglog("Spinning up queue: '%s'", queueName);
this.processQueue(queueName);
});
}
disableQueue(queueName) {
var index = this.activeQueues.indexOf(queueName);
if (index >= 0) this.activeQueues.splice(index, 1);
logger$2.info("Stopping queue '%s' as it is now empty", queueName);
}
clearQueue(queueName, err) {
logger$2.info("clearing queue '%s'", queueName);
var obj;
while (obj = this.removeNextEvent(queueName)) obj.resolvers.reject(err);
this.disableQueue(queueName);
}
peekNextEvent(queueName) {
var queue = this.queues[queueName];
if (!Array.isArray(queue)) return;
return queue[0];
}
removeNextEvent(queueName) {
var queue = this.queues[queueName];
if (!Array.isArray(queue)) return;
return queue.shift();
}
};
/* istanbul ignore next */
function debuglog() {
if (DEBUG) logger$2.log(...arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/ToDeviceMessageQueue.js
var MAX_BATCH_SIZE = 20;
/**
* Maintains a queue of outgoing to-device messages, sending them
* as soon as the homeserver is reachable.
*/
var ToDeviceMessageQueue = class {
constructor(client, logger) {
var _this = this;
this.client = client;
this.logger = logger;
(0, import_defineProperty.default)(this, "sending", false);
(0, import_defineProperty.default)(this, "running", true);
(0, import_defineProperty.default)(this, "retryTimeout", null);
(0, import_defineProperty.default)(this, "retryAttempts", 0);
(0, import_defineProperty.default)(this, "sendQueue", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
if (_this.retryTimeout !== null) clearTimeout(_this.retryTimeout);
_this.retryTimeout = null;
if (_this.sending || !_this.running) return;
_this.logger.debug("Attempting to send queued to-device messages");
_this.sending = true;
var headBatch;
try {
while (_this.running) {
headBatch = yield _this.client.store.getOldestToDeviceBatch();
if (headBatch === null) break;
yield _this.sendBatch(headBatch);
yield _this.client.store.removeToDeviceBatch(headBatch.id);
_this.retryAttempts = 0;
}
if (!_this.running) return;
_this.logger.debug("All queued to-device messages sent");
} catch (e) {
++_this.retryAttempts;
var retryDelay = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, _this.retryAttempts, e);
if (retryDelay === -1) {
if (Math.floor(e.httpStatus / 100) === 4) {
_this.logger.error("Fatal error when sending to-device message - dropping to-device batch!", e);
yield _this.client.store.removeToDeviceBatch(headBatch.id);
} else _this.logger.info("Automatic retry limit reached for to-device messages.");
return;
}
_this.logger.info("Failed to send batch of to-device messages. Will retry in ".concat(retryDelay, "ms"), e);
_this.retryTimeout = setTimeout(_this.sendQueue, retryDelay);
} finally {
_this.sending = false;
}
}));
/**
* Listen to sync state changes and automatically resend any pending events
* once syncing is resumed
*/
(0, import_defineProperty.default)(this, "onResumedSync", (state, oldState) => {
if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {
this.logger.info("Resuming queue after resumed sync");
this.sendQueue();
}
});
}
start() {
this.running = true;
this.sendQueue();
this.client.on(ClientEvent.Sync, this.onResumedSync);
}
stop() {
this.running = false;
if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);
this.retryTimeout = null;
this.client.removeListener(ClientEvent.Sync, this.onResumedSync);
}
queueBatch(batch) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var batches = [];
for (var i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) {
var batchWithTxnId = {
eventType: batch.eventType,
batch: batch.batch.slice(i, i + MAX_BATCH_SIZE),
txnId: _this2.client.makeTxnId()
};
batches.push(batchWithTxnId);
var msgmap = batchWithTxnId.batch.map((msg) => "".concat(msg.userId, "/").concat(msg.deviceId, " (msgid ").concat(msg.payload[ToDeviceMessageId], ")"));
_this2.logger.info("Enqueuing batch of to-device messages. type=".concat(batch.eventType, " txnid=").concat(batchWithTxnId.txnId), msgmap);
}
yield _this2.client.store.saveToDeviceBatches(batches);
_this2.sendQueue();
})();
}
/**
* Attempts to send a batch of to-device messages.
*/
sendBatch(batch) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
var contentMap = new MapWithDefault(() => /* @__PURE__ */ new Map());
for (var item of batch.batch) contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);
_this3.logger.info("Sending batch of ".concat(batch.batch.length, " to-device messages with ID ").concat(batch.id, " and txnId ").concat(batch.txnId));
yield _this3.client.sendToDevice(batch.eventType, contentMap, batch.txnId);
})();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/invites-ignorer-types.js
var POLICIES_ACCOUNT_EVENT_TYPE = new import_lib$1.UnstableValue("m.policies", "org.matrix.msc3847.policies");
var IGNORE_INVITES_ACCOUNT_EVENT_KEY = new import_lib$1.UnstableValue("m.ignore.invites", "org.matrix.msc3847.ignore.invites");
var PolicyRecommendation = /* @__PURE__ */ function(PolicyRecommendation) {
PolicyRecommendation["Ban"] = "m.ban";
return PolicyRecommendation;
}({});
/**
* The various scopes for policies.
*/
var PolicyScope = /* @__PURE__ */ function(PolicyScope) {
/**
* The policy deals with an individual user, e.g. reject invites
* from this user.
*/
PolicyScope["User"] = "m.policy.user";
/**
* The policy deals with a room, e.g. reject invites towards
* a specific room.
*/
PolicyScope["Room"] = "m.policy.room";
/**
* The policy deals with a server, e.g. reject invites from
* this server.
*/
PolicyScope["Server"] = "m.policy.server";
return PolicyScope;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/invites-ignorer.js
var scopeToEventTypeMap = {
[PolicyScope.User]: EventType.PolicyRuleUser,
[PolicyScope.Room]: EventType.PolicyRuleRoom,
[PolicyScope.Server]: EventType.PolicyRuleServer
};
/**
* A container for ignored invites.
*
* # Performance
*
* This implementation is extremely naive. It expects that we are dealing
* with a very short list of sources (e.g. only one). If real-world
* applications turn out to require longer lists, we may need to rework
* our data structures.
*/
var IgnoredInvites = class {
constructor(client) {
this.client = client;
}
/**
* Add a new rule.
*
* @param scope - The scope for this rule.
* @param entity - The entity covered by this rule. Globs are supported.
* @param reason - A human-readable reason for introducing this new rule.
* @returns The event id for the new rule.
*/
addRule(scope, entity, reason) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var target = yield _this.getOrCreateTargetRoom();
return (yield _this.client.sendStateEvent(target.roomId, scopeToEventTypeMap[scope], {
entity,
reason,
recommendation: PolicyRecommendation.Ban
})).event_id;
})();
}
/**
* Remove a rule.
*/
removeRule(event) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this2.client.redactEvent(event.getRoomId(), event.getId());
})();
}
/**
* Add a new room to the list of sources. If the user isn't a member of the
* room, attempt to join it.
*
* @param roomId - A valid room id. If this room is already in the list
* of sources, it will not be duplicated.
* @returns `true` if the source was added, `false` if it was already present.
* @throws If `roomId` isn't the id of a room that the current user is already
* member of or can join.
*
* # Safety
*
* This method will rewrite the `Policies` object in the user's account data.
* This rewrite is inherently racy and could overwrite or be overwritten by
* other concurrent rewrites of the same object.
*/
addSource(roomId) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this3.client.joinRoom(roomId);
var sources = (yield _this3.getOrCreateSourceRooms()).map((room) => room.roomId);
if (sources.includes(roomId)) return false;
sources.push(roomId);
yield _this3.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {
ignoreInvitesPolicies.sources = sources;
});
return true;
})();
}
/**
* Find out whether an invite should be ignored.
*
* @param params
* @param params.sender - The user id for the user who issued the invite.
* @param params.roomId - The room to which the user is invited.
* @returns A rule matching the entity, if any was found, `null` otherwise.
*/
getRuleForInvite(_ref) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { sender, roomId } = _ref;
var policyRooms = yield _this4.getOrCreateSourceRooms();
var senderServer = sender.split(":")[1];
var roomServer = roomId.split(":")[1];
for (var room of policyRooms) {
var state = room.getUnfilteredTimelineSet().getLiveTimeline().getState(EventTimeline.FORWARDS);
for (var { scope, entities } of [
{
scope: PolicyScope.Room,
entities: [roomId]
},
{
scope: PolicyScope.User,
entities: [sender]
},
{
scope: PolicyScope.Server,
entities: [senderServer, roomServer]
}
]) for (var event of state.getStateEvents(scopeToEventTypeMap[scope])) {
var content = event.getContent();
if ((content === null || content === void 0 ? void 0 : content.recommendation) != PolicyRecommendation.Ban) continue;
var glob = content === null || content === void 0 ? void 0 : content.entity;
if (!glob) continue;
var regexp = void 0;
try {
regexp = new RegExp(globToRegexp(glob));
} catch (_unused) {
continue;
}
for (var entity of entities) if (entity && regexp.test(entity)) return event;
}
}
return null;
})();
}
/**
* Get the target room, i.e. the room in which any new rule should be written.
*
* If there is no target room setup, a target room is created.
*
* Note: This method is public for testing reasons. Most clients should not need
* to call it directly.
*
* # Safety
*
* This method will rewrite the `Policies` object in the user's account data.
* This rewrite is inherently racy and could overwrite or be overwritten by
* other concurrent rewrites of the same object.
*/
getOrCreateTargetRoom() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var target = _this5.getIgnoreInvitesPolicies().target;
if (typeof target !== "string") target = null;
if (target) {
var room = _this5.client.getRoom(target);
if (room) return room;
else target = null;
}
target = (yield _this5.client.createRoom({
name: "Individual Policy Room",
preset: Preset.PrivateChat
})).room_id;
yield _this5.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {
ignoreInvitesPolicies.target = target;
});
return _this5.client.getRoom(target);
})();
}
/**
* Get the list of source rooms, i.e. the rooms from which rules need to be read.
*
* If no source rooms are setup, the target room is used as sole source room.
*
* Note: This method is public for testing reasons. Most clients should not need
* to call it directly.
*
* # Safety
*
* This method will rewrite the `Policies` object in the user's account data.
* This rewrite is inherently racy and could overwrite or be overwritten by
* other concurrent rewrites of the same object.
*/
getOrCreateSourceRooms() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var sources = _this6.getIgnoreInvitesPolicies().sources;
var hasChanges = false;
if (!Array.isArray(sources)) {
hasChanges = true;
sources = [];
}
var sourceRooms = sources.filter((roomId) => typeof roomId === "string").map((roomId) => _this6.client.getRoom(roomId)).filter((room) => !!room);
if (sourceRooms.length != sources.length) hasChanges = true;
if (sourceRooms.length == 0) {
var target = yield _this6.getOrCreateTargetRoom();
hasChanges = true;
sourceRooms = [target];
}
if (hasChanges) yield _this6.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {
ignoreInvitesPolicies.sources = sources;
});
return sourceRooms;
})();
}
/**
* Fetch the `IGNORE_INVITES_POLICIES` object from account data.
*
* If both an unstable prefix version and a stable prefix version are available,
* it will return the stable prefix version preferentially.
*
* The result is *not* validated but is guaranteed to be a non-null object.
*
* @returns A non-null object.
*/
getIgnoreInvitesPolicies() {
return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies;
}
/**
* Modify in place the `IGNORE_INVITES_POLICIES` object from account data.
*/
withIgnoreInvitesPolicies(cb) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { policies, ignoreInvitesPolicies } = _this7.getPoliciesAndIgnoreInvitesPolicies();
cb(ignoreInvitesPolicies);
policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;
yield _this7.client.setAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name, policies);
})();
}
/**
* As `getIgnoreInvitesPolicies` but also return the `POLICIES_ACCOUNT_EVENT_TYPE`
* object.
*/
getPoliciesAndIgnoreInvitesPolicies() {
var policies = {};
for (var key of [POLICIES_ACCOUNT_EVENT_TYPE.name, POLICIES_ACCOUNT_EVENT_TYPE.altName]) {
var _this$client$getAccou;
if (!key) continue;
var value = (_this$client$getAccou = this.client.getAccountData(key)) === null || _this$client$getAccou === void 0 ? void 0 : _this$client$getAccou.getContent();
if (value) {
policies = value;
break;
}
}
var ignoreInvitesPolicies = {};
var hasIgnoreInvitesPolicies = false;
for (var _key of [IGNORE_INVITES_ACCOUNT_EVENT_KEY.name, IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]) {
if (!_key) continue;
var _value = policies[_key];
if (_value && typeof _value == "object") {
ignoreInvitesPolicies = _value;
hasIgnoreInvitesPolicies = true;
break;
}
}
if (!hasIgnoreInvitesPolicies) policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;
return {
policies,
ignoreInvitesPolicies
};
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/rust-crypto/constants.js
/** The prefix used on indexeddbs created by rust-crypto */
var RUST_SDK_STORE_PREFIX = "matrix-js-sdk";
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto-api/verification.js
/**
* An incoming, or outgoing, request to verify a user or a device via cross-signing.
*/
/** Events emitted by {@link VerificationRequest}. */
var VerificationRequestEvent = /* @__PURE__ */ function(VerificationRequestEvent) {
/**
* Fires whenever the state of the request object has changed.
*
* There is no payload to the event.
*/
VerificationRequestEvent["Change"] = "change";
return VerificationRequestEvent;
}({});
/**
* Listener type map for {@link VerificationRequestEvent}s.
*
* @internal
*/
/** The current phase of a verification request. */
var VerificationPhase = /* @__PURE__ */ function(VerificationPhase) {
/** Initial state: no event yet exchanged */
VerificationPhase[VerificationPhase["Unsent"] = 1] = "Unsent";
/** An `m.key.verification.request` event has been sent or received */
VerificationPhase[VerificationPhase["Requested"] = 2] = "Requested";
/** An `m.key.verification.ready` event has been sent or received, indicating the verification request is accepted. */
VerificationPhase[VerificationPhase["Ready"] = 3] = "Ready";
/**
* The verification is in flight.
*
* This means that an `m.key.verification.start` event has been sent or received, choosing a verification method;
* however the verification has not yet completed or been cancelled.
*/
VerificationPhase[VerificationPhase["Started"] = 4] = "Started";
/**
* An `m.key.verification.cancel` event has been sent or received at any time before the `done` event, cancelling
* the verification request
*/
VerificationPhase[VerificationPhase["Cancelled"] = 5] = "Cancelled";
/**
* The verification request is complete.
*
* Normally this means that `m.key.verification.done` events have been sent and received.
*/
VerificationPhase[VerificationPhase["Done"] = 6] = "Done";
return VerificationPhase;
}({});
/**
* A `Verifier` is responsible for performing the verification using a particular method, such as via QR code or SAS
* (emojis).
*
* A verifier object can be created by calling `VerificationRequest.beginVerification`; one is also created
* automatically when a `m.key.verification.start` event is received for an existing VerificationRequest.
*
* Once a verifier object is created, the verification can be started by calling the {@link Verifier#verify} method.
*/
/** Events emitted by {@link Verifier} */
var VerifierEvent = /* @__PURE__ */ function(VerifierEvent) {
/**
* The verification has been cancelled, by us or the other side.
*
* The payload is either an {@link Error}, or an (incoming or outgoing) {@link MatrixEvent}, depending on
* unspecified reasons.
*/
VerifierEvent["Cancel"] = "cancel";
/**
* SAS data has been exchanged and should be displayed to the user.
*
* The payload is the {@link ShowSasCallbacks} object.
*/
VerifierEvent["ShowSas"] = "show_sas";
/**
* The user should confirm if the other side has scanned our QR code.
*
* The payload is the {@link ShowQrCodeCallbacks} object.
*/
VerifierEvent["ShowReciprocateQr"] = "show_reciprocate_qr";
return VerifierEvent;
}({});
//#endregion
//#region node_modules/base-x/src/esm/index.js
function base(ALPHABET) {
if (ALPHABET.length >= 255) throw new TypeError("Alphabet too long");
const BASE_MAP = new Uint8Array(256);
for (let j = 0; j < BASE_MAP.length; j++) BASE_MAP[j] = 255;
for (let i = 0; i < ALPHABET.length; i++) {
const x = ALPHABET.charAt(i);
const xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) throw new TypeError(x + " is ambiguous");
BASE_MAP[xc] = i;
}
const BASE = ALPHABET.length;
const LEADER = ALPHABET.charAt(0);
const FACTOR = Math.log(BASE) / Math.log(256);
const iFACTOR = Math.log(256) / Math.log(BASE);
function encode(source) {
if (source instanceof Uint8Array) {} else if (ArrayBuffer.isView(source)) source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
else if (Array.isArray(source)) source = Uint8Array.from(source);
if (!(source instanceof Uint8Array)) throw new TypeError("Expected Uint8Array");
if (source.length === 0) return "";
let zeroes = 0;
let length = 0;
let pbegin = 0;
const pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
const size = (pend - pbegin) * iFACTOR + 1 >>> 0;
const b58 = new Uint8Array(size);
while (pbegin !== pend) {
let carry = source[pbegin];
let i = 0;
for (let it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {
carry += 256 * b58[it1] >>> 0;
b58[it1] = carry % BASE >>> 0;
carry = carry / BASE >>> 0;
}
if (carry !== 0) throw new Error("Non-zero carry");
length = i;
pbegin++;
}
let it2 = size - length;
while (it2 !== size && b58[it2] === 0) it2++;
let str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) str += ALPHABET.charAt(b58[it2]);
return str;
}
function decodeUnsafe(source) {
if (typeof source !== "string") throw new TypeError("Expected String");
if (source.length === 0) return new Uint8Array();
let psz = 0;
let zeroes = 0;
let length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
const size = (source.length - psz) * FACTOR + 1 >>> 0;
const b256 = new Uint8Array(size);
while (psz < source.length) {
const charCode = source.charCodeAt(psz);
if (charCode > 255) return;
let carry = BASE_MAP[charCode];
if (carry === 255) return;
let i = 0;
for (let it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {
carry += BASE * b256[it3] >>> 0;
b256[it3] = carry % 256 >>> 0;
carry = carry / 256 >>> 0;
}
if (carry !== 0) throw new Error("Non-zero carry");
length = i;
psz++;
}
let it4 = size - length;
while (it4 !== size && b256[it4] === 0) it4++;
const vch = new Uint8Array(zeroes + (size - it4));
let j = zeroes;
while (it4 !== size) vch[j++] = b256[it4++];
return vch;
}
function decode(string) {
const buffer = decodeUnsafe(string);
if (buffer) return buffer;
throw new Error("Non-base" + BASE + " character");
}
return {
encode,
decodeUnsafe,
decode
};
}
var esm_default = base("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto-api/recovery-key.js
var OLM_RECOVERY_KEY_PREFIX = [139, 1];
var KEY_SIZE = 32;
/**
* Encode a recovery key using the Matrix {@link https://spec.matrix.org/v1.11/appendices/#cryptographic-key-representation | Cryptographic key representation}
* @param key
*/
function encodeRecoveryKey(key) {
var _base58key$match;
var buf = new Uint8Array(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1);
buf.set(OLM_RECOVERY_KEY_PREFIX, 0);
buf.set(key, OLM_RECOVERY_KEY_PREFIX.length);
var parity = 0;
for (var i = 0; i < buf.length - 1; ++i) parity ^= buf[i];
buf[buf.length - 1] = parity;
return (_base58key$match = esm_default.encode(buf).match(/.{1,4}/g)) === null || _base58key$match === void 0 ? void 0 : _base58key$match.join(" ");
}
/**
* Decode a recovery key encoded with the Matrix {@link https://spec.matrix.org/v1.11/appendices/#cryptographic-key-representation | Cryptographic key representation} encoding.
* @param recoveryKey
*/
function decodeRecoveryKey(recoveryKey) {
var result = esm_default.decode(recoveryKey.replace(/ /g, ""));
var parity = 0;
for (var b of result) parity ^= b;
if (parity !== 0) throw new Error("Incorrect parity");
for (var i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) throw new Error("Incorrect prefix");
if (result.length !== OLM_RECOVERY_KEY_PREFIX.length + KEY_SIZE + 1) throw new Error("Incorrect length");
return Uint8Array.from(result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + KEY_SIZE));
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto-api/key-passphrase.js
var DEFAULT_BIT_SIZE = 256;
/**
* Derive a recovery key from a passphrase and salt using PBKDF2.
* @see https://spec.matrix.org/v1.11/client-server-api/#deriving-keys-from-passphrases
*
* @param passphrase - The passphrase to derive the key from
* @param salt - The salt to use in the derivation
* @param iterations - The number of iterations to use in the derivation
* @param numBits - The number of bits to derive
*/
function deriveRecoveryKeyFromPassphrase(_x, _x2, _x3) {
return _deriveRecoveryKeyFromPassphrase.apply(this, arguments);
}
function _deriveRecoveryKeyFromPassphrase() {
_deriveRecoveryKeyFromPassphrase = (0, import_asyncToGenerator.default)(function* (passphrase, salt, iterations) {
var numBits = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : DEFAULT_BIT_SIZE;
if (!globalThis.crypto.subtle || !TextEncoder) throw new Error("Password-based backup is not available on this platform");
var key = yield globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(passphrase), { name: "PBKDF2" }, false, ["deriveBits"]);
var keybits = yield globalThis.crypto.subtle.deriveBits({
name: "PBKDF2",
salt: new TextEncoder().encode(salt),
iterations,
hash: "SHA-512"
}, key, numBits);
return new Uint8Array(keybits);
});
return _deriveRecoveryKeyFromPassphrase.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto-api/CryptoEvent.js
/**
* Cryptography-related events emitted by the {@link matrix.MatrixClient}.
*/
var CryptoEvent = /* @__PURE__ */ function(CryptoEvent) {
/**
* Fires when the trust status of a user changes.
* The payload is a pair (userId, userTrustLevel). The trust level is one of the values from UserVerificationStatus.
*/
CryptoEvent["UserTrustStatusChanged"] = "userTrustStatusChanged";
/**
* Fires when the key backup status changes.
* The payload is a boolean indicating whether the key backup is enabled.
*/
CryptoEvent["KeyBackupStatus"] = "crypto.keyBackupStatus";
/**
* Fires when we failed to back up the keys
* The payload is the error code of the error that occurred.
*/
CryptoEvent["KeyBackupFailed"] = "crypto.keyBackupFailed";
/**
* Fires when the number of sessions that can be backed up changes.
* The payload is the remaining number of sessions that can be backed up.
*/
CryptoEvent["KeyBackupSessionsRemaining"] = "crypto.keyBackupSessionsRemaining";
/**
* Fires when a new valid backup decryption key is in cache.
* This will happen when a secret is received from another session, from secret storage,
* or when a new backup is created from this session.
*
* The payload is the version of the backup for which we have the key for.
*
* This event is only fired by the rust crypto backend.
*/
CryptoEvent["KeyBackupDecryptionKeyCached"] = "crypto.keyBackupDecryptionKeyCached";
/**
* Fires when a key verification request is received.
* The payload is a VerificationRequest object representing the request.
*/
CryptoEvent["VerificationRequestReceived"] = "crypto.verificationRequestReceived";
/** @deprecated Use {@link DevicesUpdated} instead when using rust crypto */
CryptoEvent["WillUpdateDevices"] = "crypto.willUpdateDevices";
/**
* Fires whenever the stored devices for a user have been updated
* The payload is a pair (userIds, initialFetch).
*/
CryptoEvent["DevicesUpdated"] = "crypto.devicesUpdated";
/**
* Fires when the user's cross-signing keys have changed or cross-signing
* has been enabled/disabled. The client can use getStoredCrossSigningForUser
* with the user ID of the logged in user to check if cross-signing is
* enabled on the account. If enabled, it can test whether the current key
* is trusted using with checkUserTrust with the user ID of the logged
* in user. The checkOwnCrossSigningTrust function may be used to reconcile
* the trust in the account key.
*
* The cross-signing API is currently UNSTABLE and may change without notice.
* @experimental
*/
CryptoEvent["KeysChanged"] = "crossSigning.keysChanged";
/**
* Fires when data is being migrated from legacy crypto to rust crypto.
*
* The payload is a pair `(progress, total)`, where `progress` is the number of steps completed so far, and
* `total` is the total number of steps. When migration is complete, a final instance of the event is emitted, with
* `progress === total === -1`.
*/
CryptoEvent["LegacyCryptoStoreMigrationProgress"] = "crypto.legacyCryptoStoreMigrationProgress";
/**
* Fires when a new dehydrated device is created locally.
*
* After the client calls {@link CryptoApi.startDehydration}, this event
* will be fired every time a new dehydrated device is created. It may fire
* before `startDehydration` returns.
*/
CryptoEvent["DehydratedDeviceCreated"] = "dehydration.DehydratedDeviceCreated";
/**
* Fires when a new dehydrated device is successfully uploaded to the server.
*
* This should fire shortly after {@link DehydratedDeviceCreated} fires. If
* upload is unsuccessful, this will be reported either by an error thrown
* by {@link CryptoApi.startDehydration} (for errors that happen before
* `startDehydration` returns), or by firing {@link DehydratedDeviceRotationError}
* (for errors that happen during regular rotation of the dehydrated device)
*/
CryptoEvent["DehydratedDeviceUploaded"] = "dehydration.DehydratedDeviceUploaded";
/**
* Fires when rehydration has started.
*
* After the client calls {@link CryptoApi.startDehydration}, this event will
* fire if a dehydrated device is found and we attempt to rehydrate it.
*/
CryptoEvent["RehydrationStarted"] = "dehydration.RehydrationStarted";
/**
* Fires during rehydration, to inform the application of rehydration progress.
*
* The payload is a pair `[roomKeyCount: number, toDeviceCount: number]`,
* where `roomKeyCount` is the number of room keys that have been received
* so far, and `toDeviceCount` is the number of to-device messages received
* so far (including the messages containing room keys).
*/
CryptoEvent["RehydrationProgress"] = "dehydration.RehydrationProgress";
/** Fires when rehydration has completed successfully. */
CryptoEvent["RehydrationCompleted"] = "dehydration.RehydrationCompleted";
/** Fires when there was an error in rehydration.
*
* The payload is an error message as a string.
*/
CryptoEvent["RehydrationError"] = "dehydration.RehydrationError";
/**
* Fires when a dehydrated device key has been cached in the local database.
*/
CryptoEvent["DehydrationKeyCached"] = "dehydration.DehydrationKeyCached";
/**
* Fires when an error occurs during periodic rotation of the dehydrated device.
*
* The payload is an error message as a string.
*/
CryptoEvent["DehydratedDeviceRotationError"] = "dehydration.DehydratedDeviceRotationError";
return CryptoEvent;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto-api/index.js
/**
* `matrix-js-sdk/lib/crypto-api`: End-to-end encryption support.
*
* The most important type is {@link CryptoApi}, an instance of which can be retrieved via
* {@link MatrixClient.getCrypto}.
*
* @packageDocumentation
*/
/**
* The options to start device dehydration.
*/
/**
* Public interface to the cryptography parts of the js-sdk
*
* @remarks Currently, this is a work-in-progress. In time, more methods will be added here.
*/
/** A reason code for a failure to decrypt an event. */
var DecryptionFailureCode = /* @__PURE__ */ function(DecryptionFailureCode) {
/** Message was encrypted with a Megolm session whose keys have not been shared with us. */
DecryptionFailureCode["MEGOLM_UNKNOWN_INBOUND_SESSION_ID"] = "MEGOLM_UNKNOWN_INBOUND_SESSION_ID";
/** A special case of {@link MEGOLM_UNKNOWN_INBOUND_SESSION_ID}: the sender has told us it is withholding the key. */
DecryptionFailureCode["MEGOLM_KEY_WITHHELD"] = "MEGOLM_KEY_WITHHELD";
/** A special case of {@link MEGOLM_KEY_WITHHELD}: the sender has told us it is withholding the key, because the current device is unverified. */
DecryptionFailureCode["MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE"] = "MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE";
/** Message was encrypted with a Megolm session which has been shared with us, but in a later ratchet state. */
DecryptionFailureCode["OLM_UNKNOWN_MESSAGE_INDEX"] = "OLM_UNKNOWN_MESSAGE_INDEX";
/**
* Message was sent before the current device was created; there is no key backup on the server, so this
* decryption failure is expected.
*/
DecryptionFailureCode["HISTORICAL_MESSAGE_NO_KEY_BACKUP"] = "HISTORICAL_MESSAGE_NO_KEY_BACKUP";
/**
* Message was sent before the current device was created; there was a key backup on the server, but we don't
* seem to have access to the backup. (Probably we don't have the right key.)
*/
DecryptionFailureCode["HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED"] = "HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED";
/**
* Message was sent before the current device was created; there was a (usable) key backup on the server, but we
* still can't decrypt. (Either the session isn't in the backup, or we just haven't gotten around to checking yet.)
*/
DecryptionFailureCode["HISTORICAL_MESSAGE_WORKING_BACKUP"] = "HISTORICAL_MESSAGE_WORKING_BACKUP";
/**
* Message was sent when the user was not a member of the room.
*/
DecryptionFailureCode["HISTORICAL_MESSAGE_USER_NOT_JOINED"] = "HISTORICAL_MESSAGE_USER_NOT_JOINED";
/**
* The sender's identity is not verified, but was previously verified.
*/
DecryptionFailureCode["SENDER_IDENTITY_PREVIOUSLY_VERIFIED"] = "SENDER_IDENTITY_PREVIOUSLY_VERIFIED";
/**
* The sender device is not cross-signed. This will only be used if the
* device isolation mode is set to `OnlySignedDevicesIsolationMode`.
*/
DecryptionFailureCode["UNSIGNED_SENDER_DEVICE"] = "UNSIGNED_SENDER_DEVICE";
/**
* We weren't able to link the message back to any known device. This will
* only be used if the device isolation mode is set to `OnlySignedDevicesIsolationMode`.
*/
DecryptionFailureCode["UNKNOWN_SENDER_DEVICE"] = "UNKNOWN_SENDER_DEVICE";
/** Unknown or unclassified error. */
DecryptionFailureCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
return DecryptionFailureCode;
}({});
/** Base {@link DeviceIsolationMode} kind. */
var DeviceIsolationModeKind = /* @__PURE__ */ function(DeviceIsolationModeKind) {
DeviceIsolationModeKind[DeviceIsolationModeKind["AllDevicesIsolationMode"] = 0] = "AllDevicesIsolationMode";
DeviceIsolationModeKind[DeviceIsolationModeKind["OnlySignedDevicesIsolationMode"] = 1] = "OnlySignedDevicesIsolationMode";
return DeviceIsolationModeKind;
}({});
/**
* A type of {@link DeviceIsolationMode}.
*
* Message encryption keys are shared with all devices in the room, except in case of
* verified user problems (see {@link errorOnVerifiedUserProblems}).
*
* Events from all senders are always decrypted (and should be decorated with message shields in case
* of authenticity warnings, see {@link EventEncryptionInfo}).
*/
var AllDevicesIsolationMode = class {
/**
*
* @param errorOnVerifiedUserProblems - Behavior when sharing keys to remote devices.
*
* If set to `true`, sharing keys will fail (i.e. message sending will fail) with an error if:
* - The user was previously verified but is not anymore, or:
* - A verified user has some unverified devices (not cross-signed).
*
* If `false`, the keys will be distributed as usual. In this case, the client UX should display
* warnings to inform the user about problematic devices/users, and stop them hitting this case.
*/
constructor(errorOnVerifiedUserProblems) {
this.errorOnVerifiedUserProblems = errorOnVerifiedUserProblems;
(0, import_defineProperty.default)(this, "kind", DeviceIsolationModeKind.AllDevicesIsolationMode);
}
};
/**
* DeviceIsolationMode represents the mode of device isolation used when encrypting or decrypting messages.
* It can be one of two types: {@link AllDevicesIsolationMode} or {@link OnlySignedDevicesIsolationMode}.
*
* Only supported by rust Crypto.
*/
/**
* Options object for `CryptoApi.bootstrapCrossSigning`.
*/
/**
* Represents the ways in which we trust a user
*/
var UserVerificationStatus = class {
constructor(crossSigningVerified, crossSigningVerifiedBefore, tofu) {
var needsUserApproval = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
this.crossSigningVerified = crossSigningVerified;
this.crossSigningVerifiedBefore = crossSigningVerifiedBefore;
this.tofu = tofu;
/**
* Indicates if the identity has changed in a way that needs user approval.
*
* This happens if the identity has changed since we first saw it, *unless* the new identity has also been verified
* by our user (eg via an interactive verification).
*
* To rectify this, either:
*
* * Conduct a verification of the new identity via {@link CryptoApi.requestVerificationDM}.
* * Pin the new identity, via {@link CryptoApi.pinCurrentUserIdentity}.
*
* @returns true if the identity has changed in a way that needs user approval.
*/
(0, import_defineProperty.default)(this, "needsUserApproval", void 0);
this.needsUserApproval = needsUserApproval;
}
/**
* @returns true if this user is verified via any means
*/
isVerified() {
return this.isCrossSigningVerified();
}
/**
* @returns true if this user is verified via cross signing
*/
isCrossSigningVerified() {
return this.crossSigningVerified;
}
/**
* @returns true if we ever verified this user before (at least for
* the history of verifications observed by this device).
*/
wasCrossSigningVerified() {
return this.crossSigningVerifiedBefore;
}
/**
* @returns true if this user's key is trusted on first use
*
* @deprecated No longer supported, with the Rust crypto stack.
*/
isTofu() {
return this.tofu;
}
};
var DeviceVerificationStatus = class {
constructor(opts) {
var _opts$signedByOwner, _opts$crossSigningVer, _opts$tofu, _opts$localVerified, _opts$trustCrossSigne;
/**
* True if this device has been signed by its owner (and that signature verified).
*
* This doesn't necessarily mean that we have verified the device, since we may not have verified the
* owner's cross-signing key.
*/
(0, import_defineProperty.default)(this, "signedByOwner", void 0);
/**
* True if this device has been verified via cross signing.
*
* This does *not* take into account `trustCrossSignedDevices`.
*/
(0, import_defineProperty.default)(this, "crossSigningVerified", void 0);
/**
* TODO: tofu magic wtf does this do?
*/
(0, import_defineProperty.default)(this, "tofu", void 0);
/**
* True if the device has been marked as locally verified.
*/
(0, import_defineProperty.default)(this, "localVerified", void 0);
/**
* True if the client has been configured to trust cross-signed devices via {@link CryptoApi#setTrustCrossSignedDevices}.
*/
(0, import_defineProperty.default)(this, "trustCrossSignedDevices", void 0);
this.signedByOwner = (_opts$signedByOwner = opts.signedByOwner) !== null && _opts$signedByOwner !== void 0 ? _opts$signedByOwner : false;
this.crossSigningVerified = (_opts$crossSigningVer = opts.crossSigningVerified) !== null && _opts$crossSigningVer !== void 0 ? _opts$crossSigningVer : false;
this.tofu = (_opts$tofu = opts.tofu) !== null && _opts$tofu !== void 0 ? _opts$tofu : false;
this.localVerified = (_opts$localVerified = opts.localVerified) !== null && _opts$localVerified !== void 0 ? _opts$localVerified : false;
this.trustCrossSignedDevices = (_opts$trustCrossSigne = opts.trustCrossSignedDevices) !== null && _opts$trustCrossSigne !== void 0 ? _opts$trustCrossSigne : false;
}
/**
* Check if we should consider this device "verified".
*
* A device is "verified" if either:
* * it has been manually marked as such via {@link CryptoApi.setDeviceVerified}.
* * it has been cross-signed with a verified signing key, **and** the client has been configured to trust
* cross-signed devices via {@link CryptoApi.setTrustCrossSignedDevices}.
*
* @returns true if this device is verified via any means.
*/
isVerified() {
return this.localVerified || this.trustCrossSignedDevices && this.crossSigningVerified;
}
};
/**
* Enum representing the different stages of importing room keys.
*
* This is the type of the `stage` property of {@link ImportRoomKeyProgressData}.
*/
var ImportRoomKeyStage = /* @__PURE__ */ function(ImportRoomKeyStage) {
/**
* The stage where room keys are being fetched.
*
* @see {@link ImportRoomKeyFetchProgress}.
*/
ImportRoomKeyStage["Fetch"] = "fetch";
/**
* The stage where room keys are being loaded.
*
* @see {@link ImportRoomKeyLoadProgress}.
*/
ImportRoomKeyStage["LoadKeys"] = "load_keys";
return ImportRoomKeyStage;
}({});
/**
* Type representing the progress during the 'fetch' stage of the room key import process.
*
* @see {@link ImportRoomKeyProgressData}.
*/
/**
* Type representing the progress during the 'load_keys' stage of the room key import process.
*
* @see {@link ImportRoomKeyProgressData}.
*/
/**
* Room key import progress report.
* Used when calling {@link CryptoApi#importRoomKeys},
* {@link CryptoApi#importRoomKeysAsJson} or {@link CryptoApi#restoreKeyBackup} as the parameter of
* the progressCallback. Used to display feedback.
*/
/**
* Options object for {@link CryptoApi#importRoomKeys} and
* {@link CryptoApi#importRoomKeysAsJson}.
*/
/**
* The result of a call to {@link CryptoApi.getCrossSigningStatus}.
*/
/**
* Crypto callbacks provided by the application
*/
/**
* The result of a call to {@link CryptoApi.getSecretStorageStatus}.
*/
/**
* Parameter of {@link CryptoApi#bootstrapSecretStorage}
*/
/** Types of cross-signing key */
var CrossSigningKey = /* @__PURE__ */ function(CrossSigningKey) {
CrossSigningKey["Master"] = "master";
CrossSigningKey["SelfSigning"] = "self_signing";
CrossSigningKey["UserSigning"] = "user_signing";
return CrossSigningKey;
}({});
/**
* Information on one of the cross-signing keys.
* @see https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysdevice_signingupload
*/
/**
* Recovery key created by {@link CryptoApi#createRecoveryKeyFromPassphrase} or {@link CreateSecretStorageOpts#createSecretStorageKey}.
*/
/**
* Result type of {@link CryptoApi#getEncryptionInfoForEvent}.
*/
/**
* Types of shield to be shown for {@link EventEncryptionInfo#shieldColour}.
*/
var EventShieldColour = /* @__PURE__ */ function(EventShieldColour) {
EventShieldColour[EventShieldColour["NONE"] = 0] = "NONE";
EventShieldColour[EventShieldColour["GREY"] = 1] = "GREY";
EventShieldColour[EventShieldColour["RED"] = 2] = "RED";
return EventShieldColour;
}({});
/**
* Reason codes for {@link EventEncryptionInfo#shieldReason}.
*/
var EventShieldReason = /* @__PURE__ */ function(EventShieldReason) {
/** An unknown reason from the crypto library (if you see this, it is a bug in matrix-js-sdk). */
EventShieldReason[EventShieldReason["UNKNOWN"] = 0] = "UNKNOWN";
/** "Encrypted by an unverified user." */
EventShieldReason[EventShieldReason["UNVERIFIED_IDENTITY"] = 1] = "UNVERIFIED_IDENTITY";
/** "Encrypted by a device not verified by its owner." */
EventShieldReason[EventShieldReason["UNSIGNED_DEVICE"] = 2] = "UNSIGNED_DEVICE";
/** "Encrypted by an unknown or deleted device." */
EventShieldReason[EventShieldReason["UNKNOWN_DEVICE"] = 3] = "UNKNOWN_DEVICE";
/**
* "The authenticity of this encrypted message can't be guaranteed on this device."
*
* ie: the key has been forwarded, or retrieved from an insecure backup.
*/
EventShieldReason[EventShieldReason["AUTHENTICITY_NOT_GUARANTEED"] = 4] = "AUTHENTICITY_NOT_GUARANTEED";
/**
* The (deprecated) sender_key field in the event does not match the Ed25519 key of the device that sent us the
* decryption keys.
*
* @deprecated The sender_key field is not checked by matrix-sdk-crypto, and this value is therefore unused since
* the migration to matrix-sdk-crypto in v37.0.0.
*/
EventShieldReason[EventShieldReason["MISMATCHED_SENDER_KEY"] = 5] = "MISMATCHED_SENDER_KEY";
/**
* The event was sent unencrypted in an encrypted room.
*
* @deprecated This has never been used. The fact it is here was due to a misunderstanding of the behaviour of
* `matrix-sdk-crypto`.
*/
EventShieldReason[EventShieldReason["SENT_IN_CLEAR"] = 6] = "SENT_IN_CLEAR";
/**
* The sender was previously verified but changed their identity.
*/
EventShieldReason[EventShieldReason["VERIFICATION_VIOLATION"] = 7] = "VERIFICATION_VIOLATION";
/**
* The `sender` field on the event does not match the owner of the device
* that established the Megolm session.
*/
EventShieldReason[EventShieldReason["MISMATCHED_SENDER"] = 8] = "MISMATCHED_SENDER";
return EventShieldReason;
}({});
/** The result of a call to {@link CryptoApi.getOwnDeviceKeys} */
/**
* Information about the encryption of a successfully decrypted to-device message.
*/
/**
* An error thrown by loadSessionBackupPrivateKeyFromSecretStorage indicating
* that the decryption key found in secret storage does not match the public key
* of the latest backup.
*/
var DecryptionKeyDoesNotMatchError = class extends Error {
constructor(message) {
super(message);
this.name = "DecryptionKeyDoesNotMatchError";
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/utils/internal/deriveKeys.js
var zeroSalt = new Uint8Array(8);
/**
* Derive AES and HMAC keys from a master key.
*
* This is used for deriving secret storage keys: see https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2 (step 1).
*
* @param key
* @param name
*/
function deriveKeys(_x, _x2) {
return _deriveKeys.apply(this, arguments);
}
function _deriveKeys() {
_deriveKeys = (0, import_asyncToGenerator.default)(function* (key, name) {
var hkdfkey = yield globalThis.crypto.subtle.importKey("raw", key, { name: "HKDF" }, false, ["deriveBits"]);
var keybits = yield globalThis.crypto.subtle.deriveBits({
name: "HKDF",
salt: zeroSalt,
info: new TextEncoder().encode(name),
hash: "SHA-256"
}, hkdfkey, 512);
var aesKey = keybits.slice(0, 32);
var hmacKey = keybits.slice(32);
var aesProm = globalThis.crypto.subtle.importKey("raw", aesKey, { name: "AES-CTR" }, false, ["encrypt", "decrypt"]);
var hmacProm = globalThis.crypto.subtle.importKey("raw", hmacKey, {
name: "HMAC",
hash: { name: "SHA-256" }
}, false, ["sign", "verify"]);
return Promise.all([aesProm, hmacProm]);
});
return _deriveKeys.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/utils/encryptAESSecretStorageItem.js
/**
* Encrypt a string as a secret storage item, using AES-CTR.
*
* @param data - the plaintext to encrypt
* @param key - the encryption key to use as an input to the HKDF function which is used to derive the AES key for
* encryption. Obviously, the same key must be provided when decrypting.
* @param name - the name of the secret. Used as an input to the HKDF operation which is used to derive the AES key,
* so again the same value must be provided when decrypting.
* @param ivStr - the base64-encoded initialization vector to use. If not supplied, a random one will be generated.
*
* @returns The encrypted result, including the ciphertext itself, the initialization vector (as supplied in `ivStr`,
* or generated), and an HMAC on the ciphertext — all base64-encoded.
*/
function encryptAESSecretStorageItem(_x, _x2, _x3, _x4) {
return _encryptAESSecretStorageItem.apply(this, arguments);
}
function _encryptAESSecretStorageItem() {
_encryptAESSecretStorageItem = (0, import_asyncToGenerator.default)(function* (data, key, name, ivStr) {
var iv;
if (ivStr) iv = decodeBase64(ivStr);
else {
iv = new Uint8Array(16);
globalThis.crypto.getRandomValues(iv);
iv[8] &= 127;
}
var [aesKey, hmacKey] = yield deriveKeys(key, name);
var encodedData = new TextEncoder().encode(data);
var ciphertext = yield globalThis.crypto.subtle.encrypt({
name: "AES-CTR",
counter: iv,
length: 64
}, aesKey, encodedData);
var hmac = yield globalThis.crypto.subtle.sign({ name: "HMAC" }, hmacKey, ciphertext);
return {
iv: encodeBase64(iv),
ciphertext: encodeBase64(new Uint8Array(ciphertext)),
mac: encodeBase64(new Uint8Array(hmac))
};
});
return _encryptAESSecretStorageItem.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/utils/decryptAESSecretStorageItem.js
/**
* Decrypt an AES-encrypted Secret Storage item.
*
* @param data - the encrypted data, returned by {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.
* @param key - the encryption key to use as an input to the HKDF function which is used to derive the AES key. Must
* be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.
* @param name - the name of the secret. Also used as an input to the HKDF operation which is used to derive the AES
* key, so again must be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.
*/
function decryptAESSecretStorageItem(_x, _x2, _x3) {
return _decryptAESSecretStorageItem.apply(this, arguments);
}
function _decryptAESSecretStorageItem() {
_decryptAESSecretStorageItem = (0, import_asyncToGenerator.default)(function* (data, key, name) {
var [aesKey, hmacKey] = yield deriveKeys(key, name);
var ciphertext = decodeBase64(data.ciphertext);
if (!(yield globalThis.crypto.subtle.verify({ name: "HMAC" }, hmacKey, decodeBase64(data.mac), ciphertext))) throw new Error("Error decrypting secret ".concat(name, ": bad MAC"));
var plaintext = yield globalThis.crypto.subtle.decrypt({
name: "AES-CTR",
counter: decodeBase64(data.iv),
length: 64
}, aesKey, ciphertext);
return new TextDecoder().decode(new Uint8Array(plaintext));
});
return _decryptAESSecretStorageItem.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/secret-storage.js
/**
* Implementation of server-side secret storage
*
* @see https://spec.matrix.org/v1.6/client-server-api/#storage
*/
var SECRET_STORAGE_ALGORITHM_V1_AES = "m.secret_storage.v1.aes-hmac-sha2";
/**
* Common base interface for Secret Storage Keys.
*
* The common properties for all encryption keys used in server-side secret storage.
*
* @see https://spec.matrix.org/v1.6/client-server-api/#key-storage
*/
/**
* Properties for a SSSS key using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.
*
* Corresponds to `AesHmacSha2KeyDescription` in the specification.
*
* @see https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2
*/
/**
* Union type for secret storage keys.
*
* For now, this is only {@link SecretStorageKeyDescriptionAesV1}, but other interfaces may be added in future.
*/
/**
* Information on how to generate the key from a passphrase.
*
* @see https://spec.matrix.org/v1.6/client-server-api/#deriving-keys-from-passphrases
*/
/**
* Options for {@link ServerSideSecretStorageImpl#addKey}.
*/
/**
* Return type for {@link ServerSideSecretStorageImpl#getKey}.
*/
/**
* Return type for {@link ServerSideSecretStorageImpl#addKey}.
*/
/** Interface for managing account data on the server.
*
* A subset of {@link MatrixClient}.
*/
/**
* Application callbacks for use with {@link SecretStorage.ServerSideSecretStorageImpl}
*/
/**
* Account Data event types which can store secret-storage-encrypted information.
*/
/**
* Account Data event content type for storing secret-storage-encrypted information.
*
* See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1
*/
/**
* Interface provided by SecretStorage implementations
*
* Normally this will just be an {@link ServerSideSecretStorageImpl}, but for backwards
* compatibility some methods allow other implementations.
*/
/**
* Implementation of Server-side secret storage.
*
* Secret *sharing* is *not* implemented here: this class is strictly about the storage component of
* SSSS.
*
* @see https://spec.matrix.org/v1.6/client-server-api/#storage
*/
var ServerSideSecretStorageImpl = class {
/**
* Construct a new `SecretStorage`.
*
* Normally, it is unnecessary to call this directly, since MatrixClient automatically constructs one.
* However, it may be useful to construct a new `SecretStorage`, if custom `callbacks` are required, for example.
*
* @param accountDataAdapter - interface for fetching and setting account data on the server. Normally an instance
* of {@link MatrixClient}.
* @param callbacks - application level callbacks for retrieving secret keys
*/
constructor(accountDataAdapter, callbacks) {
this.accountDataAdapter = accountDataAdapter;
this.callbacks = callbacks;
}
/**
* Get the current default key ID for encrypting secrets.
*
* @returns The default key ID or null if no default key ID is set
*/
getDefaultKeyId() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var _defaultKey$key;
var defaultKey = yield _this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");
if (!defaultKey) return null;
return (_defaultKey$key = defaultKey.key) !== null && _defaultKey$key !== void 0 ? _defaultKey$key : null;
})();
}
/**
* Implementation of {@link ServerSideSecretStorage#setDefaultKeyId}.
*/
setDefaultKeyId(keyId) {
return new Promise((resolve, reject) => {
var listener = (ev) => {
if (ev.getType() !== "m.secret_storage.default_key") return;
var content = ev.getContent();
if (keyId === null ? Object.keys(content).length === 0 : content.key === keyId) {
this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);
resolve();
}
};
this.accountDataAdapter.on(ClientEvent.AccountData, listener);
var newValue = keyId === null ? {} : { key: keyId };
this.accountDataAdapter.setAccountData("m.secret_storage.default_key", newValue).catch((e) => {
this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);
reject(e);
});
});
}
/**
* Add a key for encrypting secrets.
*
* @param algorithm - the algorithm used by the key.
* @param opts - the options for the algorithm. The properties used
* depend on the algorithm given.
* @param keyId - the ID of the key. If not given, a random
* ID will be generated.
*
* @returns An object with:
* keyId: the ID of the key
* keyInfo: details about the key (iv, mac, passphrase)
*/
addKey(algorithm, opts, keyId) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (algorithm !== "m.secret_storage.v1.aes-hmac-sha2") throw new Error("Unknown key algorithm ".concat(algorithm));
var keyInfo = { algorithm };
if (opts.name) keyInfo.name = opts.name;
if (opts.passphrase) keyInfo.passphrase = opts.passphrase;
var { iv, mac } = yield calculateKeyCheck(opts.key);
keyInfo.iv = iv;
keyInfo.mac = mac;
if (!keyId) do
keyId = secureRandomString(32);
while (yield _this2.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(keyId)));
yield _this2.accountDataAdapter.setAccountData("m.secret_storage.key.".concat(keyId), keyInfo);
return {
keyId,
keyInfo
};
})();
}
/**
* Get the key information for a given ID.
*
* @param keyId - The ID of the key to check
* for. Defaults to the default key ID if not provided.
* @returns If the key was found, the return value is an array of
* the form [keyId, keyInfo]. Otherwise, null is returned.
* XXX: why is this an array when addKey returns an object?
*/
getKey(keyId) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!keyId) keyId = yield _this3.getDefaultKeyId();
if (!keyId) return null;
var keyInfo = yield _this3.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(keyId));
return keyInfo ? [keyId, keyInfo] : null;
})();
}
/**
* Check whether we have a key with a given ID.
*
* @param keyId - The ID of the key to check
* for. Defaults to the default key ID if not provided.
* @returns Whether we have the key.
*/
hasKey(keyId) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var key = yield _this4.getKey(keyId);
return Boolean(key);
})();
}
/**
* Check whether a key matches what we expect based on the key info
*
* @param key - the key to check
* @param info - the key info
*
* @returns whether or not the key matches
*/
checkKey(key, info) {
return (0, import_asyncToGenerator.default)(function* () {
if (info.algorithm === "m.secret_storage.v1.aes-hmac-sha2") if (info.mac) {
var { mac } = yield calculateKeyCheck(key, info.iv);
return trimTrailingEquals(info.mac) === trimTrailingEquals(mac);
} else return true;
else throw new Error("Unknown algorithm");
})();
}
/**
* Implementation of {@link ServerSideSecretStorage#store}.
*/
store(name, secret, keys) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (secret === null) {
yield _this5.accountDataAdapter.setAccountData(name, {});
return;
}
var encrypted = {};
if (!keys) {
var defaultKeyId = yield _this5.getDefaultKeyId();
if (!defaultKeyId) throw new Error("No keys specified and no default key present");
keys = [defaultKeyId];
}
if (keys.length === 0) throw new Error("Zero keys given to encrypt with!");
for (var _keyId of keys) {
var _keyInfo = yield _this5.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(_keyId));
if (!_keyInfo) throw new Error("Unknown key: " + _keyId);
if (_keyInfo.algorithm === "m.secret_storage.v1.aes-hmac-sha2") {
var _keys = { [_keyId]: _keyInfo };
var [, encryption] = yield _this5.getSecretStorageKey(_keys, name);
encrypted[_keyId] = yield encryption.encrypt(secret);
} else logger$2.warn("unknown algorithm for secret storage key " + _keyId + ": " + _keyInfo.algorithm);
}
yield _this5.accountDataAdapter.setAccountData(name, { encrypted });
})();
}
/**
* Get a secret from storage, and decrypt it.
*
* {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage
* key to decrypt the secret.
*
* @param name - the name of the secret - i.e., the "event type" stored in the account data
*
* @returns the decrypted contents of the secret, or "undefined" if `name` is not found in
* the user's account data.
*/
get(name) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var secretInfo = yield _this6.accountDataAdapter.getAccountDataFromServer(name);
if (!secretInfo) return;
if (!secretInfo.encrypted) throw new Error("Content is not encrypted!");
var keys = {};
for (var _keyId2 of Object.keys(secretInfo.encrypted)) {
var _keyInfo2 = yield _this6.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(_keyId2));
var _encInfo = secretInfo.encrypted[_keyId2];
if ((_keyInfo2 === null || _keyInfo2 === void 0 ? void 0 : _keyInfo2.algorithm) === "m.secret_storage.v1.aes-hmac-sha2") {
if (_encInfo.iv && _encInfo.ciphertext && _encInfo.mac) keys[_keyId2] = _keyInfo2;
}
}
if (Object.keys(keys).length === 0) throw new Error("Could not decrypt ".concat(name, " because none of ") + "the keys it is encrypted with are for a supported algorithm");
var [keyId, decryption] = yield _this6.getSecretStorageKey(keys, name);
var encInfo = secretInfo.encrypted[keyId];
return decryption.decrypt(encInfo);
})();
}
/**
* Check if a secret is stored on the server.
*
* @param name - the name of the secret
*
* @returns map of key name to key info the secret is encrypted
* with, or null if it is not present or not encrypted with a trusted
* key
*/
isStored(name) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var secretInfo = yield _this7.accountDataAdapter.getAccountDataFromServer(name);
if (!(secretInfo !== null && secretInfo !== void 0 && secretInfo.encrypted)) return null;
var ret = {};
for (var _keyId3 of Object.keys(secretInfo.encrypted)) {
var _keyInfo3 = yield _this7.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(_keyId3));
if (!_keyInfo3) continue;
var encInfo = secretInfo.encrypted[_keyId3];
if (_keyInfo3.algorithm === "m.secret_storage.v1.aes-hmac-sha2") {
if (encInfo.iv && encInfo.ciphertext && encInfo.mac) ret[_keyId3] = _keyInfo3;
}
}
return Object.keys(ret).length ? ret : null;
})();
}
getSecretStorageKey(keys, name) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this8.callbacks.getSecretStorageKey) throw new Error("No getSecretStorageKey callback supplied");
var returned = yield _this8.callbacks.getSecretStorageKey({ keys }, name);
if (!returned) throw new Error("getSecretStorageKey callback returned falsey");
if (returned.length < 2) throw new Error("getSecretStorageKey callback returned invalid data");
var [keyId, privateKey] = returned;
if (!keys[keyId]) throw new Error("App returned unknown key from getSecretStorageKey!");
if (keys[keyId].algorithm === "m.secret_storage.v1.aes-hmac-sha2") return [keyId, {
encrypt: function encrypt(secret) {
return encryptAESSecretStorageItem(secret, privateKey, name);
},
decrypt: function decrypt(encInfo) {
return decryptAESSecretStorageItem(encInfo, privateKey, name);
}
}];
else throw new Error("Unknown key type: " + keys[keyId].algorithm);
})();
}
};
/** trim trailing instances of '=' from a string
*
* @internal
*
* @param input - input string
*/
function trimTrailingEquals(input) {
var i = input.length;
while (i >= 1 && input.charCodeAt(i - 1) == 61) i--;
if (i < input.length) return input.substring(0, i);
else return input;
}
var ZERO_STR = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
/**
* Calculate the MAC for checking the key.
* See https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2, steps 3 and 4.
*
* @param key - the key to use
* @param iv - The initialization vector as a base64-encoded string.
* If omitted, a random initialization vector will be created.
* @returns An object that contains, `mac` and `iv` properties.
*/
function calculateKeyCheck(key, iv) {
return encryptAESSecretStorageItem(ZERO_STR, key, "", iv);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/EncryptionManager.js
/**
* The string used for the keys in the the encryption key map.
* `@bob:examle.org:DEVICEID(UUIDRANDOM_MEMBERID_RANDOMUUID)`
*/
function getEncryptionKeyMapKey(membership) {
return "".concat(membership.userId, ":").concat(membership.deviceId, "(").concat(membership.memberId, ")");
}
/**
* This interface is for testing and for making it possible to interchange the encryption manager.
* @internal
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/utils.js
/**
* Detects when a key for a given index is outdated.
*/
var OutdatedKeyFilter = class {
constructor() {
(0, import_defineProperty.default)(this, "tsBuffer", /* @__PURE__ */ new Map());
}
/**
* Check if there is a recent key with the same keyId (index) and then use the creationTS to decide what to
* do with the key. If the key received is older than the one already in the buffer, it is ignored.
* @param participantId
* @param item
*/
isOutdated(membership, item) {
var _this$tsBuffer$get;
var mapKey = getEncryptionKeyMapKey(membership);
if (!this.tsBuffer.has(mapKey)) this.tsBuffer.set(mapKey, /* @__PURE__ */ new Map());
var latestTimestamp = (_this$tsBuffer$get = this.tsBuffer.get(mapKey)) === null || _this$tsBuffer$get === void 0 ? void 0 : _this$tsBuffer$get.get(item.keyIndex);
if (latestTimestamp && latestTimestamp > item.creationTS) return true;
this.tsBuffer.get(mapKey).set(item.keyIndex, item.creationTS);
return false;
}
};
/**
* Converts a slot ID into it's component application and ID portions.
* @param slotId e.g. `m.call#call_id`
* @throws If the format of `slotId` is invalid.
*/
function slotIdToDescription(slotId) {
var [application, id, ...unexpectedAdditionalValues] = slotId.split("#");
if (unexpectedAdditionalValues.length) throw Error("MatrixRTC Slot IDs *must* only contain two components seperated by one '#'. Additional '#' characters detected.");
return {
application,
id
};
}
/**
* Converts a SlotDescription into it's slot ID format.
*/
function computeSlotId(slotDescription) {
return "".concat(slotDescription.application, "#").concat(slotDescription.id);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/common.js
/**
* Thrown when an event is not valid for use with MatrixRTC.
*/
var MatrixRTCMembershipParseError = class extends AggregateError {
constructor(type, errors) {
super(errors, "Does not match ".concat(type, ":\n").concat(errors.join("\n")));
this.type = type;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/session.js
/**
* (MatrixRTC) session membership data.
* This represents the *OLD* form of MSC4143, which uses state events to store membership.
* Represents the `session` in the memberships section of an m.call.member event as it is on the wire.
**/
/**
* Validates that `data` matches the format expected by the legacy form of MSC4143.
* @param data The event content.
* @returns true if `data` is valid SessionMembershipData
* @throws {MatrixRTCMembershipParseError} if the content is not valid
*/
var checkSessionsMembershipData = (data) => {
var _data$focus_active;
var prefix = " - ";
var errors = [];
if (typeof data.device_id !== "string") errors.push(prefix + "device_id must be string");
if (typeof data.call_id !== "string") errors.push(prefix + "call_id must be string");
if (typeof data.application !== "string") errors.push(prefix + "application must be a string");
if (data.focus_active === void 0) errors.push(prefix + "focus_active has an invalid type");
if (typeof ((_data$focus_active = data.focus_active) === null || _data$focus_active === void 0 ? void 0 : _data$focus_active.type) !== "string") errors.push(prefix + "focus_active.type must be a string");
if (data.foci_preferred !== void 0 && !(Array.isArray(data.foci_preferred) && data.foci_preferred.every((f) => typeof f === "object" && f !== null && typeof f.type === "string"))) errors.push(prefix + "foci_preferred must be an array of transport objects");
if (data.created_ts !== void 0 && typeof data.created_ts !== "number") errors.push(prefix + "created_ts must be number");
if (data.scope !== void 0 && typeof data.scope !== "string") errors.push(prefix + "scope must be string");
if (data["m.call.intent"] !== void 0 && typeof data["m.call.intent"] !== "string") errors.push(prefix + "m.call.intent must be a string");
if (errors.length) throw new MatrixRTCMembershipParseError("SessionMembership", errors);
return true;
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/digest.js
/**
* Computes a SHA-256 hash of a string (after utf-8 encoding) and returns it as an ArrayBuffer.
*
* @param plaintext The string to hash
* @returns An Uint8Array containing the SHA-256 hash of the input string
* @throws If the subtle crypto API is not available, for example if the code is running
* in a web page with an insecure context (eg. served over plain HTTP).
*/
function sha256(_x) {
return _sha.apply(this, arguments);
}
function _sha() {
_sha = (0, import_asyncToGenerator.default)(function* (plaintext) {
if (!globalThis.crypto.subtle) throw new Error("Crypto.subtle is not available: insecure context?");
var utf8 = new TextEncoder().encode(plaintext);
var digest = yield globalThis.crypto.subtle.digest("SHA-256", utf8);
return new Uint8Array(digest);
});
return _sha.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/rtc.js
/**
* Represents the current form of MSC4143, which uses sticky events to store membership.
*/
/**
* Validates that `data` matches the format expected by MSC4143.
* @param data The event content.
* @param sender The sender of the event.
* @returns true if `data` is valid RtcMembershipData
* @throws {MatrixRTCMembershipParseError} if the content is not valid
*/
var checkRtcMembershipData = (data, sender) => {
var _data$application, _data$sticky_key;
var errors = [];
var prefix = " - ";
var expectedSlotPrefix = "".concat(data === null || data === void 0 || (_data$application = data.application) === null || _data$application === void 0 ? void 0 : _data$application.type, "#");
if (typeof data.slot_id !== "string") errors.push(prefix + "slot_id must be string");
else if (!data.slot_id.startsWith(expectedSlotPrefix)) errors.push(prefix + "slot_id must start with ".concat(expectedSlotPrefix));
else try {
slotIdToDescription(data.slot_id);
} catch (ex) {
errors.push(prefix + "slot_id was badly formed".concat(ex instanceof Error ? ": ".concat(ex.message) : ""));
}
if (typeof data.member !== "object" || data.member === null) errors.push(prefix + "member must be an object");
else {
if (typeof data.member.user_id !== "string") errors.push(prefix + "member.user_id must be string");
else if (!MXID_PATTERN.test(data.member.user_id)) errors.push(prefix + "member.user_id must be a valid mxid");
else if (data.member.user_id !== sender) errors.push(prefix + "member.user_id must match the sender");
if (typeof data.member.device_id !== "string") errors.push(prefix + "member.device_id must be string");
if (typeof data.member.id !== "string") errors.push(prefix + "member.id must be string");
}
if (typeof data.application !== "object" || data.application === null) errors.push(prefix + "application must be an object");
else if (typeof data.application.type !== "string") errors.push(prefix + "application.type must be a string");
else if (data.application.type.includes("#")) errors.push(prefix + "application.type must not include \"#\"");
if (data.rtc_transports === void 0 || !Array.isArray(data.rtc_transports)) errors.push(prefix + "rtc_transports must be an array");
else for (var t of data.rtc_transports) if (typeof t !== "object" || t === null || typeof t.type !== "string") {
errors.push(prefix + "rtc_transports entries must be objects with a string type");
break;
}
if (data.versions === void 0 || !Array.isArray(data.versions)) errors.push(prefix + "versions must be an array");
else if (!data.versions.every((v) => typeof v === "string")) errors.push(prefix + "versions must be an array of strings");
if (((_data$sticky_key = data.sticky_key) !== null && _data$sticky_key !== void 0 ? _data$sticky_key : data.msc4354_sticky_key) === void 0) errors.push(prefix + "sticky_key or msc4354_sticky_key must be a defined");
if (data.sticky_key !== void 0 && typeof data.sticky_key !== "string") errors.push(prefix + "sticky_key must be a string");
if (data.msc4354_sticky_key !== void 0 && typeof data.msc4354_sticky_key !== "string") errors.push(prefix + "msc4354_sticky_key must be a string");
if (data.sticky_key !== void 0 && data.msc4354_sticky_key !== void 0 && data.sticky_key !== data.msc4354_sticky_key) errors.push(prefix + "sticky_key and msc4354_sticky_key must be equal if both are defined");
if (data["m.relates_to"] !== void 0) {
var rel = data["m.relates_to"];
if (typeof rel !== "object" || rel === null) errors.push(prefix + "m.relates_to must be an object if provided");
else {
if (typeof rel.event_id !== "string") errors.push(prefix + "m.relates_to.event_id must be a string");
if (rel.rel_type !== "m.reference") errors.push(prefix + "m.relates_to.rel_type must be m.reference");
}
}
if (errors.length) throw new MatrixRTCMembershipParseError("RtcMembership", errors);
return true;
};
function computeRtcIdentityRaw(_x, _x2, _x3) {
return _computeRtcIdentityRaw.apply(this, arguments);
}
function _computeRtcIdentityRaw() {
_computeRtcIdentityRaw = (0, import_asyncToGenerator.default)(function* (userId, deviceId, memberId) {
return encodeUnpaddedBase64Url(yield sha256("".concat(userId, "|").concat(deviceId, "|").concat(memberId)));
});
return _computeRtcIdentityRaw.apply(this, arguments);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/CallMembership.js
/**
* The default duration in milliseconds that a membership is considered valid for.
* Ordinarily the client responsible for the session will update the membership before it expires.
* We use this duration as the fallback case where stale sessions are present for some reason.
*/
var DEFAULT_EXPIRE_DURATION = 1e3 * 60 * 60 * 4;
/**
* Describes the source event type that provided the membership data.
*/
var MembershipKind = /* @__PURE__ */ function(MembershipKind) {
/**
* The modern MSC4143 format event.
*/
MembershipKind["RTC"] = "rtc";
/**
* The legacy call event type.
*/
MembershipKind["Session"] = "session";
return MembershipKind;
}(MembershipKind || {});
var CallMembership = class CallMembership {
/**
* Parse the membershipdata from a call membership event.
* @param matrixEvent The Matrix event to read.
* @returns MembershipData in either MembershipKind.RTC or MembershipKind.Session format.
* @throws If the content is neither format.
*/
static membershipDataFromMatrixEvent(matrixEvent) {
var sender = matrixEvent.getSender();
var evType = matrixEvent.getType();
var data = matrixEvent.getContent();
if (sender === void 0) throw new Error("matrixEvent is missing sender field");
try {
if (evType === EventType.RTCMembership && checkRtcMembershipData(data, sender)) return {
kind: MembershipKind.RTC,
data
};
else if (evType === EventType.GroupCallMemberPrefix && checkSessionsMembershipData(data)) return {
kind: MembershipKind.Session,
data
};
else throw Error("'".concat(evType, " is not a known call membership type"));
} catch (ex) {
if (ex instanceof MatrixRTCMembershipParseError) logger$2.debug("CallMembership.MatrixRTCMembershipParseError provided invalid data", data);
throw ex;
}
}
/**
* Parse the contents of a MatrixEvent and create a CallMembership instance.
* @param matrixEvent The Matrix event to read.
*/
static parseFromEvent(matrixEvent) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var membershipData = _this.membershipDataFromMatrixEvent(matrixEvent);
return new CallMembership(matrixEvent, membershipData, membershipData.kind === MembershipKind.RTC ? yield computeRtcIdentityRaw(membershipData.data.member.user_id, membershipData.data.member.device_id, membershipData.data.member.id) : "".concat(matrixEvent.getSender(), ":").concat(membershipData.data.device_id));
})();
}
static equal(a, b) {
return deepCompare(a === null || a === void 0 ? void 0 : a.membershipData, b === null || b === void 0 ? void 0 : b.membershipData);
}
/**
* Use `parseFromEvent`.
* Constructor should only be used by tests.
* @private
* @param matrixEvent
* @param membershipData
* @param rtcBackendIdentity
*/
constructor(matrixEvent, membershipData, rtcBackendIdentity) {
this.matrixEvent = matrixEvent;
this.membershipData = membershipData;
this.rtcBackendIdentity = rtcBackendIdentity;
(0, import_defineProperty.default)(this, "logger", void 0);
/** The parsed data from the Matrix event.
* To access checked eventId and sender from the matrixEvent.
* Class construction will fail if these values cannot get obtained. */
(0, import_defineProperty.default)(this, "matrixEventData", void 0);
var eventId = matrixEvent.getId();
var sender = matrixEvent.getSender();
if (eventId === void 0) throw new Error("parentEvent is missing eventId field");
if (sender === void 0) throw new Error("parentEvent is missing sender field");
this.logger = logger$2.getChild("[CallMembership ".concat(sender, ":").concat(this.deviceId, "]"));
this.matrixEventData = {
eventId,
sender
};
}
/** @deprecated use userId instead */
get sender() {
return this.userId;
}
get userId() {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return data.member.user_id;
case MembershipKind.Session:
default: return this.matrixEventData.sender;
}
}
get eventId() {
return this.matrixEventData.eventId;
}
/**
* The ID of the MatrixRTC slot that this membership belongs to (format `{application}#{id}`).
* This is computed in case SessionMembershipData is used.
*/
get slotId() {
var _this$logger2;
var { kind, data } = this.membershipData;
if (data.application === "m.call") switch (kind) {
case MembershipKind.RTC: return data.slot_id;
case MembershipKind.Session:
default:
var [application, id] = [data.application, data.call_id];
var compatibilityAdaptedId;
if (id === "") {
var _this$logger;
compatibilityAdaptedId = "ROOM";
(_this$logger = this.logger) === null || _this$logger === void 0 || _this$logger.info("use slotId compat hack emptyString -> ROOM");
} else compatibilityAdaptedId = id;
return computeSlotId({
application,
id: compatibilityAdaptedId
});
}
(_this$logger2 = this.logger) === null || _this$logger2 === void 0 || _this$logger2.info("NOT using slotId compat hack emptyString -> ROOM");
switch (kind) {
case MembershipKind.RTC: return data.slot_id;
case MembershipKind.Session:
default: return computeSlotId({
application: data.application,
id: data.call_id
});
}
}
get deviceId() {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return data.member.device_id;
case MembershipKind.Session:
default: return data.device_id;
}
}
get callIntent() {
var intent = this.applicationData["m.call.intent"];
if (typeof intent === "string") return intent;
this.logger.warn("RTC membership has invalid m.call.intent");
}
/**
* Parsed `slot_id` (format `{application}#{id}`) into its components (application and id).
*/
get slotDescription() {
var { kind, data } = this.membershipData;
if (kind === MembershipKind.RTC) {
var id = data.slot_id.slice("".concat(data.application.type, "#").length);
return {
application: data.application.type,
id
};
}
return slotIdToDescription(this.slotId);
}
/**
* The application `type`.
* @deprecated Use @see applicationData
*/
get application() {
return this.applicationData.type;
}
/**
* Information about the application being used for the RTC session.
* May contain extra keys specific to the application.
*/
get applicationData() {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return data.application;
case MembershipKind.Session:
default: return {
"type": data.application,
"m.call.intent": data["m.call.intent"]
};
}
}
/** @deprecated scope is not used and will be removed in future versions. replaced by application specific types.*/
get scope() {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return;
case MembershipKind.Session:
default: return data.scope;
}
}
/**
* This computes the membership ID for the membership.
* For the sticky event based rtcSessionData this is trivial it is `member.id`.
* This is not supposed to be used to identity on an rtc backend. This is just a nouance for
* a generated (sha256) anonymised identity. Only send `rtcBackendIdentity` to any rtc backend service.
*
* For the legacy sessionMemberEvents it is a bit more complex. Here we sometimes do not have this data
* in the event content and we expected the SFU and the client to use `${this.matrixEventData.sender}:${data.device_id}`.
*
* So if there is no membershipID we use the hard coded jwt id default (`${this.matrixEventData.sender}:${data.device_id}`)
* value (used until version 0.16.0)
*
* It is also possible for a session event to set a custom membershipID. in that case this will be used.
*/
get memberId() {
var _data$membershipID;
var { kind, data } = this.membershipData;
switch (kind) {
case "rtc": return data.member.id;
case "session": return (_data$membershipID = data.membershipID) !== null && _data$membershipID !== void 0 ? _data$membershipID : "".concat(this.matrixEventData.sender, ":").concat(data.device_id);
default: throw Error("Not possible to get memberID without knowing the membership event kind");
}
}
/**
* @deprecated renamed to `memberId`
*/
get membershipID() {
return this.memberId;
}
createdTs() {
var _data$created_ts;
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return this.matrixEvent.getTs();
case MembershipKind.Session:
default: return (_data$created_ts = data.created_ts) !== null && _data$created_ts !== void 0 ? _data$created_ts : this.matrixEvent.getTs();
}
}
/**
* Gets the absolute expiry timestamp of the membership.
* @returns The absolute expiry time of the membership as a unix timestamp in milliseconds or undefined if not applicable
*/
getAbsoluteExpiry() {
var _data$expires;
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return;
case MembershipKind.Session:
default: return this.createdTs() + ((_data$expires = data.expires) !== null && _data$expires !== void 0 ? _data$expires : DEFAULT_EXPIRE_DURATION);
}
}
/**
* @returns The number of milliseconds until the membership expires or undefined if applicable
* @deprecated Not used by RTC events.
*/
getMsUntilExpiry() {
var { kind } = this.membershipData;
if (kind === MembershipKind.Session) {
var absExpiry = this.getAbsoluteExpiry();
if (absExpiry) return absExpiry - Date.now();
}
}
/**
* @returns true if the membership has expired, otherwise false
*/
isExpired() {
var { kind } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return false;
case MembershipKind.Session:
default: return this.getMsUntilExpiry() <= 0;
}
}
/**
* ## RTC Membership
* Gets the primary transport to use for this RTC membership (m.rtc.member).
* This will return the primary transport that is used by this call membership to publish their media.
* Directly relates to the `rtc_transports` field.
*
* ## Legacy session membership
* In case of a legacy session membership (m.call.member) this will return the selected transport where
* media is published. How this selection happens depends on the `focus_active` field of the session membership.
* If the `focus_selection` is `oldest_membership` this will return the transport of the oldest membership
* in the room (based on the `created_ts` field of the session membership).
* If the `focus_selection` is `multi_sfu` it will return the first transport of the `foci_preferred` list.
* (`multi_sfu` is equivalent to how `m.rtc.member` `rtc_transports` work).
* @param oldestMembership For backwards compatibility with session membership (legacy). Unused in case of RTC membership.
* Always required to make the consumer not care if it deals with RTC or session memberships.
* @returns The transport this membership uses to publish media or undefined if no transport is available.
*/
getTransport(oldestMembership) {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return data.rtc_transports[0];
case MembershipKind.Session:
switch (data.focus_active.focus_selection) {
case "oldest_membership":
if (CallMembership.equal(this, oldestMembership)) return data.foci_preferred[0];
if (oldestMembership !== void 0) return oldestMembership.getTransport(oldestMembership);
break;
case "multi_sfu": return data.foci_preferred[0];
default: return;
}
break;
default: return;
}
}
/**
* The value of the `rtc_transports` field for RTC memberships (m.rtc.member).
* Or the value of the `foci_preferred` field for legacy session memberships (m.call.member).
*/
get transports() {
var { kind, data } = this.membershipData;
switch (kind) {
case MembershipKind.RTC: return data.rtc_transports;
case MembershipKind.Session:
default: return data.foci_preferred;
}
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/types.js
/**
* Interface for `org.matrix.msc4075.rtc.notification` events.
* Don't cast event content to this directly. Use `parseCallNotificationContent` instead to validate the content first.
*/
/**
* MSC4310 decline event content for `org.matrix.msc4310.rtc.decline`.
* Sent as a standard m.reference relation to an `org.matrix.msc4075.rtc.notification` event.
*/
var Status = /* @__PURE__ */ function(Status) {
Status["Disconnected"] = "Disconnected";
Status["Connecting"] = "Connecting";
Status["Connected"] = "Connected";
Status["Disconnecting"] = "Disconnecting";
Status["Unknown"] = "Unknown";
return Status;
}({});
/**
* A type collecting call encryption statistics for a session.
*/
var isMyMembership = (m, userId, deviceId) => m.sender === userId && m.deviceId === deviceId;
/**
* A RTC transport is a JSON object that describes how to connect to a RTC member.
*/
/**
* Event content for a `m.rtc.slot` state event.
*/
/**
* The session description is used to identify a session. Used in the state event.
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManagerActionScheduler.js
/** @internal */
/** @internal */
/**
* This scheduler tracks the state of the current membership participation
* and runs one central timer that wakes up a handler callback with the correct action + state
* whenever necessary.
*
* It can also be awakened whenever a new action is added which is
* earlier then the current "next awake".
* @internal
*/
var ActionScheduler = class {
constructor(membershipLoopHandler, parentLogger) {
this.membershipLoopHandler = membershipLoopHandler;
(0, import_defineProperty.default)(this, "logger", void 0);
/**
* This is tracking the state of the scheduler loop.
* Only used to prevent starting the loop twice.
*/
(0, import_defineProperty.default)(this, "running", false);
(0, import_defineProperty.default)(this, "wakeup", (update) => {
this.logger.error("Cannot call wakeup before calling `startWithJoin()`");
});
(0, import_defineProperty.default)(this, "_actions", []);
this.logger = (parentLogger !== null && parentLogger !== void 0 ? parentLogger : logger$2).getChild("[NewMembershipActionScheduler]");
}
get actions() {
return this._actions;
}
/**
* This starts the main loop of the membership manager that handles event sending, delayed event sending and delayed event restarting.
* @param initialActions The initial actions the manager will start with. It should be enough to pass: DelayedLeaveActionType.Initial
* @returns Promise that resolves once all actions have run and no more are scheduled.
* @throws This throws an error if one of the actions throws.
* In most other error cases the manager will try to handle any server errors by itself.
*/
startWithJoin() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this.running) {
_this.logger.error("Cannot call startWithJoin() on NewMembershipActionScheduler while already running");
return;
}
_this.running = true;
_this._actions = [{
ts: Date.now(),
type: MembershipActionType.SendDelayedEvent
}];
try {
var _loop = function* _loop() {
_this._actions.sort((a, b) => a.ts - b.ts);
var nextAction = _this._actions[0];
var wakeupUpdate = void 0;
var wakeupPromise = new Promise((resolve) => {
_this.wakeup = (update) => {
wakeupUpdate = update;
resolve();
};
});
if (nextAction.ts > Date.now()) yield Promise.race([wakeupPromise, sleep(nextAction.ts - Date.now())]);
var handlerResult = {};
if (!wakeupUpdate) {
_this.logger.debug("Current MembershipManager processing: ".concat(nextAction.type, "\nQueue:"), _this._actions, "\nDate.now: \"".concat(Date.now()));
try {
handlerResult = yield _this.membershipLoopHandler(nextAction.type);
} catch (e) {
throw Error("The MembershipManager shut down because of the end condition: ".concat(e));
}
}
_this._actions.splice(0, 1);
var actionUpdate = wakeupUpdate !== null && wakeupUpdate !== void 0 ? wakeupUpdate : handlerResult;
if ("replace" in actionUpdate) _this._actions = actionUpdate.replace;
else if ("insert" in actionUpdate) _this._actions.push(...actionUpdate.insert);
};
while (_this._actions.length > 0) yield* _loop();
} finally {
_this.running = false;
}
_this.logger.debug("Leave MembershipManager ActionScheduler loop (no more actions)");
})();
}
initiateJoin() {
var _this$wakeup;
(_this$wakeup = this.wakeup) === null || _this$wakeup === void 0 || _this$wakeup.call(this, { replace: [{
ts: Date.now(),
type: MembershipActionType.SendDelayedEvent
}] });
}
initiateLeave() {
var _this$wakeup2;
(_this$wakeup2 = this.wakeup) === null || _this$wakeup2 === void 0 || _this$wakeup2.call(this, { replace: [{
ts: Date.now(),
type: MembershipActionType.SendScheduledDelayedLeaveEvent
}] });
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/errors.js
var InvalidCryptoStoreState = /* @__PURE__ */ function(InvalidCryptoStoreState) {
InvalidCryptoStoreState["TooNew"] = "TOO_NEW";
return InvalidCryptoStoreState;
}({});
var InvalidCryptoStoreError = class extends Error {
constructor(reason) {
var message = "Crypto store is invalid because ".concat(reason, ", ") + "please stop the client, delete all data and start the client again";
super(message);
this.reason = reason;
this.name = "InvalidCryptoStoreError";
}
};
(0, import_defineProperty.default)(InvalidCryptoStoreError, "TOO_NEW", InvalidCryptoStoreState.TooNew);
/**
* It is invalid to call most methods once {@link MatrixClient#stopClient} has been called.
*
* This error will be thrown if you attempt to do so.
*
* {@link MatrixClient#stopClient} itself is an exception to this: it may safely be called multiple times on the same
* instance.
*/
var ClientStoppedError = class extends Error {
constructor() {
super("MatrixClient has been stopped");
}
};
/**
* This error is thrown when the Homeserver does not support the delayed events endpoints.
*/
var UnsupportedDelayedEventsEndpointError = class extends Error {
constructor(message, clientEndpoint) {
super(message);
this.clientEndpoint = clientEndpoint;
this.name = "UnsupportedDelayedEventsEndpointError";
}
};
/**
* This error is thrown when the Homeserver does not support the sticky events endpoints.
*/
var UnsupportedStickyEventsEndpointError = class extends Error {
constructor(message, clientEndpoint) {
super(message);
this.clientEndpoint = clientEndpoint;
this.name = "UnsupportedStickyEventsEndpointError";
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/IMembershipManager.js
var MembershipManagerEvent = /* @__PURE__ */ function(MembershipManagerEvent) {
MembershipManagerEvent["StatusChanged"] = "StatusChanged";
/**
* Emitted when the membership manager has not heard back from the server for the duration
* of the delayed event and hence failed to restart the delayed event.
* This means that the user is probably not joined anymore and the leave event was distributed to other session members.
*/
MembershipManagerEvent["ProbablyLeft"] = "ProbablyLeft";
/**
* Once the membershipManger has aquired the a delay id (after sending the state event)
* It will emit and share the delay id.
*/
MembershipManagerEvent["DelayIdChanged"] = "DelayIdChanged";
return MembershipManagerEvent;
}({});
/**
* This interface defines what a MembershipManager uses and exposes.
* This interface is what we use to write tests and allows changing the actual implementation
* without breaking tests because of some internal method renaming.
*
* @internal
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/LivekitTransport.js
var isLivekitTransportConfig = (object) => object.type === "livekit" && "livekit_service_url" in object;
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.js
function ownKeys$4(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;
}
function _objectSpread$4(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$4(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* Call membership should always remain sticky for this amount
* of time.
*/
var MEMBERSHIP_STICKY_DURATION_MS = 3600 * 1e3;
/**
* The different types of actions the MembershipManager can take.
* @internal
*/
var MembershipActionType = /* @__PURE__ */ function(MembershipActionType) {
MembershipActionType["SendDelayedEvent"] = "SendDelayedEvent";
MembershipActionType["SendJoinEvent"] = "SendJoinEvent";
MembershipActionType["RestartDelayedEvent"] = "RestartDelayedEvent";
MembershipActionType["UpdateExpiry"] = "UpdateExpiry";
MembershipActionType["SendScheduledDelayedLeaveEvent"] = "SendScheduledDelayedLeaveEvent";
MembershipActionType["SendLeaveEvent"] = "SendLeaveEvent";
return MembershipActionType;
}({});
/**
* @internal
*/
function createInsertActionUpdate(type, offset) {
return { insert: [{
ts: Date.now() + (offset !== null && offset !== void 0 ? offset : 0),
type
}] };
}
function createReplaceActionUpdate(type, offset) {
return { replace: [{
ts: Date.now() + (offset !== null && offset !== void 0 ? offset : 0),
type
}] };
}
/**
* This class is responsible for sending all events relating to the own membership of a matrixRTC call.
* It has the following tasks:
* - Send the users leave delayed event before sending the membership
* - Send the users membership if the state machine is started
* - Check if the delayed event was canceled due to sending the membership
* - update the delayed event (`restart`)
* - Update the state event every ~5h = `DEFAULT_EXPIRE_DURATION` (so it does not get treated as expired)
* - When the state machine is stopped:
* - Disconnect the member
* - Stop the timer for the delay refresh
* - Stop the timer for updating the state event
*/
var MembershipManager = class MembershipManager extends TypedEventEmitter {
isActivated() {
return this.activated;
}
isJoined() {
return this.isActivated();
}
/**
* Puts the MembershipManager in a state where it tries to be joined.
* It will send delayed events and membership events
* @param fociPreferred the list of preferred foci to use in the joined RTC membership event.
* If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.
* @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the
* membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`
* transport selection will be used instead.
* @param onError This will be called once the membership manager encounters an unrecoverable error.
* This should bubble up the the frontend to communicate that the call does not work in the current environment.
*/
join(fociPreferred, multiSfuFocus, onError) {
if (this.scheduler.running) {
this.logger.error("MembershipManager is already running. Ignoring join request.");
return;
}
this.fociPreferred = fociPreferred;
this.rtcTransport = multiSfuFocus;
this.leavePromiseResolvers = void 0;
this.activated = true;
this.oldStatus = this.status;
this.state = MembershipManager.defaultState;
this.scheduler.startWithJoin().catch((e) => {
this.logger.error("MembershipManager stopped because: ", e);
onError === null || onError === void 0 || onError(e);
}).finally(() => {
this.activated = false;
if (this.oldStatus && this.oldStatus !== this.status) this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);
if (!this.scheduler.running) {
var _this$leavePromiseRes;
(_this$leavePromiseRes = this.leavePromiseResolvers) === null || _this$leavePromiseRes === void 0 || _this$leavePromiseRes.resolve(true);
this.leavePromiseResolvers = void 0;
}
});
}
/**
* Leave from the call (Send an rtc session event with content: `{}`)
* @param timeout the maximum duration this promise will take to resolve
* @returns true if it managed to leave and false if the timeout condition happened.
*/
leave(timeout) {
if (!this.scheduler.running) {
this.logger.warn("Called MembershipManager.leave() even though the MembershipManager is not running");
return Promise.resolve(true);
}
if (!this.leavePromiseResolvers) {
this.leavePromiseResolvers = Promise.withResolvers();
this.activated = false;
this.scheduler.initiateLeave();
if (timeout) setTimeout(() => {
var _this$leavePromiseRes2;
return (_this$leavePromiseRes2 = this.leavePromiseResolvers) === null || _this$leavePromiseRes2 === void 0 ? void 0 : _this$leavePromiseRes2.resolve(false);
}, timeout);
}
return this.leavePromiseResolvers.promise;
}
onRTCSessionMemberUpdate(memberships) {
if (!this.isActivated()) return Promise.resolve();
this._ownMembership = memberships.find((m) => isMyMembership(m, this.userId, this.deviceId));
if (!this._ownMembership) {
var sendingMembershipActions = [MembershipActionType.SendDelayedEvent, MembershipActionType.SendJoinEvent];
this.logger.warn("Missing own membership: force re-join");
this.state.hasMemberStateEvent = false;
if (this.scheduler.actions.some((a) => sendingMembershipActions.includes(a.type))) this.logger.error("tried adding another `SendDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:", this.scheduler.actions);
else this.scheduler.initiateJoin();
}
return Promise.resolve();
}
updateCallIntent(callIntent) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this.activated || !_this.ownMembership) throw Error("You cannot update your intent before joining the call");
if (_this.ownMembership.callIntent === callIntent) return;
_this.callIntent = callIntent;
yield _this.sendJoinEvent();
})();
}
/**
* @throws if the client does not return user or device id.
* @param joinConfig
* @param room
* @param client
*/
constructor(joinConfig, room, client, slotDescription, parentLogger) {
super();
this.joinConfig = joinConfig;
this.room = room;
this.client = client;
this.slotDescription = slotDescription;
(0, import_defineProperty.default)(this, "activated", false);
(0, import_defineProperty.default)(this, "logger", void 0);
(0, import_defineProperty.default)(this, "callIntent", void 0);
(0, import_defineProperty.default)(this, "leavePromiseResolvers", void 0);
(0, import_defineProperty.default)(this, "_ownMembership", void 0);
(0, import_defineProperty.default)(this, "oldStatus", void 0);
(0, import_defineProperty.default)(this, "scheduler", void 0);
(0, import_defineProperty.default)(this, "state", void 0);
(0, import_defineProperty.default)(this, "deviceId", void 0);
(0, import_defineProperty.default)(this, "userId", void 0);
(0, import_defineProperty.default)(this, "stateKey", void 0);
(0, import_defineProperty.default)(this, "rtcTransport", void 0);
/** @deprecated This will be removed in favor or rtcTransport becoming a list of actively used transports */
(0, import_defineProperty.default)(this, "fociPreferred", void 0);
(0, import_defineProperty.default)(this, "delayedLeaveEventDelayMsOverride", void 0);
(0, import_defineProperty.default)(this, "clientSendDelayedDisconnectMembership", () => this.client._unstable_sendDelayedStateEvent(this.room.roomId, { delay: this.delayedLeaveEventDelayMs }, EventType.GroupCallMemberPrefix, {}, this.stateKey));
(0, import_defineProperty.default)(this, "clientSendMembership", (myMembership) => {
return this.client.sendStateEvent(this.room.roomId, EventType.GroupCallMemberPrefix, myMembership, this.stateKey);
});
this.logger = (parentLogger !== null && parentLogger !== void 0 ? parentLogger : logger$2).getChild("[MembershipManager]");
var [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];
if (userId === null) throw Error("Missing userId in client");
if (deviceId === null) throw Error("Missing deviceId in client");
this.deviceId = deviceId;
this.userId = userId;
this.stateKey = this.makeMembershipStateKey(userId, deviceId);
this.state = MembershipManager.defaultState;
this.callIntent = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.callIntent;
this.scheduler = new ActionScheduler((type) => {
if (this.oldStatus) {
this.logger.debug("MembershipManager applied action changes. Status: ".concat(this.oldStatus, " -> ").concat(this.status));
if (this.oldStatus !== this.status) this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);
}
this.oldStatus = this.status;
this.logger.debug("MembershipManager before processing action. status=".concat(this.oldStatus));
return this.membershipLoopHandler(type);
}, this.logger);
}
get ownMembership() {
return this._ownMembership;
}
static get defaultState() {
return {
hasMemberStateEvent: false,
delayId: void 0,
startTime: 0,
rateLimitRetries: /* @__PURE__ */ new Map(),
networkErrorRetries: /* @__PURE__ */ new Map(),
expireUpdateIterations: 1,
probablyLeft: false
};
}
get networkErrorRetryMs() {
var _this$joinConfig$netw, _this$joinConfig;
return (_this$joinConfig$netw = (_this$joinConfig = this.joinConfig) === null || _this$joinConfig === void 0 ? void 0 : _this$joinConfig.networkErrorRetryMs) !== null && _this$joinConfig$netw !== void 0 ? _this$joinConfig$netw : 3e3;
}
get membershipEventExpiryMs() {
var _this$joinConfig$memb, _this$joinConfig2;
return (_this$joinConfig$memb = (_this$joinConfig2 = this.joinConfig) === null || _this$joinConfig2 === void 0 ? void 0 : _this$joinConfig2.membershipEventExpiryMs) !== null && _this$joinConfig$memb !== void 0 ? _this$joinConfig$memb : DEFAULT_EXPIRE_DURATION;
}
get membershipEventExpiryHeadroomMs() {
var _this$joinConfig$memb2, _this$joinConfig3;
return (_this$joinConfig$memb2 = (_this$joinConfig3 = this.joinConfig) === null || _this$joinConfig3 === void 0 ? void 0 : _this$joinConfig3.membershipEventExpiryHeadroomMs) !== null && _this$joinConfig$memb2 !== void 0 ? _this$joinConfig$memb2 : 5e3;
}
computeNextExpiryActionTs(iteration) {
return this.state.startTime + Math.min(this.membershipEventExpiryMs, MEMBERSHIP_STICKY_DURATION_MS) * iteration - this.membershipEventExpiryHeadroomMs;
}
get delayedLeaveEventDelayMs() {
var _ref, _this$delayedLeaveEve, _this$joinConfig4;
return (_ref = (_this$delayedLeaveEve = this.delayedLeaveEventDelayMsOverride) !== null && _this$delayedLeaveEve !== void 0 ? _this$delayedLeaveEve : (_this$joinConfig4 = this.joinConfig) === null || _this$joinConfig4 === void 0 ? void 0 : _this$joinConfig4.delayedLeaveEventDelayMs) !== null && _ref !== void 0 ? _ref : 8e3;
}
get delayedLeaveEventRestartMs() {
var _this$joinConfig$dela, _this$joinConfig5;
return (_this$joinConfig$dela = (_this$joinConfig5 = this.joinConfig) === null || _this$joinConfig5 === void 0 ? void 0 : _this$joinConfig5.delayedLeaveEventRestartMs) !== null && _this$joinConfig$dela !== void 0 ? _this$joinConfig$dela : 5e3;
}
get maximumRateLimitRetryCount() {
var _this$joinConfig$maxi, _this$joinConfig6;
return (_this$joinConfig$maxi = (_this$joinConfig6 = this.joinConfig) === null || _this$joinConfig6 === void 0 ? void 0 : _this$joinConfig6.maximumRateLimitRetryCount) !== null && _this$joinConfig$maxi !== void 0 ? _this$joinConfig$maxi : 10;
}
get maximumNetworkErrorRetryCount() {
var _this$joinConfig$maxi2, _this$joinConfig7;
return (_this$joinConfig$maxi2 = (_this$joinConfig7 = this.joinConfig) === null || _this$joinConfig7 === void 0 ? void 0 : _this$joinConfig7.maximumNetworkErrorRetryCount) !== null && _this$joinConfig$maxi2 !== void 0 ? _this$joinConfig$maxi2 : 10;
}
get delayedLeaveEventRestartLocalTimeoutMs() {
var _this$joinConfig$dela2, _this$joinConfig8;
return (_this$joinConfig$dela2 = (_this$joinConfig8 = this.joinConfig) === null || _this$joinConfig8 === void 0 ? void 0 : _this$joinConfig8.delayedLeaveEventRestartLocalTimeoutMs) !== null && _this$joinConfig$dela2 !== void 0 ? _this$joinConfig$dela2 : 2e3;
}
membershipLoopHandler(type) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
switch (type) {
case MembershipActionType.SendDelayedEvent: if (!_this2.state.delayId) return _this2.sendOrResendDelayedLeaveEvent();
else return _this2.cancelKnownDelayIdBeforeSendDelayedEvent(_this2.state.delayId);
case MembershipActionType.RestartDelayedEvent:
if (!_this2.state.delayId) return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);
return _this2.restartDelayedEvent(_this2.state.delayId);
case MembershipActionType.SendScheduledDelayedLeaveEvent:
if (!_this2.state.hasMemberStateEvent) return { replace: [] };
if (_this2.state.delayId) return _this2.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(_this2.state.delayId);
else return createInsertActionUpdate(MembershipActionType.SendLeaveEvent);
case MembershipActionType.SendJoinEvent: return _this2.sendJoinEvent();
case MembershipActionType.UpdateExpiry: return _this2.updateExpiryOnJoinedEvent();
case MembershipActionType.SendLeaveEvent:
if (!_this2.state.hasMemberStateEvent) return { replace: [] };
return _this2.sendFallbackLeaveEvent();
}
})();
}
sendOrResendDelayedLeaveEvent() {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this3.clientSendDelayedDisconnectMembership().then((response) => {
_this3.state.expectedServerDelayLeaveTs = Date.now() + _this3.delayedLeaveEventDelayMs;
_this3.setAndEmitProbablyLeft(false);
_this3.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);
_this3.setAndEmitDelayId(response.delay_id);
if (_this3.state.hasMemberStateEvent) return createInsertActionUpdate(MembershipActionType.RestartDelayedEvent, _this3.delayedLeaveEventRestartMs);
else return createInsertActionUpdate(MembershipActionType.SendJoinEvent);
}).catch((e) => {
var repeatActionType = MembershipActionType.SendDelayedEvent;
if (_this3.manageMaxDelayExceededSituation(e)) return createInsertActionUpdate(repeatActionType);
var update = _this3.actionUpdateFromErrors(e, repeatActionType, "_unstable_sendDelayedStateEvent");
if (update) return update;
if (_this3.state.hasMemberStateEvent) {
if (_this3.isUnsupportedDelayedEndpoint(e)) return {};
throw Error("Could not send delayed event, even though delayed events are supported. " + e);
} else {
if (_this3.isUnsupportedDelayedEndpoint(e)) _this3.logger.info("Not using delayed event because the endpoint is not supported");
else _this3.logger.info("Not using delayed event because: " + e);
return createInsertActionUpdate(MembershipActionType.SendJoinEvent);
}
});
})();
}
cancelKnownDelayIdBeforeSendDelayedEvent(delayId) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this4.client._unstable_cancelScheduledDelayedEvent(delayId).then(() => {
_this4.setAndEmitDelayId(void 0);
_this4.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);
return createReplaceActionUpdate(MembershipActionType.SendDelayedEvent);
}).catch((e) => {
var repeatActionType = MembershipActionType.SendDelayedEvent;
var update = _this4.actionUpdateFromErrors(e, repeatActionType, "cancelScheduledDelayedEvent");
if (update) return update;
if (_this4.isNotFoundError(e)) {
_this4.setAndEmitDelayId(void 0);
return createReplaceActionUpdate(repeatActionType);
}
if (_this4.isUnsupportedDelayedEndpoint(e)) return createReplaceActionUpdate(MembershipActionType.SendJoinEvent);
throw Error("We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle");
});
})();
}
setAndEmitProbablyLeft(probablyLeft) {
if (this.state.probablyLeft === probablyLeft) return;
this.state.probablyLeft = probablyLeft;
this.emit(MembershipManagerEvent.ProbablyLeft, this.state.probablyLeft);
}
setAndEmitDelayId(delayId) {
if (this.state.delayId === delayId) return;
this.state.delayId = delayId;
this.emit(MembershipManagerEvent.DelayIdChanged, this.state.delayId);
}
restartDelayedEvent(delayId) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var durationUntilServerDelayedLeave = _this5.state.expectedServerDelayLeaveTs ? _this5.state.expectedServerDelayLeaveTs - Date.now() : void 0;
var abortPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new AbortError("Restart delayed event timed out before the HS responded"));
}, durationUntilServerDelayedLeave !== void 0 && !_this5.state.probablyLeft ? Math.min(_this5.delayedLeaveEventRestartLocalTimeoutMs, durationUntilServerDelayedLeave) : _this5.delayedLeaveEventRestartLocalTimeoutMs);
});
return yield Promise.race([_this5.client._unstable_restartScheduledDelayedEvent(delayId), abortPromise]).then(() => {
_this5.state.expectedServerDelayLeaveTs = Date.now() + _this5.delayedLeaveEventDelayMs;
_this5.resetRateLimitCounter(MembershipActionType.RestartDelayedEvent);
_this5.setAndEmitProbablyLeft(false);
return createInsertActionUpdate(MembershipActionType.RestartDelayedEvent, _this5.delayedLeaveEventRestartMs);
}).catch((e) => {
if (_this5.state.expectedServerDelayLeaveTs && _this5.state.expectedServerDelayLeaveTs <= Date.now()) _this5.setAndEmitProbablyLeft(true);
var repeatActionType = MembershipActionType.RestartDelayedEvent;
if (_this5.isNotFoundError(e)) {
_this5.setAndEmitDelayId(void 0);
return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);
}
if (_this5.isUnsupportedDelayedEndpoint(e)) return {};
var update = _this5.actionUpdateFromErrors(e, repeatActionType, "restartScheduledDelayedEvent");
if (update) return update;
throw Error("Could not restart delayed event, even though delayed events are supported. " + e);
});
})();
}
sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(delayId) {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this6.client._unstable_sendScheduledDelayedEvent(delayId).then(() => {
_this6.state.hasMemberStateEvent = false;
_this6.setAndEmitDelayId(void 0);
_this6.resetRateLimitCounter(MembershipActionType.SendScheduledDelayedLeaveEvent);
return { replace: [] };
}).catch((e) => {
var repeatActionType = MembershipActionType.SendLeaveEvent;
if (_this6.isUnsupportedDelayedEndpoint(e)) return {};
if (_this6.isNotFoundError(e)) {
_this6.setAndEmitDelayId(void 0);
return createInsertActionUpdate(repeatActionType);
}
var update = _this6.actionUpdateFromErrors(e, repeatActionType, "sendScheduledDelayedEvent");
if (update) return update;
_this6.logger.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent", e);
return createInsertActionUpdate(repeatActionType);
});
})();
}
sendJoinEvent() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this7.clientSendMembership(_this7.makeMyMembership(_this7.membershipEventExpiryMs)).then(() => {
_this7.setAndEmitProbablyLeft(false);
_this7.state.startTime = Date.now();
_this7.state.expireUpdateIterations = 1;
_this7.state.hasMemberStateEvent = true;
_this7.resetRateLimitCounter(MembershipActionType.SendJoinEvent);
return { replace: [
..._this7.scheduler.actions.filter((a) => a.type !== MembershipActionType.UpdateExpiry && a.type !== MembershipActionType.SendJoinEvent),
{
ts: Date.now(),
type: MembershipActionType.RestartDelayedEvent
},
{
ts: _this7.computeNextExpiryActionTs(_this7.state.expireUpdateIterations),
type: MembershipActionType.UpdateExpiry
}
] };
}).catch((e) => {
var update = _this7.actionUpdateFromErrors(e, MembershipActionType.SendJoinEvent, "sendStateEvent");
if (update) return update;
throw e;
});
})();
}
updateExpiryOnJoinedEvent() {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var nextExpireUpdateIteration = _this8.state.expireUpdateIterations + 1;
return yield _this8.clientSendMembership(_this8.makeMyMembership(_this8.membershipEventExpiryMs * nextExpireUpdateIteration)).then(() => {
_this8.resetRateLimitCounter(MembershipActionType.UpdateExpiry);
_this8.state.expireUpdateIterations = nextExpireUpdateIteration;
return { insert: [{
ts: _this8.computeNextExpiryActionTs(nextExpireUpdateIteration),
type: MembershipActionType.UpdateExpiry
}] };
}).catch((e) => {
var update = _this8.actionUpdateFromErrors(e, MembershipActionType.UpdateExpiry, "sendStateEvent");
if (update) return update;
throw e;
});
})();
}
sendFallbackLeaveEvent() {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this9.clientSendMembership({}).then(() => {
_this9.resetRateLimitCounter(MembershipActionType.SendLeaveEvent);
_this9.state.hasMemberStateEvent = false;
return { replace: [] };
}).catch((e) => {
var update = _this9.actionUpdateFromErrors(e, MembershipActionType.SendLeaveEvent, "sendStateEvent");
if (update) return update;
throw e;
});
})();
}
/**
* this creates `${localUserId}_${localDeviceId}_${this.slotDescription.application}${this.slotDescription.id}`
* which is not compatible with membershipID of session type member events. They have to be `${localUserId}:${localDeviceId}`
*/
makeMembershipStateKey(localUserId, localDeviceId) {
var application = this.slotDescription.application;
var slotId = application === "m.call" && this.slotDescription.id === "ROOM" ? "" : this.slotDescription.id;
var stateKey = "".concat(localUserId, "_").concat(localDeviceId, "_").concat(application).concat(slotId);
if (/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())) return stateKey;
else return "_".concat(stateKey);
}
/**
* Constructs our own membership
* @returns Only returns `SessionMembershipData`
*/
makeMyMembership(expires) {
var _this$fociPreferred, _this$fociPreferred2;
var ownMembership = this.ownMembership;
var needsEmptyStringRoomFix = this.slotDescription.application === "m.call" && this.slotDescription.id === "ROOM";
var focusObjects = this.rtcTransport === void 0 ? {
focus_active: {
type: "livekit",
focus_selection: "oldest_membership"
},
foci_preferred: (_this$fociPreferred = this.fociPreferred) !== null && _this$fociPreferred !== void 0 ? _this$fociPreferred : []
} : {
focus_active: {
type: "livekit",
focus_selection: "multi_sfu"
},
foci_preferred: [this.rtcTransport, ...(_this$fociPreferred2 = this.fociPreferred) !== null && _this$fociPreferred2 !== void 0 ? _this$fociPreferred2 : []]
};
return _objectSpread$4(_objectSpread$4({
"application": this.slotDescription.application,
"call_id": needsEmptyStringRoomFix ? "" : this.slotDescription.id,
"scope": "m.room",
"device_id": this.deviceId,
"membershipID": "".concat(this.userId, ":").concat(this.deviceId),
expires,
"m.call.intent": this.callIntent
}, focusObjects), ownMembership !== void 0 ? { created_ts: ownMembership.createdTs() } : void 0);
}
/**
* Check if its a NOT_FOUND error
* @param error the error causing this handler check/execution
* @returns true if its a not found error
*/
isNotFoundError(error) {
return error instanceof MatrixError && error.errcode === "M_NOT_FOUND";
}
/**
* Check if this is a DelayExceeded timeout and update the TimeoutOverride for the next try
* @param error the error causing this handler check/execution
* @returns true if its a delay exceeded error and we updated the local TimeoutOverride
*/
manageMaxDelayExceededSituation(error) {
if (error instanceof MatrixError && error.errcode === "M_UNKNOWN" && error.data["org.matrix.msc4140.errcode"] === "M_MAX_DELAY_EXCEEDED") {
var maxDelayAllowed = error.data["org.matrix.msc4140.max_delay"];
if (typeof maxDelayAllowed === "number" && this.delayedLeaveEventDelayMs > maxDelayAllowed) this.delayedLeaveEventDelayMsOverride = maxDelayAllowed;
this.logger.warn("Retry sending delayed disconnection event due to server timeout limitations:", error);
return true;
}
return false;
}
actionUpdateFromErrors(error, type, method) {
var updateLimit = this.actionUpdateFromRateLimitError(error, method, type);
if (updateLimit) return updateLimit;
var updateNetwork = this.actionUpdateFromNetworkErrorRetry(error, type);
if (updateNetwork) return updateNetwork;
}
/**
* Check if we have a rate limit error and schedule the same action again if we dont exceed the rate limit retry count yet.
* @param error the error causing this handler check/execution
* @param method the method used for the throw message
* @param type which MembershipActionType we reschedule because of a rate limit.
* @throws If it is a rate limit error and the retry count got exceeded
* @returns Returns true if we handled the error by rescheduling the correct next action.
* Returns false if it is not a network error.
*/
actionUpdateFromRateLimitError(error, method, type) {
var _this$state$rateLimit;
if (!((error instanceof HTTPError || error instanceof MatrixError) && error.isRateLimitError())) return;
var rateLimitRetries = (_this$state$rateLimit = this.state.rateLimitRetries.get(type)) !== null && _this$state$rateLimit !== void 0 ? _this$state$rateLimit : 0;
if (rateLimitRetries < this.maximumRateLimitRetryCount) {
var resendDelay;
var defaultMs = 5e3;
try {
var _error$getRetryAfterM;
resendDelay = (_error$getRetryAfterM = error.getRetryAfterMs()) !== null && _error$getRetryAfterM !== void 0 ? _error$getRetryAfterM : defaultMs;
this.logger.info("Rate limited by server, retrying in ".concat(resendDelay, "ms"));
} catch (e) {
this.logger.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(defaultMs), e);
resendDelay = defaultMs;
}
this.state.rateLimitRetries.set(type, rateLimitRetries + 1);
return createInsertActionUpdate(type, resendDelay);
}
throw Error("Exceeded maximum retries for " + type + " attempts (client." + method + ")", { cause: error });
}
/**
* FIXME Don't Check the error and retry the same MembershipAction again in the configured time and for the configured retry count.
* @param error the error causing this handler check/execution
* @param type the action type that we need to repeat because of the error
* @throws If it is a network error and the retry count got exceeded
* @returns
* Returns true if we handled the error by rescheduling the correct next action.
* Returns false if it is not a network error.
*/
actionUpdateFromNetworkErrorRetry(error, type) {
var _this$state$networkEr;
var retries = (_this$state$networkEr = this.state.networkErrorRetries.get(type)) !== null && _this$state$networkEr !== void 0 ? _this$state$networkEr : 0;
var retryDurationString = this.networkErrorRetryMs / 1e3 + "s";
var retryCounterString = "(" + retries + "/" + this.maximumNetworkErrorRetryCount + ")";
var retryDuration = this.networkErrorRetryMs;
if (error instanceof Error && error.name === "AbortError") {
retryDuration = 0;
this.logger.warn("Network local timeout error while sending event, immediate retry (" + retryCounterString + ")", error);
} else if (error instanceof Error && error.message.includes("updating delayed event")) this.logger.warn("delayed event update timeout error, retrying in " + retryDurationString + " " + retryCounterString, error);
else if (error instanceof ConnectionError) this.logger.warn("Network connection error while sending event, retrying in " + retryDurationString + " " + retryCounterString, error);
else if ((error instanceof HTTPError || error instanceof MatrixError) && typeof error.httpStatus === "number" && error.httpStatus >= 500 && error.httpStatus < 600) this.logger.warn("Server error while sending event, retrying in " + retryDurationString + " " + retryCounterString, error);
else return;
if (retries < this.maximumNetworkErrorRetryCount) {
this.state.networkErrorRetries.set(type, retries + 1);
return createInsertActionUpdate(type, retryDuration);
}
throw Error("Reached maximum (" + this.maximumNetworkErrorRetryCount + ") retries cause by: " + error);
}
/**
* Check if its an UnsupportedDelayedEventsEndpointError and which implies that we cannot do any delayed event logic
* @param error The error to check
* @returns true it its an UnsupportedDelayedEventsEndpointError
*/
isUnsupportedDelayedEndpoint(error) {
return error instanceof UnsupportedDelayedEventsEndpointError;
}
resetRateLimitCounter(type) {
this.state.rateLimitRetries.set(type, 0);
this.state.networkErrorRetries.set(type, 0);
}
get status() {
var actions = this.scheduler.actions;
if (actions.length === 1) {
var { type } = actions[0];
switch (type) {
case MembershipActionType.SendDelayedEvent:
case MembershipActionType.SendJoinEvent: return Status.Connecting;
case MembershipActionType.UpdateExpiry: return Status.Connected;
case MembershipActionType.SendScheduledDelayedLeaveEvent:
case MembershipActionType.SendLeaveEvent: return Status.Disconnecting;
default:
}
} else if (actions.length === 2) {
var types = actions.map((a) => a.type);
if ((types.includes(MembershipActionType.RestartDelayedEvent) || types.includes(MembershipActionType.SendDelayedEvent) && this.state.hasMemberStateEvent) && types.includes(MembershipActionType.UpdateExpiry)) return Status.Connected;
} else if (actions.length === 3) {
var _types = actions.map((a) => a.type);
if (_types.filter((t) => t === MembershipActionType.RestartDelayedEvent).length === 2 && _types.includes(MembershipActionType.UpdateExpiry)) return Status.Connected;
}
if (!this.scheduler.running) return Status.Disconnected;
this.logger.error("MembershipManager has an unknown state. Actions: ", actions);
return Status.Unknown;
}
get probablyLeft() {
return this.state.probablyLeft;
}
get delayId() {
return this.state.delayId;
}
};
/**
* Implementation of the Membership manager that uses sticky events
* rather than state events.
*/
var StickyEventMembershipManager = class StickyEventMembershipManager extends MembershipManager {
constructor(joinConfig, room, clientWithSticky, sessionDescription, memberId, parentLogger) {
super(joinConfig, room, clientWithSticky, sessionDescription, parentLogger);
this.clientWithSticky = clientWithSticky;
this.memberId = memberId;
(0, import_defineProperty.default)(this, "clientSendDelayedDisconnectMembership", () => this.clientWithSticky._unstable_sendStickyDelayedEvent(this.room.roomId, MEMBERSHIP_STICKY_DURATION_MS, { delay: this.delayedLeaveEventDelayMs }, null, EventType.RTCMembership, { msc4354_sticky_key: this.memberId }));
(0, import_defineProperty.default)(this, "clientSendMembership", (myMembership) => {
return this.clientWithSticky._unstable_sendStickyEvent(this.room.roomId, MEMBERSHIP_STICKY_DURATION_MS, null, EventType.RTCMembership, _objectSpread$4(_objectSpread$4({}, myMembership), {}, { msc4354_sticky_key: this.memberId }));
});
}
actionUpdateFromErrors(e, t, m) {
var _StickyEventMembershi;
return super.actionUpdateFromErrors(e, t, (_StickyEventMembershi = StickyEventMembershipManager.nameMap.get(m)) !== null && _StickyEventMembershi !== void 0 ? _StickyEventMembershi : "unknown");
}
/**
*
* @returns Only returns `RtcMembershipData`
*/
makeMyMembership() {
var ownMembership = this.ownMembership;
var livekitTransport = isLivekitTransportConfig(this.rtcTransport) ? this.rtcTransport : void 0;
var relationObject = ownMembership !== null && ownMembership !== void 0 && ownMembership.eventId ? { "m.relation": {
rel_type: RelationType.Reference,
event_id: ownMembership === null || ownMembership === void 0 ? void 0 : ownMembership.eventId
} } : {};
return _objectSpread$4({
application: _objectSpread$4({ type: this.slotDescription.application }, this.callIntent ? { "m.call.intent": this.callIntent } : {}),
slot_id: computeSlotId(this.slotDescription),
rtc_transports: livekitTransport ? [{
type: livekitTransport.type,
livekit_service_url: livekitTransport.livekit_service_url
}] : [],
member: {
device_id: this.deviceId,
user_id: this.userId,
id: this.memberId
},
versions: []
}, relationObject);
}
};
(0, import_defineProperty.default)(StickyEventMembershipManager, "nameMap", new Map([["sendStateEvent", "_unstable_sendStickyEvent"], ["sendDelayedStateEvent", "_unstable_sendStickyDelayedEvent"]]));
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/IKeyTransport.js
var KeyTransportEvents = /* @__PURE__ */ function(KeyTransportEvents) {
KeyTransportEvents["ReceivedKeys"] = "received_keys";
KeyTransportEvents["NotSupportedError"] = "not_supported_error";
return KeyTransportEvents;
}({});
/**
* Generic interface for the transport used to share room keys.
* Keys can be shared using different transports, e.g. to-device messages or room messages.
*/
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/RTCEncryptionManager.js
/**
* RTCEncryptionManager is used to manage the encryption keys for a call.
*
* It is responsible for distributing the keys to the other participants and rotating the keys if needed.
*
* This manager when used with to-device transport will share the existing key only to new joiners, and rotate
* if there is a leaver.
*
* XXX In the future we want to distribute a ratcheted key not the current one for new joiners.
*/
var RTCEncryptionManager = class {
/**
*
* @param ownMembership - our own membership info
* @param getMemberships - function to get current memberships
* @param transport - key transport (room or to-device)
* @param statistics - statistics collector
* @param onEncryptionKeysChanged - callback to notify the media layer of new keys
* @param parentLogger - optional parent logger
* @param rtcBackendIdProvider - A function to compute the rtc backend identity, exposed for testing purposes
*/
constructor(ownMembership, getMemberships, transport, onEncryptionKeysChanged, parentLogger, rtcBackendIdProvider) {
this.ownMembership = ownMembership;
this.getMemberships = getMemberships;
this.transport = transport;
this.onEncryptionKeysChanged = onEncryptionKeysChanged;
(0, import_defineProperty.default)(this, "manageMediaKeys", false);
(0, import_defineProperty.default)(this, "useHashedRtcBackendIdentity", false);
(0, import_defineProperty.default)(this, "ownRtcBackendIdentityCache", void 0);
/**
* Store the key rings for each participant.
* The encryption manager stores the keys because the application layer might not be ready yet to handle the keys.
* The keys are stored and can be retrieved later when the application layer is ready {@link RTCEncryptionManager#getEncryptionKeys}.
*/
(0, import_defineProperty.default)(this, "participantKeyRings", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "outboundSession", null);
/**
* Ensures that there is only one distribute operation at a time for that call.
*/
(0, import_defineProperty.default)(this, "currentKeyDistributionPromise", null);
/**
* The time to wait before using the outbound session after it has been distributed.
* This is to ensure that the key is delivered to all participants before it is used.
* When creating the first key, this is set to 0 so that the key can be used immediately.
*/
(0, import_defineProperty.default)(this, "useKeyDelay", 5e3);
/**
* We want to avoid rolling out a new outbound key when the previous one was created less than `keyRotationGracePeriodMs` milliseconds ago.
* This is to avoid expensive key rotations when users quickly join the call in a row.
*
* This must be higher than `useKeyDelay` to have an effect.
* If it is lower, the current key will always be older than the grace period.
* @private
*/
(0, import_defineProperty.default)(this, "keyRotationGracePeriodMs", 1e4);
/**
* If a new key distribution is being requested while one is going on, we will set this flag to true.
* This will ensure that a new round is started after the current one.
* @private
*/
(0, import_defineProperty.default)(this, "needToEnsureKeyAgain", false);
/**
* There is a possibility that keys arrive in the wrong order.
* For example, after a quick join/leave/join, there will be 2 keys of index 0 distributed, and
* if they are received in the wrong order, the stream won't be decryptable.
* For that reason we keep a small buffer of keys for a limited time to disambiguate.
* @private
*/
(0, import_defineProperty.default)(this, "keyBuffer", new OutdatedKeyFilter());
(0, import_defineProperty.default)(this, "logger", void 0);
(0, import_defineProperty.default)(this, "rtcIdentityProvider", void 0);
(0, import_defineProperty.default)(this, "keysWithoutMatchingRTCMembership", []);
(0, import_defineProperty.default)(this, "onNewKeyReceived", (membership, keyBase64Encoded, index, timestamp) => {
var _this$logger2;
if (!this.manageMediaKeys) {
var _this$logger;
(_this$logger = this.logger) === null || _this$logger === void 0 || _this$logger.warn("Received key over transport ".concat(membership.userId, ":").concat(membership.deviceId, " at index ").concat(index, " but media keys are disabled"));
return;
}
(_this$logger2 = this.logger) === null || _this$logger2 === void 0 || _this$logger2.debug("Received key over transport ".concat(membership.userId, ":").concat(membership.deviceId, " at index ").concat(index));
var candidateInboundSession = {
key: decodeBase64(keyBase64Encoded),
membership,
keyIndex: index,
creationTS: timestamp
};
if (!this.keyBuffer.isOutdated(membership, candidateInboundSession)) this.addKeyToParticipant(candidateInboundSession.key, candidateInboundSession.keyIndex, candidateInboundSession.membership);
else {
var _this$logger3;
(_this$logger3 = this.logger) === null || _this$logger3 === void 0 || _this$logger3.info("Received an out of order key for ".concat(membership.userId, ":").concat(membership.deviceId, ", dropping it"));
}
});
this.logger = parentLogger === null || parentLogger === void 0 ? void 0 : parentLogger.getChild("[EncryptionManager]");
this.rtcIdentityProvider = rtcBackendIdProvider !== null && rtcBackendIdProvider !== void 0 ? rtcBackendIdProvider : computeRtcIdentityRaw;
}
getOwnRtcBackendIdentity() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this.ownRtcBackendIdentityCache) return _this.ownRtcBackendIdentityCache;
if (_this.useHashedRtcBackendIdentity) {
var _this$logger4;
var { userId, deviceId, memberId } = _this.ownMembership;
(_this$logger4 = _this.logger) === null || _this$logger4 === void 0 || _this$logger4.info("Computing RTC backend identity for ".concat(userId, ":").concat(deviceId, ":").concat(memberId, " (SHOULD ONLY BE CALLED ONCE)"));
_this.ownRtcBackendIdentityCache = yield _this.rtcIdentityProvider(userId, deviceId, memberId);
} else _this.ownRtcBackendIdentityCache = "".concat(_this.ownMembership.userId, ":").concat(_this.ownMembership.deviceId);
return _this.ownRtcBackendIdentityCache;
})();
}
getEncryptionKeys() {
return new Map(this.participantKeyRings);
}
checkKeysWithoutMatchingRTCMembership() {
var keyInfoTemp = this.keysWithoutMatchingRTCMembership;
this.keysWithoutMatchingRTCMembership = [];
keyInfoTemp.forEach((keyInfo) => {
this.addKeyToParticipant(keyInfo.key, keyInfo.keyIndex, keyInfo.membership);
});
}
addKeyToParticipant(key, keyIndex, membership) {
var fullMembership = this.getMemberships().find((member) => member.userId === membership.userId && member.deviceId === membership.deviceId);
if (!fullMembership) {
var _this$logger5;
(_this$logger5 = this.logger) === null || _this$logger5 === void 0 || _this$logger5.info("No matching RTC membership for key from ".concat(membership.userId, ":").concat(membership.deviceId, ", delaying key addition"));
this.keysWithoutMatchingRTCMembership.push({
key,
keyIndex,
membership
});
return;
}
this.addKeyToParticipantWithBackendIdentity(key, keyIndex, membership, fullMembership.rtcBackendIdentity);
}
addKeyToParticipantWithBackendIdentity(key, keyIndex, membership, rtcBackendIdentity) {
var mapKey = getEncryptionKeyMapKey(membership);
if (!this.participantKeyRings.has(mapKey)) this.participantKeyRings.set(mapKey, []);
this.participantKeyRings.get(mapKey).push({
key,
keyIndex,
membership,
rtcBackendIdentity
});
this.onEncryptionKeysChanged(key, keyIndex, membership, rtcBackendIdentity);
}
join(joinConfig) {
var _joinConfig$manageMed, _joinConfig$unstableS, _joinConfig$useKeyDel, _joinConfig$keyRotati, _this$logger6;
this.manageMediaKeys = (_joinConfig$manageMed = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.manageMediaKeys) !== null && _joinConfig$manageMed !== void 0 ? _joinConfig$manageMed : true;
this.useHashedRtcBackendIdentity = (_joinConfig$unstableS = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.unstableSendStickyEvents) !== null && _joinConfig$unstableS !== void 0 ? _joinConfig$unstableS : false;
this.useKeyDelay = (_joinConfig$useKeyDel = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.useKeyDelay) !== null && _joinConfig$useKeyDel !== void 0 ? _joinConfig$useKeyDel : 1e3;
this.keyRotationGracePeriodMs = (_joinConfig$keyRotati = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.keyRotationGracePeriodMs) !== null && _joinConfig$keyRotati !== void 0 ? _joinConfig$keyRotati : 1e4;
this.transport.on(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);
this.getOwnRtcBackendIdentity();
(_this$logger6 = this.logger) === null || _this$logger6 === void 0 || _this$logger6.info("Joining room");
this.transport.start();
}
leave() {
this.transport.off(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);
this.transport.stop();
this.participantKeyRings.clear();
}
/**
* Will ensure that a new key is distributed and used to encrypt our media.
* If there is already a key distribution in progress, it will schedule a new distribution round just after the current one is completed.
* If this function is called repeatedly while a distribution is in progress,
* the calls will be coalesced to a single new distribution (that will start just after the current one has completed).
*/
ensureKeyDistribution() {
if (!this.manageMediaKeys) return;
if (this.currentKeyDistributionPromise == null) {
var _this$logger7;
(_this$logger7 = this.logger) === null || _this$logger7 === void 0 || _this$logger7.debug("No active rollout, start a new one");
this.currentKeyDistributionPromise = this.rolloutOutboundKey().then(() => {
var _this$logger8;
(_this$logger8 = this.logger) === null || _this$logger8 === void 0 || _this$logger8.debug("Rollout completed");
this.currentKeyDistributionPromise = null;
if (this.needToEnsureKeyAgain) {
var _this$logger9;
(_this$logger9 = this.logger) === null || _this$logger9 === void 0 || _this$logger9.debug("New Rollout needed");
this.needToEnsureKeyAgain = false;
this.ensureKeyDistribution();
}
});
} else {
var _this$logger0;
(_this$logger0 = this.logger) === null || _this$logger0 === void 0 || _this$logger0.debug("Rollout in progress, a new rollout will be started after the current one");
this.needToEnsureKeyAgain = true;
}
}
/**
* Called when the ownMembership of the call changes.
* This encryption manager is very basic, it will rotate the key everytime this is called.
* @param oldMemberships - This parameter is not used here, but it is kept for compatibility with the interface.
*/
onMembershipsUpdate() {
var _this$logger1;
arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
(_this$logger1 = this.logger) === null || _this$logger1 === void 0 || _this$logger1.trace("onMembershipsUpdate");
this.ensureKeyDistribution();
this.checkKeysWithoutMatchingRTCMembership();
}
rolloutOutboundKey() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this2$outboundSessio, _this2$outboundSessio2;
if (_this2.outboundSession == null) {
var firstKey = {
key: _this2.generateRandomKey(),
creationTS: Date.now(),
sharedWith: [],
keyId: 0
};
_this2.outboundSession = firstKey;
_this2.addKeyToParticipantWithBackendIdentity(firstKey.key, firstKey.keyId, _this2.ownMembership, yield _this2.getOwnRtcBackendIdentity());
}
var toShareWith = _this2.getMemberships().filter((membership) => {
return membership.sender != void 0;
}).map((membership) => {
return {
userId: membership.sender,
deviceId: membership.deviceId,
membershipTs: membership.createdTs()
};
});
var alreadySharedWith = (_this2$outboundSessio = (_this2$outboundSessio2 = _this2.outboundSession) === null || _this2$outboundSessio2 === void 0 ? void 0 : _this2$outboundSessio2.sharedWith) !== null && _this2$outboundSessio !== void 0 ? _this2$outboundSessio : [];
alreadySharedWith = alreadySharedWith.filter((x) => !toShareWith.some((o) => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs != o.membershipTs));
var anyLeft = alreadySharedWith.filter((x) => !toShareWith.some((o) => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs == o.membershipTs));
var anyJoined = toShareWith.filter((x) => !alreadySharedWith.some((o) => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs == o.membershipTs));
var toDistributeTo = [];
var outboundKey;
var hasKeyChanged = false;
if (anyLeft.length > 0) {
var newOutboundKey = _this2.createNewOutboundSession();
hasKeyChanged = true;
toDistributeTo = toShareWith;
outboundKey = newOutboundKey;
} else if (anyJoined.length > 0) {
var keyAge = Date.now() - _this2.outboundSession.creationTS;
if (keyAge < _this2.keyRotationGracePeriodMs) {
var _this2$logger;
(_this2$logger = _this2.logger) === null || _this2$logger === void 0 || _this2$logger.debug("New joiners detected, but the key is recent enough (age:".concat(keyAge, "), keeping it"));
toDistributeTo = anyJoined;
outboundKey = _this2.outboundSession;
} else {
var _this2$logger2;
(_this2$logger2 = _this2.logger) === null || _this2$logger2 === void 0 || _this2$logger2.debug("New joiners detected, rotating the key");
var _newOutboundKey = _this2.createNewOutboundSession();
hasKeyChanged = true;
toDistributeTo = toShareWith;
outboundKey = _newOutboundKey;
}
} else return;
try {
var _this2$logger3, _this2$logger4;
(_this2$logger3 = _this2.logger) === null || _this2$logger3 === void 0 || _this2$logger3.trace("Sending key...");
yield _this2.transport.sendKey(encodeBase64(outboundKey.key), outboundKey.keyId, toDistributeTo);
outboundKey.sharedWith.push(...toDistributeTo);
(_this2$logger4 = _this2.logger) === null || _this2$logger4 === void 0 || _this2$logger4.trace("key index:".concat(outboundKey.keyId, " sent to ").concat(outboundKey.sharedWith.map((m) => "".concat(m.userId, ":").concat(m.deviceId)).join(",")));
if (hasKeyChanged) {
var _this2$logger5, _this2$logger6;
(_this2$logger5 = _this2.logger) === null || _this2$logger5 === void 0 || _this2$logger5.trace("Delay Rollout for key:".concat(outboundKey.keyId, "..."));
yield sleep(_this2.useKeyDelay);
(_this2$logger6 = _this2.logger) === null || _this2$logger6 === void 0 || _this2$logger6.trace("...Delayed rollout of index:".concat(outboundKey.keyId, " "));
_this2.addKeyToParticipantWithBackendIdentity(outboundKey.key, outboundKey.keyId, _this2.ownMembership, yield _this2.getOwnRtcBackendIdentity());
}
} catch (err) {
var _this2$logger7;
(_this2$logger7 = _this2.logger) === null || _this2$logger7 === void 0 || _this2$logger7.error("Failed to rollout key", err);
}
})();
}
createNewOutboundSession() {
var _this$logger10;
var newOutboundKey = {
key: this.generateRandomKey(),
creationTS: Date.now(),
sharedWith: [],
keyId: this.nextKeyIndex()
};
(_this$logger10 = this.logger) === null || _this$logger10 === void 0 || _this$logger10.info("creating new outbound key index:".concat(newOutboundKey.keyId));
this.outboundSession = newOutboundKey;
return newOutboundKey;
}
nextKeyIndex() {
if (this.outboundSession) return (this.outboundSession.keyId + 1) % 256;
return 0;
}
generateRandomKey() {
var key = new Uint8Array(16);
globalThis.crypto.getRandomValues(key);
return key;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/ToDeviceKeyTransport.js
var NotSupportedError = class extends Error {
constructor(message) {
super(message);
}
get name() {
return "NotSupportedError";
}
};
/**
* ToDeviceKeyTransport is used to send MatrixRTC keys to other devices using the
* to-device CS-API.
*/
var ToDeviceKeyTransport = class extends TypedEventEmitter {
setParentLogger(parentLogger) {
this.logger = parentLogger.getChild("[ToDeviceKeyTransport]");
}
constructor(membership, roomId, client, statistics, parentLogger) {
super();
this.membership = membership;
this.roomId = roomId;
this.client = client;
this.statistics = statistics;
(0, import_defineProperty.default)(this, "logger", logger$2);
(0, import_defineProperty.default)(this, "onToDeviceEvent", (event) => {
if (event.getType() !== EventType.CallEncryptionKeysPrefix) return;
var content = this.getValidEventContent(event);
if (!content) return;
if (!event.getSender()) return;
this.receiveCallKeyEvent(event.getSender(), content);
});
this.setParentLogger(parentLogger !== null && parentLogger !== void 0 ? parentLogger : logger$2);
}
start() {
this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
stop() {
this.client.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
sendKey(keyBase64Encoded, index, members) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var content = {
keys: {
index,
key: keyBase64Encoded
},
room_id: _this.roomId,
member: {
claimed_device_id: _this.membership.deviceId,
id: _this.membership.memberId
},
session: {
call_id: "",
application: "m.call",
scope: "m.room"
},
sent_ts: Date.now()
};
var targets = members.map((member) => {
return {
userId: member.userId,
deviceId: member.deviceId
};
}).filter((member) => !(member.userId == _this.membership.userId && member.deviceId == _this.membership.deviceId));
if (targets.length > 0) {
yield _this.client.encryptAndSendToDevice(EventType.CallEncryptionKeysPrefix, targets, content).catch((error) => {
var msg = error.message;
if (msg.includes("unknown variant") && msg.includes("send_to_device") || msg.includes("not supported")) throw new NotSupportedError("The widget driver does not support to-device encryption");
});
_this.statistics.counters.roomEventEncryptionKeysSent += 1;
} else _this.logger.warn("No targets found for sending key");
})();
}
receiveCallKeyEvent(fromUser, content) {
var _content$member$id;
this.statistics.counters.roomEventEncryptionKeysReceived += 1;
var now = Date.now();
var age = now - (typeof content.sent_ts === "number" ? content.sent_ts : now);
this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge += age;
var hardcodedMemberIdAlternative = "".concat(fromUser, ":").concat(content.member.claimed_device_id);
this.emit(KeyTransportEvents.ReceivedKeys, {
userId: fromUser,
deviceId: content.member.claimed_device_id,
memberId: (_content$member$id = content.member.id) !== null && _content$member$id !== void 0 ? _content$member$id : hardcodedMemberIdAlternative
}, content.keys.key, content.keys.index, now);
}
getValidEventContent(event) {
var content = event.getContent();
var roomId = content.room_id;
if (!roomId) {
this.logger.warn("Malformed Event: invalid call encryption keys event, no roomId");
return;
}
if (roomId !== this.roomId) {
this.logger.warn("Malformed Event: Mismatch roomId");
return;
}
if (!content.keys || !content.keys.key || typeof content.keys.index !== "number") {
this.logger.warn("Malformed Event: Missing keys field");
return;
}
if (!content.member || !content.member.claimed_device_id) {
this.logger.warn("Malformed Event: Missing claimed_device_id");
return;
}
return content;
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.js
function ownKeys$3(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;
}
function _objectSpread$3(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$3(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* Events emitted by MatrixRTCSession
*/
var MatrixRTCSessionEvent = /* @__PURE__ */ function(MatrixRTCSessionEvent) {
MatrixRTCSessionEvent["MembershipsChanged"] = "memberships_changed";
MatrixRTCSessionEvent["JoinStateChanged"] = "join_state_changed";
MatrixRTCSessionEvent["EncryptionKeyChanged"] = "encryption_key_changed";
/** The membership manager had to shut down caused by an unrecoverable error */
MatrixRTCSessionEvent["MembershipManagerError"] = "membership_manager_error";
/** The RTCSession did send a call notification caused by joining the call as the first member */
MatrixRTCSessionEvent["DidSendCallNotification"] = "did_send_call_notification";
return MatrixRTCSessionEvent;
}({});
var DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS = {
listenForStickyEvents: true,
listenForMemberStateEvents: true
};
/**
* A MatrixRTCSession manages the membership & properties of a MatrixRTC session.
* This class doesn't deal with media at all, just membership & properties of a session.
*/
var MatrixRTCSession = class MatrixRTCSession extends TypedEventEmitter {
get membershipStatus() {
var _this$membershipManag;
return (_this$membershipManag = this.membershipManager) === null || _this$membershipManag === void 0 ? void 0 : _this$membershipManag.status;
}
get probablyLeft() {
var _this$membershipManag2;
return (_this$membershipManag2 = this.membershipManager) === null || _this$membershipManag2 === void 0 ? void 0 : _this$membershipManag2.probablyLeft;
}
get delayId() {
var _this$membershipManag3;
return (_this$membershipManag3 = this.membershipManager) === null || _this$membershipManag3 === void 0 ? void 0 : _this$membershipManag3.delayId;
}
/**
* The callId (sessionId) of the call.
*
* It can be undefined since the callId is only known once the first membership joins.
* The callId is the property that, per definition, groups memberships into one call.
* @deprecated use `slotId` instead.
*/
get callId() {
var _this$slotDescription;
return (_this$slotDescription = this.slotDescription) === null || _this$slotDescription === void 0 ? void 0 : _this$slotDescription.id;
}
/**
* The slotId of the call.
* `{application}#{appSpecificId}`
* It can be undefined since the slotId is only known once the first membership joins.
* The slotId is the property that, per definition, groups memberships into one call.
*/
get slotId() {
return computeSlotId(this.slotDescription);
}
/**
* Returns all the call memberships for a room that match the provided `sessionDescription`,
* oldest first.
*
* By default, this will return *both* sticky and member state events.
*/
static sessionMembershipsForSlot(room, slotDescription) {
var _arguments = arguments;
return (0, import_asyncToGenerator.default)(function* () {
var options = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS;
var logger = logger$2.getChild("[MatrixRTCSession ".concat(room.roomId, " ").concat(slotDescription.application, "#").concat(slotDescription.id, "]"));
var callMemberships = yield computeBackendIdentityAndVerifyMemberEvents(room, collectMembersEvents(room, options, logger), slotDescription, logger);
callMemberships.sort((a, b) => a.createdTs() - b.createdTs());
if (callMemberships.length > 1) logger.debug("Call memberships in room ".concat(room.roomId, ", in order: "), callMemberships.map((m) => [m.createdTs(), m.userId]));
return callMemberships;
})();
}
/**
* Return the MatrixRTC session for the room.
* This returned session can be used to find out if there are active sessions
* for the requested room and `slotDescription`.
*/
static sessionForSlot(client, room, slotDescription, opts) {
return new MatrixRTCSession(client, room, slotDescription, opts);
}
/**
* WARN: this can in theory only be a subset of the room with the properties required by
* this class.
* Outside of tests this most likely will be a full room, however.
* @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking
* the room object in your own code and passing it in when needed.
*/
get room() {
return this.roomSubset;
}
/**
* This constructs a room session. When using MatrixRTC inside the js-sdk this is expected
* to be used with the MatrixRTCSessionManager exclusively.
*
* In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone
* to manage a joined MatrixRTC session.
*
* @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.
* @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.
* @param slotDescription The slot description is a virtual address where participants are allowed to meet.
* This session will only manage memberships that match this slot description.Sessions are distinct if any of
* those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.
* @param calculateMembershipsOpts - Options to configure how memberships are calculated for this session.
*/
constructor(client, roomSubset, slotDescription, calculateMembershipsOpts) {
var _this;
super();
_this = this;
this.client = client;
this.roomSubset = roomSubset;
this.slotDescription = slotDescription;
this.calculateMembershipsOpts = calculateMembershipsOpts;
(0, import_defineProperty.default)(this, "membershipManager", void 0);
(0, import_defineProperty.default)(this, "encryptionManager", void 0);
(0, import_defineProperty.default)(this, "joinConfig", void 0);
(0, import_defineProperty.default)(this, "logger", void 0);
(0, import_defineProperty.default)(this, "pendingNotificationToSend", void 0);
/**
* This timeout is responsible to track any expiration. We need to know when we have to start
* to ignore other call members. There is no callback for this. This timeout will always be configured to
* emit when the next membership expires.
*/
(0, import_defineProperty.default)(this, "expiryTimeout", void 0);
(0, import_defineProperty.default)(this, "memberships", []);
/**
* Resolves when the session has calculated the initial membership of the session.
*/
(0, import_defineProperty.default)(this, "initialMembershipCalculated", void 0);
/**
* Does membership need to be recalculated? This is set to false upon
* recalculation.
*/
(0, import_defineProperty.default)(this, "membershipNeedsRecalculation", false);
/**
* The statistics for this session.
*/
(0, import_defineProperty.default)(this, "statistics", {
counters: {
roomEventEncryptionKeysSent: 0,
roomEventEncryptionKeysReceived: 0
},
totals: { roomEventEncryptionKeysReceivedTotalAge: 0 }
});
(0, import_defineProperty.default)(this, "reEmitter", new TypedReEmitter(this));
/**
* Call this when the Matrix room members have changed.
*/
(0, import_defineProperty.default)(this, "onRoomMemberUpdate", () => {
this.ensureRecalculateSessionMembers();
});
/**
* Call this when a sticky event update has occured.
*/
(0, import_defineProperty.default)(this, "onStickyEventUpdate", (added, updated, removed) => {
if ([
...added,
...removed,
...updated.flatMap((v) => [v.current, v.previous])
].some((e) => e.getType() === EventType.RTCMembership)) this.ensureRecalculateSessionMembers();
});
/**
* Call this when something changed that may impacts the current MatrixRTC members in this session.
*/
(0, import_defineProperty.default)(this, "_onRTCSessionMemberUpdate", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
yield _this.recalculateSessionMembers();
}));
(0, import_defineProperty.default)(this, "recalculateSessionMembersPromise", Promise.resolve());
/**
* Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.
*
* Examines the latest call memberships and handles any encryption key sending or rotation that is needed.
*
* This function should be called when the room members or call memberships might have changed.
*/
(0, import_defineProperty.default)(this, "recalculateSessionMembers", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
var _this$encryptionManag;
_this.membershipNeedsRecalculation = false;
var oldMemberships = _this.memberships;
_this.memberships = yield MatrixRTCSession.sessionMembershipsForSlot(_this.room, _this.slotDescription, _this.calculateMembershipsOpts);
if (oldMemberships.length != _this.memberships.length || oldMemberships.some((m, i) => !CallMembership.equal(m, _this.memberships[i]))) {
var _this$membershipManag4, _this$membershipManag5;
_this.logger.info("Memberships for call in room ".concat(_this.roomSubset.roomId, " have changed: emitting (").concat(_this.memberships.length, " members)"));
logDurationSync(_this.logger, "emit MatrixRTCSessionEvent.MembershipsChanged", () => {
_this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, _this.memberships);
});
(_this$membershipManag4 = _this.membershipManager) === null || _this$membershipManag4 === void 0 || _this$membershipManag4.onRTCSessionMemberUpdate(_this.memberships);
var ownMembership = (_this$membershipManag5 = _this.membershipManager) === null || _this$membershipManag5 === void 0 ? void 0 : _this$membershipManag5.ownMembership;
if (_this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {
var _this$joinConfig;
if (ownMembership.eventId && (_this$joinConfig = _this.joinConfig) !== null && _this$joinConfig !== void 0 && _this$joinConfig.notificationType) _this.sendCallNotify(ownMembership.eventId, _this.joinConfig.notificationType, ownMembership.callIntent);
else _this.logger.warn("Own membership eventId is undefined, cannot send call notification");
}
if (_this.memberships.length > 0) _this.pendingNotificationToSend = void 0;
} else _this.logger.debug("No membership changes detected for room ".concat(_this.roomSubset.roomId));
(_this$encryptionManag = _this.encryptionManager) === null || _this$encryptionManag === void 0 || _this$encryptionManag.onMembershipsUpdate(oldMemberships);
_this.setExpiryTimer();
}));
this.logger = logger$2.getChild("[MatrixRTCSession ".concat(roomSubset.roomId, " ").concat(slotDescription.application, "#").concat(slotDescription.id, "]"));
this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);
this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);
this.initialMembershipCalculated = this.ensureRecalculateSessionMembers();
this.setExpiryTimer();
}
isJoined() {
var _this$membershipManag6, _this$membershipManag7;
return (_this$membershipManag6 = (_this$membershipManag7 = this.membershipManager) === null || _this$membershipManag7 === void 0 ? void 0 : _this$membershipManag7.isJoined()) !== null && _this$membershipManag6 !== void 0 ? _this$membershipManag6 : false;
}
/**
* Performs cleanup & removes timers for client shutdown
*/
stop() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this2$membershipMana;
yield (_this2$membershipMana = _this2.membershipManager) === null || _this2$membershipMana === void 0 ? void 0 : _this2$membershipMana.leave(1e3);
if (_this2.expiryTimeout) {
clearTimeout(_this2.expiryTimeout);
_this2.expiryTimeout = void 0;
}
_this2.roomSubset.off(RoomStateEvent.Members, _this2.onRoomMemberUpdate);
_this2.roomSubset.off(RoomStickyEventsEvent.Update, _this2.onStickyEventUpdate);
})();
}
/**
* Announces this user and device as joined to the MatrixRTC session,
* and continues to update the membership event to keep it valid until
* leaveRoomSession() is called
* This will not subscribe to updates: remember to call subscribe() separately if
* desired.
* This method will return immediately and the session will be joined in the background.
* @param ownMembershipIdentity the identity of the user and device joining the session.
* This will be put into the content.member.
* @param fociPreferred the list of preferred foci to use in the joined RTC membership event.
* If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.
* @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the
* membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`
* transport selection will be used instead.
* @param joinConfig - Additional configuration for the joined session.
*/
joinRTCSession(ownMembershipIdentity, fociPreferred, multiSfuFocus, joinConfig) {
var _this$joinConfig2;
if (this.isJoined()) {
this.logger.info("Already joined to session in room ".concat(this.roomSubset.roomId, ": ignoring join call"));
return;
} else {
this.membershipManager = joinConfig !== null && joinConfig !== void 0 && joinConfig.unstableSendStickyEvents ? new StickyEventMembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, ownMembershipIdentity.memberId, this.logger) : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);
this.reEmitter.reEmit(this.membershipManager, [
MembershipManagerEvent.ProbablyLeft,
MembershipManagerEvent.StatusChanged,
MembershipManagerEvent.DelayIdChanged
]);
var [room, _client, statistics] = [
this.roomSubset,
this.client,
this.statistics
];
this.encryptionManager = new RTCEncryptionManager(ownMembershipIdentity, () => this.memberships, new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, _client, statistics), (keyBin, encryptionKeyIndex, membership, rtcBackendIdentity) => {
this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, membership, rtcBackendIdentity);
}, this.logger);
}
this.joinConfig = joinConfig;
this.pendingNotificationToSend = (_this$joinConfig2 = this.joinConfig) === null || _this$joinConfig2 === void 0 ? void 0 : _this$joinConfig2.notificationType;
this.membershipManager.join(fociPreferred, multiSfuFocus, (e) => {
this.logger.error("MembershipManager encountered an unrecoverable error: ", e);
this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);
this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());
});
this.encryptionManager.join(joinConfig);
this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);
}
/**
*
* @param fociPreferred
* @param multiSfuFocus
* @param joinConfig
* @deprecated use the joinRTCSession method instead
*/
joinRoomSession(fociPreferred, multiSfuFocus, joinConfig) {
var [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];
var memberId = "".concat(userId, ":").concat(deviceId);
this.joinRTCSession({
userId,
deviceId,
memberId
}, fociPreferred, multiSfuFocus, joinConfig);
}
/**
* Announces this user and device as having left the MatrixRTC session
* and stops scheduled updates.
* This will not unsubscribe from updates: remember to call unsubscribe() separately if
* desired.
* The membership update required to leave the session will retry if it fails.
* Without network connection the promise will never resolve.
* A timeout can be provided so that there is a guarantee for the promise to resolve.
* @returns Whether the membership update was attempted and did not time out.
*/
leaveRoomSession() {
var _arguments2 = arguments, _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
var timeout = _arguments2.length > 0 && _arguments2[0] !== void 0 ? _arguments2[0] : void 0;
if (!_this3.isJoined()) {
_this3.logger.info("Not joined to session in room ".concat(_this3.roomSubset.roomId, ": ignoring leave call"));
return false;
}
_this3.logger.info("Leaving call session in room ".concat(_this3.roomSubset.roomId));
_this3.encryptionManager.leave();
var leavePromise = _this3.membershipManager.leave(timeout);
_this3.emit(MatrixRTCSessionEvent.JoinStateChanged, false);
return yield leavePromise;
})();
}
/**
* This returns the focus in use by the oldest membership.
* Do not use since this might be just the focus for the oldest membership. others might use a different focus.
* @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.
*/
getFocusInUse() {
var oldestMembership = this.getOldestMembership();
return oldestMembership === null || oldestMembership === void 0 ? void 0 : oldestMembership.getTransport(oldestMembership);
}
getOldestMembership() {
return this.memberships[0];
}
/**
* Get the call intent for the current call, based on what members are advertising. If one or more
* members disagree on the current call intent, or nobody specifies one then `undefined` is returned.
*
* If all members that specify a call intent agree, that value is returned.
* @returns A call intent, or `undefined` if no consensus or not given.
*/
getConsensusCallIntent() {
var _this$memberships$fin;
var getFirstCallIntent = (_this$memberships$fin = this.memberships.find((m) => !!m.callIntent)) === null || _this$memberships$fin === void 0 ? void 0 : _this$memberships$fin.callIntent;
if (!getFirstCallIntent) return;
if (this.memberships.every((m) => !m.callIntent || m.callIntent === getFirstCallIntent)) return getFirstCallIntent;
}
updateCallIntent(callIntent) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this4$membershipMana, _this4$membershipMana2;
if (!((_this4$membershipMana = _this4.membershipManager) === null || _this4$membershipMana === void 0 ? void 0 : _this4$membershipMana.ownMembership)) throw Error("Not connected yet");
yield (_this4$membershipMana2 = _this4.membershipManager) === null || _this4$membershipMana2 === void 0 ? void 0 : _this4$membershipMana2.updateCallIntent(callIntent);
})();
}
/**
* Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export
* the keys.
*/
reemitEncryptionKeys() {
var _this$encryptionManag2;
(_this$encryptionManag2 = this.encryptionManager) === null || _this$encryptionManag2 === void 0 || _this$encryptionManag2.getEncryptionKeys().forEach((keyRing, key) => {
keyRing.forEach((keyInfo) => {
this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyInfo.key, keyInfo.keyIndex, keyInfo.membership, keyInfo.rtcBackendIdentity);
});
});
}
/**
* Sets a timer for the soonest membership expiry
*/
setExpiryTimer() {
if (this.expiryTimeout) {
clearTimeout(this.expiryTimeout);
this.expiryTimeout = void 0;
}
var soonestExpiry;
for (var membership of this.memberships) {
var thisExpiry = membership.getMsUntilExpiry();
if (thisExpiry !== void 0 && (soonestExpiry === void 0 || thisExpiry < soonestExpiry)) soonestExpiry = thisExpiry;
}
if (soonestExpiry != void 0) this.expiryTimeout = setTimeout(() => void this.ensureRecalculateSessionMembers(), soonestExpiry);
}
/**
* Sends notification events to indiciate the call has started.
* Note: This does not return a promise, instead scheduling the notification events to be sent.
* @param parentEventId Event id linking to your RTC call membership event.
* @param notificationType The type of notification to send
* @param callIntent The type of call this is (e.g. "audio").
*/
sendCallNotify(parentEventId, notificationType, callIntent) {
var _this5 = this;
(/* @__PURE__ */ (function() {
var _ref3 = (0, import_asyncToGenerator.default)(function* () {
var content = {
"m.mentions": {
user_ids: [],
room: true
},
"notification_type": notificationType,
"m.relates_to": {
event_id: parentEventId,
rel_type: RelationType.Reference
},
"sender_ts": Date.now(),
"lifetime": 3e4
};
if (callIntent) content["m.call.intent"] = callIntent;
return {
response: yield _this5.client.sendEvent(_this5.roomSubset.roomId, EventType.RTCNotification, content),
content
};
});
return function sendNotificationEvent() {
return _ref3.apply(this, arguments);
};
})())().then((notification) => {
var newResult = _objectSpread$3(_objectSpread$3({}, notification.response), notification.content);
this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);
}).catch((_ref4) => {
var [errorLegacy, errorNew] = _ref4;
return this.logger.error("Failed to send call notification", errorLegacy, errorNew);
});
}
/**
* Ensures that membership is recalculated when the state of the session may have changed.
* Also ensures that only one recalculation is made at a time.
* @returns A promise resolving when the state has been recalculated.
*/
ensureRecalculateSessionMembers() {
if (this.membershipNeedsRecalculation) return this.recalculateSessionMembersPromise;
this.membershipNeedsRecalculation = true;
this.recalculateSessionMembersPromise = this.recalculateSessionMembersPromise.finally().then(() => this.recalculateSessionMembers());
return this.recalculateSessionMembersPromise;
}
};
function computeBackendIdentityAndVerifyMemberEvents(_x, _x2, _x3, _x4) {
return _computeBackendIdentityAndVerifyMemberEvents.apply(this, arguments);
}
function _computeBackendIdentityAndVerifyMemberEvents() {
_computeBackendIdentityAndVerifyMemberEvents = (0, import_asyncToGenerator.default)(function* (room, callMemberEvents, slotDescription, logger) {
var callMemberships = [];
for (var memberEvent of callMemberEvents) {
if (!quickFilterNonRelevantContents(memberEvent.getContent(), logger)) continue;
try {
var membership = yield CallMembership.parseFromEvent(memberEvent);
if (isValidMembership(membership, room, slotDescription, logger)) callMemberships.push(membership);
} catch (e) {
logger.warn("Couldn't construct call membership: ", e);
}
}
return callMemberships;
});
return _computeBackendIdentityAndVerifyMemberEvents.apply(this, arguments);
}
function quickFilterNonRelevantContents(content, logger) {
var eventKeysCount = Object.keys(content).filter((k) => k !== "msc4354_sticky_key").length;
if (eventKeysCount === 0) return false;
if (eventKeysCount > 1 && "application" in content) return true;
else if (eventKeysCount === 1 && "memberships" in content) {
logger.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session");
return false;
} else return false;
}
function isValidMembership(membership, room, slotDescription, logger) {
var _membership$userId;
if (membership.slotDescription.id !== slotDescription.id) {
logger.info("Ignoring membership of user ".concat(membership.userId, " for a different slot. Theirs: ").concat(JSON.stringify(membership.slotDescription), ", Expected: ").concat(JSON.stringify(slotDescription)));
return false;
}
if (membership.isExpired()) {
logger.info("Ignoring expired device membership ".concat(membership.userId, "/").concat(membership.deviceId));
return false;
}
if (!room.hasMembershipState((_membership$userId = membership.userId) !== null && _membership$userId !== void 0 ? _membership$userId : "", KnownMembership.Join)) {
logger.info("Ignoring membership of user ".concat(membership.userId, " who is not in the room."));
return false;
}
return true;
}
/**
* Collects the raw member events from room state and sticky store.
*/
function collectMembersEvents(room, options, logger) {
var { listenForStickyEvents, listenForMemberStateEvents } = options;
var callMemberEvents = [];
if (listenForStickyEvents) callMemberEvents = [...room._unstable_getStickyEvents()].filter((e) => e.getType() === EventType.RTCMembership);
if (listenForMemberStateEvents) {
var roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);
if (!roomState) {
logger.warn("Couldn't get state for room " + room.roomId + "using empty membership array");
return [];
}
var callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);
callMemberEvents = callMemberEvents.concat(callMemberStateEvents.filter((callMemberStateEvent) => !callMemberEvents.some((stickyEvent) => stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey())));
}
return callMemberEvents;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSessionManager.js
var MatrixRTCSessionManagerEvents = /* @__PURE__ */ function(MatrixRTCSessionManagerEvents) {
MatrixRTCSessionManagerEvents["SessionStarted"] = "session_started";
MatrixRTCSessionManagerEvents["SessionEnded"] = "session_ended";
return MatrixRTCSessionManagerEvents;
}({});
/**
* Holds all active MatrixRTC session objects and creates new ones as events arrive.
* One `MatrixRTCSessionManager` is required for each MatrixRTC sessionDescription (application, session id) that the client wants to support.
* If no application type is specified in the constructor, the default is "m.call".
*
* This interface is UNSTABLE and may change without warning.
*/
var MatrixRTCSessionManager = class extends TypedEventEmitter {
constructor(rootLogger, client) {
var slotDescription = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {
application: "m.call",
id: "ROOM"
};
super();
this.client = client;
this.slotDescription = slotDescription;
(0, import_defineProperty.default)(this, "roomSessions", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "logger", void 0);
(0, import_defineProperty.default)(this, "onRoom", (room) => {
this.refreshRoom(room);
});
(0, import_defineProperty.default)(this, "onEvent", (event) => {
if (!event.unstableStickyExpiresAt) return;
if (event.getType() !== EventType.RTCMembership) return;
var room = this.client.getRoom(event.getRoomId());
if (!room) return;
this.refreshRoom(room);
});
(0, import_defineProperty.default)(this, "onRoomState", (event) => {
if (event.getType() !== EventType.GroupCallMemberPrefix) return;
var room = this.client.getRoom(event.getRoomId());
if (!room) {
this.logger.error("Got room state event for unknown room ".concat(event.getRoomId(), "!"));
return;
}
this.refreshRoom(room);
});
this.logger = rootLogger.getChild("[MatrixRTCSessionManager ".concat(computeSlotId(slotDescription), "]"));
}
start() {
for (var room of (_this$client$getRooms = this.client.getRooms()) !== null && _this$client$getRooms !== void 0 ? _this$client$getRooms : []) {
var _this$client$getRooms;
var session = MatrixRTCSession.sessionForSlot(this.client, room, this.slotDescription);
if (session.memberships.length > 0) this.roomSessions.set(room.roomId, session);
}
this.client.on(ClientEvent.Room, this.onRoom);
this.client.on(ClientEvent.Event, this.onEvent);
this.client.on(RoomStateEvent.Events, this.onRoomState);
}
stop() {
for (var sess of this.roomSessions.values()) sess.stop();
this.roomSessions.clear();
this.client.off(ClientEvent.Room, this.onRoom);
this.client.off(ClientEvent.Event, this.onEvent);
this.client.off(RoomStateEvent.Events, this.onRoomState);
}
/**
* Gets the main MatrixRTC session for a room, or undefined if there is
* no current session
*/
getActiveRoomSession(room) {
return this.roomSessions.get(room.roomId);
}
/**
* Gets the main MatrixRTC session for a room, returning an empty session
* if no members are currently participating
*/
getRoomSession(room) {
if (!this.roomSessions.has(room.roomId)) this.roomSessions.set(room.roomId, MatrixRTCSession.sessionForSlot(this.client, room, this.slotDescription));
return this.roomSessions.get(room.roomId);
}
refreshRoom(room) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var isNewSession = !_this.roomSessions.has(room.roomId);
var session = _this.getRoomSession(room);
var wasActiveAndKnown = session.memberships.length > 0 && !isNewSession;
yield session._onRTCSessionMemberUpdate().catch((error) => {
_this.logger.error("Error updating RTC session members for ".concat(room.roomId, ": ").concat(error));
});
var nowActive = session.memberships.length > 0;
if (wasActiveAndKnown && !nowActive) {
_this.logger.trace("Session ended for ".concat(room.roomId, " (").concat(session.memberships.length, " members)"));
_this.emit(MatrixRTCSessionManagerEvents.SessionEnded, room.roomId, _this.roomSessions.get(room.roomId));
} else if (!wasActiveAndKnown && nowActive) {
_this.logger.trace("Session started for ".concat(room.roomId, " (").concat(session.memberships.length, " members)"));
_this.emit(MatrixRTCSessionManagerEvents.SessionStarted, room.roomId, _this.roomSessions.get(room.roomId));
}
})();
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/thread-utils.js
/**
* Returns a filter function for the /relations endpoint to filter out relations directly
* to the thread root event that should not live in the thread timeline
*
* @param threadId - the thread ID (ie. the event ID of the root event of the thread)
* @returns the filtered list of events
*/
function getRelationsThreadFilter(threadId) {
return (e) => {
var _e$content, _e$content2;
return ((_e$content = e.content) === null || _e$content === void 0 || (_e$content = _e$content["m.relates_to"]) === null || _e$content === void 0 ? void 0 : _e$content.event_id) !== threadId || ((_e$content2 = e.content) === null || _e$content2 === void 0 || (_e$content2 = _e$content2["m.relates_to"]) === null || _e$content2 === void 0 ? void 0 : _e$content2.rel_type) === THREAD_RELATION_TYPE.name;
};
}
//#endregion
//#region node_modules/jwt-decode/build/esm/index.js
var InvalidTokenError = class extends Error {};
InvalidTokenError.prototype.name = "InvalidTokenError";
function b64DecodeUnicode(str) {
return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {
let code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) code = "0" + code;
return "%" + code;
}));
}
function base64UrlDecode(str) {
let output = str.replace(/-/g, "+").replace(/_/g, "/");
switch (output.length % 4) {
case 0: break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default: throw new Error("base64 string is not of the correct length");
}
try {
return b64DecodeUnicode(output);
} catch (err) {
return atob(output);
}
}
function jwtDecode(token, options) {
if (typeof token !== "string") throw new InvalidTokenError("Invalid token specified: must be a string");
options || (options = {});
const pos = options.header === true ? 0 : 1;
const part = token.split(".")[pos];
if (typeof part !== "string") throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);
let decoded;
try {
decoded = base64UrlDecode(part);
} catch (e) {
throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);
}
try {
return JSON.parse(decoded);
} catch (e) {
throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);
}
}
//#endregion
//#region node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js
var nopLogger = {
debug: () => void 0,
info: () => void 0,
warn: () => void 0,
error: () => void 0
};
var level;
var logger;
var Log = /* @__PURE__ */ ((Log2) => {
Log2[Log2["NONE"] = 0] = "NONE";
Log2[Log2["ERROR"] = 1] = "ERROR";
Log2[Log2["WARN"] = 2] = "WARN";
Log2[Log2["INFO"] = 3] = "INFO";
Log2[Log2["DEBUG"] = 4] = "DEBUG";
return Log2;
})(Log || {});
((Log2) => {
function reset() {
level = 3;
logger = nopLogger;
}
Log2.reset = reset;
function setLevel(value) {
if (!(0 <= value && value <= 4)) throw new Error("Invalid log level");
level = value;
}
Log2.setLevel = setLevel;
function setLogger(value) {
logger = value;
}
Log2.setLogger = setLogger;
})(Log || (Log = {}));
var Logger = class _Logger {
constructor(_name) {
this._name = _name;
}
debug(...args) {
if (level >= 4) logger.debug(_Logger._format(this._name, this._method), ...args);
}
info(...args) {
if (level >= 3) logger.info(_Logger._format(this._name, this._method), ...args);
}
warn(...args) {
if (level >= 2) logger.warn(_Logger._format(this._name, this._method), ...args);
}
error(...args) {
if (level >= 1) logger.error(_Logger._format(this._name, this._method), ...args);
}
throw(err) {
this.error(err);
throw err;
}
create(method) {
const methodLogger = Object.create(this);
methodLogger._method = method;
methodLogger.debug("begin");
return methodLogger;
}
static createStatic(name, staticMethod) {
const staticLogger = new _Logger(`${name}.${staticMethod}`);
staticLogger.debug("begin");
return staticLogger;
}
static _format(name, method) {
const prefix = `[${name}]`;
return method ? `${prefix} ${method}:` : prefix;
}
static debug(name, ...args) {
if (level >= 4) logger.debug(_Logger._format(name), ...args);
}
static info(name, ...args) {
if (level >= 3) logger.info(_Logger._format(name), ...args);
}
static warn(name, ...args) {
if (level >= 2) logger.warn(_Logger._format(name), ...args);
}
static error(name, ...args) {
if (level >= 1) logger.error(_Logger._format(name), ...args);
}
};
Log.reset();
var JwtUtils = class {
static decode(token) {
try {
return jwtDecode(token);
} catch (err) {
Logger.error("JwtUtils.decode", err);
throw err;
}
}
static async generateSignedJwt(header, payload, privateKey) {
const encodedToken = `${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(header)))}.${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`;
const signature = await window.crypto.subtle.sign({
name: "ECDSA",
hash: { name: "SHA-256" }
}, privateKey, new TextEncoder().encode(encodedToken));
return `${encodedToken}.${CryptoUtils.encodeBase64Url(new Uint8Array(signature))}`;
}
static async generateSignedJwtWithHmac(header, payload, secretKey) {
const encodedToken = `${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(header)))}.${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`;
const signature = await window.crypto.subtle.sign("HMAC", secretKey, new TextEncoder().encode(encodedToken));
return `${encodedToken}.${CryptoUtils.encodeBase64Url(new Uint8Array(signature))}`;
}
};
var UUID_V4_TEMPLATE = "10000000-1000-4000-8000-100000000000";
var toBase64 = (val) => btoa([...new Uint8Array(val)].map((chr) => String.fromCharCode(chr)).join(""));
var _CryptoUtils = class _CryptoUtils {
static _randomWord() {
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return arr[0];
}
/**
* Generates RFC4122 version 4 guid
*/
static generateUUIDv4() {
return UUID_V4_TEMPLATE.replace(/[018]/g, (c) => (+c ^ _CryptoUtils._randomWord() & 15 >> +c / 4).toString(16)).replace(/-/g, "");
}
/**
* PKCE: Generate a code verifier
*/
static generateCodeVerifier() {
return _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4();
}
/**
* PKCE: Generate a code challenge
*/
static async generateCodeChallenge(code_verifier) {
if (!crypto.subtle) throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");
try {
const data = new TextEncoder().encode(code_verifier);
return toBase64(await crypto.subtle.digest("SHA-256", data)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
} catch (err) {
Logger.error("CryptoUtils.generateCodeChallenge", err);
throw err;
}
}
/**
* Generates a base64-encoded string for a basic auth header
*/
static generateBasicAuth(client_id, client_secret) {
return toBase64(new TextEncoder().encode([client_id, client_secret].join(":")));
}
/**
* Generates a hash of a string using a given algorithm
* @param alg
* @param message
*/
static async hash(alg, message) {
const msgUint8 = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest(alg, msgUint8);
return new Uint8Array(hashBuffer);
}
/**
* Generates a rfc7638 compliant jwk thumbprint
* @param jwk
*/
static async customCalculateJwkThumbprint(jwk) {
let jsonObject;
switch (jwk.kty) {
case "RSA":
jsonObject = {
"e": jwk.e,
"kty": jwk.kty,
"n": jwk.n
};
break;
case "EC":
jsonObject = {
"crv": jwk.crv,
"kty": jwk.kty,
"x": jwk.x,
"y": jwk.y
};
break;
case "OKP":
jsonObject = {
"crv": jwk.crv,
"kty": jwk.kty,
"x": jwk.x
};
break;
case "oct":
jsonObject = {
"crv": jwk.k,
"kty": jwk.kty
};
break;
default: throw new Error("Unknown jwk type");
}
const utf8encodedAndHashed = await _CryptoUtils.hash("SHA-256", JSON.stringify(jsonObject));
return _CryptoUtils.encodeBase64Url(utf8encodedAndHashed);
}
static async generateDPoPProof({ url, accessToken, httpMethod, keyPair, nonce }) {
let hashedToken;
let encodedHash;
const payload = {
"jti": window.crypto.randomUUID(),
"htm": httpMethod != null ? httpMethod : "GET",
"htu": url,
"iat": Math.floor(Date.now() / 1e3)
};
if (accessToken) {
hashedToken = await _CryptoUtils.hash("SHA-256", accessToken);
encodedHash = _CryptoUtils.encodeBase64Url(hashedToken);
payload.ath = encodedHash;
}
if (nonce) payload.nonce = nonce;
try {
const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
const header = {
"alg": "ES256",
"typ": "dpop+jwt",
"jwk": {
"crv": publicJwk.crv,
"kty": publicJwk.kty,
"x": publicJwk.x,
"y": publicJwk.y
}
};
return await JwtUtils.generateSignedJwt(header, payload, keyPair.privateKey);
} catch (err) {
if (err instanceof TypeError) throw new Error(`Error exporting dpop public key: ${err.message}`);
else throw err;
}
}
static async generateDPoPJkt(keyPair) {
try {
const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
return await _CryptoUtils.customCalculateJwkThumbprint(publicJwk);
} catch (err) {
if (err instanceof TypeError) throw new Error(`Could not retrieve dpop keys from storage: ${err.message}`);
else throw err;
}
}
static async generateDPoPKeys() {
return await window.crypto.subtle.generateKey({
name: "ECDSA",
namedCurve: "P-256"
}, false, ["sign", "verify"]);
}
/**
* Generates a client assertion JWT for client_secret_jwt authentication
* @param client_id The client identifier
* @param client_secret The client secret
* @param audience The token endpoint URL (audience)
* @param algorithm The HMAC algorithm to use (HS256, HS384, HS512). Defaults to HS256
*/
static async generateClientAssertionJwt(client_id, client_secret, audience, algorithm = "HS256") {
const now = Math.floor(Date.now() / 1e3);
const header = {
"alg": algorithm,
"typ": "JWT"
};
const payload = {
"iss": client_id,
"sub": client_id,
"aud": audience,
"jti": _CryptoUtils.generateUUIDv4(),
"exp": now + 300,
"iat": now
};
const hashFunction = {
"HS256": "SHA-256",
"HS384": "SHA-384",
"HS512": "SHA-512"
}[algorithm];
if (!hashFunction) throw new Error(`Unsupported algorithm: ${algorithm}. Supported algorithms are: HS256, HS384, HS512`);
const encoder = new TextEncoder();
const secretKey = await crypto.subtle.importKey("raw", encoder.encode(client_secret), {
name: "HMAC",
hash: hashFunction
}, false, ["sign"]);
return await JwtUtils.generateSignedJwtWithHmac(header, payload, secretKey);
}
};
/**
* Generates a base64url encoded string
*/
_CryptoUtils.encodeBase64Url = (input) => {
return toBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
};
var CryptoUtils = _CryptoUtils;
var Event = class {
constructor(_name) {
this._name = _name;
this._callbacks = [];
this._logger = new Logger(`Event('${this._name}')`);
}
addHandler(cb) {
this._callbacks.push(cb);
return () => this.removeHandler(cb);
}
removeHandler(cb) {
const idx = this._callbacks.lastIndexOf(cb);
if (idx >= 0) this._callbacks.splice(idx, 1);
}
async raise(...ev) {
this._logger.debug("raise:", ...ev);
for (const cb of this._callbacks) await cb(...ev);
}
};
var Timer = class _Timer extends Event {
constructor() {
super(...arguments);
this._logger = new Logger(`Timer('${this._name}')`);
this._timerHandle = null;
this._expiration = 0;
this._callback = () => {
const diff = this._expiration - _Timer.getEpochTime();
this._logger.debug("timer completes in", diff);
if (this._expiration <= _Timer.getEpochTime()) {
this.cancel();
super.raise();
}
};
}
static getEpochTime() {
return Math.floor(Date.now() / 1e3);
}
init(durationInSeconds) {
const logger2 = this._logger.create("init");
durationInSeconds = Math.max(Math.floor(durationInSeconds), 1);
const expiration = _Timer.getEpochTime() + durationInSeconds;
if (this.expiration === expiration && this._timerHandle) {
logger2.debug("skipping since already initialized for expiration at", this.expiration);
return;
}
this.cancel();
logger2.debug("using duration", durationInSeconds);
this._expiration = expiration;
const timerDurationInSeconds = Math.min(durationInSeconds, 5);
this._timerHandle = setInterval(this._callback, timerDurationInSeconds * 1e3);
}
get expiration() {
return this._expiration;
}
cancel() {
this._logger.create("cancel");
if (this._timerHandle) {
clearInterval(this._timerHandle);
this._timerHandle = null;
}
}
};
var URL_STATE_DELIMITER = ";";
var ErrorResponse = class extends Error {
constructor(args, form) {
var _a, _b, _c;
super(args.error_description || args.error || "");
this.form = form;
/** Marker to detect class: "ErrorResponse" */
this.name = "ErrorResponse";
if (!args.error) {
Logger.error("ErrorResponse", "No error passed");
throw new Error("No error passed");
}
this.error = args.error;
this.error_description = (_a = args.error_description) != null ? _a : null;
this.error_uri = (_b = args.error_uri) != null ? _b : null;
this.state = args.userState;
this.session_state = (_c = args.session_state) != null ? _c : null;
this.url_state = args.url_state;
}
};
var ErrorTimeout = class extends Error {
constructor(message) {
super(message);
/** Marker to detect class: "ErrorTimeout" */
this.name = "ErrorTimeout";
}
};
var InMemoryWebStorage = class {
constructor() {
this._logger = new Logger("InMemoryWebStorage");
this._data = {};
}
clear() {
this._logger.create("clear");
this._data = {};
}
getItem(key) {
this._logger.create(`getItem('${key}')`);
return this._data[key];
}
setItem(key, value) {
this._logger.create(`setItem('${key}')`);
this._data[key] = value;
}
removeItem(key) {
this._logger.create(`removeItem('${key}')`);
delete this._data[key];
}
get length() {
return Object.getOwnPropertyNames(this._data).length;
}
key(index) {
return Object.getOwnPropertyNames(this._data)[index];
}
};
var ErrorDPoPNonce = class extends Error {
constructor(nonce, message) {
super(message);
/** Marker to detect class: "ErrorDPoPNonce" */
this.name = "ErrorDPoPNonce";
this.nonce = nonce;
}
};
var JsonService = class {
constructor(additionalContentTypes = [], _jwtHandler = null, _extraHeaders = {}) {
this._jwtHandler = _jwtHandler;
this._extraHeaders = _extraHeaders;
this._logger = new Logger("JsonService");
this._contentTypes = [];
this._contentTypes.push(...additionalContentTypes, "application/json");
if (_jwtHandler) this._contentTypes.push("application/jwt");
}
async fetchWithTimeout(input, init = {}) {
const { timeoutInSeconds, ...initFetch } = init;
if (!timeoutInSeconds) return await fetch(input, initFetch);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutInSeconds * 1e3);
try {
return await fetch(input, {
...init,
signal: controller.signal
});
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") throw new ErrorTimeout("Network timed out");
throw err;
} finally {
clearTimeout(timeoutId);
}
}
async getJson(url, { token, credentials, timeoutInSeconds } = {}) {
const logger2 = this._logger.create("getJson");
const headers = { "Accept": this._contentTypes.join(", ") };
if (token) {
logger2.debug("token passed, setting Authorization header");
headers["Authorization"] = "Bearer " + token;
}
this._appendExtraHeaders(headers);
let response;
try {
logger2.debug("url:", url);
response = await this.fetchWithTimeout(url, {
method: "GET",
headers,
timeoutInSeconds,
credentials
});
} catch (err) {
logger2.error("Network Error");
throw err;
}
logger2.debug("HTTP response received, status", response.status);
const contentType = response.headers.get("Content-Type");
if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) logger2.throw(/* @__PURE__ */ new Error(`Invalid response Content-Type: ${contentType != null ? contentType : "undefined"}, from URL: ${url}`));
if (response.ok && this._jwtHandler && (contentType == null ? void 0 : contentType.startsWith("application/jwt"))) return await this._jwtHandler(await response.text());
let json;
try {
json = await response.json();
} catch (err) {
logger2.error("Error parsing JSON response", err);
if (response.ok) throw err;
throw new Error(`${response.statusText} (${response.status})`);
}
if (!response.ok) {
logger2.error("Error from server:", json);
if (json.error) throw new ErrorResponse(json);
throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);
}
return json;
}
async postForm(url, { body, basicAuth, timeoutInSeconds, initCredentials, extraHeaders }) {
const logger2 = this._logger.create("postForm");
const headers = {
"Accept": this._contentTypes.join(", "),
"Content-Type": "application/x-www-form-urlencoded",
...extraHeaders
};
if (basicAuth !== void 0) headers["Authorization"] = "Basic " + basicAuth;
this._appendExtraHeaders(headers);
let response;
try {
logger2.debug("url:", url);
response = await this.fetchWithTimeout(url, {
method: "POST",
headers,
body,
timeoutInSeconds,
credentials: initCredentials
});
} catch (err) {
logger2.error("Network error");
throw err;
}
logger2.debug("HTTP response received, status", response.status);
const contentType = response.headers.get("Content-Type");
if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) throw new Error(`Invalid response Content-Type: ${contentType != null ? contentType : "undefined"}, from URL: ${url}`);
const responseText = await response.text();
let json = {};
if (responseText) try {
json = JSON.parse(responseText);
} catch (err) {
logger2.error("Error parsing JSON response", err);
if (response.ok) throw err;
throw new Error(`${response.statusText} (${response.status})`);
}
if (!response.ok) {
logger2.error("Error from server:", json);
if (response.headers.has("dpop-nonce")) throw new ErrorDPoPNonce(response.headers.get("dpop-nonce"), `${JSON.stringify(json)}`);
if (json.error) throw new ErrorResponse(json, body);
throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);
}
return json;
}
_appendExtraHeaders(headers) {
const logger2 = this._logger.create("appendExtraHeaders");
const customKeys = Object.keys(this._extraHeaders);
const protectedHeaders = ["accept", "content-type"];
const preventOverride = ["authorization"];
if (customKeys.length === 0) return;
customKeys.forEach((headerName) => {
if (protectedHeaders.includes(headerName.toLocaleLowerCase())) {
logger2.warn("Protected header could not be set", headerName, protectedHeaders);
return;
}
if (preventOverride.includes(headerName.toLocaleLowerCase()) && Object.keys(headers).includes(headerName)) {
logger2.warn("Header could not be overridden", headerName, preventOverride);
return;
}
const content = typeof this._extraHeaders[headerName] === "function" ? this._extraHeaders[headerName]() : this._extraHeaders[headerName];
if (content && content !== "") headers[headerName] = content;
});
}
};
var MetadataService = class {
constructor(_settings) {
this._settings = _settings;
this._logger = new Logger("MetadataService");
this._signingKeys = null;
this._metadata = null;
this._metadataUrl = this._settings.metadataUrl;
this._jsonService = new JsonService(["application/jwk-set+json"], null, this._settings.extraHeaders);
if (this._settings.signingKeys) {
this._logger.debug("using signingKeys from settings");
this._signingKeys = this._settings.signingKeys;
}
if (this._settings.metadata) {
this._logger.debug("using metadata from settings");
this._metadata = this._settings.metadata;
}
if (this._settings.fetchRequestCredentials) {
this._logger.debug("using fetchRequestCredentials from settings");
this._fetchRequestCredentials = this._settings.fetchRequestCredentials;
}
}
resetSigningKeys() {
this._signingKeys = null;
}
async getMetadata() {
const logger2 = this._logger.create("getMetadata");
if (this._metadata) {
logger2.debug("using cached values");
return this._metadata;
}
if (!this._metadataUrl) {
logger2.throw(/* @__PURE__ */ new Error("No authority or metadataUrl configured on settings"));
throw null;
}
logger2.debug("getting metadata from", this._metadataUrl);
const metadata = await this._jsonService.getJson(this._metadataUrl, {
credentials: this._fetchRequestCredentials,
timeoutInSeconds: this._settings.requestTimeoutInSeconds
});
logger2.debug("merging remote JSON with seed metadata");
this._metadata = Object.assign({}, metadata, this._settings.metadataSeed);
return this._metadata;
}
getIssuer() {
return this._getMetadataProperty("issuer");
}
getAuthorizationEndpoint() {
return this._getMetadataProperty("authorization_endpoint");
}
getUserInfoEndpoint() {
return this._getMetadataProperty("userinfo_endpoint");
}
getTokenEndpoint(optional = true) {
return this._getMetadataProperty("token_endpoint", optional);
}
getCheckSessionIframe() {
return this._getMetadataProperty("check_session_iframe", true);
}
getEndSessionEndpoint() {
return this._getMetadataProperty("end_session_endpoint", true);
}
getRevocationEndpoint(optional = true) {
return this._getMetadataProperty("revocation_endpoint", optional);
}
getKeysEndpoint(optional = true) {
return this._getMetadataProperty("jwks_uri", optional);
}
async _getMetadataProperty(name, optional = false) {
const logger2 = this._logger.create(`_getMetadataProperty('${name}')`);
const metadata = await this.getMetadata();
logger2.debug("resolved");
if (metadata[name] === void 0) {
if (optional === true) {
logger2.warn("Metadata does not contain optional property");
return;
}
logger2.throw(/* @__PURE__ */ new Error("Metadata does not contain property " + name));
}
return metadata[name];
}
async getSigningKeys() {
const logger2 = this._logger.create("getSigningKeys");
if (this._signingKeys) {
logger2.debug("returning signingKeys from cache");
return this._signingKeys;
}
const jwks_uri = await this.getKeysEndpoint(false);
logger2.debug("got jwks_uri", jwks_uri);
const keySet = await this._jsonService.getJson(jwks_uri, { timeoutInSeconds: this._settings.requestTimeoutInSeconds });
logger2.debug("got key set", keySet);
if (!Array.isArray(keySet.keys)) {
logger2.throw(/* @__PURE__ */ new Error("Missing keys on keyset"));
throw null;
}
this._signingKeys = keySet.keys;
return this._signingKeys;
}
};
var WebStorageStateStore = class {
constructor({ prefix = "oidc.", store = localStorage } = {}) {
this._logger = new Logger("WebStorageStateStore");
this._store = store;
this._prefix = prefix;
}
async set(key, value) {
this._logger.create(`set('${key}')`);
key = this._prefix + key;
await this._store.setItem(key, value);
}
async get(key) {
this._logger.create(`get('${key}')`);
key = this._prefix + key;
return await this._store.getItem(key);
}
async remove(key) {
this._logger.create(`remove('${key}')`);
key = this._prefix + key;
const item = await this._store.getItem(key);
await this._store.removeItem(key);
return item;
}
async getAllKeys() {
this._logger.create("getAllKeys");
const len = await this._store.length;
const keys = [];
for (let index = 0; index < len; index++) {
const key = await this._store.key(index);
if (key && key.indexOf(this._prefix) === 0) keys.push(key.substr(this._prefix.length));
}
return keys;
}
};
var DefaultResponseType = "code";
var DefaultScope = "openid";
var DefaultClientAuthentication = "client_secret_post";
var DefaultStaleStateAgeInSeconds = 900;
var OidcClientSettingsStore = class {
constructor({ authority, metadataUrl, metadata, signingKeys, metadataSeed, client_id, client_secret, response_type = DefaultResponseType, scope = DefaultScope, redirect_uri, post_logout_redirect_uri, client_authentication = DefaultClientAuthentication, token_endpoint_auth_signing_alg = "HS256", prompt, display, max_age, ui_locales, acr_values, resource, response_mode, filterProtocolClaims = true, loadUserInfo = false, requestTimeoutInSeconds, staleStateAgeInSeconds = DefaultStaleStateAgeInSeconds, mergeClaimsStrategy = { array: "replace" }, disablePKCE = false, stateStore, revokeTokenAdditionalContentTypes, fetchRequestCredentials, refreshTokenAllowedScope, extraQueryParams = {}, extraTokenParams = {}, extraHeaders = {}, dpop, omitScopeWhenRequesting = false }) {
var _a;
this.authority = authority;
if (metadataUrl) this.metadataUrl = metadataUrl;
else {
this.metadataUrl = authority;
if (authority) {
if (!this.metadataUrl.endsWith("/")) this.metadataUrl += "/";
this.metadataUrl += ".well-known/openid-configuration";
}
}
this.metadata = metadata;
this.metadataSeed = metadataSeed;
this.signingKeys = signingKeys;
this.client_id = client_id;
this.client_secret = client_secret;
this.response_type = response_type;
this.scope = scope;
this.redirect_uri = redirect_uri;
this.post_logout_redirect_uri = post_logout_redirect_uri;
this.client_authentication = client_authentication;
this.token_endpoint_auth_signing_alg = token_endpoint_auth_signing_alg;
this.prompt = prompt;
this.display = display;
this.max_age = max_age;
this.ui_locales = ui_locales;
this.acr_values = acr_values;
this.resource = resource;
this.response_mode = response_mode;
this.filterProtocolClaims = filterProtocolClaims != null ? filterProtocolClaims : true;
this.loadUserInfo = !!loadUserInfo;
this.staleStateAgeInSeconds = staleStateAgeInSeconds;
this.mergeClaimsStrategy = mergeClaimsStrategy;
this.omitScopeWhenRequesting = omitScopeWhenRequesting;
this.disablePKCE = !!disablePKCE;
this.revokeTokenAdditionalContentTypes = revokeTokenAdditionalContentTypes;
this.fetchRequestCredentials = fetchRequestCredentials ? fetchRequestCredentials : "same-origin";
this.requestTimeoutInSeconds = requestTimeoutInSeconds;
if (stateStore) this.stateStore = stateStore;
else this.stateStore = new WebStorageStateStore({ store: typeof window !== "undefined" ? window.localStorage : new InMemoryWebStorage() });
this.refreshTokenAllowedScope = refreshTokenAllowedScope;
this.extraQueryParams = extraQueryParams;
this.extraTokenParams = extraTokenParams;
this.extraHeaders = extraHeaders;
this.dpop = dpop;
if (this.dpop && !((_a = this.dpop) == null ? void 0 : _a.store)) throw new Error("A DPoPStore is required when dpop is enabled");
}
};
var State = class _State {
constructor(args) {
this.id = args.id || CryptoUtils.generateUUIDv4();
this.data = args.data;
if (args.created && args.created > 0) this.created = args.created;
else this.created = Timer.getEpochTime();
this.request_type = args.request_type;
this.url_state = args.url_state;
}
toStorageString() {
new Logger("State").create("toStorageString");
return JSON.stringify({
id: this.id,
data: this.data,
created: this.created,
request_type: this.request_type,
url_state: this.url_state
});
}
static fromStorageString(storageString) {
Logger.createStatic("State", "fromStorageString");
return Promise.resolve(new _State(JSON.parse(storageString)));
}
static async clearStaleState(storage, age) {
const logger2 = Logger.createStatic("State", "clearStaleState");
const cutoff = Timer.getEpochTime() - age;
const keys = await storage.getAllKeys();
logger2.debug("got keys", keys);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const item = await storage.get(key);
let remove = false;
if (item) try {
const state = await _State.fromStorageString(item);
logger2.debug("got item from key:", key, state.created);
if (state.created <= cutoff) remove = true;
} catch (err) {
logger2.error("Error parsing state for key:", key, err);
remove = true;
}
else {
logger2.debug("no item in storage for key:", key);
remove = true;
}
if (remove) {
logger2.debug("removed item for key:", key);
storage.remove(key);
}
}
}
};
var SigninState = class _SigninState extends State {
constructor(args) {
super(args);
this.code_verifier = args.code_verifier;
this.code_challenge = args.code_challenge;
this.authority = args.authority;
this.client_id = args.client_id;
this.redirect_uri = args.redirect_uri;
this.scope = args.scope;
this.client_secret = args.client_secret;
this.extraTokenParams = args.extraTokenParams;
this.response_mode = args.response_mode;
this.skipUserInfo = args.skipUserInfo;
this.nonce = args.nonce;
}
static async create(args) {
const code_verifier = args.code_verifier === true ? CryptoUtils.generateCodeVerifier() : args.code_verifier || void 0;
const code_challenge = code_verifier ? await CryptoUtils.generateCodeChallenge(code_verifier) : void 0;
return new _SigninState({
...args,
code_verifier,
code_challenge
});
}
toStorageString() {
new Logger("SigninState").create("toStorageString");
return JSON.stringify({
id: this.id,
data: this.data,
created: this.created,
request_type: this.request_type,
url_state: this.url_state,
code_verifier: this.code_verifier,
authority: this.authority,
client_id: this.client_id,
redirect_uri: this.redirect_uri,
scope: this.scope,
client_secret: this.client_secret,
extraTokenParams: this.extraTokenParams,
response_mode: this.response_mode,
skipUserInfo: this.skipUserInfo,
nonce: this.nonce
});
}
static fromStorageString(storageString) {
Logger.createStatic("SigninState", "fromStorageString");
const data = JSON.parse(storageString);
return _SigninState.create(data);
}
};
var _SigninRequest = class _SigninRequest {
constructor(args) {
this.url = args.url;
this.state = args.state;
}
static async create({ url, authority, client_id, redirect_uri, response_type, scope, state_data, response_mode, request_type, client_secret, nonce, url_state, resource, skipUserInfo, extraQueryParams, extraTokenParams, disablePKCE, dpopJkt, omitScopeWhenRequesting, ...optionalParams }) {
if (!url) {
this._logger.error("create: No url passed");
throw new Error("url");
}
if (!client_id) {
this._logger.error("create: No client_id passed");
throw new Error("client_id");
}
if (!redirect_uri) {
this._logger.error("create: No redirect_uri passed");
throw new Error("redirect_uri");
}
if (!response_type) {
this._logger.error("create: No response_type passed");
throw new Error("response_type");
}
if (!scope) {
this._logger.error("create: No scope passed");
throw new Error("scope");
}
if (!authority) {
this._logger.error("create: No authority passed");
throw new Error("authority");
}
const state = await SigninState.create({
data: state_data,
request_type,
url_state,
code_verifier: !disablePKCE,
client_id,
authority,
redirect_uri,
response_mode,
client_secret,
scope,
extraTokenParams,
skipUserInfo,
nonce
});
const parsedUrl = new URL(url);
parsedUrl.searchParams.append("client_id", client_id);
parsedUrl.searchParams.append("redirect_uri", redirect_uri);
parsedUrl.searchParams.append("response_type", response_type);
if (!omitScopeWhenRequesting) parsedUrl.searchParams.append("scope", scope);
if (nonce) parsedUrl.searchParams.append("nonce", nonce);
if (dpopJkt) parsedUrl.searchParams.append("dpop_jkt", dpopJkt);
let stateParam = state.id;
if (url_state) stateParam = `${stateParam}${URL_STATE_DELIMITER}${url_state}`;
parsedUrl.searchParams.append("state", stateParam);
if (state.code_challenge) {
parsedUrl.searchParams.append("code_challenge", state.code_challenge);
parsedUrl.searchParams.append("code_challenge_method", "S256");
}
if (resource) (Array.isArray(resource) ? resource : [resource]).forEach((r) => parsedUrl.searchParams.append("resource", r));
for (const [key, value] of Object.entries({
response_mode,
...optionalParams,
...extraQueryParams
})) if (value != null) parsedUrl.searchParams.append(key, value.toString());
return new _SigninRequest({
url: parsedUrl.href,
state
});
}
};
_SigninRequest._logger = new Logger("SigninRequest");
//#endregion
//#region node_modules/matrix-js-sdk/lib/oidc/error.js
/**
* Errors expected to be encountered during OIDC discovery, client registration, and authentication.
* Not intended to be displayed directly to the user.
*/
var OidcError = /* @__PURE__ */ function(OidcError) {
OidcError["NotSupported"] = "OIDC authentication not supported";
OidcError["Misconfigured"] = "OIDC is misconfigured";
OidcError["General"] = "Something went wrong with OIDC discovery";
OidcError["OpSupport"] = "Configured OIDC OP does not support required functions";
OidcError["DynamicRegistrationNotSupported"] = "Dynamic registration not supported";
OidcError["DynamicRegistrationFailed"] = "Dynamic registration failed";
OidcError["DynamicRegistrationInvalid"] = "Dynamic registration invalid response";
OidcError["CodeExchangeFailed"] = "Failed to exchange code for token";
OidcError["InvalidBearerTokenResponse"] = "Invalid bearer token response";
OidcError["InvalidIdToken"] = "Invalid ID token";
OidcError["MissingOrInvalidStoredState"] = "State required to finish logging in is not found in storage.";
return OidcError;
}({});
//#endregion
//#region node_modules/matrix-js-sdk/lib/oidc/validate.js
/**
* Metadata from OAuth 2.0 client authentication API as per
* https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
* With validated properties required in type
*/
var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
var requiredStringProperty = (wellKnown, key) => {
if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {
logger$2.error("Missing or invalid property: ".concat(key));
return false;
}
return true;
};
var optionalStringProperty = (wellKnown, key) => {
if (!!wellKnown[key] && typeof wellKnown[key] !== "string") {
logger$2.error("Invalid property: ".concat(key));
return false;
}
return true;
};
var optionalStringArrayProperty = (wellKnown, key) => {
if (!!wellKnown[key] && (!Array.isArray(wellKnown[key]) || !wellKnown[key].every((v) => typeof v === "string"))) {
logger$2.error("Invalid property: ".concat(key));
return false;
}
return true;
};
var requiredArrayValue = (wellKnown, key, value) => {
var array = wellKnown[key];
if (!array || !Array.isArray(array) || !array.includes(value)) {
logger$2.error("Invalid property: ".concat(key, ". ").concat(value, " is required."));
return false;
}
return true;
};
/**
* Validates OAuth 2.0 auth metadata as defined by
* https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
* is compatible with Element's OAuth/OIDC flow
* @param authMetadata - json object
* @returns valid issuer config
* @throws Error - when issuer config is not found or is invalid
*/
var validateAuthMetadata = (authMetadata) => {
if (!isRecord(authMetadata)) {
logger$2.error("Issuer configuration not found or malformed");
throw new Error(OidcError.OpSupport);
}
if (![
requiredStringProperty(authMetadata, "issuer"),
requiredStringProperty(authMetadata, "authorization_endpoint"),
requiredStringProperty(authMetadata, "token_endpoint"),
requiredStringProperty(authMetadata, "revocation_endpoint"),
optionalStringProperty(authMetadata, "registration_endpoint"),
optionalStringProperty(authMetadata, "account_management_uri"),
optionalStringProperty(authMetadata, "device_authorization_endpoint"),
optionalStringArrayProperty(authMetadata, "account_management_actions_supported"),
requiredArrayValue(authMetadata, "response_types_supported", "code"),
requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode),
requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256"),
optionalStringArrayProperty(authMetadata, "prompt_values_supported")
].some((isValid) => !isValid)) return authMetadata;
logger$2.error("Issuer configuration not valid");
throw new Error(OidcError.OpSupport);
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/oidc/discovery.js
function ownKeys$2(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;
}
function _objectSpread$2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$2(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
/**
* @experimental
* Discover and validate delegated auth configuration
* - delegated auth issuer openid-configuration is reachable
* - delegated auth issuer openid-configuration is configured correctly for us
* Fetches https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.
* When successful, validated metadata is returned
* @param issuer - the OIDC issuer as returned by the /auth_issuer API
* @returns validated authentication metadata and optionally signing keys
* @throws when delegated auth config is invalid or unreachable
* @deprecated in favour of {@link MatrixClient#getAuthMetadata}
*/
var discoverAndValidateOIDCIssuerWellKnown = /* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (issuer) {
var issuerOpenIdConfigUrl = new URL(".well-known/openid-configuration", issuer);
return validateAuthMetadataAndKeys(yield (yield fetch(issuerOpenIdConfigUrl, {
method: Method.Get,
signal: timeoutSignal(5e3)
})).json());
});
return function discoverAndValidateOIDCIssuerWellKnown(_x) {
return _ref.apply(this, arguments);
};
}();
/**
* @experimental
* Validate the authentication metadata and fetch the signing keys from the jwks_uri in the metadata
* @param authMetadata - the authentication metadata to validate
* @returns validated authentication metadata and signing keys
*/
var validateAuthMetadataAndKeys = /* @__PURE__ */ function() {
var _ref2 = (0, import_asyncToGenerator.default)(function* (authMetadata) {
var validatedIssuerConfig = validateAuthMetadata(authMetadata);
var metadataService = new MetadataService(new OidcClientSettingsStore({
authority: validatedIssuerConfig.issuer,
metadata: validatedIssuerConfig,
redirect_uri: "",
client_id: ""
}));
return _objectSpread$2(_objectSpread$2({}, validatedIssuerConfig), {}, { signingKeys: yield metadataService.getSigningKeys() });
});
return function validateAuthMetadataAndKeys(_x2) {
return _ref2.apply(this, arguments);
};
}();
//#endregion
//#region node_modules/matrix-js-sdk/lib/oidc/register.js
/**
* Client metadata passed to registration endpoint
*/
/**
* Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966
*/
/**
* The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
*/
var OAuthGrantType = /* @__PURE__ */ function(OAuthGrantType) {
/**
* See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
*/
OAuthGrantType["AuthorizationCode"] = "authorization_code";
/**
* https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant
*/
OAuthGrantType["RefreshToken"] = "refresh_token";
/**
* The OAuth 2.0 Device Authorization Grant type identifier as per
* https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from
* [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).
*
* @experimental Note that this is UNSTABLE and may have breaking changes without notice.
*/
OAuthGrantType["DeviceAuthorization"] = "urn:ietf:params:oauth:grant-type:device_code";
return OAuthGrantType;
}({});
OAuthGrantType.DeviceAuthorization;
//#endregion
//#region node_modules/matrix-js-sdk/lib/client.js
/**
* This is an internal module. See {@link MatrixClient} for the public class.
*/
var import_objectWithoutProperties = /* @__PURE__ */ __toESM(require_objectWithoutProperties(), 1);
var _excluded = [
"server",
"limit",
"since"
];
function ownKeys$1(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;
}
function _objectSpread$1(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$1(Object(t), !0).forEach(function(r) {
(0, import_defineProperty.default)(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
var SCROLLBACK_DELAY_MS = 3e3;
var TURN_CHECK_INTERVAL = 600 * 1e3;
new UnstableValue$3("last_seen_user_agent", "org.matrix.msc3852.last_seen_user_agent");
var PendingEventOrdering = /* @__PURE__ */ function(PendingEventOrdering) {
PendingEventOrdering["Chronological"] = "chronological";
PendingEventOrdering["Detached"] = "detached";
return PendingEventOrdering;
}({});
new NamespacedValue$1("m.get_login_token", "org.matrix.msc3882.get_login_token");
var UNSTABLE_MSC2666_SHARED_ROOMS = "uk.half-shot.msc2666";
var UNSTABLE_MSC2666_MUTUAL_ROOMS = "uk.half-shot.msc2666.mutual_rooms";
var UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = "uk.half-shot.msc2666.query_mutual_rooms";
var UNSTABLE_MSC4140_DELAYED_EVENTS = "org.matrix.msc4140";
/**
* The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse
* Proposed at https://github.com/matrix-org/matrix-doc/pull/3266
*/
var EVENT_ID_PREFIX = "$";
var ClientEvent = /* @__PURE__ */ function(ClientEvent) {
/**
* Fires whenever the SDK's syncing state is updated. The state can be one of:
* <ul>
*
* <li>PREPARED: The client has synced with the server at least once and is
* ready for methods to be called on it. This will be immediately followed by
* a state of SYNCING. <i>This is the equivalent of "syncComplete" in the
* previous API.</i></li>
*
* <li>CATCHUP: The client has detected the connection to the server might be
* available again and will now try to do a sync again. As this sync might take
* a long time (depending how long ago was last synced, and general server
* performance) the client is put in this mode so the UI can reflect trying
* to catch up with the server after losing connection.</li>
*
* <li>SYNCING : The client is currently polling for new events from the server.
* This will be called <i>after</i> processing latest events from a sync.</li>
*
* <li>ERROR : The client has had a problem syncing with the server. If this is
* called <i>before</i> PREPARED then there was a problem performing the initial
* sync. If this is called <i>after</i> PREPARED then there was a problem polling
* the server for updates. This may be called multiple times even if the state is
* already ERROR. <i>This is the equivalent of "syncError" in the previous
* API.</i></li>
*
* <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that
* should be considered erroneous.
* </li>
*
* <li>STOPPED: The client has stopped syncing with server due to stopClient
* being called.
* </li>
* </ul>
* State transition diagram:
* ```
* +---->STOPPED
* |
* +----->PREPARED -------> SYNCING <--+
* | ^ | ^ |
* | CATCHUP ----------+ | | |
* | ^ V | |
* null ------+ | +------- RECONNECTING |
* | V V |
* +------->ERROR ---------------------+
*
* NB: 'null' will never be emitted by this event.
*
* ```
* Transitions:
* <ul>
*
* <li>`null -> PREPARED` : Occurs when the initial sync is completed
* first time. This involves setting up filters and obtaining push rules.
*
* <li>`null -> ERROR` : Occurs when the initial sync failed first time.
*
* <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds
* after previously failing.
*
* <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning
* to PREPARED. Starts listening for live updates rather than catching up.
*
* <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.
*
* <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls
* continue to fail, but the keepalive calls (to /versions) succeed.
*
* <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails
*
* <li>`ERROR -> SYNCING` : Occurs when the client has performed a
* live update after having previously failed.
*
* <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive
* for a second time or more.</li>
*
* <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live
* update. This is called <i>after</i> processing.</li>
*
* <li>`* -> STOPPED` : Occurs once the client has stopped syncing or
* trying to sync after stopClient has been called.</li>
* </ul>
*
* The payloads consits of the following 3 parameters:
*
* - state - An enum representing the syncing state. One of "PREPARED",
* "SYNCING", "ERROR", "STOPPED".
*
* - prevState - An enum representing the previous syncing state.
* One of "PREPARED", "SYNCING", "ERROR", "STOPPED" <b>or null</b>.
*
* - data - Data about this transition.
*
* @example
* ```
* matrixClient.on("sync", function(state, prevState, data) {
* switch (state) {
* case "ERROR":
* // update UI to say "Connection Lost"
* break;
* case "SYNCING":
* // update UI to remove any "Connection Lost" message
* break;
* case "PREPARED":
* // the client instance is ready to be queried.
* var rooms = matrixClient.getRooms();
* break;
* }
* });
* ```
*/
ClientEvent["Sync"] = "sync";
/**
* Fires whenever the SDK receives a new event.
* <p>
* This is only fired for live events received via /sync - it is not fired for
* events received over context, search, or pagination APIs.
*
* The payload is the matrix event which caused this event to fire.
* @example
* ```
* matrixClient.on("event", function(event){
* var sender = event.getSender();
* });
* ```
*/
ClientEvent["Event"] = "event";
/** @deprecated Use {@link ReceivedToDeviceMessage}.
* Fires whenever the SDK receives a new to-device event.
* The payload is the matrix event ({@link MatrixEvent}) which caused this event to fire.
* @example
* ```
* matrixClient.on("toDeviceEvent", function(event){
* var sender = event.getSender();
* });
* ```
*/
ClientEvent["ToDeviceEvent"] = "toDeviceEvent";
/**
* Fires whenever the SDK receives a new (potentially decrypted) to-device message.
* The payload is the to-device message and the encryption info for that message ({@link ReceivedToDeviceMessage}).
* @example
* ```
* matrixClient.on("receivedToDeviceMessage", function(payload){
* const { message, encryptionInfo } = payload;
* var claimed_sender = encryptionInfo ? encryptionInfo.sender : message.sender;
* var isVerified = encryptionInfo ? encryptionInfo.verified : false;
* var type = message.type;
* });
*/
ClientEvent["ReceivedToDeviceMessage"] = "receivedToDeviceMessage";
/**
* Fires whenever new user-scoped account_data is added.
* The payload is a pair of event ({@link MatrixEvent}) describing the account_data just added, and the previous event, if known:
* - event: The event describing the account_data just added
* - oldEvent: The previous account data, if known.
* @example
* ```
* matrixClient.on("accountData", function(event, oldEvent){
* myAccountData[event.type] = event.content;
* });
* ```
*/
ClientEvent["AccountData"] = "accountData";
/**
* Fires whenever a new Room is added. This will fire when you are invited to a
* room, as well as when you join a room. <strong>This event is experimental and
* may change.</strong>
*
* The payload is the newly created room, fully populated.
* @example
* ```
* matrixClient.on("Room", function(room){
* var roomId = room.roomId;
* });
* ```
*/
ClientEvent["Room"] = "Room";
/**
* Fires whenever a Room is removed. This will fire when you forget a room.
* <strong>This event is experimental and may change.</strong>
* The payload is the roomId of the deleted room.
* @example
* ```
* matrixClient.on("deleteRoom", function(roomId){
* // update UI from getRooms()
* });
* ```
*/
ClientEvent["DeleteRoom"] = "deleteRoom";
ClientEvent["SyncUnexpectedError"] = "sync.unexpectedError";
/**
* Fires when the client .well-known info is fetched.
* The payload is the JSON object (see {@link IClientWellKnown}) returned by the server
*/
ClientEvent["ClientWellKnown"] = "WellKnown.client";
ClientEvent["ReceivedVoipEvent"] = "received_voip_event";
ClientEvent["TurnServers"] = "turnServers";
ClientEvent["TurnServersError"] = "turnServers.error";
return ClientEvent;
}({});
var SSO_ACTION_PARAM = new UnstableValue$3("action", "org.matrix.msc3824.action");
/**
* Represents a Matrix Client. Only directly construct this if you want to use
* custom modules. Normally, {@link createClient} should be used
* as it specifies 'sensible' defaults for these modules.
*/
var MatrixClient = class extends TypedEventEmitter {
constructor(opts) {
var _opts$logger, _opts$usingExternalCr, _this, _opts$disableVoip, _opts$enableEncrypted, _opts$cryptoCallbacks;
super();
_this = this;
(0, import_defineProperty.default)(this, "logger", void 0);
(0, import_defineProperty.default)(this, "reEmitter", new TypedReEmitter(this));
(0, import_defineProperty.default)(this, "olmVersion", null);
(0, import_defineProperty.default)(this, "usingExternalCrypto", false);
(0, import_defineProperty.default)(this, "_store", void 0);
(0, import_defineProperty.default)(this, "deviceId", void 0);
(0, import_defineProperty.default)(this, "credentials", void 0);
/**
* Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.
*
* As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.
* Used for migration from the legacy crypto to the rust crypto
*/
(0, import_defineProperty.default)(this, "legacyPickleKey", void 0);
(0, import_defineProperty.default)(this, "scheduler", void 0);
(0, import_defineProperty.default)(this, "clientRunning", false);
(0, import_defineProperty.default)(this, "timelineSupport", false);
(0, import_defineProperty.default)(this, "urlPreviewCache", {});
(0, import_defineProperty.default)(this, "identityServer", void 0);
(0, import_defineProperty.default)(this, "http", void 0);
(0, import_defineProperty.default)(this, "cryptoBackend", void 0);
/**
* Support MSC4362: Simplified Encrypted State Events.
*
* The client must be recreated for changes to this setting to take effect
* reliably.
*
* When this setting is true, if we find a state event that is encrypted
* (within a room that supports encrypted state), we will attempt to decrypt
* it as specified in MSC4362. If the user was in the room at the time an
* encrypted state event was received (meaning we have the key), even if
* this setting was set to false at the time it was received, recreating the
* client with this setting set to true will allow decrypting that event.
*
* When this setting is false, any state event that is encrypted will not be
* decrypted, meaning it will have no effect. This matched the behaviour of
* a client that does not support MSC4362.
*/
(0, import_defineProperty.default)(this, "enableEncryptedStateEvents", void 0);
(0, import_defineProperty.default)(this, "cryptoCallbacks", void 0);
(0, import_defineProperty.default)(this, "callEventHandler", void 0);
(0, import_defineProperty.default)(this, "groupCallEventHandler", void 0);
(0, import_defineProperty.default)(this, "supportsCallTransfer", false);
(0, import_defineProperty.default)(this, "forceTURN", false);
(0, import_defineProperty.default)(this, "iceCandidatePoolSize", 0);
(0, import_defineProperty.default)(this, "idBaseUrl", void 0);
(0, import_defineProperty.default)(this, "baseUrl", void 0);
(0, import_defineProperty.default)(this, "isVoipWithNoMediaAllowed", void 0);
(0, import_defineProperty.default)(this, "disableVoip", void 0);
(0, import_defineProperty.default)(this, "useLivekitForGroupCalls", void 0);
(0, import_defineProperty.default)(this, "canSupportVoip", false);
(0, import_defineProperty.default)(this, "peekSync", null);
(0, import_defineProperty.default)(this, "isGuestAccount", false);
(0, import_defineProperty.default)(this, "ongoingScrollbacks", {});
(0, import_defineProperty.default)(this, "notifTimelineSet", null);
/**
* Legacy crypto store used for migration from the legacy crypto to the rust crypto
* @private
*/
(0, import_defineProperty.default)(this, "legacyCryptoStore", void 0);
(0, import_defineProperty.default)(this, "verificationMethods", void 0);
(0, import_defineProperty.default)(this, "fallbackICEServerAllowed", false);
(0, import_defineProperty.default)(this, "syncApi", void 0);
(0, import_defineProperty.default)(this, "roomNameGenerator", void 0);
(0, import_defineProperty.default)(this, "pushRules", void 0);
(0, import_defineProperty.default)(this, "syncLeftRoomsPromise", void 0);
(0, import_defineProperty.default)(this, "syncedLeftRooms", false);
(0, import_defineProperty.default)(this, "clientOpts", void 0);
(0, import_defineProperty.default)(this, "clientWellKnownIntervalID", void 0);
(0, import_defineProperty.default)(this, "canResetTimelineCallback", void 0);
(0, import_defineProperty.default)(this, "canSupport", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "pushProcessor", new PushProcessor(this));
(0, import_defineProperty.default)(this, "serverVersionsPromise", void 0);
(0, import_defineProperty.default)(this, "clientWellKnown", void 0);
(0, import_defineProperty.default)(this, "clientWellKnownPromise", void 0);
(0, import_defineProperty.default)(this, "turnServers", []);
(0, import_defineProperty.default)(this, "turnServersExpiry", 0);
(0, import_defineProperty.default)(this, "checkTurnServersIntervalID", void 0);
(0, import_defineProperty.default)(this, "txnCtr", 0);
(0, import_defineProperty.default)(this, "mediaHandler", new MediaHandler(this));
(0, import_defineProperty.default)(this, "sessionId", void 0);
/** IDs of events which are currently being encrypted.
*
* This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,
* that tells us that it has been cancelled, and we should not send it.
*/
(0, import_defineProperty.default)(this, "eventsBeingEncrypted", /* @__PURE__ */ new Set());
(0, import_defineProperty.default)(this, "useE2eForGroupCall", true);
(0, import_defineProperty.default)(this, "toDeviceMessageQueue", void 0);
(0, import_defineProperty.default)(this, "livekitServiceURL", void 0);
(0, import_defineProperty.default)(this, "_secretStorage", void 0);
(0, import_defineProperty.default)(this, "ignoredInvites", void 0);
(0, import_defineProperty.default)(this, "matrixRTC", void 0);
(0, import_defineProperty.default)(this, "serverCapabilitiesService", void 0);
(0, import_defineProperty.default)(this, "startCallEventHandler", () => {
if (this.isInitialSyncComplete()) {
if (supportsMatrixCall()) {
this.callEventHandler.start();
this.groupCallEventHandler.start();
}
this.off(ClientEvent.Sync, this.startCallEventHandler);
}
});
(0, import_defineProperty.default)(this, "startMatrixRTC", () => {
if (this.isInitialSyncComplete()) {
this.matrixRTC.start();
this.off(ClientEvent.Sync, this.startMatrixRTC);
}
});
/**
* Once the client has been initialised, we want to clear notifications we
* know for a fact should be here.
* This issue should also be addressed on synapse's side and is tracked as part
* of https://github.com/matrix-org/synapse/issues/14837
*
* We consider a room or a thread as fully read if the current user has sent
* the last event in the live timeline of that context and if the read receipt
* we have on record matches.
*/
(0, import_defineProperty.default)(this, "fixupRoomNotifications", () => {
if (this.isInitialSyncComplete()) {
var _this$getRooms;
for (var _room of ((_this$getRooms = this.getRooms()) !== null && _this$getRooms !== void 0 ? _this$getRooms : []).filter((room) => {
return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;
})) {
var currentUserId = this.getSafeUserId();
_room.fixupNotifications(currentUserId);
}
this.off(ClientEvent.Sync, this.fixupRoomNotifications);
}
});
this.logger = (_opts$logger = opts.logger) !== null && _opts$logger !== void 0 ? _opts$logger : logger$2;
opts.baseUrl = ensureNoTrailingSlash(opts.baseUrl);
opts.idBaseUrl = ensureNoTrailingSlash(opts.idBaseUrl);
this.baseUrl = opts.baseUrl;
this.idBaseUrl = opts.idBaseUrl;
this.identityServer = opts.identityServer;
this.usingExternalCrypto = (_opts$usingExternalCr = opts.usingExternalCrypto) !== null && _opts$usingExternalCr !== void 0 ? _opts$usingExternalCr : false;
this.store = opts.store || new StubStore();
this.deviceId = opts.deviceId || null;
this.sessionId = secureRandomString(10);
this.credentials = { userId: opts.userId || null };
this.http = new MatrixHttpApi(this, {
fetchFn: opts.fetchFn,
baseUrl: opts.baseUrl,
idBaseUrl: opts.idBaseUrl,
accessToken: opts.accessToken,
refreshToken: opts.refreshToken,
tokenRefreshFunction: opts.tokenRefreshFunction,
prefix: ClientPrefix.V3,
onlyData: true,
extraParams: opts.queryParams,
localTimeoutMs: opts.localTimeoutMs,
useAuthorizationHeader: opts.useAuthorizationHeader,
logger: this.logger
});
if (opts.pickleKey) this.legacyPickleKey = opts.pickleKey;
this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);
this.scheduler = opts.scheduler;
if (this.scheduler) this.scheduler.setProcessFunction(/* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (eventToSend) {
var room = _this.getRoom(eventToSend.getRoomId());
if (eventToSend.status !== EventStatus.SENDING) _this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);
var res = yield _this.sendEventHttpRequest(eventToSend);
if (room) room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);
return res;
});
return function(_x) {
return _ref.apply(this, arguments);
};
}());
this.disableVoip = (_opts$disableVoip = opts.disableVoip) !== null && _opts$disableVoip !== void 0 ? _opts$disableVoip : false;
if (!this.disableVoip && supportsMatrixCall()) {
this.callEventHandler = new CallEventHandler(this);
this.groupCallEventHandler = new GroupCallEventHandler(this);
this.canSupportVoip = true;
this.on(ClientEvent.Sync, this.startCallEventHandler);
}
this.matrixRTC = new MatrixRTCSessionManager(this.logger, this);
this.serverCapabilitiesService = new ServerCapabilities(this.logger, this.http);
this.on(ClientEvent.Sync, this.fixupRoomNotifications);
this.timelineSupport = Boolean(opts.timelineSupport);
this.legacyCryptoStore = opts.cryptoStore;
this.verificationMethods = opts.verificationMethods;
this.cryptoCallbacks = opts.cryptoCallbacks || {};
this.enableEncryptedStateEvents = (_opts$enableEncrypted = opts.enableEncryptedStateEvents) !== null && _opts$enableEncrypted !== void 0 ? _opts$enableEncrypted : false;
this.forceTURN = opts.forceTURN || false;
this.iceCandidatePoolSize = opts.iceCandidatePoolSize === void 0 ? 0 : opts.iceCandidatePoolSize;
this.supportsCallTransfer = opts.supportsCallTransfer || false;
this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;
this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;
if (opts.useE2eForGroupCall !== void 0) this.useE2eForGroupCall = opts.useE2eForGroupCall;
this.livekitServiceURL = opts.livekitServiceURL;
this.roomNameGenerator = opts.roomNameGenerator;
this.toDeviceMessageQueue = new ToDeviceMessageQueue(this, this.logger);
this.on(MatrixEventEvent.Decrypted, (event) => {
fixNotificationCountOnDecryption(this, event);
});
this.ignoredInvites = new IgnoredInvites(this);
this._secretStorage = new ServerSideSecretStorageImpl(this, (_opts$cryptoCallbacks = opts.cryptoCallbacks) !== null && _opts$cryptoCallbacks !== void 0 ? _opts$cryptoCallbacks : {});
this.setMaxListeners(0);
}
set store(newStore) {
this._store = newStore;
this._store.setUserCreator((userId) => User.createUser(userId, this));
}
get store() {
return this._store;
}
/**
* High level helper method to begin syncing and poll for new events. To listen for these
* events, add a listener for {@link ClientEvent.Event}
* via {@link MatrixClient#on}. Alternatively, listen for specific
* state change events.
* @param opts - Options to apply when syncing.
*/
startClient(opts) {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this2.clientRunning) return;
_this2.clientRunning = true;
_this2.on(ClientEvent.Sync, _this2.startMatrixRTC);
var userId = _this2.getUserId();
if (userId) _this2.store.storeUser(new User(userId));
if (_this2.supportsVoip()) {
_this2.checkTurnServersIntervalID = setInterval(() => {
_this2.checkTurnServers();
}, TURN_CHECK_INTERVAL);
_this2.checkTurnServers();
}
if (_this2.syncApi) {
_this2.logger.error("Still have sync object whilst not running: stopping old one");
_this2.syncApi.stop();
}
try {
yield _this2.getVersions();
var { threads, list, fwdPagination } = yield _this2.doesServerSupportThread();
Thread.setServerSideSupport(threads);
Thread.setServerSideListSupport(list);
Thread.setServerSideFwdPaginationSupport(fwdPagination);
} catch (e) {
_this2.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later", e);
}
_this2.clientOpts = opts !== null && opts !== void 0 ? opts : {};
if (_this2.clientOpts.slidingSync) _this2.syncApi = new SlidingSyncSdk(_this2.clientOpts.slidingSync, _this2, _this2.clientOpts, _this2.buildSyncApiOptions());
else _this2.syncApi = new SyncApi(_this2, _this2.clientOpts, _this2.buildSyncApiOptions());
_this2.syncApi.sync().catch((e) => _this2.logger.info("Sync startup aborted with an error:", e));
if (_this2.clientOpts.clientWellKnownPollPeriod !== void 0) {
_this2.clientWellKnownIntervalID = setInterval(() => {
_this2.fetchClientWellKnown();
}, 1e3 * _this2.clientOpts.clientWellKnownPollPeriod);
_this2.fetchClientWellKnown();
}
_this2.toDeviceMessageQueue.start();
_this2.serverCapabilitiesService.start();
})();
}
/**
* Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor
*/
buildSyncApiOptions() {
return {
cryptoCallbacks: this.cryptoBackend,
canResetEntireTimeline: (roomId) => {
if (!this.canResetTimelineCallback) return false;
return this.canResetTimelineCallback(roomId);
},
logger: this.logger.getChild("sync")
};
}
/**
* High level helper method to stop the client from polling and allow a
* clean shutdown.
*/
stopClient() {
var _this$cryptoBackend, _this$syncApi, _this$peekSync, _this$callEventHandle, _this$groupCallEventH;
(_this$cryptoBackend = this.cryptoBackend) === null || _this$cryptoBackend === void 0 || _this$cryptoBackend.stop();
this.off(ClientEvent.Sync, this.startMatrixRTC);
if (!this.clientRunning) return;
this.logger.debug("stopping MatrixClient");
this.clientRunning = false;
(_this$syncApi = this.syncApi) === null || _this$syncApi === void 0 || _this$syncApi.stop();
this.syncApi = void 0;
(_this$peekSync = this.peekSync) === null || _this$peekSync === void 0 || _this$peekSync.stopPeeking();
(_this$callEventHandle = this.callEventHandler) === null || _this$callEventHandle === void 0 || _this$callEventHandle.stop();
(_this$groupCallEventH = this.groupCallEventHandler) === null || _this$groupCallEventH === void 0 || _this$groupCallEventH.stop();
this.callEventHandler = void 0;
this.groupCallEventHandler = void 0;
globalThis.clearInterval(this.checkTurnServersIntervalID);
this.checkTurnServersIntervalID = void 0;
if (this.clientWellKnownIntervalID !== void 0) globalThis.clearInterval(this.clientWellKnownIntervalID);
this.toDeviceMessageQueue.stop();
this.matrixRTC.stop();
this.serverCapabilitiesService.stop();
}
/**
* Clear any data out of the persistent stores used by the client.
*
* @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.
* @returns Promise which resolves when the stores have been cleared.
*/
clearStores() {
var _this3 = this;
var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
if (this.clientRunning) throw new Error("Cannot clear stores while client is running");
var promises = [];
promises.push(this.store.deleteAllData());
if (this.legacyCryptoStore) promises.push(this.legacyCryptoStore.deleteAllData());
var deleteRustSdkStore = /* @__PURE__ */ function() {
var _ref2 = (0, import_asyncToGenerator.default)(function* () {
var indexedDB;
try {
indexedDB = globalThis.indexedDB;
if (!indexedDB) return;
} catch (_unused) {
return;
}
var _loop = function* _loop(dbname) {
yield new Promise((resolve, reject) => {
_this3.logger.info("Removing IndexedDB instance ".concat(dbname));
var req = indexedDB.deleteDatabase(dbname);
req.onsuccess = (_) => {
_this3.logger.info("Removed IndexedDB instance ".concat(dbname));
resolve(0);
};
req.onerror = (e) => {
_this3.logger.warn("Failed to remove IndexedDB instance ".concat(dbname, ":"), e);
resolve(0);
};
req.onblocked = (e) => {
_this3.logger.info("cannot yet remove IndexedDB instance ".concat(dbname));
};
});
};
for (var dbname of ["".concat((_args$cryptoDatabaseP = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP !== void 0 ? _args$cryptoDatabaseP : RUST_SDK_STORE_PREFIX, "::matrix-sdk-crypto"), "".concat((_args$cryptoDatabaseP2 = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP2 !== void 0 ? _args$cryptoDatabaseP2 : RUST_SDK_STORE_PREFIX, "::matrix-sdk-crypto-meta")]) {
var _args$cryptoDatabaseP, _args$cryptoDatabaseP2;
yield* _loop(dbname);
}
});
return function deleteRustSdkStore() {
return _ref2.apply(this, arguments);
};
}();
promises.push(deleteRustSdkStore());
return Promise.all(promises).then();
}
/**
* Get the user-id of the logged-in user
*
* @returns MXID for the logged-in user, or null if not logged in
*/
getUserId() {
var _this$credentials$use, _this$credentials;
return (_this$credentials$use = (_this$credentials = this.credentials) === null || _this$credentials === void 0 ? void 0 : _this$credentials.userId) !== null && _this$credentials$use !== void 0 ? _this$credentials$use : null;
}
/**
* Get the user-id of the logged-in user
*
* @returns MXID for the logged-in user
* @throws Error if not logged in
*/
getSafeUserId() {
var userId = this.getUserId();
if (!userId) throw new Error("Expected logged in user but found none.");
return userId;
}
/**
* Get the domain for this client's MXID
* @returns Domain of this MXID
*/
getDomain() {
var _this$credentials2;
if ((_this$credentials2 = this.credentials) !== null && _this$credentials2 !== void 0 && _this$credentials2.userId) return this.credentials.userId.replace(/^.*?:/, "");
return null;
}
/**
* Get the local part of the current user ID e.g. "foo" in "\@foo:bar".
* @returns The user ID localpart or null.
*/
getUserIdLocalpart() {
var _this$credentials$use2, _this$credentials3;
return (_this$credentials$use2 = (_this$credentials3 = this.credentials) === null || _this$credentials3 === void 0 || (_this$credentials3 = _this$credentials3.userId) === null || _this$credentials3 === void 0 ? void 0 : _this$credentials3.split(":")[0].substring(1)) !== null && _this$credentials$use2 !== void 0 ? _this$credentials$use2 : null;
}
/**
* Get the device ID of this client
* @returns device ID
*/
getDeviceId() {
return this.deviceId;
}
/**
* Get the session ID of this client
* @returns session ID
*/
getSessionId() {
return this.sessionId;
}
/**
* Check if the runtime environment supports VoIP calling.
* @returns True if VoIP is supported.
*/
supportsVoip() {
return !this.disableVoip && this.canSupportVoip;
}
/**
* @returns
*/
getMediaHandler() {
return this.mediaHandler;
}
/**
* Set whether VoIP calls are forced to use only TURN
* candidates. This is the same as the forceTURN option
* when creating the client.
* @param force - True to force use of TURN servers
*/
setForceTURN(force) {
this.forceTURN = force;
}
/**
* Set whether to advertise transfer support to other parties on Matrix calls.
* @param support - True to advertise the 'm.call.transferee' capability
*/
setSupportsCallTransfer(support) {
this.supportsCallTransfer = support;
}
/**
* Returns true if to-device signalling for group calls will be encrypted with Olm.
* If false, it will be sent unencrypted.
* @returns boolean Whether group call signalling will be encrypted
*/
getUseE2eForGroupCall() {
return this.useE2eForGroupCall;
}
/**
* Creates a new call.
* The place*Call methods on the returned call can be used to actually place a call
*
* @param roomId - The room the call is to be placed in.
* @returns the call or null if the browser doesn't support calling.
*/
createCall(roomId) {
return createNewMatrixCall(this, roomId);
}
/**
* Creates a new group call and sends the associated state event
* to alert other members that the room now has a group call.
*
* @param roomId - The room the call is to be placed in.
*/
createGroupCall(roomId, type, isPtt, intent, dataChannelsEnabled, dataChannelOptions) {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this4.getGroupCallForRoom(roomId)) throw new Error("".concat(roomId, " already has an existing group call"));
var room = _this4.getRoom(roomId);
if (!room) throw new Error("Cannot find room ".concat(roomId));
return new GroupCall(_this4, room, type, isPtt, intent, void 0, dataChannelsEnabled || _this4.isVoipWithNoMediaAllowed, dataChannelOptions, _this4.isVoipWithNoMediaAllowed, _this4.useLivekitForGroupCalls, _this4.livekitServiceURL).create();
})();
}
getLivekitServiceURL() {
return this.livekitServiceURL;
}
setLivekitServiceURL(newURL) {
this.livekitServiceURL = newURL;
}
/**
* Wait until an initial state for the given room has been processed by the
* client and the client is aware of any ongoing group calls. Awaiting on
* the promise returned by this method before calling getGroupCallForRoom()
* avoids races where getGroupCallForRoom is called before the state for that
* room has been processed. It does not, however, fix other races, eg. two
* clients both creating a group call at the same time.
* @param roomId - The room ID to wait for
* @returns A promise that resolves once existing group calls in the room
* have been processed.
*/
waitUntilRoomReadyForGroupCalls(roomId) {
return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(roomId);
}
/**
* Get an existing group call for the provided room.
* @returns The group call or null if it doesn't already exist.
*/
getGroupCallForRoom(roomId) {
return this.groupCallEventHandler.groupCalls.get(roomId) || null;
}
/**
* Get the current sync state.
* @returns the sync state, which may be null.
* @see MatrixClient#event:"sync"
*/
getSyncState() {
var _this$syncApi$getSync, _this$syncApi2;
return (_this$syncApi$getSync = (_this$syncApi2 = this.syncApi) === null || _this$syncApi2 === void 0 ? void 0 : _this$syncApi2.getSyncState()) !== null && _this$syncApi$getSync !== void 0 ? _this$syncApi$getSync : null;
}
/**
* Returns the additional data object associated with
* the current sync state, or null if there is no
* such data.
* Sync errors, if available, are put in the 'error' key of
* this object.
*/
getSyncStateData() {
if (!this.syncApi) return null;
return this.syncApi.getSyncStateData();
}
/**
* Whether the initial sync has completed.
* @returns True if at least one sync has happened.
*/
isInitialSyncComplete() {
var state = this.getSyncState();
if (!state) return false;
return state === SyncState.Prepared || state === SyncState.Syncing;
}
/**
* Return whether the client is configured for a guest account.
* @returns True if this is a guest access_token (or no token is supplied).
*/
isGuest() {
return this.isGuestAccount;
}
/**
* Set whether this client is a guest account. <b>This method is experimental
* and may change without warning.</b>
* @param guest - True if this is a guest account.
* @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'
* access token, which means that the SDK can determine this entirely without
* the dev manually flipping this flag.
*/
setGuest(guest) {
this.isGuestAccount = guest;
}
/**
* Return the provided scheduler, if any.
* @returns The scheduler or undefined
*/
getScheduler() {
return this.scheduler;
}
/**
* Retry a backed off syncing request immediately. This should only be used when
* the user <b>explicitly</b> attempts to retry their lost connection.
* Will also retry any outbound to-device messages currently in the queue to be sent
* (retries of regular outgoing events are handled separately, per-event).
* @returns True if this resulted in a request being retried.
*/
retryImmediately() {
var _this$syncApi$retryIm, _this$syncApi3;
this.toDeviceMessageQueue.sendQueue();
return (_this$syncApi$retryIm = (_this$syncApi3 = this.syncApi) === null || _this$syncApi3 === void 0 ? void 0 : _this$syncApi3.retryImmediately()) !== null && _this$syncApi$retryIm !== void 0 ? _this$syncApi$retryIm : false;
}
/**
* Return the global notification EventTimelineSet, if any
*
* @returns the globl notification EventTimelineSet
*/
getNotifTimelineSet() {
return this.notifTimelineSet;
}
/**
* Set the global notification EventTimelineSet
*
*/
setNotifTimelineSet(set) {
this.notifTimelineSet = set;
}
/**
* Gets the cached capabilities of the homeserver, returning cached ones if available.
* If there are no cached capabilities and none can be fetched, throw an exception.
*
* @returns Promise resolving with The capabilities of the homeserver
*/
getCapabilities() {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var caps = _this5.serverCapabilitiesService.getCachedCapabilities();
if (caps) return caps;
return _this5.serverCapabilitiesService.fetchCapabilities();
})();
}
/**
* Gets the cached capabilities of the homeserver. If none have been fetched yet,
* return undefined.
*
* @returns The capabilities of the homeserver
*/
getCachedCapabilities() {
return this.serverCapabilitiesService.getCachedCapabilities();
}
/**
* Fetches the latest capabilities from the homeserver, ignoring any cached
* versions. The newly returned version is cached.
*
* @returns A promise which resolves to the capabilities of the homeserver
*/
fetchCapabilities() {
return this.serverCapabilitiesService.fetchCapabilities();
}
/**
* Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.
*
* **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to
* the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for
* ensuring that only one `MatrixClient` issue is instantiated at a time.
*
* @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.
* @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.
* Unused if useIndexedDB is 'false'.
* @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly
* 32 bytes of data, and must be the same each time the client is initialised for a given device.
* If both this and `storagePassword` are unspecified, the store will be unencrypted.
* @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to
* encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer
* to pass a `storageKey` directly where possible.
*
* @returns a Promise which will resolve when the crypto layer has been
* successfully initialised.
*/
initRustCrypto() {
var _arguments = arguments, _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _args$cryptoDatabaseP3, _this6$legacyPickleKe;
var args = _arguments.length > 0 && _arguments[0] !== void 0 ? _arguments[0] : {};
if (_this6.cryptoBackend) {
_this6.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");
return;
}
var userId = _this6.getUserId();
if (userId === null) throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");
var deviceId = _this6.getDeviceId();
if (deviceId === null) throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");
_this6.logger.debug("Downloading Rust crypto library");
var rustCrypto = yield (yield import("./rust-crypto--bypo4Ng.js")).initRustCrypto({
logger: _this6.logger,
http: _this6.http,
userId,
deviceId,
secretStorage: _this6.secretStorage,
cryptoCallbacks: _this6.cryptoCallbacks,
storePrefix: args.useIndexedDB === false ? null : (_args$cryptoDatabaseP3 = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP3 !== void 0 ? _args$cryptoDatabaseP3 : RUST_SDK_STORE_PREFIX,
storeKey: args.storageKey,
storePassphrase: args.storagePassword,
legacyCryptoStore: _this6.legacyCryptoStore,
legacyPickleKey: (_this6$legacyPickleKe = _this6.legacyPickleKey) !== null && _this6$legacyPickleKe !== void 0 ? _this6$legacyPickleKe : "DEFAULT_KEY",
legacyMigrationProgressListener: (progress, total) => {
_this6.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total);
},
enableEncryptedStateEvents: _this6.enableEncryptedStateEvents
});
rustCrypto.setSupportedVerificationMethods(_this6.verificationMethods);
_this6.cryptoBackend = rustCrypto;
_this6.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto));
_this6.on(ClientEvent.Event, (event) => {
rustCrypto.onLiveEventFromSync(event);
});
_this6.reEmitter.reEmit(rustCrypto, [
CryptoEvent.VerificationRequestReceived,
CryptoEvent.UserTrustStatusChanged,
CryptoEvent.KeyBackupStatus,
CryptoEvent.KeyBackupSessionsRemaining,
CryptoEvent.KeyBackupFailed,
CryptoEvent.KeyBackupDecryptionKeyCached,
CryptoEvent.KeysChanged,
CryptoEvent.DevicesUpdated,
CryptoEvent.WillUpdateDevices,
CryptoEvent.DehydratedDeviceCreated,
CryptoEvent.DehydratedDeviceUploaded,
CryptoEvent.RehydrationStarted,
CryptoEvent.RehydrationProgress,
CryptoEvent.RehydrationCompleted,
CryptoEvent.RehydrationError,
CryptoEvent.DehydrationKeyCached,
CryptoEvent.DehydratedDeviceRotationError
]);
})();
}
/**
* Access the server-side secret storage API for this client.
*/
get secretStorage() {
return this._secretStorage;
}
/**
* Access the crypto API for this client.
*
* If end-to-end encryption has been enabled for this client (via {@link initRustCrypto}),
* returns an object giving access to the crypto API. Otherwise, returns `undefined`.
*/
getCrypto() {
return this.cryptoBackend;
}
/**
* Whether encryption is enabled for a room.
* @param roomId - the room id to query.
* @returns whether encryption is enabled.
*
* @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or
* {@link Room.hasEncryptionStateEvent}.
*/
isRoomEncrypted(roomId) {
var room = this.getRoom(roomId);
if (!room) return false;
return room.hasEncryptionStateEvent();
}
/**
* Check whether the key backup private key is stored in secret storage.
* @returns map of key name to key info the secret is
* encrypted with, or null if it is not present or not encrypted with a
* trusted key
*/
isKeyBackupKeyStored() {
return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"));
}
makeKeyBackupPath(roomId, sessionId, version) {
var path;
if (sessionId !== void 0) path = encodeUri("/room_keys/keys/$roomId/$sessionId", {
$roomId: roomId,
$sessionId: sessionId
});
else if (roomId !== void 0) path = encodeUri("/room_keys/keys/$roomId", { $roomId: roomId });
else path = "/room_keys/keys";
return {
path,
queryData: version === void 0 ? void 0 : { version }
};
}
deleteKeysFromBackup(roomId, sessionId, version) {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var path = _this7.makeKeyBackupPath(roomId, sessionId, version);
yield _this7.http.authedRequest(Method.Delete, path.path, path.queryData, void 0, { prefix: ClientPrefix.V3 });
})();
}
/**
* Get the config for the media repository.
*
* @param useAuthenticatedMedia - If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support
* for authenticated media will *not* be checked - it is the caller's responsibility
* to do so before calling this function.
*
* @returns Promise which resolves with an object containing the config.
*/
getMediaConfig() {
var useAuthenticatedMedia = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
var path = useAuthenticatedMedia ? "/media/config" : "/config";
return this.http.authedRequest(Method.Get, path, void 0, void 0, { prefix: useAuthenticatedMedia ? ClientPrefix.V1 : MediaPrefix.V3 });
}
/**
* Get the room for the given room ID.
* This function will return a valid room for any room for which a Room event
* has been emitted. Note in particular that other events, eg. RoomState.members
* will be emitted for a room before this function will return the given room.
* @param roomId - The room ID
* @returns The Room or null if it doesn't exist or there is no data store.
*/
getRoom(roomId) {
if (!roomId) return null;
return this.store.getRoom(roomId);
}
/**
* Retrieve all known rooms.
* @returns A list of rooms, or an empty list if there is no data store.
*/
getRooms() {
return this.store.getRooms();
}
/**
* Retrieve all rooms that should be displayed to the user
* This is essentially getRooms() with some rooms filtered out, eg. old versions
* of rooms that have been replaced or (in future) other rooms that have been
* marked at the protocol level as not to be displayed to the user.
*
* @param msc3946ProcessDynamicPredecessor - if true, look for an
* m.room.predecessor state event and
* use it if found (MSC3946).
* @returns A list of rooms, or an empty list if there is no data store.
*/
getVisibleRooms() {
var msc3946ProcessDynamicPredecessor = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
var allRooms = this.store.getRooms();
var visibleRooms = new Set(allRooms);
for (var _room2 of visibleRooms) for (var predecessor of this.findPredecessorRooms(_room2, true, msc3946ProcessDynamicPredecessor)) visibleRooms.delete(predecessor);
return Array.from(visibleRooms);
}
/**
* Retrieve a user.
* @param userId - The user ID to retrieve.
* @returns A user or null if there is no data store or the user does
* not exist.
*/
getUser(userId) {
return this.store.getUser(userId);
}
/**
* Retrieve all known users.
* @returns A list of users, or an empty list if there is no data store.
*/
getUsers() {
return this.store.getUsers();
}
/**
* Set account data event for the current user, and wait for the result to be echoed over `/sync`.
*
* Waiting for the remote echo ensures that a subsequent call to {@link getAccountData} will return the updated
* value.
*
* If called before the client is started with {@link startClient}, logs a warning and falls back to
* {@link setAccountDataRaw}.
*
* Retries the request up to 5 times in the case of an {@link ConnectionError}.
*
* @param eventType - The event type
* @param content - the contents object for the event
*/
setAccountData(eventType, content) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this8.clientRunning) {
_this8.logger.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results.");
return yield retryNetworkOperation(5, () => _this8.setAccountDataRaw(eventType, content));
}
var existingData = _this8.store.getAccountData(eventType);
if (existingData && deepCompare(existingData.event.content, content)) return {};
var updatedResolvers = Promise.withResolvers();
function accountDataListener(event) {
if (event.getType() === eventType) updatedResolvers.resolve();
}
_this8.addListener(ClientEvent.AccountData, accountDataListener);
try {
var result = yield retryNetworkOperation(5, () => _this8.setAccountDataRaw(eventType, content));
yield updatedResolvers.promise;
return result;
} finally {
_this8.removeListener(ClientEvent.AccountData, accountDataListener);
}
})();
}
/**
* Set account data event for the current user, without waiting for the remote echo.
*
* @param eventType - The event type
* @param content - the contents object for the event
*/
setAccountDataRaw(eventType, content) {
var path = encodeUri("/user/$userId/account_data/$type", {
$userId: this.credentials.userId,
$type: eventType
});
return this.http.authedRequest(Method.Put, path, void 0, content);
}
/**
* Get account data event of given type for the current user.
* @param eventType - The event type
* @returns The contents of the given account data event
*/
getAccountData(eventType) {
return this.store.getAccountData(eventType);
}
/**
* Get account data event of given type for the current user. This variant
* gets account data directly from the homeserver if the local store is not
* ready, which can be useful very early in startup before the initial sync.
* @param eventType - The event type
* @returns Promise which resolves: The contents of the given account data event.
* @returns Rejects: with an error response.
*/
getAccountDataFromServer(eventType) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this9.isInitialSyncComplete()) {
var _event = _this9.store.getAccountData(eventType);
if (!_event) return null;
return _event.getContent();
}
var path = encodeUri("/user/$userId/account_data/$type", {
$userId: _this9.credentials.userId,
$type: eventType
});
try {
return yield _this9.http.authedRequest(Method.Get, path);
} catch (e) {
var _data;
if (((_data = e.data) === null || _data === void 0 ? void 0 : _data.errcode) === "M_NOT_FOUND") return null;
throw e;
}
})();
}
deleteAccountData(eventType) {
var _this0 = this;
return (0, import_asyncToGenerator.default)(function* () {
var msc3391DeleteAccountDataServerSupport = _this0.canSupport.get(Feature.AccountDataDeletion);
if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {
yield _this0.setAccountData(eventType, {});
return;
}
var path = encodeUri("/user/$userId/account_data/$type", {
$userId: _this0.getSafeUserId(),
$type: eventType
});
var options = msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable ? { prefix: "/_matrix/client/unstable/org.matrix.msc3391" } : void 0;
return yield _this0.http.authedRequest(Method.Delete, path, void 0, void 0, options);
})();
}
/**
* Gets the users that are ignored by this client
* @returns The array of users that are ignored (empty if none)
*/
getIgnoredUsers() {
var event = this.getAccountData(EventType.IgnoredUserList);
if (!(event !== null && event !== void 0 && event.getContent()["ignored_users"])) return [];
return Object.keys(event.getContent()["ignored_users"]);
}
/**
* Sets the users that the current user should ignore.
* @param userIds - the user IDs to ignore
* @returns Promise which resolves: an empty object
* @returns Rejects: with an error response.
*/
setIgnoredUsers(userIds) {
var content = { ignored_users: {} };
userIds.forEach((u) => {
content.ignored_users[u] = {};
});
return this.setAccountData(EventType.IgnoredUserList, content);
}
/**
* Gets whether or not a specific user is being ignored by this client.
* @param userId - the user ID to check
* @returns true if the user is ignored, false otherwise
*/
isUserIgnored(userId) {
return this.getIgnoredUsers().includes(userId);
}
/**
* Join a room. If you have already joined the room, this will no-op.
* @param roomIdOrAlias - The room ID or room alias to join.
* @param opts - Options when joining the room.
* @returns Promise which resolves: Room object.
* @returns Rejects: with an error response.
*/
joinRoom(roomIdOrAlias) {
var _arguments2 = arguments, _this1 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _roomMember$events$me, _roomMember$events$me2;
var opts = _arguments2.length > 1 && _arguments2[1] !== void 0 ? _arguments2[1] : {};
var room = _this1.getRoom(roomIdOrAlias);
var roomMember = room === null || room === void 0 ? void 0 : room.getMember(_this1.getSafeUserId());
var preJoinMembership = roomMember === null || roomMember === void 0 ? void 0 : roomMember.membership;
var inviter = preJoinMembership == KnownMembership.Invite ? (_roomMember$events$me = roomMember === null || roomMember === void 0 || (_roomMember$events$me2 = roomMember.events.member) === null || _roomMember$events$me2 === void 0 ? void 0 : _roomMember$events$me2.getSender()) !== null && _roomMember$events$me !== void 0 ? _roomMember$events$me : null : null;
_this1.logger.debug("joinRoom[".concat(roomIdOrAlias, "]: preJoinMembership=").concat(preJoinMembership, ", inviter=").concat(inviter, ", opts=").concat(JSON.stringify(opts)));
if (preJoinMembership == KnownMembership.Join) return room;
var signPromise = Promise.resolve();
if (opts.inviteSignUrl) {
var _url = new URL(opts.inviteSignUrl);
_url.searchParams.set("mxid", _this1.credentials.userId);
signPromise = _this1.http.requestOtherUrl(Method.Post, _url);
}
var queryParams = {};
if (opts.viaServers) queryParams.via = queryParams.server_name = opts.viaServers.slice(0, 3);
var data = {};
var signedInviteObj = yield signPromise;
if (signedInviteObj) data.third_party_signed = signedInviteObj;
var path = encodeUri("/join/$roomid", { $roomid: roomIdOrAlias });
var roomId = (yield _this1.http.authedRequest(Method.Post, path, queryParams, data)).room_id;
if (opts.acceptSharedHistory && inviter && _this1.cryptoBackend) {
yield _this1.cryptoBackend.markRoomAsPendingKeyBundle(roomId, inviter);
yield _this1.cryptoBackend.maybeAcceptKeyBundle(roomId, inviter);
}
var resolvedRoom = _this1.getRoom(roomId);
if (resolvedRoom !== null && resolvedRoom !== void 0 && resolvedRoom.hasMembershipState(_this1.credentials.userId, KnownMembership.Join)) return resolvedRoom;
return new SyncApi(_this1, _this1.clientOpts, _this1.buildSyncApiOptions()).createRoom(roomId);
})();
}
/**
* Knock a room. If you have already knocked the room, this will no-op.
* @param roomIdOrAlias - The room ID or room alias to knock.
* @param opts - Options when knocking the room.
* @returns Promise which resolves: `{room_id: {string}}`
* @returns Rejects: with an error response.
*/
knockRoom(roomIdOrAlias) {
var opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var room = this.getRoom(roomIdOrAlias);
if (room !== null && room !== void 0 && room.hasMembershipState(this.credentials.userId, KnownMembership.Knock)) return Promise.resolve({ room_id: room.roomId });
var path = encodeUri("/knock/$roomIdOrAlias", { $roomIdOrAlias: roomIdOrAlias });
var queryParams = {};
if (opts.viaServers) {
var viaServers = Array.isArray(opts.viaServers) ? opts.viaServers.slice(0, 3) : [opts.viaServers];
queryParams.server_name = viaServers;
queryParams.via = viaServers;
}
var body = {};
if (opts.reason) body.reason = opts.reason;
return this.http.authedRequest(Method.Post, path, queryParams, body);
}
/**
* Resend an event. Will also retry any to-device messages waiting to be sent.
* @param event - The event to resend.
* @param room - Optional. The room the event is in. Will update the
* timeline entry if provided.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
resendEvent(event, room) {
this.toDeviceMessageQueue.sendQueue();
this.updatePendingEventStatus(room, event, EventStatus.SENDING);
return this.encryptAndSendEvent(room, event);
}
/**
* Cancel a queued or unsent event.
*
* @param event - Event to cancel
* @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state
*/
cancelPendingEvent(event) {
if (![
EventStatus.QUEUED,
EventStatus.NOT_SENT,
EventStatus.ENCRYPTING
].includes(event.status)) throw new Error("cannot cancel an event with status " + event.status);
if (event.status === EventStatus.ENCRYPTING) this.eventsBeingEncrypted.delete(event.getId());
else if (this.scheduler && event.status === EventStatus.QUEUED) this.scheduler.removeEventFromQueue(event);
var room = this.getRoom(event.getRoomId());
this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);
}
/**
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setRoomName(roomId, name) {
return this.sendStateEvent(roomId, EventType.RoomName, { name });
}
/**
* @param roomId - The room to update the topic in.
* @param topic - The plaintext topic. May be empty to remove the topic.
* @param htmlTopic - Optional.
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setRoomTopic(roomId, topic, htmlTopic) {
var content = makeTopicContent(topic, htmlTopic);
return this.sendStateEvent(roomId, EventType.RoomTopic, content);
}
/**
* @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.
* @returns Rejects: with an error response.
*/
getRoomTags(roomId) {
var path = encodeUri("/user/$userId/rooms/$roomId/tags", {
$userId: this.credentials.userId,
$roomId: roomId
});
return this.http.authedRequest(Method.Get, path);
}
/**
* @param tagName - name of room tag to be set
* @param metadata - associated with that tag to be stored
* @returns Promise which resolves: to an empty object
* @returns Rejects: with an error response.
*/
setRoomTag(roomId, tagName) {
var metadata = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
var path = encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
$userId: this.credentials.userId,
$roomId: roomId,
$tag: tagName
});
return this.http.authedRequest(Method.Put, path, void 0, metadata);
}
/**
* @param tagName - name of room tag to be removed
* @returns Promise which resolves: to an empty object
* @returns Rejects: with an error response.
*/
deleteRoomTag(roomId, tagName) {
var path = encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
$userId: this.credentials.userId,
$roomId: roomId,
$tag: tagName
});
return this.http.authedRequest(Method.Delete, path);
}
/**
* @param roomId - the ID of the room this event should be stored within
* @param eventType - event type to be set
* @param content - event content
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setRoomAccountData(roomId, eventType, content) {
var path = encodeUri("/user/$userId/rooms/$roomId/account_data/$type", {
$userId: this.credentials.userId,
$roomId: roomId,
$type: eventType
});
return this.http.authedRequest(Method.Put, path, void 0, content);
}
/**
* Set a power level to one or multiple users.
* Will apply changes atop of current power level event from local state if running & synced, falling back
* to fetching latest from the `/state/` API.
* @param roomId - the room to update power levels in
* @param userId - the ID of the user or users to update power levels of
* @param powerLevel - the numeric power level to update given users to
* @returns Promise which resolves: to an ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setPowerLevel(roomId, userId, powerLevel) {
var _this10 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _content;
var content;
if (_this10.clientRunning && _this10.isInitialSyncComplete()) {
var _this10$getRoom;
content = (_this10$getRoom = _this10.getRoom(roomId)) === null || _this10$getRoom === void 0 || (_this10$getRoom = _this10$getRoom.currentState) === null || _this10$getRoom === void 0 || (_this10$getRoom = _this10$getRoom.getStateEvents(EventType.RoomPowerLevels, "")) === null || _this10$getRoom === void 0 ? void 0 : _this10$getRoom.getContent();
}
if (!content) try {
content = yield _this10.getStateEvent(roomId, EventType.RoomPowerLevels, "");
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_NOT_FOUND") content = {};
else throw e;
}
content = deepCopy(content);
if (!((_content = content) !== null && _content !== void 0 && _content.users)) content.users = {};
for (var user of Array.isArray(userId) ? userId : [userId]) if (powerLevel == null) delete content.users[user];
else content.users[user] = powerLevel;
return _this10.sendStateEvent(roomId, EventType.RoomPowerLevels, content, "");
})();
}
/**
* Create an m.beacon_info event
* @returns
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
unstable_createLiveBeacon(roomId, beaconInfoContent) {
var _this11 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this11.unstable_setLiveBeacon(roomId, beaconInfoContent);
})();
}
/**
* Upsert a live beacon event
* using a specific m.beacon_info.* event variable type
* @param roomId - string
* @returns
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
unstable_setLiveBeacon(roomId, beaconInfoContent) {
var _this12 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this12.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, _this12.getUserId());
})();
}
/**
* Send a Matrix timeline event.
* @param roomId The room to send to.
* @param eventType The event type.
* @param content The event content.
* @param txnId An optional ID to deduplicate requests in case of repeated attempts.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendEvent(roomId, threadIdOrEventType, eventTypeOrContent, contentOrTxnId, txnIdOrVoid) {
var threadId;
var eventType;
var content;
var txnId;
if (!(threadIdOrEventType !== null && threadIdOrEventType !== void 0 && threadIdOrEventType.startsWith(EVENT_ID_PREFIX)) && threadIdOrEventType !== null) {
txnId = contentOrTxnId;
content = eventTypeOrContent;
eventType = threadIdOrEventType;
threadId = null;
} else {
txnId = txnIdOrVoid;
content = contentOrTxnId;
eventType = eventTypeOrContent;
threadId = threadIdOrEventType;
}
this.addThreadRelationIfNeeded(content, threadId, roomId);
return this.sendCompleteEvent({
roomId,
threadId,
eventObject: {
type: eventType,
content
},
txnId
});
}
/**
* If we expect that an event is part of a thread but is missing the relation
* we need to add it manually, as well as the reply fallback
*/
addThreadRelationIfNeeded(content, threadId, roomId) {
var _content$mRelates_to;
if (threadId && !((_content$mRelates_to = content["m.relates_to"]) !== null && _content$mRelates_to !== void 0 && _content$mRelates_to.rel_type)) {
var _content$mRelates_to2, _this$getRoom;
var isReply = !!((_content$mRelates_to2 = content["m.relates_to"]) !== null && _content$mRelates_to2 !== void 0 && _content$mRelates_to2["m.in_reply_to"]);
content["m.relates_to"] = _objectSpread$1(_objectSpread$1({}, content["m.relates_to"]), {}, {
rel_type: THREAD_RELATION_TYPE.name,
event_id: threadId,
is_falling_back: !isReply
});
var thread = (_this$getRoom = this.getRoom(roomId)) === null || _this$getRoom === void 0 ? void 0 : _this$getRoom.getThread(threadId);
if (thread && !isReply) {
var _thread$lastReply$get, _thread$lastReply;
content["m.relates_to"]["m.in_reply_to"] = { event_id: (_thread$lastReply$get = (_thread$lastReply = thread.lastReply((ev) => {
return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;
})) === null || _thread$lastReply === void 0 ? void 0 : _thread$lastReply.getId()) !== null && _thread$lastReply$get !== void 0 ? _thread$lastReply$get : threadId };
}
}
}
/**
* @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.
* @param txnId - Optional.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
/**
* Sends a delayed event (MSC4140).
* @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.
* @param delayOpts - Properties of the delay for this event.
* @param txnId - Optional.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
sendCompleteEvent(_ref3) {
var { roomId, threadId, eventObject, delayOpts, queryDict, txnId } = _ref3;
if (!txnId) txnId = this.makeTxnId();
var localEvent = new MatrixEvent(Object.assign(eventObject, {
event_id: "~" + roomId + ":" + txnId,
user_id: this.credentials.userId,
sender: this.credentials.userId,
room_id: roomId,
origin_server_ts: (/* @__PURE__ */ new Date()).getTime()
}));
var room = this.getRoom(roomId);
var thread = threadId ? room === null || room === void 0 ? void 0 : room.getThread(threadId) : void 0;
if (thread) localEvent.setThread(thread);
if (!delayOpts) {
this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);
room === null || room === void 0 || room.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);
}
var targetId = localEvent.getAssociatedId();
if (targetId !== null && targetId !== void 0 && targetId.startsWith("~")) {
var target = room === null || room === void 0 ? void 0 : room.getPendingEvents().find((e) => e.getId() === targetId);
target === null || target === void 0 || target.once(MatrixEventEvent.LocalEventIdReplaced, () => {
localEvent.updateAssociatedId(target.getId());
});
}
var type = localEvent.getType();
this.logger.debug("sendEvent of type ".concat(type, " in ").concat(roomId, " with txnId ").concat(txnId).concat(delayOpts ? " (delayed event)" : "").concat(queryDict ? " query params: " + JSON.stringify(queryDict) : ""));
localEvent.setTxnId(txnId);
localEvent.setStatus(EventStatus.SENDING);
if (!delayOpts) {
room === null || room === void 0 || room.addPendingEvent(localEvent, txnId);
if (localEvent.status === EventStatus.NOT_SENT) return Promise.reject(/* @__PURE__ */ new Error("Event blocked by other events not yet sent"));
return this.encryptAndSendEvent(room, localEvent, queryDict);
} else return this.encryptAndSendEvent(room, localEvent, delayOpts, queryDict);
}
/**
* encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent
* @returns returns a promise which resolves with the result of the send request
*/
/**
* Simply sends a delayed event without encrypting it.
* TODO: Allow encrypted delayed events, and encrypt them properly
* @param delayOpts - Properties of the delay for this event.
* @returns returns a promise which resolves with the result of the delayed send request
*/
encryptAndSendEvent(room, event, delayOptsOrQuery, queryDict) {
var _this13 = this;
return (0, import_asyncToGenerator.default)(function* () {
var queryOpts = queryDict;
if (delayOptsOrQuery && isSendDelayedEventRequestOpts(delayOptsOrQuery)) return _this13.sendEventHttpRequest(event, delayOptsOrQuery, queryOpts);
else if (!queryOpts) queryOpts = delayOptsOrQuery;
try {
var cancelled;
_this13.eventsBeingEncrypted.add(event.getId());
try {
yield _this13.encryptEventIfNeeded(event, room !== null && room !== void 0 ? room : void 0);
} finally {
cancelled = !_this13.eventsBeingEncrypted.delete(event.getId());
}
if (cancelled) return {};
if (event.status === EventStatus.ENCRYPTING) _this13.updatePendingEventStatus(room, event, EventStatus.SENDING);
var promise = null;
if (_this13.scheduler) {
promise = _this13.scheduler.queueEvent(event);
if (promise && _this13.scheduler.getQueueForEvent(event).length > 1) _this13.updatePendingEventStatus(room, event, EventStatus.QUEUED);
}
if (!promise) {
promise = _this13.sendEventHttpRequest(event, queryOpts);
if (room) promise = promise.then((res) => {
room.updatePendingEvent(event, EventStatus.SENT, res["event_id"]);
return res;
});
}
return yield promise;
} catch (err) {
_this13.logger.error("Error sending event", err);
try {
event.error = err;
_this13.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);
} catch (e) {
_this13.logger.error("Exception in error handler!", e);
}
if (err instanceof MatrixError) err.event = event;
throw err;
}
})();
}
encryptEventIfNeeded(event, room) {
var _this14 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!room) return;
if (!(yield _this14.shouldEncryptEventForRoom(event, room))) return;
if (!_this14.cryptoBackend && _this14.usingExternalCrypto) return;
if (!_this14.cryptoBackend) throw new Error("This room is configured to use encryption, but your client does not support encryption.");
_this14.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);
yield _this14.cryptoBackend.encryptEvent(event, room);
})();
}
/**
* Determine whether a given event should be encrypted when we send it to the given room.
*
* This takes into account event type and room configuration.
*/
shouldEncryptEventForRoom(event, room) {
var _this15 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this15$cryptoBackend;
if (event.isEncrypted()) return false;
if (event.getType() === EventType.Reaction) return false;
if (event.isRedaction()) return false;
if (room.hasEncryptionStateEvent()) return true;
if (yield (_this15$cryptoBackend = _this15.cryptoBackend) === null || _this15$cryptoBackend === void 0 ? void 0 : _this15$cryptoBackend.isEncryptionEnabledInRoom(room.roomId)) return true;
return false;
})();
}
/**
* Returns the eventType that should be used taking encryption into account
* for a given eventType.
* @param roomId - the room for the events `eventType` relates to
* @param eventType - the event type
* @returns the event type taking encryption into account
*/
getEncryptedIfNeededEventType(roomId, eventType) {
var _this$getRoom2;
if (eventType === EventType.Reaction) return eventType;
return (_this$getRoom2 = this.getRoom(roomId)) !== null && _this$getRoom2 !== void 0 && _this$getRoom2.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;
}
updatePendingEventStatus(room, event, newStatus) {
if (room) room.updatePendingEvent(event, newStatus);
else event.setStatus(newStatus);
}
sendEventHttpRequest(event, queryOrDelayOpts, queryDict) {
var txnId = event.getTxnId();
if (!txnId) {
txnId = this.makeTxnId();
event.setTxnId(txnId);
}
var pathParams = {
$roomId: event.getRoomId(),
$eventType: event.getWireType(),
$stateKey: event.getStateKey(),
$txnId: txnId
};
var path;
if (event.isState()) {
var pathTemplate = "/rooms/$roomId/state/$eventType";
if (event.getStateKey() && event.getStateKey().length > 0) pathTemplate = "/rooms/$roomId/state/$eventType/$stateKey";
path = encodeUri(pathTemplate, pathParams);
} else if (event.isRedaction() && event.event.redacts) path = encodeUri("/rooms/$roomId/redact/$redactsEventId/$txnId", _objectSpread$1({ $redactsEventId: event.event.redacts }, pathParams));
else path = encodeUri("/rooms/$roomId/send/$eventType/$txnId", pathParams);
var delayOpts = queryOrDelayOpts && isSendDelayedEventRequestOpts(queryOrDelayOpts) ? queryOrDelayOpts : void 0;
var queryOpts = !delayOpts ? queryOrDelayOpts : queryDict;
var content = event.getWireContent();
if (delayOpts) return this.http.authedRequest(Method.Put, path, _objectSpread$1(_objectSpread$1({}, getUnstableDelayQueryOpts(delayOpts)), queryOpts), content);
else return this.http.authedRequest(Method.Put, path, queryOpts, content).then((res) => {
this.logger.debug("Event sent to ".concat(event.getRoomId(), " with event id ").concat(res.event_id));
return res;
});
}
/**
* @param txnId - transaction id. One will be made up if not supplied.
* @param opts - Redact options
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
* @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.
* Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
redactEvent(roomId, threadId, eventId, txnId, opts) {
var _eventId, _opts, _opts2;
if (!((_eventId = eventId) !== null && _eventId !== void 0 && _eventId.startsWith(EVENT_ID_PREFIX))) {
opts = txnId;
txnId = eventId;
eventId = threadId;
threadId = null;
}
var content = { reason: (_opts = opts) === null || _opts === void 0 ? void 0 : _opts.reason };
if (((_opts2 = opts) === null || _opts2 === void 0 ? void 0 : _opts2.with_rel_types) !== void 0) {
if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) throw new Error("Server does not support relation based redactions " + "roomId ".concat(roomId, " eventId ").concat(eventId, " txnId: ").concat(txnId, " threadId ").concat(threadId));
var withRelTypesPropName = this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable;
content[withRelTypesPropName] = opts.with_rel_types;
}
return this.sendCompleteEvent({
roomId,
threadId,
eventObject: {
type: EventType.RoomRedaction,
content,
redacts: eventId
},
txnId
});
}
/**
* @param txnId - Optional.
* @returns Promise which resolves: to an ISendEventResponse object
* @returns Rejects: with an error response.
*/
sendMessage(roomId, threadId, content, txnId) {
if (typeof threadId !== "string" && threadId !== null) {
txnId = content;
content = threadId;
threadId = null;
}
var eventType = EventType.RoomMessage;
var sendContent = content;
return this.sendEvent(roomId, threadId, eventType, sendContent, txnId);
}
/**
* @param txnId - Optional.
* @returns
* @returns Rejects: with an error response.
*/
sendTextMessage(roomId, threadId, body, txnId) {
var _threadId;
if (!((_threadId = threadId) !== null && _threadId !== void 0 && _threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
txnId = body;
body = threadId;
threadId = null;
}
var content = makeTextMessage(body);
return this.sendMessage(roomId, threadId, content, txnId);
}
/**
* @param txnId - Optional.
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
*/
sendNotice(roomId, threadId, body, txnId) {
var _threadId2;
if (!((_threadId2 = threadId) !== null && _threadId2 !== void 0 && _threadId2.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
txnId = body;
body = threadId;
threadId = null;
}
var content = makeNotice(body);
return this.sendMessage(roomId, threadId, content, txnId);
}
/**
* @param txnId - Optional.
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendEmoteMessage(roomId, threadId, body, txnId) {
var _threadId3;
if (!((_threadId3 = threadId) !== null && _threadId3 !== void 0 && _threadId3.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
txnId = body;
body = threadId;
threadId = null;
}
var content = makeEmoteMessage(body);
return this.sendMessage(roomId, threadId, content, txnId);
}
/**
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendImageMessage(roomId, threadId, url, info) {
var _threadId4;
var text = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : "Image";
if (!((_threadId4 = threadId) !== null && _threadId4 !== void 0 && _threadId4.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
text = info || "Image";
info = url;
url = threadId;
threadId = null;
}
var content = {
msgtype: MsgType.Image,
url,
info,
body: text
};
return this.sendMessage(roomId, threadId, content);
}
/**
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendStickerMessage(roomId, threadId, url, info) {
var _threadId5;
var text = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : "Sticker";
if (!((_threadId5 = threadId) !== null && _threadId5 !== void 0 && _threadId5.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
text = info || "Sticker";
info = url;
url = threadId;
threadId = null;
}
var content = {
url,
info,
body: text
};
return this.sendEvent(roomId, threadId, EventType.Sticker, content);
}
/**
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendHtmlMessage(roomId, threadId, body, htmlBody) {
var _threadId6;
if (!((_threadId6 = threadId) !== null && _threadId6 !== void 0 && _threadId6.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
htmlBody = body;
body = threadId;
threadId = null;
}
var content = makeHtmlMessage(body, htmlBody);
return this.sendMessage(roomId, threadId, content);
}
/**
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendHtmlNotice(roomId, threadId, body, htmlBody) {
var _threadId7;
if (!((_threadId7 = threadId) !== null && _threadId7 !== void 0 && _threadId7.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
htmlBody = body;
body = threadId;
threadId = null;
}
var content = makeHtmlNotice(body, htmlBody);
return this.sendMessage(roomId, threadId, content);
}
/**
* @returns Promise which resolves: to a ISendEventResponse object
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendHtmlEmote(roomId, threadId, body, htmlBody) {
var _threadId8;
if (!((_threadId8 = threadId) !== null && _threadId8 !== void 0 && _threadId8.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {
htmlBody = body;
body = threadId;
threadId = null;
}
var content = makeHtmlEmote(body, htmlBody);
return this.sendMessage(roomId, threadId, content);
}
/**
* Send a delayed timeline event.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
_unstable_sendDelayedEvent(roomId, delayOpts, threadId, eventType, content, txnId) {
var _this16 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this16.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "sendDelayedEvent");
_this16.addThreadRelationIfNeeded(content, threadId, roomId);
return _this16.sendCompleteEvent({
roomId,
threadId,
eventObject: {
type: eventType,
content
},
delayOpts,
txnId
});
})();
}
/**
* Send a delayed sticky timeline event.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) and
* [MSC4354](https://github.com/matrix-org/matrix-spec-proposals/pull/4354) for more details.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
_unstable_sendStickyDelayedEvent(roomId, stickDuration, delayOpts, threadId, eventType, content, txnId) {
var _this17 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this17.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "getDelayedEvents");
if (!(yield _this17.doesServerSupportUnstableFeature("org.matrix.msc4354"))) throw new UnsupportedStickyEventsEndpointError("Server does not support the sticky events", "sendStickyEvent");
_this17.addThreadRelationIfNeeded(content, threadId, roomId);
return _this17.sendCompleteEvent({
roomId,
threadId,
eventObject: {
type: eventType,
content
},
queryDict: { "org.matrix.msc4354.sticky_duration_ms": stickDuration },
delayOpts,
txnId
});
})();
}
/**
* Send a delayed state event.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
_unstable_sendDelayedStateEvent(roomId, delayOpts, eventType, content) {
var _arguments3 = arguments, _this18 = this;
return (0, import_asyncToGenerator.default)(function* () {
var stateKey = _arguments3.length > 4 && _arguments3[4] !== void 0 ? _arguments3[4] : "";
var opts = _arguments3.length > 5 && _arguments3[5] !== void 0 ? _arguments3[5] : {};
if (!(yield _this18.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "sendDelayedStateEvent");
var pathParams = {
$roomId: roomId,
$eventType: eventType,
$stateKey: stateKey
};
var path = encodeUri("/rooms/$roomId/state/$eventType", pathParams);
if (stateKey !== void 0) path = encodeUri(path + "/$stateKey", pathParams);
return _this18.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content, opts);
})();
}
/**
* Send a sticky timeline event.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4354](https://github.com/matrix-org/matrix-spec-proposals/pull/4354) for more details.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
_unstable_sendStickyEvent(roomId, stickDuration, threadId, eventType, content, txnId) {
var _this19 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this19.doesServerSupportUnstableFeature("org.matrix.msc4354"))) throw new UnsupportedStickyEventsEndpointError("Server does not support the sticky events", "sendStickyEvent");
_this19.addThreadRelationIfNeeded(content, threadId, roomId);
return _this19.sendCompleteEvent({
roomId,
threadId,
eventObject: {
type: eventType,
content
},
queryDict: { "org.matrix.msc4354.sticky_duration_ms": stickDuration },
txnId
});
})();
}
/**
* Get information about delayed events owned by the requesting user.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
*/
_unstable_getDelayedEvents(status, delayId, fromToken) {
var _this20 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this20.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "getDelayedEvents");
var queryDict = {
from: fromToken,
status,
delay_id: delayId
};
return yield _this20.http.authedRequest(Method.Get, "/delayed_events", queryDict, void 0, { prefix: "".concat(ClientPrefix.Unstable, "/").concat(UNSTABLE_MSC4140_DELAYED_EVENTS) });
})();
}
/**
* Manage a delayed event associated with the given delay_id.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
*
* @deprecated Instead use one of:
* - {@link _unstable_cancelScheduledDelayedEvent}
* - {@link _unstable_restartScheduledDelayedEvent}
* - {@link _unstable_sendScheduledDelayedEvent}
*/
_unstable_updateDelayedEvent(delayId, action) {
var _arguments4 = arguments, _this21 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments4.length > 2 && _arguments4[2] !== void 0 ? _arguments4[2] : {};
if (!(yield _this21.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "updateDelayedEvent");
return yield _this21.updateScheduledDelayedEventWithActionInBody(delayId, action, requestOptions);
})();
}
/**
* Cancel the scheduled delivery of the delayed event matching the provided delayId.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
*
* @throws A M_NOT_FOUND error if no matching delayed event could be found.
*/
_unstable_cancelScheduledDelayedEvent(delayId) {
var _arguments5 = arguments, _this22 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments5.length > 1 && _arguments5[1] !== void 0 ? _arguments5[1] : {};
return yield _this22.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Cancel, requestOptions);
})();
}
/**
* Restart the scheduled delivery of the delayed event matching the given delayId.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
*
* @throws A M_NOT_FOUND error if no matching delayed event could be found.
*/
_unstable_restartScheduledDelayedEvent(delayId) {
var _arguments6 = arguments, _this23 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments6.length > 1 && _arguments6[1] !== void 0 ? _arguments6[1] : {};
return yield _this23.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Restart, requestOptions);
})();
}
/**
* Immediately send the delayed event matching the given delayId,
* instead of waiting for its scheduled delivery.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.
*
* @throws A M_NOT_FOUND error if no matching delayed event could be found.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
_unstable_sendScheduledDelayedEvent(delayId) {
var _arguments7 = arguments, _this24 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments7.length > 1 && _arguments7[1] !== void 0 ? _arguments7[1] : {};
return yield _this24.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Send, requestOptions);
})();
}
updateScheduledDelayedEvent(delayId, action) {
var _arguments8 = arguments, _this25 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments8.length > 2 && _arguments8[2] !== void 0 ? _arguments8[2] : {};
if (!(yield _this25.doesServerSupportUnstableFeature("org.matrix.msc4140"))) throw new UnsupportedDelayedEventsEndpointError("Server does not support the delayed events API", "".concat(action, "ScheduledDelayedEvent"));
try {
var path = encodeUri("/delayed_events/$delayId/$action", {
$delayId: delayId,
$action: action
});
return yield _this25.http.request(Method.Post, path, void 0, void 0, _objectSpread$1(_objectSpread$1({}, requestOptions), {}, { prefix: "".concat(ClientPrefix.Unstable, "/").concat(UNSTABLE_MSC4140_DELAYED_EVENTS) }));
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_UNRECOGNIZED") return yield _this25.updateScheduledDelayedEventWithActionInBody(delayId, action, requestOptions);
else throw e;
}
})();
}
/**
* @deprecated Present for backwards compatibility with an older version of MSC4140
* which had a single, authenticated endpoint for updating a delayed event, instead
* of one unauthenticated endpoint per update action.
*/
updateScheduledDelayedEventWithActionInBody(delayId, action) {
var _arguments9 = arguments, _this26 = this;
return (0, import_asyncToGenerator.default)(function* () {
var requestOptions = _arguments9.length > 2 && _arguments9[2] !== void 0 ? _arguments9[2] : {};
var path = encodeUri("/delayed_events/$delayId", { $delayId: delayId });
var data = { action };
try {
return yield _this26.http.request(Method.Post, path, void 0, data, _objectSpread$1(_objectSpread$1({}, requestOptions), {}, { prefix: "".concat(ClientPrefix.Unstable, "/").concat(UNSTABLE_MSC4140_DELAYED_EVENTS) }));
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_MISSING_TOKEN") return yield _this26.http.authedRequest(Method.Post, path, void 0, data, _objectSpread$1(_objectSpread$1({}, requestOptions), {}, { prefix: "".concat(ClientPrefix.Unstable, "/").concat(UNSTABLE_MSC4140_DELAYED_EVENTS) }));
else throw e;
}
})();
}
/**
* Send a receipt.
* @param event - The event being acknowledged
* @param receiptType - The kind of receipt e.g. "m.read". Other than
* ReceiptType.Read are experimental!
* @param body - Additional content to send alongside the receipt.
* @param unthreaded - An unthreaded receipt will clear room+thread notifications
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
sendReceipt(event, receiptType, body) {
var _arguments0 = arguments, _this27 = this;
return (0, import_asyncToGenerator.default)(function* () {
var unthreaded = _arguments0.length > 3 && _arguments0[3] !== void 0 ? _arguments0[3] : false;
if (_this27.isGuest()) return Promise.resolve({});
var path = encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
$roomId: event.getRoomId(),
$receiptType: receiptType,
$eventId: event.getId()
});
var fullBody = !unthreaded && _this27.supportsThreads() ? _objectSpread$1(_objectSpread$1({}, body), {}, { thread_id: threadIdForReceipt(event) }) : body;
var promise = _this27.http.authedRequest(Method.Post, path, void 0, fullBody || {});
var room = _this27.getRoom(event.getRoomId());
if (room && _this27.credentials.userId) room.addLocalEchoReceipt(_this27.credentials.userId, event, receiptType, unthreaded);
return promise;
})();
}
/**
* Send a read receipt.
* @param event - The event that has been read.
* @param receiptType - other than ReceiptType.Read are experimental! Optional.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
sendReadReceipt(event) {
var _arguments1 = arguments, _this28 = this;
return (0, import_asyncToGenerator.default)(function* () {
var receiptType = _arguments1.length > 1 && _arguments1[1] !== void 0 ? _arguments1[1] : ReceiptType.Read;
var unthreaded = _arguments1.length > 2 && _arguments1[2] !== void 0 ? _arguments1[2] : false;
if (!event) return;
var eventId = event.getId();
var room = _this28.getRoom(event.getRoomId());
if (room !== null && room !== void 0 && room.hasPendingEvent(eventId)) throw new Error("Cannot set read receipt to a pending event (".concat(eventId, ")"));
return _this28.sendReceipt(event, receiptType, {}, unthreaded);
})();
}
/**
* Set a marker to indicate the point in a room before which the user has read every
* event. This can be retrieved from room account data (the event type is `m.fully_read`)
* and displayed as a horizontal line in the timeline that is visually distinct to the
* position of the user's own read receipt.
* @param roomId - ID of the room that has been read
* @param rmEventId - ID of the event that has been read
* @param rrEvent - the event tracked by the read receipt. This is here for
* convenience because the RR and the RM are commonly updated at the same time as each
* other. The local echo of this receipt will be done if set. Optional.
* @param rpEvent - the m.read.private read receipt event for when we don't
* want other users to see the read receipts. This is experimental. Optional.
* @returns Promise which resolves: the empty object, `{}`.
*/
setRoomReadMarkers(roomId, rmEventId, rrEvent, rpEvent) {
var _this29 = this;
return (0, import_asyncToGenerator.default)(function* () {
var room = _this29.getRoom(roomId);
if (room !== null && room !== void 0 && room.hasPendingEvent(rmEventId)) throw new Error("Cannot set read marker to a pending event (".concat(rmEventId, ")"));
var rrEventId;
if (rrEvent) {
rrEventId = rrEvent.getId();
if (room !== null && room !== void 0 && room.hasPendingEvent(rrEventId)) throw new Error("Cannot set read receipt to a pending event (".concat(rrEventId, ")"));
room === null || room === void 0 || room.addLocalEchoReceipt(_this29.credentials.userId, rrEvent, ReceiptType.Read);
}
var rpEventId;
if (rpEvent) {
rpEventId = rpEvent.getId();
if (room !== null && room !== void 0 && room.hasPendingEvent(rpEventId)) throw new Error("Cannot set read receipt to a pending event (".concat(rpEventId, ")"));
room === null || room === void 0 || room.addLocalEchoReceipt(_this29.credentials.userId, rpEvent, ReceiptType.ReadPrivate);
}
return yield _this29.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);
})();
}
/**
*
* @param roomId
* @param notificationEventId
* @returns
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
sendRtcDecline(roomId, notificationEventId) {
return this.sendEvent(roomId, EventType.RTCDecline, { "m.relates_to": {
event_id: notificationEventId,
rel_type: RelationType.Reference
} });
}
/**
* Get a preview of the given URL as of (roughly) the given point in time,
* described as an object with OpenGraph keys and associated values.
* Attributes may be synthesized where actual OG metadata is lacking.
* Caches results to prevent hammering the server.
* @param url - The URL to get preview data for
* @param ts - The preferred point in time that the preview should
* describe (ms since epoch). The preview returned will either be the most
* recent one preceding this timestamp if available, or failing that the next
* most recent available preview.
* @returns Promise which resolves: Object of OG metadata.
* @returns Rejects: with an error response.
* May return synthesized attributes if the URL lacked OG meta.
*/
getUrlPreview(url, ts) {
var _this30 = this;
return (0, import_asyncToGenerator.default)(function* () {
ts = Math.floor(ts / 6e4) * 6e4;
var parsed = new URL(url);
parsed.hash = "";
url = parsed.toString();
var key = ts + "_" + url;
if (key in _this30.urlPreviewCache) return _this30.urlPreviewCache[key];
var supportsNewEndpoint = yield _this30.isVersionSupported("v1.11");
var resp = _this30.http.authedRequest(Method.Get, supportsNewEndpoint ? "/media/preview_url" : "/preview_url", {
url,
ts: ts.toString()
}, void 0, {
prefix: supportsNewEndpoint ? ClientPrefix.V1 : MediaPrefix.V3,
priority: "low"
});
_this30.urlPreviewCache[key] = resp;
return resp;
})();
}
/**
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
sendTyping(roomId, isTyping, timeoutMs) {
if (this.isGuest()) return Promise.resolve({});
var path = encodeUri("/rooms/$roomId/typing/$userId", {
$roomId: roomId,
$userId: this.getUserId()
});
var data = { typing: isTyping };
if (isTyping) data.timeout = timeoutMs ? timeoutMs : 2e4;
return this.http.authedRequest(Method.Put, path, void 0, data);
}
/**
* Determines the history of room upgrades for a given room, as far as the
* client can see. Returns an array of Rooms where the first entry is the
* oldest and the last entry is the newest (likely current) room. If the
* provided room is not found, this returns an empty list. This works in
* both directions, looking for older and newer rooms of the given room.
* @param roomId - The room ID to search from
* @param verifyLinks - If true, the function will only return rooms
* which can be proven to be linked. For example, rooms which have a create
* event pointing to an old room which the client is not aware of or doesn't
* have a matching tombstone would not be returned.
* @param msc3946ProcessDynamicPredecessor - if true, look for
* m.room.predecessor state events as well as create events, and prefer
* predecessor events where they exist (MSC3946).
* @returns An array of rooms representing the upgrade
* history.
*/
getRoomUpgradeHistory(roomId) {
var verifyLinks = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var msc3946ProcessDynamicPredecessor = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
var currentRoom = this.getRoom(roomId);
if (!currentRoom) return [];
var before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);
var after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);
return [
...before,
currentRoom,
...after
];
}
findPredecessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) {
var _room$findPredecessor;
var ret = [];
var seenRoomIDs = new Set([room.roomId]);
var predecessorRoomId = (_room$findPredecessor = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _room$findPredecessor === void 0 ? void 0 : _room$findPredecessor.roomId;
while (predecessorRoomId !== null) {
var _room$findPredecessor2;
if (predecessorRoomId) {
if (seenRoomIDs.has(predecessorRoomId)) break;
seenRoomIDs.add(predecessorRoomId);
}
var predecessorRoom = this.getRoom(predecessorRoomId);
if (predecessorRoom === null) break;
if (verifyLinks) {
var tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, "");
if (!tombstone || tombstone.getContent()["replacement_room"] !== room.roomId) break;
}
ret.splice(0, 0, predecessorRoom);
room = predecessorRoom;
predecessorRoomId = (_room$findPredecessor2 = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _room$findPredecessor2 === void 0 ? void 0 : _room$findPredecessor2.roomId;
}
return ret;
}
findSuccessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) {
var ret = [];
var tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, "");
while (tombstoneEvent) {
var successorRoom = this.getRoom(tombstoneEvent.getContent()["replacement_room"]);
if (!successorRoom) break;
if (successorRoom.roomId === room.roomId) break;
if (verifyLinks) {
var _successorRoom$findPr;
var predecessorRoomId = (_successorRoom$findPr = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _successorRoom$findPr === void 0 ? void 0 : _successorRoom$findPr.roomId;
if (!predecessorRoomId || predecessorRoomId !== room.roomId) break;
}
ret.push(successorRoom);
if (new Set(ret.map((ref) => ref.roomId)).size < ret.length) return ret.slice(0, ret.length - 1);
room = successorRoom;
tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, "");
}
return ret;
}
/**
* Send an invite to the given user to join the given room.
*
* @param roomId - The ID of the room to which the user should be invited.
* @param userId - The ID of the user that should be invited.
* @param opts - Optional reason object. For backwards compatibility, a string is also accepted, and will be interpreted as a reason.
*
* @returns An empty object.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
invite(roomId, userId) {
var _arguments10 = arguments, _this31 = this;
return (0, import_asyncToGenerator.default)(function* () {
var opts = _arguments10.length > 2 && _arguments10[2] !== void 0 ? _arguments10[2] : {};
if (typeof opts != "object") opts = { reason: opts };
if (opts.shareEncryptedHistory) {
var _this31$getRoom$getHi, _this31$getRoom;
var historyVisibility = (_this31$getRoom$getHi = (_this31$getRoom = _this31.getRoom(roomId)) === null || _this31$getRoom === void 0 ? void 0 : _this31$getRoom.getHistoryVisibility()) !== null && _this31$getRoom$getHi !== void 0 ? _this31$getRoom$getHi : HistoryVisibility.Shared;
if ([HistoryVisibility.Invited, HistoryVisibility.Joined].includes(historyVisibility)) _this31.logger.debug("Not sharing message history as the room history visibility is currently unshared");
else {
var _this31$cryptoBackend;
yield (_this31$cryptoBackend = _this31.cryptoBackend) === null || _this31$cryptoBackend === void 0 ? void 0 : _this31$cryptoBackend.shareRoomHistoryWithUser(roomId, userId);
}
}
return yield _this31.membershipChange(roomId, userId, KnownMembership.Invite, opts.reason);
})();
}
/**
* Invite a user to a room based on their email address.
* @param roomId - The room to invite the user to.
* @param email - The email address to invite.
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
inviteByEmail(roomId, email) {
return this.inviteByThreePid(roomId, "email", email);
}
/**
* Invite a user to a room based on a third-party identifier.
* @param roomId - The room to invite the user to.
* @param medium - The medium to invite the user e.g. "email".
* @param address - The address for the specified medium.
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
inviteByThreePid(roomId, medium, address) {
var _this32 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this32$identityServe;
var path = encodeUri("/rooms/$roomId/invite", { $roomId: roomId });
var identityServerUrl = _this32.getIdentityServerUrl(true);
if (!identityServerUrl) return Promise.reject(new MatrixError({
error: "No supplied identity server URL",
errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM"
}));
var params = {
id_server: identityServerUrl,
medium,
address
};
if ((_this32$identityServe = _this32.identityServer) !== null && _this32$identityServe !== void 0 && _this32$identityServe.getAccessToken) {
var identityAccessToken = yield _this32.identityServer.getAccessToken();
if (identityAccessToken) params["id_access_token"] = identityAccessToken;
}
return _this32.http.authedRequest(Method.Post, path, void 0, params);
})();
}
/**
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
*/
leave(roomId) {
return this.membershipChange(roomId, void 0, KnownMembership.Leave);
}
/**
* Leaves all rooms in the chain of room upgrades based on the given room. By
* default, this will leave all the previous and upgraded rooms, including the
* given room. To only leave the given room and any previous rooms, keeping the
* upgraded (modern) rooms untouched supply `false` to `includeFuture`.
* @param roomId - The room ID to start leaving at
* @param includeFuture - If true, the whole chain (past and future) of
* upgraded rooms will be left.
* @returns Promise which resolves when completed with an object keyed
* by room ID and value of the error encountered when leaving or null.
*/
leaveRoomChain(roomId) {
var includeFuture = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
var upgradeHistory = this.getRoomUpgradeHistory(roomId, true);
var eligibleToLeave = upgradeHistory;
if (!includeFuture) {
eligibleToLeave = [];
for (var _room3 of upgradeHistory) {
eligibleToLeave.push(_room3);
if (_room3.roomId === roomId) break;
}
}
var populationResults = {};
var promises = [];
var doLeave = (roomId) => {
return this.leave(roomId).then(() => {
delete populationResults[roomId];
}).catch((err) => {
populationResults[roomId] = err;
});
};
for (var _room4 of eligibleToLeave) promises.push(doLeave(_room4.roomId));
return Promise.all(promises).then(() => populationResults);
}
/**
* @param reason - Optional.
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
ban(roomId, userId, reason) {
return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);
}
/**
* @param deleteRoom - True to delete the room from the store on success.
* Default: true.
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
*/
forget(roomId) {
var _arguments11 = arguments, _this33 = this;
return (0, import_asyncToGenerator.default)(function* () {
var deleteRoom = _arguments11.length > 1 && _arguments11[1] !== void 0 ? _arguments11[1] : true;
var path = encodeUri("/rooms/$room_id/forget", { $room_id: roomId });
var response = yield _this33.http.authedRequest(Method.Post, path);
if (deleteRoom) {
_this33.store.removeRoom(roomId);
_this33.emit(ClientEvent.DeleteRoom, roomId);
}
return response;
})();
}
/**
* @returns Promise which resolves: Object (currently empty)
* @returns Rejects: with an error response.
*/
unban(roomId, userId) {
var path = encodeUri("/rooms/$roomId/unban", { $roomId: roomId });
var data = { user_id: userId };
return this.http.authedRequest(Method.Post, path, void 0, data);
}
/**
* @param reason - Optional.
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
*/
kick(roomId, userId, reason) {
var path = encodeUri("/rooms/$roomId/kick", { $roomId: roomId });
var data = {
user_id: userId,
reason
};
return this.http.authedRequest(Method.Post, path, void 0, data);
}
membershipChange(roomId, userId, membership, reason) {
var path = encodeUri("/rooms/$room_id/$membership", {
$room_id: roomId,
$membership: membership
});
return this.http.authedRequest(Method.Post, path, void 0, {
user_id: userId,
reason
});
}
/**
* Obtain a dict of actions which should be performed for this event according
* to the push rules for this user. Caches the dict on the event.
* @param event - The event to get push actions for.
* @param forceRecalculate - forces to recalculate actions for an event
* Useful when an event just got decrypted
* @returns A dict of actions to perform.
*/
getPushActionsForEvent(event) {
var forceRecalculate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
if (!event.getPushActions() || forceRecalculate) {
var { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);
event.setPushDetails(actions, rule);
}
return event.getPushActions();
}
/**
* Obtain a dict of actions which should be performed for this event according
* to the push rules for this user. Caches the dict on the event.
* @param event - The event to get push actions for.
* @param forceRecalculate - forces to recalculate actions for an event
* Useful when an event just got decrypted
* @returns A dict of actions to perform.
*/
getPushDetailsForEvent(event) {
var forceRecalculate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
if (!event.getPushDetails() || forceRecalculate) {
var { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);
event.setPushDetails(actions, rule);
}
return event.getPushDetails();
}
/**
* @param info - The kind of info to set (e.g. 'avatar_url')
* @param data - The JSON object to set.
* @returns
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setProfileInfo(info, data) {
var path = encodeUri("/profile/$userId/$info", {
$userId: this.credentials.userId,
$info: info
});
return this.http.authedRequest(Method.Put, path, void 0, data);
}
/**
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setDisplayName(name) {
var _this34 = this;
return (0, import_asyncToGenerator.default)(function* () {
var prom = yield _this34.setProfileInfo("displayname", { displayname: name });
var user = _this34.getUser(_this34.getUserId());
if (user) {
user.displayName = name;
user.emit(UserEvent.DisplayName, user.events.presence, user);
}
return prom;
})();
}
/**
* @returns Promise which resolves: `{}` an empty object.
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
setAvatarUrl(url) {
var _this35 = this;
return (0, import_asyncToGenerator.default)(function* () {
var prom = yield _this35.setProfileInfo("avatar_url", { avatar_url: url });
var user = _this35.getUser(_this35.getUserId());
if (user) {
user.avatarUrl = url;
user.emit(UserEvent.AvatarUrl, user.events.presence, user);
}
return prom;
})();
}
/**
* Turn an MXC URL into an HTTP one. <strong>This method is experimental and
* may change.</strong>
* @param mxcUrl - The MXC URL
* @param width - The desired width of the thumbnail.
* @param height - The desired height of the thumbnail.
* @param resizeMethod - The thumbnail resize method to use, either
* "crop" or "scale".
* @param allowDirectLinks - If true, return any non-mxc URLs
* directly. Fetching such URLs will leak information about the user to
* anyone they share a room with. If false, will return null for such URLs.
* @param allowRedirects - If true, the caller supports the URL being 307 or
* 308 redirected to another resource upon request. If false, redirects
* are not expected. Implied `true` when `useAuthentication` is `true`.
* @param useAuthentication - If true, the caller supports authenticated
* media and wants an authentication-required URL. Note that server support
* for authenticated media will *not* be checked - it is the caller's responsibility
* to do so before calling this function. Note also that `useAuthentication`
* implies `allowRedirects`. Defaults to false (unauthenticated endpoints).
* @returns the avatar URL or null.
*/
mxcUrlToHttp(mxcUrl, width, height, resizeMethod, allowDirectLinks, allowRedirects, useAuthentication) {
return getHttpUriForMxc(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks, allowRedirects, useAuthentication);
}
/**
* Specify the set_presence value to be used for subsequent calls to the Sync API.
* This has an advantage over calls to the PUT /presence API in that it
* doesn't clobber status_msg set by other devices.
* @param presence - the presence to specify to set_presence of sync calls
*/
setSyncPresence(presence) {
var _this36 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this36$syncApi;
(_this36$syncApi = _this36.syncApi) === null || _this36$syncApi === void 0 || _this36$syncApi.setPresence(presence);
})();
}
/**
* @param opts - Options to apply
* @returns Promise which resolves
* @returns Rejects: with an error response.
* @throws If 'presence' isn't a valid presence enum value.
*/
setPresence(opts) {
var _this37 = this;
return (0, import_asyncToGenerator.default)(function* () {
var path = encodeUri("/presence/$userId/status", { $userId: _this37.credentials.userId });
if ([
"offline",
"online",
"unavailable"
].indexOf(opts.presence) === -1) throw new Error("Bad presence value: " + opts.presence);
yield _this37.http.authedRequest(Method.Put, path, void 0, opts);
})();
}
/**
* @param userId - The user to get presence for
* @returns Promise which resolves: The presence state for this user.
* @returns Rejects: with an error response.
*/
getPresence(userId) {
var path = encodeUri("/presence/$userId/status", { $userId: userId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Retrieve older messages from the given room and put them in the timeline.
*
* If this is called multiple times whilst a request is ongoing, the <i>same</i>
* Promise will be returned. If there was a problem requesting scrollback, there
* will be a small delay before another request can be made (to prevent tight-looping
* when there is no connection).
*
* @param room - The room to get older messages in.
* @param limit - Optional. The maximum number of previous events to
* pull in. Default: 30.
* @returns Promise which resolves: Room. If you are at the beginning
* of the timeline, `Room.oldState.paginationToken` will be
* `null`.
* @returns Rejects: with an error response.
*/
scrollback(room) {
var limit = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 30;
var timeToWaitMs = 0;
var info = this.ongoingScrollbacks[room.roomId] || {};
if (info.promise) return info.promise;
else if (info.errorTs) {
var timeWaitedMs = Date.now() - info.errorTs;
timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);
}
if (room.oldState.paginationToken === null) return Promise.resolve(room);
var numAdded = this.store.scrollback(room, limit).length;
if (numAdded === limit) return Promise.resolve(room);
limit = limit - numAdded;
var promise = new Promise((resolve, reject) => {
sleep(timeToWaitMs).then(() => {
return this.createMessagesRequest(room.roomId, room.oldState.paginationToken, limit, Direction.Backward);
}).then((res) => {
var _res$end, _res$end2;
var matrixEvents = res.chunk.map(this.getEventMapper());
if (res.state) {
var stateEvents = res.state.map(this.getEventMapper());
room.currentState.setUnknownStateEvents(stateEvents);
}
var [timelineEvents, threadedEvents, unknownRelations] = room.partitionThreadedEvents(matrixEvents);
this.processAggregatedTimelineEvents(room, timelineEvents);
room.addEventsToTimeline(timelineEvents, true, true, room.getLiveTimeline());
this.processThreadEvents(room, threadedEvents, true);
unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));
room.oldState.paginationToken = (_res$end = res.end) !== null && _res$end !== void 0 ? _res$end : null;
if (res.chunk.length === 0) room.oldState.paginationToken = null;
this.store.storeEvents(room, matrixEvents, (_res$end2 = res.end) !== null && _res$end2 !== void 0 ? _res$end2 : null, true);
delete this.ongoingScrollbacks[room.roomId];
resolve(room);
}).catch((err) => {
this.ongoingScrollbacks[room.roomId] = { errorTs: Date.now() };
reject(err);
});
});
info = { promise };
this.ongoingScrollbacks[room.roomId] = info;
return promise;
}
getEventMapper(options) {
return eventMapperFor(this, options || {});
}
/**
* Calls the `/context` API for the given room ID & event ID.
* Returns the response, with `event` asserted and all optional arrays defaulted to an empty array.
* @param roomId - the room ID to request a context for
* @param eventId - the event ID to request a context for
* @throws if `event` in the response is missing
* @private
*/
getEventContext(roomId, eventId) {
var _this38 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this38$clientOpts;
var path = encodeUri("/rooms/$roomId/context/$eventId", {
$roomId: roomId,
$eventId: eventId
});
var params = { limit: "0" };
if ((_this38$clientOpts = _this38.clientOpts) !== null && _this38$clientOpts !== void 0 && _this38$clientOpts.lazyLoadMembers) params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);
var res = yield _this38.http.authedRequest(Method.Get, path, params);
if (res.event) {
var _res$events_after, _res$events_before, _res$state;
return {
start: res.start,
end: res.end,
event: res.event,
events_after: (_res$events_after = res.events_after) !== null && _res$events_after !== void 0 ? _res$events_after : [],
events_before: (_res$events_before = res.events_before) !== null && _res$events_before !== void 0 ? _res$events_before : [],
state: (_res$state = res.state) !== null && _res$state !== void 0 ? _res$state : []
};
}
throw new Error("'event' not in '/context' result - homeserver too old?");
})();
}
/**
* Get an EventTimeline for the given event
*
* <p>If the EventTimelineSet object already has the given event in its store, the
* corresponding timeline will be returned. Otherwise, a /context request is
* made, and used to construct an EventTimeline.
* If the event does not belong to this EventTimelineSet then undefined will be returned.
*
* @param timelineSet - The timelineSet to look for the event in, must be bound to a room
* @param eventId - The ID of the event to look for
*
* @returns Promise which resolves:
* {@link EventTimeline} including the given event
*/
getEventTimeline(timelineSet, eventId) {
var _this39 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _ref4, _timelineSet$getTimel, _timelineSet$room$fin;
if (!_this39.timelineSupport) throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");
if (!(timelineSet !== null && timelineSet !== void 0 && timelineSet.room)) throw new Error("getEventTimeline only supports room timelines");
if (timelineSet.getTimelineForEvent(eventId)) return timelineSet.getTimelineForEvent(eventId);
if (timelineSet.thread && _this39.supportsThreads()) {
var _yield$_this39$getThr;
return (_yield$_this39$getThr = yield _this39.getThreadTimeline(timelineSet, eventId)) !== null && _yield$_this39$getThr !== void 0 ? _yield$_this39$getThr : null;
}
var res = yield _this39.getEventContext(timelineSet.room.roomId, eventId);
if (timelineSet.getTimelineForEvent(eventId)) return timelineSet.getTimelineForEvent(eventId);
var mapper = _this39.getEventMapper();
var event = mapper(res.event);
if (event.isRelation(THREAD_RELATION_TYPE.name)) {
_this39.logger.warn("Tried loading a regular timeline at the position of a thread event");
return null;
}
var events = [
...res.events_after.reverse().map(mapper),
event,
...res.events_before.map(mapper)
];
var timeline = timelineSet.getTimelineForEvent(events[0].getId());
if (timeline) timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));
else {
var _res$end3;
timeline = timelineSet.addTimeline();
timeline.initialiseState(res.state.map(mapper));
timeline.getState(EventTimeline.FORWARDS).paginationToken = (_res$end3 = res.end) !== null && _res$end3 !== void 0 ? _res$end3 : null;
}
var [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);
timelineSet.addEventsToTimeline(timelineEvents, true, false, timeline, res.start);
_this39.processThreadEvents(timelineSet.room, threadedEvents, true);
_this39.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);
unknownRelations.forEach((event) => timelineSet.relations.aggregateChildEvent(event));
return (_ref4 = (_timelineSet$getTimel = timelineSet.getTimelineForEvent(eventId)) !== null && _timelineSet$getTimel !== void 0 ? _timelineSet$getTimel : (_timelineSet$room$fin = timelineSet.room.findThreadForEvent(event)) === null || _timelineSet$room$fin === void 0 ? void 0 : _timelineSet$room$fin.liveTimeline) !== null && _ref4 !== void 0 ? _ref4 : timeline;
})();
}
getThreadTimeline(timelineSet, eventId) {
var _this40 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this40.supportsThreads()) throw new Error("could not get thread timeline: no client support");
if (!timelineSet.room) throw new Error("could not get thread timeline: not a room timeline");
if (!timelineSet.thread) throw new Error("could not get thread timeline: not a thread timeline");
var res = yield _this40.getEventContext(timelineSet.room.roomId, eventId);
var mapper = _this40.getEventMapper();
var event = mapper(res.event);
if (!timelineSet.canContain(event)) return;
var recurse = _this40.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;
if (Thread.hasServerSideSupport) if (Thread.hasServerSideFwdPaginationSupport) {
var _resOlder$next_batch, _resNewer$next_batch, _timelineSet$getTimel2;
if (!timelineSet.thread) throw new Error("could not get thread timeline: not a thread timeline");
var thread = timelineSet.thread;
var resOlder = yield _this40.fetchRelations(timelineSet.room.roomId, thread.id, null, null, {
dir: Direction.Backward,
from: res.start,
recurse: recurse || void 0
});
var resNewer = yield _this40.fetchRelations(timelineSet.room.roomId, thread.id, null, null, {
dir: Direction.Forward,
from: res.end,
recurse: recurse || void 0
});
var events = [
...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper),
event,
...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper)
];
for (var _event2 of events) {
var _timelineSet$thread;
yield (_timelineSet$thread = timelineSet.thread) === null || _timelineSet$thread === void 0 ? void 0 : _timelineSet$thread.processEvent(_event2);
}
var timeline = timelineSet.getTimelineForEvent(event.getId());
if (timeline) timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));
else {
timeline = timelineSet.addTimeline();
timeline.initialiseState(res.state.map(mapper));
}
timelineSet.addEventsToTimeline(events, true, false, timeline, resNewer.next_batch);
if (!resOlder.next_batch) {
var originalEvent = yield _this40.fetchRoomEvent(timelineSet.room.roomId, thread.id);
timelineSet.addEventsToTimeline([mapper(originalEvent)], true, false, timeline, null);
}
timeline.setPaginationToken((_resOlder$next_batch = resOlder.next_batch) !== null && _resOlder$next_batch !== void 0 ? _resOlder$next_batch : null, Direction.Backward);
timeline.setPaginationToken((_resNewer$next_batch = resNewer.next_batch) !== null && _resNewer$next_batch !== void 0 ? _resNewer$next_batch : null, Direction.Forward);
_this40.processAggregatedTimelineEvents(timelineSet.room, events);
return (_timelineSet$getTimel2 = timelineSet.getTimelineForEvent(eventId)) !== null && _timelineSet$getTimel2 !== void 0 ? _timelineSet$getTimel2 : timeline;
} else {
var _resOlder$next_batch2;
var _thread = timelineSet.thread;
var _resOlder = yield _this40.fetchRelations(timelineSet.room.roomId, _thread.id, THREAD_RELATION_TYPE.name, null, {
dir: Direction.Backward,
from: res.start,
recurse: recurse || void 0
});
var eventsNewer = [];
var nextBatch = res.end;
while (nextBatch) {
var _resNewer = yield _this40.fetchRelations(timelineSet.room.roomId, _thread.id, THREAD_RELATION_TYPE.name, null, {
dir: Direction.Forward,
from: nextBatch,
recurse: recurse || void 0
});
nextBatch = _resNewer.next_batch;
eventsNewer.push(..._resNewer.chunk);
}
var _events = [
...eventsNewer.reverse().map(mapper),
event,
..._resOlder.chunk.map(mapper)
];
for (var _event3 of _events) {
var _timelineSet$thread2;
yield (_timelineSet$thread2 = timelineSet.thread) === null || _timelineSet$thread2 === void 0 ? void 0 : _timelineSet$thread2.processEvent(_event3);
}
var _timeline = timelineSet.getLiveTimeline();
_timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));
timelineSet.addEventsToTimeline(_events, true, false, _timeline, null);
if (!_resOlder.next_batch) {
var _originalEvent = yield _this40.fetchRoomEvent(timelineSet.room.roomId, _thread.id);
timelineSet.addEventsToTimeline([mapper(_originalEvent)], true, false, _timeline, null);
}
_timeline.setPaginationToken((_resOlder$next_batch2 = _resOlder.next_batch) !== null && _resOlder$next_batch2 !== void 0 ? _resOlder$next_batch2 : null, Direction.Backward);
_timeline.setPaginationToken(null, Direction.Forward);
_this40.processAggregatedTimelineEvents(timelineSet.room, _events);
return _timeline;
}
})();
}
/**
* Get an EventTimeline for the latest events in the room. This will just
* call `/messages` to get the latest message in the room, then use
* `client.getEventTimeline(...)` to construct a new timeline from it.
*
* @param timelineSet - The timelineSet to find or add the timeline to
*
* @returns Promise which resolves:
* {@link EventTimeline} timeline with the latest events in the room
*/
getLatestTimeline(timelineSet) {
var _this41 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this41.timelineSupport) throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");
if (!timelineSet.room) throw new Error("getLatestTimeline only supports room timelines");
var event;
if (timelineSet.threadListType !== null) {
var _res$chunk;
event = (_res$chunk = (yield _this41.createThreadListMessagesRequest(timelineSet.room.roomId, null, 1, Direction.Backward, timelineSet.threadListType, timelineSet.getFilter())).chunk) === null || _res$chunk === void 0 ? void 0 : _res$chunk[0];
} else if (timelineSet.thread && Thread.hasServerSideSupport) {
var _res$chunk2;
var recurse = _this41.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;
event = (_res$chunk2 = (yield _this41.fetchRelations(timelineSet.room.roomId, timelineSet.thread.id, THREAD_RELATION_TYPE.name, null, {
dir: Direction.Backward,
limit: 1,
recurse: recurse || void 0
})).chunk) === null || _res$chunk2 === void 0 ? void 0 : _res$chunk2[0];
} else {
var _this41$clientOpts, _res2$chunk;
var messagesPath = encodeUri("/rooms/$roomId/messages", { $roomId: timelineSet.room.roomId });
var _params = { dir: "b" };
if ((_this41$clientOpts = _this41.clientOpts) !== null && _this41$clientOpts !== void 0 && _this41$clientOpts.lazyLoadMembers) _params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);
event = (_res2$chunk = (yield _this41.http.authedRequest(Method.Get, messagesPath, _params)).chunk) === null || _res2$chunk === void 0 ? void 0 : _res2$chunk[0];
}
if (!event) throw new Error("No message returned when trying to construct getLatestTimeline");
return _this41.getEventTimeline(timelineSet, event.event_id);
})();
}
/**
* Makes a request to /messages with the appropriate lazy loading filter set.
* XXX: if we do get rid of scrollback (as it's not used at the moment),
* we could inline this method again in paginateEventTimeline as that would
* then be the only call-site
* @param limit - the maximum amount of events the retrieve
* @param dir - 'f' or 'b'
* @param timelineFilter - the timeline filter to pass
*/
createMessagesRequest(roomId, fromToken) {
var _this$clientOpts;
var limit = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 30;
var dir = arguments.length > 3 ? arguments[3] : void 0;
var timelineFilter = arguments.length > 4 ? arguments[4] : void 0;
var path = encodeUri("/rooms/$roomId/messages", { $roomId: roomId });
var params = {
limit: limit.toString(),
dir
};
if (fromToken) params.from = fromToken;
var filter = null;
if ((_this$clientOpts = this.clientOpts) !== null && _this$clientOpts !== void 0 && _this$clientOpts.lazyLoadMembers) filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);
if (timelineFilter) {
var _timelineFilter$getRo;
filter = filter || {};
Object.assign(filter, (_timelineFilter$getRo = timelineFilter.getRoomTimelineFilterComponent()) === null || _timelineFilter$getRo === void 0 ? void 0 : _timelineFilter$getRo.toJSON());
}
if (filter) params.filter = JSON.stringify(filter);
return this.http.authedRequest(Method.Get, path, params);
}
/**
* Makes a request to /messages with the appropriate lazy loading filter set.
* XXX: if we do get rid of scrollback (as it's not used at the moment),
* we could inline this method again in paginateEventTimeline as that would
* then be the only call-site
* @param limit - the maximum amount of events the retrieve
* @param dir - 'f' or 'b'
* @param timelineFilter - the timeline filter to pass
*/
createThreadListMessagesRequest(roomId, fromToken) {
var _this$clientOpts2;
var limit = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 30;
var dir = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : Direction.Backward;
var threadListType = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : ThreadFilterType.All;
var timelineFilter = arguments.length > 5 ? arguments[5] : void 0;
var path = encodeUri("/rooms/$roomId/threads", { $roomId: roomId });
var params = {
limit: limit.toString(),
dir,
include: threadFilterTypeToFilter(threadListType)
};
if (fromToken) params.from = fromToken;
var filter = {};
if ((_this$clientOpts2 = this.clientOpts) !== null && _this$clientOpts2 !== void 0 && _this$clientOpts2.lazyLoadMembers) filter = _objectSpread$1({}, Filter.LAZY_LOADING_MESSAGES_FILTER);
if (timelineFilter) {
var _timelineFilter$getRo2;
filter = _objectSpread$1(_objectSpread$1({}, filter), (_timelineFilter$getRo2 = timelineFilter.getRoomTimelineFilterComponent()) === null || _timelineFilter$getRo2 === void 0 ? void 0 : _timelineFilter$getRo2.toJSON());
}
if (Object.keys(filter).length) params.filter = JSON.stringify(filter);
var opts = { prefix: Thread.hasServerSideListSupport === FeatureSupport.Stable ? ClientPrefix.V1 : "/_matrix/client/unstable/org.matrix.msc3856" };
return this.http.authedRequest(Method.Get, path, params, void 0, opts).then((res) => {
var _res$chunk3;
return _objectSpread$1(_objectSpread$1({}, res), {}, {
chunk: (_res$chunk3 = res.chunk) === null || _res$chunk3 === void 0 ? void 0 : _res$chunk3.reverse(),
start: res.prev_batch,
end: res.next_batch
});
});
}
/**
* Take an EventTimeline, and back/forward-fill results.
*
* @param eventTimeline - timeline object to be updated
*
* @returns Promise which resolves to a boolean: false if there are no
* events and we reached either end of the timeline; else true.
*/
paginateEventTimeline(eventTimeline, opts) {
var _this42 = this;
var isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;
var room = this.getRoom(eventTimeline.getRoomId());
var threadListType = eventTimeline.getTimelineSet().threadListType;
var thread = eventTimeline.getTimelineSet().thread;
opts = opts || {};
var backwards = opts.backwards || false;
if (isNotifTimeline) {
if (!backwards) throw new Error("paginateNotifTimeline can only paginate backwards");
}
var dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;
var token = eventTimeline.getPaginationToken(dir);
var pendingRequest = eventTimeline.paginationRequests[dir];
if (pendingRequest) return pendingRequest;
var path;
var params;
var promise;
if (isNotifTimeline) {
var _opts$limit;
path = "/notifications";
params = {
limit: ((_opts$limit = opts.limit) !== null && _opts$limit !== void 0 ? _opts$limit : 30).toString(),
only: "highlight"
};
if (token && token !== "end") params.from = token;
promise = this.http.authedRequest(Method.Get, path, params).then(/* @__PURE__ */ function() {
var _ref5 = (0, import_asyncToGenerator.default)(function* (res) {
var token = res.next_token;
var matrixEvents = [];
res.notifications = res.notifications.filter(noUnsafeEventProps);
for (var i = 0; i < res.notifications.length; i++) {
var notification = res.notifications[i];
var _event4 = _this42.getEventMapper()(notification.event);
_this42.getPushDetailsForEvent(_event4, true);
_event4.event.room_id = notification.room_id;
matrixEvents[i] = _event4;
}
var timelineSet = eventTimeline.getTimelineSet();
timelineSet.addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, token);
_this42.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);
if (backwards && !res.next_token) eventTimeline.setPaginationToken(null, dir);
return Boolean(res.next_token);
});
return function(_x2) {
return _ref5.apply(this, arguments);
};
}()).finally(() => {
eventTimeline.paginationRequests[dir] = null;
});
eventTimeline.paginationRequests[dir] = promise;
} else if (threadListType !== null) {
if (!room) throw new Error("Unknown room " + eventTimeline.getRoomId());
if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");
promise = this.createThreadListMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, threadListType, eventTimeline.getFilter()).then((res) => {
if (res.state) {
var roomState = eventTimeline.getState(dir);
var stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());
roomState.setUnknownStateEvents(stateEvents);
}
var token = res.end;
var matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());
eventTimeline.getTimelineSet().addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, token);
this.processAggregatedTimelineEvents(room, matrixEvents);
this.processThreadRoots(room, matrixEvents, backwards);
if (backwards && res.end == res.start) eventTimeline.setPaginationToken(null, dir);
return res.end !== res.start;
}).finally(() => {
eventTimeline.paginationRequests[dir] = null;
});
eventTimeline.paginationRequests[dir] = promise;
} else if (thread) {
var _eventTimeline$getRoo, _eventTimeline$getRoo2;
var _room5 = this.getRoom((_eventTimeline$getRoo = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo !== void 0 ? _eventTimeline$getRoo : void 0);
if (!_room5) throw new Error("Unknown room " + eventTimeline.getRoomId());
var recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;
promise = this.fetchRelations((_eventTimeline$getRoo2 = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo2 !== void 0 ? _eventTimeline$getRoo2 : "", thread.id, null, null, {
dir,
limit: opts.limit,
from: token !== null && token !== void 0 ? token : void 0,
recurse: recurse || void 0
}).then(/* @__PURE__ */ function() {
var _ref6 = (0, import_asyncToGenerator.default)(function* (res) {
var mapper = _this42.getEventMapper();
var matrixEvents = res.chunk.filter(noUnsafeEventProps).filter(getRelationsThreadFilter(thread.id)).map(mapper);
for (var _event5 of matrixEvents.slice().reverse()) {
yield thread === null || thread === void 0 ? void 0 : thread.processEvent(_event5);
var sender = _event5.getSender();
if (!backwards || (thread === null || thread === void 0 ? void 0 : thread.getEventReadUpTo(sender)) === null) _room5.addLocalEchoReceipt(sender, _event5, ReceiptType.Read);
}
var newToken = res.next_batch;
var timelineSet = eventTimeline.getTimelineSet();
timelineSet.addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, newToken !== null && newToken !== void 0 ? newToken : null);
if (!newToken && backwards) {
var _thread$rootEvent, _eventTimeline$getRoo3;
var originalEvent = (_thread$rootEvent = thread.rootEvent) !== null && _thread$rootEvent !== void 0 ? _thread$rootEvent : mapper(yield _this42.fetchRoomEvent((_eventTimeline$getRoo3 = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo3 !== void 0 ? _eventTimeline$getRoo3 : "", thread.id));
timelineSet.addEventsToTimeline([originalEvent], true, false, eventTimeline, null);
}
_this42.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);
if (backwards && !newToken) eventTimeline.setPaginationToken(null, dir);
return Boolean(newToken);
});
return function(_x3) {
return _ref6.apply(this, arguments);
};
}()).finally(() => {
eventTimeline.paginationRequests[dir] = null;
});
eventTimeline.paginationRequests[dir] = promise;
} else {
if (!room) throw new Error("Unknown room " + eventTimeline.getRoomId());
promise = this.createMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, eventTimeline.getFilter()).then((res) => {
if (res.state) {
var roomState = eventTimeline.getState(dir);
var stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());
roomState.setUnknownStateEvents(stateEvents);
}
var token = res.end;
var matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());
var timelineSet = eventTimeline.getTimelineSet();
var [timelineEvents, , unknownRelations] = room.partitionThreadedEvents(matrixEvents);
timelineSet.addEventsToTimeline(timelineEvents, backwards, false, eventTimeline, token);
this.processAggregatedTimelineEvents(room, timelineEvents);
this.processThreadRoots(room, timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)), false);
unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));
var atEnd = res.end === void 0 || res.end === res.start;
if (backwards && atEnd) eventTimeline.setPaginationToken(null, dir);
return !atEnd;
}).finally(() => {
eventTimeline.paginationRequests[dir] = null;
});
eventTimeline.paginationRequests[dir] = promise;
}
return promise;
}
/**
* Reset the notifTimelineSet entirely, paginating in some historical notifs as
* a starting point for subsequent pagination.
*/
resetNotifTimelineSet() {
if (!this.notifTimelineSet) return;
this.notifTimelineSet.resetLiveTimeline("end");
}
/**
* Peek into a room and receive updates about the room. This only works if the
* history visibility for the room is world_readable.
* @param roomId - The room to attempt to peek into.
* @param limit - The number of timeline events to initially retrieve.
* @returns Promise which resolves: Room object
* @returns Rejects: with an error response.
*/
peekInRoom(roomId) {
var _this$peekSync2;
var limit = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 20;
(_this$peekSync2 = this.peekSync) === null || _this$peekSync2 === void 0 || _this$peekSync2.stopPeeking();
this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());
return this.peekSync.peek(roomId, limit);
}
/**
* Stop any ongoing room peeking.
*/
stopPeeking() {
if (this.peekSync) {
this.peekSync.stopPeeking();
this.peekSync = null;
}
}
/**
* Set r/w flags for guest access in a room.
* @param roomId - The room to configure guest access in.
* @param opts - Options
* @returns Promise which resolves
* @returns Rejects: with an error response.
*/
setGuestAccess(roomId, opts) {
var writePromise = this.sendStateEvent(roomId, EventType.RoomGuestAccess, { guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden }, "");
var readPromise = Promise.resolve();
if (opts.allowRead) readPromise = this.sendStateEvent(roomId, EventType.RoomHistoryVisibility, { history_visibility: HistoryVisibility.WorldReadable }, "");
return Promise.all([readPromise, writePromise]).then();
}
/**
* Requests an email verification token for the purposes of registration.
* This API requests a token from the homeserver.
* The doesServerRequireIdServerParam() method can be used to determine if
* the server requires the id_server parameter to be provided.
*
* Parameters and return value are as for requestEmailToken
* @param email - As requestEmailToken
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestRegisterEmailToken(email, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/register/email/requestToken", {
email,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Requests a text message verification token for the purposes of registration.
* This API requests a token from the homeserver.
* The doesServerRequireIdServerParam() method can be used to determine if
* the server requires the id_server parameter to be provided.
*
* @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which
* phoneNumber should be parsed relative to.
* @param phoneNumber - The phone number, in national or international format
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestRegisterMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/register/msisdn/requestToken", {
country: phoneCountry,
phone_number: phoneNumber,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Requests an email verification token for the purposes of adding a
* third party identifier to an account.
* This API requests a token from the homeserver.
* The doesServerRequireIdServerParam() method can be used to determine if
* the server requires the id_server parameter to be provided.
* If an account with the given email address already exists and is
* associated with an account other than the one the user is authed as,
* it will either send an email to the address informing them of this
* or return M_THREEPID_IN_USE (which one is up to the homeserver).
*
* @param email - As requestEmailToken
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestAdd3pidEmailToken(email, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/account/3pid/email/requestToken", {
email,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Requests a text message verification token for the purposes of adding a
* third party identifier to an account.
* This API proxies the identity server /validate/email/requestToken API,
* adding specific behaviour for the addition of phone numbers to an
* account, as requestAdd3pidEmailToken.
*
* @param phoneCountry - As requestRegisterMsisdnToken
* @param phoneNumber - As requestRegisterMsisdnToken
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestAdd3pidMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken", {
country: phoneCountry,
phone_number: phoneNumber,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Requests an email verification token for the purposes of resetting
* the password on an account.
* This API proxies the identity server /validate/email/requestToken API,
* adding specific behaviour for the password resetting. Specifically,
* if no account with the given email address exists, it may either
* return M_THREEPID_NOT_FOUND or send an email
* to the address informing them of this (which one is up to the homeserver).
*
* requestEmailToken calls the equivalent API directly on the identity server,
* therefore bypassing the password reset specific logic.
*
* @param email - As requestEmailToken
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestPasswordEmailToken(email, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/account/password/email/requestToken", {
email,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Requests a text message verification token for the purposes of resetting
* the password on an account.
* This API proxies the identity server /validate/email/requestToken API,
* adding specific behaviour for the password resetting, as requestPasswordEmailToken.
*
* @param phoneCountry - As requestRegisterMsisdnToken
* @param phoneNumber - As requestRegisterMsisdnToken
* @param clientSecret - As requestEmailToken
* @param sendAttempt - As requestEmailToken
* @param nextLink - As requestEmailToken
* @returns Promise which resolves: As requestEmailToken
*/
requestPasswordMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {
return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken", {
country: phoneCountry,
phone_number: phoneNumber,
client_secret: clientSecret,
send_attempt: sendAttempt,
next_link: nextLink
});
}
/**
* Internal utility function for requesting validation tokens from usage-specific
* requestToken endpoints.
*
* @param endpoint - The endpoint to send the request to
* @param params - Parameters for the POST request
* @returns Promise which resolves: As requestEmailToken
*/
requestTokenFromEndpoint(endpoint, params) {
var _this43 = this;
return (0, import_asyncToGenerator.default)(function* () {
var postParams = Object.assign({}, params);
return _this43.http.request(Method.Post, endpoint, void 0, postParams);
})();
}
/**
* Get the room-kind push rule associated with a room.
* @param scope - "global" or device-specific.
* @param roomId - the id of the room.
* @returns the rule or undefined.
*/
getRoomPushRule(scope, roomId) {
if (this.pushRules) {
var _this$pushRules$scope;
return (_this$pushRules$scope = this.pushRules[scope]) === null || _this$pushRules$scope === void 0 || (_this$pushRules$scope = _this$pushRules$scope.room) === null || _this$pushRules$scope === void 0 ? void 0 : _this$pushRules$scope.find((rule) => rule.rule_id === roomId);
} else throw new Error("SyncApi.sync() must be done before accessing to push rules.");
}
/**
* Set a room-kind muting push rule in a room.
* The operation also updates MatrixClient.pushRules at the end.
* @param scope - "global" or device-specific.
* @param roomId - the id of the room.
* @param mute - the mute state.
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
setRoomMutePushRule(scope, roomId, mute) {
var promise;
var hasDontNotifyRule = false;
var roomPushRule = this.getRoomPushRule(scope, roomId);
if (roomPushRule !== null && roomPushRule !== void 0 && roomPushRule.actions.includes(PushRuleActionName.DontNotify)) hasDontNotifyRule = true;
if (!mute) {
if (hasDontNotifyRule) promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id);
} else if (!roomPushRule) promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, { actions: [PushRuleActionName.DontNotify] });
else if (!hasDontNotifyRule) {
var doneResolvers = Promise.withResolvers();
this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id).then(() => {
this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, { actions: [PushRuleActionName.DontNotify] }).then(() => {
doneResolvers.resolve();
}).catch((err) => {
doneResolvers.reject(err);
});
}).catch((err) => {
doneResolvers.reject(err);
});
promise = doneResolvers.promise;
}
if (promise) return new Promise((resolve, reject) => {
promise.then(() => {
this.getPushRules().then((result) => {
this.pushRules = result;
resolve();
}).catch((err) => {
reject(err);
});
}).catch((err) => {
this.getPushRules().then((result) => {
this.pushRules = result;
reject(err);
}).catch((err2) => {
reject(err);
});
});
});
}
searchMessageText(opts) {
var roomEvents = { search_term: opts.query };
if ("keys" in opts) roomEvents.keys = opts.keys;
return this.search({ body: { search_categories: { room_events: roomEvents } } });
}
/**
* Perform a server-side search for room events.
*
* The returned promise resolves to an object containing the fields:
*
* * count: estimate of the number of results
* * next_batch: token for back-pagination; if undefined, there are no more results
* * highlights: a list of words to highlight from the stemming algorithm
* * results: a list of results
*
* Each entry in the results list is a SearchResult.
*
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
searchRoomEvents(opts) {
var body = { search_categories: { room_events: {
search_term: opts.term,
filter: opts.filter,
order_by: SearchOrderBy.Recent,
event_context: {
before_limit: 1,
after_limit: 1,
include_profile: true
}
} } };
var searchResults = {
_query: body,
results: [],
highlights: []
};
return this.search({ body }).then((res) => this.processRoomEventsSearch(searchResults, res));
}
/**
* Take a result from an earlier searchRoomEvents call, and backfill results.
*
* @param searchResults - the results object to be updated
* @returns Promise which resolves: updated result object
* @returns Rejects: with an error response.
*/
backPaginateRoomEventsSearch(searchResults) {
if (!searchResults.next_batch) return Promise.reject(/* @__PURE__ */ new Error("Cannot backpaginate event search any further"));
if (searchResults.pendingRequest) return searchResults.pendingRequest;
var searchOpts = {
body: searchResults._query,
next_batch: searchResults.next_batch
};
var promise = this.search(searchOpts, searchResults.abortSignal).then((res) => this.processRoomEventsSearch(searchResults, res)).finally(() => {
searchResults.pendingRequest = void 0;
});
searchResults.pendingRequest = promise;
return promise;
}
/**
* helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the
* response from the API call and updates the searchResults
*
* @returns searchResults
* @internal
*/
processRoomEventsSearch(searchResults, response) {
var _roomEvents$results$l, _roomEvents$results;
var roomEvents = response.search_categories.room_events;
searchResults.count = roomEvents.count;
searchResults.next_batch = roomEvents.next_batch;
var highlights = new Set(roomEvents.highlights);
searchResults.highlights.forEach((hl) => {
highlights.add(hl);
});
searchResults.highlights = Array.from(highlights);
var mapper = this.getEventMapper();
var resultsLength = (_roomEvents$results$l = (_roomEvents$results = roomEvents.results) === null || _roomEvents$results === void 0 ? void 0 : _roomEvents$results.length) !== null && _roomEvents$results$l !== void 0 ? _roomEvents$results$l : 0;
for (var i = 0; i < resultsLength; i++) {
var sr = SearchResult.fromJson(roomEvents.results[i], mapper);
var _room6 = this.getRoom(sr.context.getEvent().getRoomId());
if (_room6) for (var ev of sr.context.getTimeline()) ev.setMetadata(_room6.currentState, false);
searchResults.results.push(sr);
}
return searchResults;
}
/**
* Populate the store with rooms the user has left.
* @returns Promise which resolves: TODO - Resolved when the rooms have
* been added to the data store.
* @returns Rejects: with an error response.
*/
syncLeftRooms() {
if (this.syncedLeftRooms) return Promise.resolve([]);
if (this.syncLeftRoomsPromise) return this.syncLeftRoomsPromise;
this.syncLeftRoomsPromise = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions()).syncLeftRooms();
this.syncLeftRoomsPromise.then(() => {
this.logger.debug("Marking success of sync left room request");
this.syncedLeftRooms = true;
}).finally(() => {
this.syncLeftRoomsPromise = void 0;
});
return this.syncLeftRoomsPromise;
}
/**
* Create a new filter.
* @param content - The HTTP body for the request
* @returns Promise which resolves to a Filter object.
* @returns Rejects: with an error response.
*/
createFilter(content) {
var path = encodeUri("/user/$userId/filter", { $userId: this.credentials.userId });
return this.http.authedRequest(Method.Post, path, void 0, content).then((response) => {
var filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);
this.store.storeFilter(filter);
return filter;
});
}
/**
* Retrieve a filter.
* @param userId - The user ID of the filter owner
* @param filterId - The filter ID to retrieve
* @param allowCached - True to allow cached filters to be returned.
* Default: True.
* @returns Promise which resolves: a Filter object
* @returns Rejects: with an error response.
*/
getFilter(userId, filterId, allowCached) {
if (allowCached) {
var filter = this.store.getFilter(userId, filterId);
if (filter) return Promise.resolve(filter);
}
var path = encodeUri("/user/$userId/filter/$filterId", {
$userId: userId,
$filterId: filterId
});
return this.http.authedRequest(Method.Get, path).then((response) => {
var filter = Filter.fromJson(userId, filterId, response);
this.store.storeFilter(filter);
return filter;
});
}
/**
* @returns Filter ID
*/
getOrCreateFilter(filterName, filter) {
var _this44 = this;
return (0, import_asyncToGenerator.default)(function* () {
var filterId = _this44.store.getFilterIdByName(filterName);
var existingId;
if (filterId) {
try {
var existingFilter = yield _this44.getFilter(_this44.credentials.userId, filterId, true);
if (existingFilter) {
if (deepCompare(existingFilter.getDefinition(), filter.getDefinition())) existingId = filterId;
}
} catch (error) {
if (error.errcode !== "M_UNKNOWN" && error.errcode !== "M_NOT_FOUND") throw error;
}
if (!existingId) _this44.store.setFilterIdByName(filterName, void 0);
}
if (existingId) return existingId;
var createdFilter = yield _this44.createFilter(filter.getDefinition());
_this44.store.setFilterIdByName(filterName, createdFilter.filterId);
return createdFilter.filterId;
})();
}
/**
* Gets a bearer token from the homeserver that the user can
* present to a third party in order to prove their ownership
* of the Matrix account they are logged into.
* @returns Promise which resolves: Token object
* @returns Rejects: with an error response.
*/
getOpenIdToken() {
var path = encodeUri("/user/$userId/openid/request_token", { $userId: this.credentials.userId });
return this.http.authedRequest(Method.Post, path, void 0, {});
}
/**
* @returns Promise which resolves: ITurnServerResponse object
* @returns Rejects: with an error response.
*/
turnServer() {
return this.http.authedRequest(Method.Get, "/voip/turnServer");
}
/**
* Get the TURN servers for this homeserver.
* @returns The servers or an empty list.
*/
getTurnServers() {
return this.turnServers || [];
}
/**
* Get the unix timestamp (in milliseconds) at which the current
* TURN credentials (from getTurnServers) expire
* @returns The expiry timestamp in milliseconds
*/
getTurnServersExpiry() {
return this.turnServersExpiry;
}
get pollingTurnServers() {
return this.checkTurnServersIntervalID !== void 0;
}
checkTurnServers() {
var _this45 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this45.supportsVoip()) return;
var credentialsGood = false;
var remainingTime = _this45.turnServersExpiry - Date.now();
if (remainingTime > TURN_CHECK_INTERVAL) {
_this45.logger.debug("TURN creds are valid for another " + remainingTime + " ms: not fetching new ones.");
credentialsGood = true;
} else {
_this45.logger.debug("Fetching new TURN credentials");
try {
var res = yield _this45.turnServer();
if (res.uris) {
_this45.logger.debug("Got TURN URIs: " + res.uris + " refresh in " + res.ttl + " secs");
_this45.turnServers = [{
urls: res.uris,
username: res.username,
credential: res.password
}];
_this45.turnServersExpiry = Date.now() + res.ttl * 1e3;
credentialsGood = true;
_this45.emit(ClientEvent.TurnServers, _this45.turnServers);
}
} catch (err) {
_this45.logger.error("Failed to get TURN URIs", err);
if (err.httpStatus === 403) {
_this45.logger.info("TURN access unavailable for this account: stopping credentials checks");
if (_this45.checkTurnServersIntervalID !== null) globalThis.clearInterval(_this45.checkTurnServersIntervalID);
_this45.checkTurnServersIntervalID = void 0;
_this45.emit(ClientEvent.TurnServersError, err, true);
} else _this45.emit(ClientEvent.TurnServersError, err, false);
}
}
return credentialsGood;
})();
}
/**
* Set whether to allow a fallback ICE server should be used for negotiating a
* WebRTC connection if the homeserver doesn't provide any servers. Defaults to
* false.
*
*/
setFallbackICEServerAllowed(allow) {
this.fallbackICEServerAllowed = allow;
}
/**
* Get whether to allow a fallback ICE server should be used for negotiating a
* WebRTC connection if the homeserver doesn't provide any servers. Defaults to
* false.
*
* @returns
*/
isFallbackICEServerAllowed() {
return this.fallbackICEServerAllowed;
}
/**
* Determines if the current user is an administrator of the Synapse homeserver.
* Returns false if untrue or the homeserver does not appear to be a Synapse
* homeserver. <strong>This function is implementation specific and may change
* as a result.</strong>
* @returns true if the user appears to be a Synapse administrator.
*/
isSynapseAdministrator() {
var path = encodeUri("/_synapse/admin/v1/users/$userId/admin", { $userId: this.getUserId() });
return this.http.authedRequest(Method.Get, path, void 0, void 0, { prefix: "" }).then((r) => r.admin);
}
/**
* Performs a whois lookup on a user using Synapse's administrator API.
* <strong>This function is implementation specific and may change as a
* result.</strong>
* @param userId - the User ID to look up.
* @returns the whois response - see Synapse docs for information.
*/
whoisSynapseUser(userId) {
var path = encodeUri("/_synapse/admin/v1/whois/$userId", { $userId: userId });
return this.http.authedRequest(Method.Get, path, void 0, void 0, { prefix: "" });
}
/**
* Deactivates a user using Synapse's administrator API. <strong>This
* function is implementation specific and may change as a result.</strong>
* @param userId - the User ID to deactivate.
* @returns the deactivate response - see Synapse docs for information.
*/
deactivateSynapseUser(userId) {
var path = encodeUri("/_synapse/admin/v1/deactivate/$userId", { $userId: userId });
return this.http.authedRequest(Method.Post, path, void 0, void 0, { prefix: "" });
}
fetchClientWellKnown() {
var _this46 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this46$getDomain;
_this46.clientWellKnownPromise = AutoDiscovery.getRawClientConfig((_this46$getDomain = _this46.getDomain()) !== null && _this46$getDomain !== void 0 ? _this46$getDomain : void 0);
_this46.clientWellKnown = yield _this46.clientWellKnownPromise;
_this46.emit(ClientEvent.ClientWellKnown, _this46.clientWellKnown);
})();
}
getClientWellKnown() {
return this.clientWellKnown;
}
waitForClientWellKnown() {
if (!this.clientRunning) throw new Error("Client is not running");
return this.clientWellKnownPromise;
}
/**
* store client options with boolean/string/numeric values
* to know in the next session what flags the sync data was
* created with (e.g. lazy loading)
* @returns for store operation
*/
storeClientOptions() {
var primTypes = [
"boolean",
"string",
"number"
];
var serializableOpts = Object.entries(this.clientOpts).filter((_ref7) => {
var [key, value] = _ref7;
return primTypes.includes(typeof value);
}).reduce((obj, _ref8) => {
var [key, value] = _ref8;
obj[key] = value;
return obj;
}, {});
return this.store.storeClientOptions(serializableOpts);
}
/**
* Gets a set of room IDs in common with another user.
*
* Note: This endpoint is unstable, and can throw an `Error`.
* Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.
*
* @param userId - The userId to check.
* @returns Promise which resolves to an array of rooms
* @returns Rejects: with an error response.
*/
_unstable_getSharedRooms(userId) {
var _this47 = this;
return (0, import_asyncToGenerator.default)(function* () {
var sharedRoomsSupport = yield _this47.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);
var mutualRoomsSupport = yield _this47.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);
var queryMutualRoomsSupport = yield _this47.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS);
if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) throw Error("Server does not support the Mutual Rooms API");
var path;
var query;
if (queryMutualRoomsSupport) {
path = "/uk.half-shot.msc2666/user/mutual_rooms";
query = { user_id: userId };
} else {
path = encodeUri("/uk.half-shot.msc2666/user/".concat(mutualRoomsSupport ? "mutual_rooms" : "shared_rooms", "/$userId"), { $userId: userId });
query = {};
}
var rooms = [];
var token = null;
do {
var tokenQuery = {};
if (token != null && queryMutualRoomsSupport) tokenQuery["batch_token"] = token;
var res = yield _this47.http.authedRequest(Method.Get, path, _objectSpread$1(_objectSpread$1({}, query), tokenQuery), void 0, { prefix: ClientPrefix.Unstable });
rooms.push(...res.joined);
if (res.next_batch_token !== void 0) token = res.next_batch_token;
else token = null;
} while (token != null);
return rooms;
})();
}
/**
* Returns a set of configured RTC transports supported by the homeserver.
* Requires homeserver support for MSC4143.
* @throws A M_NOT_FOUND error if not supported by the homeserver.
*/
_unstable_getRTCTransports() {
var _this48 = this;
return (0, import_asyncToGenerator.default)(function* () {
return (yield _this48.http.authedRequest(Method.Get, "/rtc/transports", void 0, void 0, { prefix: "".concat(ClientPrefix.Unstable, "/org.matrix.msc4143") })).rtc_transports;
})();
}
/**
* Get the API versions supported by the server, along with any
* unstable APIs it supports
* @returns The server /versions response
*/
getVersions() {
var _this49 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_this49.serverVersionsPromise) return _this49.serverVersionsPromise;
_this49.serverVersionsPromise = _this49.http.authedRequest(Method.Get, "/_matrix/client/versions", void 0, void 0, { prefix: "" }).catch((e) => {
_this49.serverVersionsPromise = void 0;
throw e;
});
_this49.canSupport = yield buildFeatureSupportMap(yield _this49.serverVersionsPromise);
return _this49.serverVersionsPromise;
})();
}
/**
* Check if a particular spec version is supported by the server.
* @param version - The spec version (such as "r0.5.0") to check for.
* @returns Whether it is supported
*/
isVersionSupported(version) {
var _this50 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { versions } = yield _this50.getVersions();
return versions && versions.includes(version);
})();
}
/**
* Query the server to see if it lists support for an unstable feature
* in the /versions response
* @param feature - the feature name
* @returns true if the feature is supported
*/
doesServerSupportUnstableFeature(feature) {
var _this51 = this;
return (0, import_asyncToGenerator.default)(function* () {
var response = yield _this51.getVersions();
if (!response) return false;
var unstableFeatures = response["unstable_features"];
return unstableFeatures && !!unstableFeatures[feature];
})();
}
/**
* Query the server to see if it is forcing encryption to be enabled for
* a given room preset, based on the /versions response.
* @param presetName - The name of the preset to check.
* @returns true if the server is forcing encryption
* for the preset.
*/
doesServerForceEncryptionForPreset(presetName) {
var _this52 = this;
return (0, import_asyncToGenerator.default)(function* () {
var response = yield _this52.getVersions();
if (!response) return false;
var unstableFeatures = response["unstable_features"];
var versionsPresetName = presetName.includes("_chat") ? presetName.substring(0, presetName.indexOf("_chat")) : presetName;
return unstableFeatures && !!unstableFeatures["io.element.e2ee_forced.".concat(versionsPresetName)];
})();
}
doesServerSupportThread() {
var _this53 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (yield _this53.isVersionSupported("v1.4")) return {
threads: FeatureSupport.Stable,
list: FeatureSupport.Stable,
fwdPagination: FeatureSupport.Stable
};
try {
var [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] = yield Promise.all([
_this53.doesServerSupportUnstableFeature("org.matrix.msc3440"),
_this53.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),
_this53.doesServerSupportUnstableFeature("org.matrix.msc3856"),
_this53.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),
_this53.doesServerSupportUnstableFeature("org.matrix.msc3715"),
_this53.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")
]);
return {
threads: determineFeatureSupport(threadStable, threadUnstable),
list: determineFeatureSupport(listStable, listUnstable),
fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable)
};
} catch (_unused2) {
return {
threads: FeatureSupport.None,
list: FeatureSupport.None,
fwdPagination: FeatureSupport.None
};
}
})();
}
/**
* Get if lazy loading members is being used.
* @returns Whether or not members are lazy loaded by this client
*/
hasLazyLoadMembersEnabled() {
var _this$clientOpts3;
return !!((_this$clientOpts3 = this.clientOpts) !== null && _this$clientOpts3 !== void 0 && _this$clientOpts3.lazyLoadMembers);
}
/**
* Set a function which is called when /sync returns a 'limited' response.
* It is called with a room ID and returns a boolean. It should return 'true' if the SDK
* can SAFELY remove events from this room. It may not be safe to remove events if there
* are other references to the timelines for this room, e.g because the client is
* actively viewing events in this room.
* Default: returns false.
* @param cb - The callback which will be invoked.
*/
setCanResetTimelineCallback(cb) {
this.canResetTimelineCallback = cb;
}
/**
* Get the callback set via `setCanResetTimelineCallback`.
* @returns The callback or null
*/
getCanResetTimelineCallback() {
return this.canResetTimelineCallback;
}
/**
* Returns relations for a given event. Handles encryption transparently,
* with the caveat that the amount of events returned might be 0, even though you get a nextBatch.
* When the returned promise resolves, all messages should have finished trying to decrypt.
* @param roomId - the room of the event
* @param eventId - the id of the event
* @param relationType - the rel_type of the relations requested
* @param eventType - the event type of the relations requested
* @param opts - options with optional values for the request.
* @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.
*/
relations(roomId, eventId, relationType, eventType) {
var _arguments12 = arguments, _this54 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _result$next_batch, _result$prev_batch;
var opts = _arguments12.length > 4 && _arguments12[4] !== void 0 ? _arguments12[4] : { dir: Direction.Backward };
var fetchedEventType = eventType ? _this54.getEncryptedIfNeededEventType(roomId, eventType) : null;
var [eventResult, result] = yield Promise.all([_this54.fetchRoomEvent(roomId, eventId), _this54.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts)]);
var mapper = _this54.getEventMapper();
var originalEvent = eventResult ? mapper(eventResult) : void 0;
var events = result.chunk.map(mapper);
if (fetchedEventType === EventType.RoomMessageEncrypted) {
var allEvents = originalEvent ? events.concat(originalEvent) : events;
yield Promise.all(allEvents.map((e) => _this54.decryptEventIfNeeded(e)));
if (eventType !== null) events = events.filter((e) => e.getType() === eventType);
}
if (originalEvent && relationType === RelationType.Replace) events = events.filter((e) => e.getSender() === originalEvent.getSender());
return {
originalEvent: originalEvent !== null && originalEvent !== void 0 ? originalEvent : null,
events,
nextBatch: (_result$next_batch = result.next_batch) !== null && _result$next_batch !== void 0 ? _result$next_batch : null,
prevBatch: (_result$prev_batch = result.prev_batch) !== null && _result$prev_batch !== void 0 ? _result$prev_batch : null
};
})();
}
/**
* Generates a random string suitable for use as a client secret. <strong>This
* method is experimental and may change.</strong>
* @returns A new client secret
*/
generateClientSecret() {
return secureRandomString(32);
}
/**
* Attempts to decrypt an event
* @param event - The event to decrypt
* @returns A decryption promise
*/
decryptEventIfNeeded(event, options) {
if (event.isState() && !this.enableEncryptedStateEvents) return Promise.resolve();
if (event.shouldAttemptDecryption() && this.getCrypto()) event.attemptDecryption(this.cryptoBackend, options);
if (event.isBeingDecrypted()) return event.getDecryptionPromise();
else return Promise.resolve();
}
termsUrlForService(serviceType, baseUrl) {
switch (serviceType) {
case SERVICE_TYPES.IS: return this.http.getUrl("/terms", void 0, IdentityPrefix.V2, baseUrl);
case SERVICE_TYPES.IM: return this.http.getUrl("/terms", void 0, "/_matrix/integrations/v1", baseUrl);
default: throw new Error("Unsupported service type");
}
}
/**
* Get the Homeserver URL of this client
* @returns Homeserver URL of this client
*/
getHomeserverUrl() {
return this.baseUrl;
}
/**
* Get the identity server URL of this client
* @param stripProto - whether or not to strip the protocol from the URL
* @returns Identity server URL of this client
*/
getIdentityServerUrl() {
var _this$idBaseUrl, _this$idBaseUrl2;
if ((arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false) && ((_this$idBaseUrl = this.idBaseUrl) !== null && _this$idBaseUrl !== void 0 && _this$idBaseUrl.startsWith("http://") || (_this$idBaseUrl2 = this.idBaseUrl) !== null && _this$idBaseUrl2 !== void 0 && _this$idBaseUrl2.startsWith("https://"))) return this.idBaseUrl.split("://")[1];
return this.idBaseUrl;
}
/**
* Set the identity server URL of this client
* @param url - New identity server URL
*/
setIdentityServerUrl(url) {
this.idBaseUrl = ensureNoTrailingSlash(url);
this.http.setIdBaseUrl(this.idBaseUrl);
}
/**
* Get the access token associated with this account.
* @returns The access_token or null
*/
getAccessToken() {
return this.http.opts.accessToken || null;
}
/**
* Get the refresh token associated with this account.
* @returns The refresh_token or null
*/
getRefreshToken() {
var _this$http$opts$refre;
return (_this$http$opts$refre = this.http.opts.refreshToken) !== null && _this$http$opts$refre !== void 0 ? _this$http$opts$refre : null;
}
/**
* Set the access token associated with this account.
* @param token - The new access token.
*/
setAccessToken(token) {
this.http.opts.accessToken = token;
this.serverVersionsPromise = void 0;
}
/**
* @returns true if there is a valid access_token for this client.
*/
isLoggedIn() {
return this.http.opts.accessToken !== void 0;
}
/**
* Make up a new transaction id
*
* @returns a new, unique, transaction id
*/
makeTxnId() {
return "m" + (/* @__PURE__ */ new Date()).getTime() + "." + this.txnCtr++;
}
/**
* Check whether a username is available prior to registration. An error response
* indicates an invalid/unavailable username.
* @param username - The username to check the availability of.
* @returns Promise which resolves: to boolean of whether the username is available.
*/
isUsernameAvailable(username) {
return this.http.authedRequest(Method.Get, "/register/available", { username }).then((response) => {
return response.available;
}).catch((response) => {
if (response.errcode === "M_USER_IN_USE") return false;
return Promise.reject(response);
});
}
/**
* @param bindThreepids - Set key 'email' to true to bind any email
* threepid uses during registration in the identity server. Set 'msisdn' to
* true to bind msisdn.
* @returns Promise which resolves to a RegisterResponse object
* @returns Rejects: with an error response.
*/
register(username, password, sessionId, auth, bindThreepids, guestAccessToken, inhibitLogin) {
if (sessionId) auth.session = sessionId;
var params = {
auth,
refresh_token: true
};
if (username !== void 0 && username !== null) params.username = username;
if (password !== void 0 && password !== null) params.password = password;
if (guestAccessToken !== void 0 && guestAccessToken !== null) params.guest_access_token = guestAccessToken;
if (inhibitLogin !== void 0 && inhibitLogin !== null) params.inhibit_login = inhibitLogin;
return this.registerRequest(params);
}
/**
* Register a guest account.
* This method returns the auth info needed to create a new authenticated client,
* Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:
* ```javascript
* const tmpClient = await sdk.createClient(MATRIX_INSTANCE);
* const { user_id, device_id, access_token } = tmpClient.registerGuest();
* const client = createClient({
* baseUrl: MATRIX_INSTANCE,
* accessToken: access_token,
* userId: user_id,
* deviceId: device_id,
* })
* client.setGuest(true);
* ```
*
* @param body - JSON HTTP body to provide.
* @returns Promise which resolves: JSON object that contains:
* `{ user_id, device_id, access_token, home_server }`
* @returns Rejects: with an error response.
*/
registerGuest() {
var { body } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
return this.registerRequest(body || {}, "guest");
}
/**
* @param data - parameters for registration request
* @param kind - type of user to register. may be "guest"
* @returns Promise which resolves: to the /register response
* @returns Rejects: with an error response.
*/
registerRequest(data, kind) {
var params = {};
if (kind) params.kind = kind;
return this.http.request(Method.Post, "/register", params, data);
}
/**
* Refreshes an access token using a provided refresh token. The refresh token
* must be valid for the current access token known to the client instance.
*
* Note that this function will not cause a logout if the token is deemed
* unknown by the server - the caller is responsible for managing logout
* actions on error.
* @param refreshToken - The refresh token.
* @returns Promise which resolves to the new token.
* @returns Rejects with an error response.
*/
refreshToken(refreshToken) {
var performRefreshRequestWithPrefix = (prefix) => this.http.authedRequest(Method.Post, "/refresh", void 0, { refresh_token: refreshToken }, {
prefix,
inhibitLogoutEmit: true
});
return performRefreshRequestWithPrefix(ClientPrefix.V3).catch((e) => {
if (e.errcode === "M_UNRECOGNIZED") return performRefreshRequestWithPrefix(ClientPrefix.V1);
throw e;
});
}
/**
* @returns Promise which resolves to the available login flows
* @returns Rejects: with an error response.
*/
loginFlows() {
return this.http.request(Method.Get, "/login");
}
/**
* @returns Promise which resolves to a LoginResponse object
* @returns Rejects: with an error response.
*
* @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the
* returned credentials. Instead, call {@link loginRequest} and create a new `MatrixClient` instance using the
* results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.
*/
login(loginType, data) {
return this.loginRequest(_objectSpread$1(_objectSpread$1({}, data), {}, { type: loginType })).then((response) => {
if (response.access_token && response.user_id) {
this.http.opts.accessToken = response.access_token;
this.credentials = { userId: response.user_id };
}
return response;
});
}
/**
* @returns Promise which resolves to a LoginResponse object
* @returns Rejects: with an error response.
*
* @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the
* returned credentials. Instead, call {@link loginRequest} with `data.type: "m.login.password"`, and create a new
* `MatrixClient` instance using the results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.
*/
loginWithPassword(user, password) {
return this.login("m.login.password", {
user,
password
});
}
/**
* @param redirectUrl - The URL to redirect to after the HS
* authenticates with CAS.
* @returns The HS URL to hit to begin the CAS login process.
*/
getCasLoginUrl(redirectUrl) {
return this.getSsoLoginUrl(redirectUrl, "cas");
}
/**
* @param redirectUrl - The URL to redirect to after the HS
* authenticates with the SSO.
* @param loginType - The type of SSO login we are doing (sso or cas).
* Defaults to 'sso'.
* @param idpId - The ID of the Identity Provider being targeted, optional.
* @param action - the SSO flow to indicate to the IdP, optional.
* @returns The HS URL to hit to begin the SSO login process.
*/
getSsoLoginUrl(redirectUrl) {
var loginType = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "sso";
var idpId = arguments.length > 2 ? arguments[2] : void 0;
var action = arguments.length > 3 ? arguments[3] : void 0;
var url = "/login/" + loginType + "/redirect";
if (idpId) url += "/" + idpId;
var params = {
redirectUrl,
[SSO_ACTION_PARAM.stable]: action,
[SSO_ACTION_PARAM.unstable]: action
};
return this.http.getUrl(url, params).href;
}
/**
* @param token - Login token previously received from homeserver
* @returns Promise which resolves to a LoginResponse object
* @returns Rejects: with an error response.
*
* @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the
* returned credentials. Instead, call {@link loginRequest} with `data.type: "m.login.token"`, and create a new
* `MatrixClient` instance using the results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.
*/
loginWithToken(token) {
return this.login("m.login.token", { token });
}
/**
* Sends a `POST /login` request to the server.
*
* If successful, this will create a new device and access token for the user.
*
* @see {@link MatrixClient.loginFlows} which makes a `GET /login` request.
* @see https://spec.matrix.org/v1.13/client-server-api/#post_matrixclientv3login
*
* @param data - Credentials and other details for the login request.
*/
loginRequest(data) {
var _this55 = this;
return (0, import_asyncToGenerator.default)(function* () {
return yield _this55.http.authedRequest(Method.Post, "/login", void 0, data);
})();
}
/**
* Logs out the current session.
* Obviously, further calls that require authorisation should fail after this
* method is called. The state of the MatrixClient object is not affected:
* it is up to the caller to either reset or destroy the MatrixClient after
* this method succeeds.
* @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.
* @returns Promise which resolves: On success, the empty object `{}`
*/
logout() {
var _arguments13 = arguments, _this56 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (_arguments13.length > 0 && _arguments13[0] !== void 0 ? _arguments13[0] : false) {
_this56.stopClient();
_this56.http.abort();
}
return _this56.http.authedRequest(Method.Post, "/logout");
})();
}
/**
* Deactivates the logged-in account.
* Obviously, further calls that require authorisation should fail after this
* method is called. The state of the MatrixClient object is not affected:
* it is up to the caller to either reset or destroy the MatrixClient after
* this method succeeds.
* @param auth - Optional. Auth data to supply for User-Interactive auth.
* @param erase - Optional. If set, send as `erase` attribute in the
* JSON request body, indicating whether the account should be erased. Defaults
* to false.
* @returns Promise which resolves: On success, the empty object
*/
deactivateAccount(auth, erase) {
var body = {};
if (auth) body.auth = auth;
if (erase !== void 0) body.erase = erase;
return this.http.authedRequest(Method.Post, "/account/deactivate", void 0, body);
}
/**
* Make a request for an `m.login.token` to be issued as per
* https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token
*
* The server may require User-Interactive auth.
*
* @param auth - Optional. Auth data to supply for User-Interactive auth.
* @returns Promise which resolves: On success, the token response
* or UIA auth data.
*/
requestLoginToken(auth) {
var _this57 = this;
return (0, import_asyncToGenerator.default)(function* () {
var body = { auth };
return _this57.http.authedRequest(Method.Post, "/login/get_token", void 0, body, { prefix: ClientPrefix.V1 });
})();
}
/**
* Get the fallback URL to use for unknown interactive-auth stages.
*
* @param loginType - the type of stage being attempted
* @param authSessionId - the auth session ID provided by the homeserver
*
* @returns HS URL to hit to for the fallback interface
*/
getFallbackAuthUrl(loginType, authSessionId) {
var path = encodeUri("/auth/$loginType/fallback/web", { $loginType: loginType });
return this.http.getUrl(path, { session: authSessionId }).href;
}
/**
* Create a new room.
* @param options - a list of options to pass to the /createRoom API.
* @returns Promise which resolves: `{room_id: {string}}`
* @returns Rejects: with an error response.
*/
createRoom(options) {
var _this58 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this58$identityServe;
var invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);
if (invitesNeedingToken.length > 0 && (_this58$identityServe = _this58.identityServer) !== null && _this58$identityServe !== void 0 && _this58$identityServe.getAccessToken) {
var identityAccessToken = yield _this58.identityServer.getAccessToken();
if (identityAccessToken) for (var invite of invitesNeedingToken) invite.id_access_token = identityAccessToken;
}
return _this58.http.authedRequest(Method.Post, "/createRoom", void 0, options);
})();
}
/**
* Fetches relations for a given event
* @param roomId - the room of the event
* @param eventId - the id of the event
* @param relationType - the rel_type of the relations requested
* @param eventType - the event type of the relations requested
* @param opts - options with optional values for the request.
* @returns the response, with chunk, prev_batch and, next_batch.
*/
fetchRelations(roomId, eventId, relationType, eventType) {
var params = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : { dir: Direction.Backward };
if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) params = replaceParam("dir", "org.matrix.msc3715.dir", params);
if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) params = replaceParam("recurse", "org.matrix.msc3981.recurse", params);
var queryString = encodeParams(params);
var templatedUrl = "/rooms/$roomId/relations/$eventId";
if (relationType !== null) {
templatedUrl += "/$relationType";
if (eventType !== null) templatedUrl += "/$eventType";
} else if (eventType !== null) {
this.logger.warn("eventType: ".concat(eventType, " ignored when fetching\n relations as relationType is null"));
eventType = null;
}
var path = encodeUri(templatedUrl + "?" + queryString, {
$roomId: roomId,
$eventId: eventId,
$relationType: relationType,
$eventType: eventType
});
return this.http.authedRequest(Method.Get, path, void 0, void 0, { prefix: ClientPrefix.V1 });
}
/**
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
roomState(roomId) {
var path = encodeUri("/rooms/$roomId/state", { $roomId: roomId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Get an event in a room by its event id.
*
* @returns Promise which resolves to an object containing the event.
* @returns Rejects: with an error response.
*/
fetchRoomEvent(roomId, eventId) {
var path = encodeUri("/rooms/$roomId/event/$eventId", {
$roomId: roomId,
$eventId: eventId
});
return this.http.authedRequest(Method.Get, path);
}
/**
* @param includeMembership - the membership type to include in the response
* @param excludeMembership - the membership type to exclude from the response
* @param atEventId - the id of the event for which moment in the timeline the members should be returned for
* @returns Promise which resolves: dictionary of userid to profile information
* @returns Rejects: with an error response.
*/
members(roomId, includeMembership, excludeMembership, atEventId) {
var queryParams = {};
if (includeMembership) queryParams.membership = includeMembership;
if (excludeMembership) queryParams.not_membership = excludeMembership;
if (atEventId) queryParams.at = atEventId;
var path = encodeUri("/rooms/$roomId/members?" + encodeParams(queryParams), { $roomId: roomId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Upgrades a room to a new protocol version
* @param newVersion - The target version to upgrade to
* @param additionalCreators - an optional list of user IDs of users who
* should have the same permissions as the user performing the
* upgrade
* @returns Promise which resolves: Object with key 'replacement_room'
* @returns Rejects: with an error response.
*/
upgradeRoom(roomId, newVersion, additionalCreators) {
var path = encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId });
return this.http.authedRequest(Method.Post, path, void 0, {
new_version: newVersion,
additional_creators: additionalCreators
});
}
/**
* Retrieve a state event.
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
getStateEvent(roomId, eventType, stateKey) {
var pathParams = {
$roomId: roomId,
$eventType: eventType,
$stateKey: stateKey
};
var path = encodeUri("/rooms/$roomId/state/$eventType", pathParams);
if (stateKey !== void 0) path = encodeUri(path + "/$stateKey", pathParams);
return this.http.authedRequest(Method.Get, path);
}
/**
* Send a state event into a room
* @param roomId - ID of the room to send the event into
* @param eventType - type of the state event to send
* @param content - content of the event to send
* @param stateKey - the stateKey to send into the room
* @param opts - Options for the request function.
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
sendStateEvent(roomId, eventType, content) {
var _arguments14 = arguments, _this59 = this;
return (0, import_asyncToGenerator.default)(function* () {
var stateKey = _arguments14.length > 3 && _arguments14[3] !== void 0 ? _arguments14[3] : "";
var opts = _arguments14.length > 4 && _arguments14[4] !== void 0 ? _arguments14[4] : {};
var room = _this59.getRoom(roomId);
var event = new MatrixEvent({
room_id: roomId,
type: eventType,
state_key: stateKey,
content
});
yield _this59.encryptStateEventIfNeeded(event, room !== null && room !== void 0 ? room : void 0);
var pathParams = {
$roomId: roomId,
$eventType: event.getWireType(),
$stateKey: event.getWireStateKey()
};
var path = encodeUri("/rooms/$roomId/state/$eventType", pathParams);
if (stateKey !== void 0) path = encodeUri(path + "/$stateKey", pathParams);
return _this59.http.authedRequest(Method.Put, path, void 0, event.getWireContent(), opts);
})();
}
encryptStateEventIfNeeded(event, room) {
var _this60 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this60.enableEncryptedStateEvents) return;
if (!room) return;
if (!_this60.cryptoBackend && _this60.usingExternalCrypto) return;
if (!_this60.cryptoBackend) throw new Error("This room is configured to use encryption, but your client does not support encryption.");
if (!(yield _this60.shouldEncryptEventForRoom(event, room))) return;
if (!(yield _this60.cryptoBackend.isStateEncryptionEnabledInRoom(room.roomId))) return;
if ([
"m.room.create",
"m.room.member",
"m.room.join_rules",
"m.room.power_levels",
"m.room.third_party_invite",
"m.room.history_visibility",
"m.room.guest_access",
"m.room.encryption"
].includes(event.getType())) return;
yield _this60.cryptoBackend.encryptEvent(event, room);
})();
}
/**
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
roomInitialSync(roomId, limit) {
var _limit$toString;
var path = encodeUri("/rooms/$roomId/initialSync", { $roomId: roomId });
return this.http.authedRequest(Method.Get, path, { limit: (_limit$toString = limit === null || limit === void 0 ? void 0 : limit.toString()) !== null && _limit$toString !== void 0 ? _limit$toString : "30" });
}
/**
* Set a marker to indicate the point in a room before which the user has read every
* event. This can be retrieved from room account data (the event type is `m.fully_read`)
* and displayed as a horizontal line in the timeline that is visually distinct to the
* position of the user's own read receipt.
* @param roomId - ID of the room that has been read
* @param rmEventId - ID of the event that has been read
* @param rrEventId - ID of the event tracked by the read receipt. This is here
* for convenience because the RR and the RM are commonly updated at the same time as
* each other. Optional.
* @param rpEventId - rpEvent the m.read.private read receipt event for when we
* don't want other users to see the read receipts. This is experimental. Optional.
* @returns Promise which resolves: the empty object, `{}`.
*/
setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId) {
var _this61 = this;
return (0, import_asyncToGenerator.default)(function* () {
var path = encodeUri("/rooms/$roomId/read_markers", { $roomId: roomId });
var content = {
[ReceiptType.FullyRead]: rmEventId,
[ReceiptType.Read]: rrEventId
};
if ((yield _this61.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")) || (yield _this61.isVersionSupported("v1.4"))) content[ReceiptType.ReadPrivate] = rpEventId;
return _this61.http.authedRequest(Method.Post, path, void 0, content);
})();
}
/**
* @returns Promise which resolves: A list of the user's current rooms
* @returns Rejects: with an error response.
*/
getJoinedRooms() {
var path = encodeUri("/joined_rooms", {});
return this.http.authedRequest(Method.Get, path);
}
/**
* Retrieve membership info. for a room.
* @param roomId - ID of the room to get membership for
* @returns Promise which resolves: A list of currently joined users
* and their profile data.
* @returns Rejects: with an error response.
*/
getJoinedRoomMembers(roomId) {
var path = encodeUri("/rooms/$roomId/joined_members", { $roomId: roomId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Get the public rooms list from the server. Supports pagination
* @param params - Options for this request
* @returns Promise which resolves: IPublicRoomsResponse
* @returns Rejects: with an error response.
* @throws May throw a `MatrixSafetyError` if content is deemed unsafe.
* @see MatrixSafetyError
*/
publicRooms() {
var _ref9 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var { server, limit, since } = _ref9, options = (0, import_objectWithoutProperties.default)(_ref9, _excluded);
if (Object.keys(options).length === 0) {
var queryParams = {
server,
limit,
since
};
return this.http.authedRequest(Method.Get, "/publicRooms", queryParams);
} else {
var _queryParams = { server };
var _body = _objectSpread$1({
limit,
since
}, options);
return this.http.authedRequest(Method.Post, "/publicRooms", _queryParams, _body);
}
}
/**
* Create an alias to room ID mapping.
* @param alias - The room alias to create.
* @param roomId - The room ID to link the alias to.
* @returns Promise which resolves: an empty object `{}`
* @returns Rejects: with an error response.
*/
createAlias(alias, roomId) {
var path = encodeUri("/directory/room/$alias", { $alias: alias });
var data = { room_id: roomId };
return this.http.authedRequest(Method.Put, path, void 0, data);
}
/**
* Delete an alias to room ID mapping. This alias must be on your local server,
* and you must have sufficient access to do this operation.
* @param alias - The room alias to delete.
* @returns Promise which resolves: an empty object `{}`.
* @returns Rejects: with an error response.
*/
deleteAlias(alias) {
var path = encodeUri("/directory/room/$alias", { $alias: alias });
return this.http.authedRequest(Method.Delete, path);
}
/**
* Gets the local aliases for the room. Note: this includes all local aliases, unlike the
* curated list from the m.room.canonical_alias state event.
* @param roomId - The room ID to get local aliases for.
* @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases
* @returns Rejects: with an error response.
*/
getLocalAliases(roomId) {
var path = encodeUri("/rooms/$roomId/aliases", { $roomId: roomId });
var prefix = ClientPrefix.V3;
return this.http.authedRequest(Method.Get, path, void 0, void 0, { prefix });
}
/**
* Get room info for the given alias.
* @param alias - The room alias to resolve.
* @returns Promise which resolves: Object with room_id and servers.
* @returns Rejects: with an error response.
*/
getRoomIdForAlias(alias) {
var path = encodeUri("/directory/room/$alias", { $alias: alias });
return this.http.authedRequest(Method.Get, path);
}
/**
* Get the visibility of a room in the current HS's room directory
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
getRoomDirectoryVisibility(roomId) {
var path = encodeUri("/directory/list/room/$roomId", { $roomId: roomId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Set the visibility of a room in the current HS's room directory
* @param visibility - "public" to make the room visible
* in the public directory, or "private" to make
* it invisible.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setRoomDirectoryVisibility(roomId, visibility) {
var path = encodeUri("/directory/list/room/$roomId", { $roomId: roomId });
return this.http.authedRequest(Method.Put, path, void 0, { visibility });
}
/**
* Query the user directory with a term matching user IDs, display names and domains.
* @param options
* @param options.term - the term with which to search.
* @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.
* @returns Promise which resolves: an array of results.
*/
searchUserDirectory(_ref0) {
var { term, limit } = _ref0;
var body = { search_term: term };
if (limit !== void 0) body.limit = limit;
return this.http.authedRequest(Method.Post, "/user_directory/search", void 0, body);
}
/**
* Upload a file to the media repository on the homeserver.
*
* @param file - The object to upload. On a browser, something that
* can be sent to XMLHttpRequest.send (typically a File). Under node.js,
* a a Buffer, String or ReadStream.
*
* @param opts - options object
*
* @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).
*/
uploadContent(file, opts) {
return this.http.uploadContent(file, opts);
}
/**
* Cancel a file upload in progress
* @param upload - The object returned from uploadContent
* @returns true if canceled, otherwise false
*/
cancelUpload(upload) {
return this.http.cancelUpload(upload);
}
/**
* Get a list of all file uploads in progress
* @returns Array of objects representing current uploads.
* Currently in progress is element 0. Keys:
* - promise: The promise associated with the upload
* - loaded: Number of bytes uploaded
* - total: Total number of bytes to upload
*/
getCurrentUploads() {
return this.http.getCurrentUploads();
}
/**
* @param info - The kind of info to retrieve (e.g. 'displayname',
* 'avatar_url').
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
*/
getProfileInfo(userId, info) {
var path = info ? encodeUri("/profile/$userId/$info", {
$userId: userId,
$info: info
}) : encodeUri("/profile/$userId", { $userId: userId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Determine if the server supports extended profiles, as described by MSC4133.
*
* @returns `true` if supported, otherwise `false`
*/
doesServerSupportExtendedProfiles() {
var _this62 = this;
return (0, import_asyncToGenerator.default)(function* () {
return (yield _this62.isVersionSupported("v1.16")) || (yield _this62.doesServerSupportUnstableFeature("uk.tcpip.msc4133")) || (yield _this62.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"));
})();
}
/**
* Get the prefix used for extended profile requests.
*
* @returns The prefix for use with `authedRequest`
*/
getExtendedProfileRequestPrefix() {
var _this63 = this;
return (0, import_asyncToGenerator.default)(function* () {
if ((yield _this63.isVersionSupported("v1.16")) || (yield _this63.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"))) return ClientPrefix.V3;
return "/_matrix/client/unstable/uk.tcpip.msc4133";
})();
}
/**
* Fetch a user's *extended* profile, which may include additional keys.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param userId The user ID to fetch the profile of.
* @returns A set of keys to property values.
*
* @throws An error if the server does not support MSC4133.
* @throws A M_NOT_FOUND error if the profile could not be found.
*/
getExtendedProfile(userId) {
var _this64 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this64.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
return _this64.http.authedRequest(Method.Get, encodeUri("/profile/$userId", { $userId: userId }), void 0, void 0, { prefix: yield _this64.getExtendedProfileRequestPrefix() });
})();
}
/**
* Fetch a specific key from the user's *extended* profile.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param userId The user ID to fetch the profile of.
* @param key The key of the property to fetch.
* @returns The property value.
*
* @throws An error if the server does not support MSC4133.
* @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.
*/
getExtendedProfileProperty(userId, key) {
var _this65 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this65.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
return (yield _this65.http.authedRequest(Method.Get, encodeUri("/profile/$userId/$key", {
$userId: userId,
$key: key
}), void 0, void 0, { prefix: yield _this65.getExtendedProfileRequestPrefix() }))[key];
})();
}
/**
* Set a property on your *extended* profile.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param key The key of the property to set.
* @param value The value to set on the property.
*
* @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.
*/
setExtendedProfileProperty(key, value) {
var _this66 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this66.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
var userId = _this66.getUserId();
yield _this66.http.authedRequest(Method.Put, encodeUri("/profile/$userId/$key", {
$userId: userId,
$key: key
}), void 0, { [key]: value }, { prefix: yield _this66.getExtendedProfileRequestPrefix() });
})();
}
/**
* Delete a property on your *extended* profile.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param key The key of the property to delete.
*
* @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.
*/
deleteExtendedProfileProperty(key) {
var _this67 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this67.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
var userId = _this67.getUserId();
yield _this67.http.authedRequest(Method.Delete, encodeUri("/profile/$userId/$key", {
$userId: userId,
$key: key
}), void 0, void 0, { prefix: yield _this67.getExtendedProfileRequestPrefix() });
})();
}
/**
* Update multiple properties on your *extended* profile. This will
* merge with any existing keys.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param profile The profile object to merge with the existing profile.
* @returns The newly merged profile.
*
* @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.
*/
patchExtendedProfile(profile) {
var _this68 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this68.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
var userId = _this68.getUserId();
return _this68.http.authedRequest(Method.Patch, encodeUri("/profile/$userId", { $userId: userId }), {}, profile, { prefix: yield _this68.getExtendedProfileRequestPrefix() });
})();
}
/**
* Set multiple properties on your *extended* profile. This will completely
* replace the existing profile, removing any unspecified keys.
*
* @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md
* @param profile The profile object to set.
*
* @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.
*/
setExtendedProfile(profile) {
var _this69 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!(yield _this69.doesServerSupportExtendedProfiles())) throw new Error("Server does not support extended profiles");
var userId = _this69.getUserId();
yield _this69.http.authedRequest(Method.Put, encodeUri("/profile/$userId", { $userId: userId }), {}, profile, { prefix: yield _this69.getExtendedProfileRequestPrefix() });
})();
}
/**
* @returns Promise which resolves to a list of the user's threepids.
* @returns Rejects: with an error response.
*/
getThreePids() {
return this.http.authedRequest(Method.Get, "/account/3pid");
}
/**
* Add a 3PID to your homeserver account. This API does not use an identity
* server, as the homeserver is expected to handle 3PID ownership validation.
*
* @param data - A object with 3PID validation data from having called
* `account/3pid/<medium>/requestToken` on the homeserver.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
addThreePidOnly(data) {
var _this70 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this70.http.authedRequest(Method.Post, "/account/3pid/add", void 0, data);
})();
}
/**
* Bind a 3PID for discovery onto an identity server via the homeserver. The
* identity server handles 3PID ownership validation and the homeserver records
* the new binding to track where all 3PIDs for the account are bound.
*
* @param data - A object with 3PID validation data from having called
* `validate/<medium>/requestToken` on the identity server. It should also
* contain `id_server` and `id_access_token` fields as well.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
bindThreePid(data) {
var _this71 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this71.http.authedRequest(Method.Post, "/account/3pid/bind", void 0, data);
})();
}
/**
* Unbind a 3PID for discovery on an identity server via the homeserver. The
* homeserver removes its record of the binding to keep an updated record of
* where all 3PIDs for the account are bound.
*
* @param medium - The threepid medium (eg. 'email')
* @param address - The threepid address (eg. 'bob\@example.com')
* this must be as returned by getThreePids.
* @returns Promise which resolves: on success
* @returns Rejects: with an error response.
*/
unbindThreePid(medium, address) {
var _this72 = this;
return (0, import_asyncToGenerator.default)(function* () {
var path = "/account/3pid/unbind";
var data = {
medium,
address,
id_server: _this72.getIdentityServerUrl(true)
};
return _this72.http.authedRequest(Method.Post, path, void 0, data);
})();
}
/**
* @param medium - The threepid medium (eg. 'email')
* @param address - The threepid address (eg. 'bob\@example.com')
* this must be as returned by getThreePids.
* @returns Promise which resolves: The server response on success
* (generally the empty JSON object)
* @returns Rejects: with an error response.
*/
deleteThreePid(medium, address) {
return this.http.authedRequest(Method.Post, "/account/3pid/delete", void 0, {
medium,
address
});
}
/**
* Make a request to change your password.
* @param newPassword - The new desired password.
* @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setPassword(authDict, newPassword, logoutDevices) {
var path = "/account/password";
var data = {
auth: authDict,
new_password: newPassword,
logout_devices: logoutDevices
};
return this.http.authedRequest(Method.Post, path, void 0, data);
}
/**
* Gets all devices recorded for the logged-in user
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
getDevices() {
return this.http.authedRequest(Method.Get, "/devices");
}
/**
* Gets specific device details for the logged-in user
* @param deviceId - device to query
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
getDevice(deviceId) {
var path = encodeUri("/devices/$device_id", { $device_id: deviceId });
return this.http.authedRequest(Method.Get, path);
}
/**
* Update the given device
*
* @param deviceId - device to update
* @param body - body of request
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setDeviceDetails(deviceId, body) {
var path = encodeUri("/devices/$device_id", { $device_id: deviceId });
return this.http.authedRequest(Method.Put, path, void 0, body);
}
/**
* Delete the given device
*
* @param deviceId - device to delete
* @param auth - Optional. Auth data to supply for User-Interactive auth.
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
deleteDevice(deviceId, auth) {
var path = encodeUri("/devices/$device_id", { $device_id: deviceId });
var body = {};
if (auth) body.auth = auth;
return this.http.authedRequest(Method.Delete, path, void 0, body);
}
/**
* Delete multiple device
*
* @param devices - IDs of the devices to delete
* @param auth - Optional. Auth data to supply for User-Interactive auth.
* @returns Promise which resolves: result object
* @returns Rejects: with an error response.
*/
deleteMultipleDevices(devices, auth) {
var body = { devices };
if (auth) body.auth = auth;
return this.http.authedRequest(Method.Post, "/delete_devices", void 0, body);
}
/**
* Gets all pushers registered for the logged-in user
*
* @returns Promise which resolves: Array of objects representing pushers
* @returns Rejects: with an error response.
*/
getPushers() {
var _this73 = this;
return (0, import_asyncToGenerator.default)(function* () {
var response = yield _this73.http.authedRequest(Method.Get, "/pushers");
if (!(yield _this73.doesServerSupportUnstableFeature("org.matrix.msc3881"))) response.pushers = response.pushers.map((pusher) => {
if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) pusher[PUSHER_ENABLED.name] = true;
return pusher;
});
return response;
})();
}
/**
* Adds a new pusher or updates an existing pusher
*
* @param pusher - Object representing a pusher
* @returns Promise which resolves: Empty json object on success
* @returns Rejects: with an error response.
*/
setPusher(pusher) {
return this.http.authedRequest(Method.Post, "/pushers/set", void 0, pusher);
}
/**
* Removes an existing pusher
* @param pushKey - pushkey of pusher to remove
* @param appId - app_id of pusher to remove
* @returns Promise which resolves: Empty json object on success
* @returns Rejects: with an error response.
*/
removePusher(pushKey, appId) {
var path = "/pushers/set";
var body = {
pushkey: pushKey,
app_id: appId,
kind: null
};
return this.http.authedRequest(Method.Post, path, void 0, body);
}
/**
* Persists local notification settings
* @returns Promise which resolves: an empty object
* @returns Rejects: with an error response.
*/
setLocalNotificationSettings(deviceId, notificationSettings) {
var key = "".concat(LOCAL_NOTIFICATION_SETTINGS_PREFIX.name, ".").concat(deviceId);
return this.setAccountData(key, notificationSettings);
}
/**
* Get the push rules for the account from the server.
* @returns Promise which resolves to the push rules.
* @returns Rejects: with an error response.
*/
getPushRules() {
return this.http.authedRequest(Method.Get, "/pushrules/").then((rules) => {
this.setPushRules(rules);
return this.pushRules;
});
}
/**
* Update the push rules for the account. This should be called whenever
* updated push rules are available.
*/
setPushRules(rules) {
this.pushRules = PushProcessor.rewriteDefaultRules(this.logger, rules, this.getUserId());
this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);
}
/**
* @returns Promise which resolves: an empty object `{}`
* @returns Rejects: with an error response.
*/
addPushRule(scope, kind, ruleId, body) {
var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind,
$ruleId: ruleId
});
return this.http.authedRequest(Method.Put, path, void 0, body);
}
/**
* @returns Promise which resolves: an empty object `{}`
* @returns Rejects: with an error response.
*/
deletePushRule(scope, kind, ruleId) {
var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind,
$ruleId: ruleId
});
return this.http.authedRequest(Method.Delete, path);
}
/**
* Enable or disable a push notification rule.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setPushRuleEnabled(scope, kind, ruleId, enabled) {
var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", {
$kind: kind,
$ruleId: ruleId
});
return this.http.authedRequest(Method.Put, path, void 0, { enabled });
}
/**
* Set the actions for a push notification rule.
* @returns Promise which resolves: to an empty object `{}`
* @returns Rejects: with an error response.
*/
setPushRuleActions(scope, kind, ruleId, actions) {
var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", {
$kind: kind,
$ruleId: ruleId
});
return this.http.authedRequest(Method.Put, path, void 0, { actions });
}
/**
* Perform a server-side search.
* @param params
* @param params.next_batch - the batch token to pass in the query string
* @param params.body - the JSON object to pass to the request body.
* @param abortSignal - optional signal used to cancel the http request.
* @returns Promise which resolves to the search response object.
* @returns Rejects: with an error response.
*/
search(_ref1, abortSignal) {
var { body, next_batch: nextBatch } = _ref1;
var queryParams = {};
if (nextBatch) queryParams.next_batch = nextBatch;
return this.http.authedRequest(Method.Post, "/search", queryParams, body, { abortSignal });
}
/**
* Upload keys
*
* @param content - body of upload request
*
* @param opts - this method no longer takes any opts,
* used to take opts.device_id but this was not removed from the spec as a redundant parameter
*
* @returns Promise which resolves: result object. Rejects: with
* an error response ({@link MatrixError}).
*/
uploadKeysRequest(content, opts) {
return this.http.authedRequest(Method.Post, "/keys/upload", void 0, content);
}
uploadKeySignatures(content) {
return this.http.authedRequest(Method.Post, "/keys/signatures/upload", void 0, content);
}
/**
* Download device keys
*
* @param userIds - list of users to get keys for
*
* @param token - sync token to pass in the query request, to help
* the HS give the most recent results
*
* @returns Promise which resolves: result object. Rejects: with
* an error response ({@link MatrixError}).
*/
downloadKeysForUsers(userIds) {
var { token } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var content = { device_keys: {} };
if (token !== void 0) content.token = token;
userIds.forEach((u) => {
content.device_keys[u] = [];
});
return this.http.authedRequest(Method.Post, "/keys/query", void 0, content);
}
/**
* Claim one-time keys
*
* @param devices - a list of [userId, deviceId] pairs
*
* @param keyAlgorithm - desired key type
*
* @param timeout - the time (in milliseconds) to wait for keys from remote
* servers
*
* @returns Promise which resolves: result object. Rejects: with
* an error response ({@link MatrixError}).
*/
claimOneTimeKeys(devices) {
var keyAlgorithm = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "signed_curve25519";
var timeout = arguments.length > 2 ? arguments[2] : void 0;
var queries = {};
if (keyAlgorithm === void 0) keyAlgorithm = "signed_curve25519";
for (var [userId, _deviceId] of devices) {
var query = queries[userId] || {};
safeSet(queries, userId, query);
safeSet(query, _deviceId, keyAlgorithm);
}
var content = { one_time_keys: queries };
if (timeout) content.timeout = timeout;
return this.http.authedRequest(Method.Post, "/keys/claim", void 0, content);
}
/**
* Ask the server for a list of users who have changed their device lists
* between a pair of sync tokens
*
*
* @returns Promise which resolves: result object. Rejects: with
* an error response ({@link MatrixError}).
*/
getKeyChanges(oldToken, newToken) {
var qps = {
from: oldToken,
to: newToken
};
return this.http.authedRequest(Method.Get, "/keys/changes", qps);
}
uploadDeviceSigningKeys(auth, keys) {
var data = Object.assign({}, keys);
if (auth) Object.assign(data, { auth });
return this.http.authedRequest(Method.Post, "/keys/device_signing/upload", void 0, data, { prefix: ClientPrefix.Unstable });
}
/**
* Register with an identity server using the OpenID token from the user's
* Homeserver, which can be retrieved via
* {@link MatrixClient#getOpenIdToken}.
*
* Note that the `/account/register` endpoint (as well as IS authentication in
* general) was added as part of the v2 API version.
*
* @returns Promise which resolves: with object containing an Identity
* Server access token.
* @returns Rejects: with an error response.
*/
registerWithIdentityServer(hsOpenIdToken) {
if (!this.idBaseUrl) throw new Error("No identity server base URL set");
var uri = this.http.getUrl("/account/register", void 0, IdentityPrefix.V2, this.idBaseUrl);
return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);
}
/**
* Requests an email verification token directly from an identity server.
*
* This API is used as part of binding an email for discovery on an identity
* server. The validation data that results should be passed to the
* `bindThreePid` method to complete the binding process.
*
* @param email - The email address to request a token for
* @param clientSecret - A secret binary string generated by the client.
* It is recommended this be around 16 ASCII characters.
* @param sendAttempt - If an identity server sees a duplicate request
* with the same sendAttempt, it will not send another email.
* To request another email to be sent, use a larger value for
* the sendAttempt param as was used in the previous request.
* @param nextLink - Optional If specified, the client will be redirected
* to this link after validation.
* @param identityAccessToken - The `access_token` field of the identity
* server `/account/register` response (see {@link registerWithIdentityServer}).
*
* @returns Promise which resolves: TODO
* @returns Rejects: with an error response.
* @throws Error if no identity server is set
*/
requestEmailToken(email, clientSecret, sendAttempt, nextLink, identityAccessToken) {
var params = {
client_secret: clientSecret,
email,
send_attempt: sendAttempt === null || sendAttempt === void 0 ? void 0 : sendAttempt.toString()
};
if (nextLink) params.next_link = nextLink;
return this.http.idServerRequest(Method.Post, "/validate/email/requestToken", params, IdentityPrefix.V2, identityAccessToken);
}
/**
* Requests a MSISDN verification token directly from an identity server.
*
* This API is used as part of binding a MSISDN for discovery on an identity
* server. The validation data that results should be passed to the
* `bindThreePid` method to complete the binding process.
*
* @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in
* which phoneNumber should be parsed relative to.
* @param phoneNumber - The phone number, in national or international
* format
* @param clientSecret - A secret binary string generated by the client.
* It is recommended this be around 16 ASCII characters.
* @param sendAttempt - If an identity server sees a duplicate request
* with the same sendAttempt, it will not send another SMS.
* To request another SMS to be sent, use a larger value for
* the sendAttempt param as was used in the previous request.
* @param nextLink - Optional If specified, the client will be redirected
* to this link after validation.
* @param identityAccessToken - The `access_token` field of the Identity
* Server `/account/register` response (see {@link registerWithIdentityServer}).
*
* @returns Promise which resolves to an object with a sid string
* @returns Rejects: with an error response.
* @throws Error if no identity server is set
*/
requestMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink, identityAccessToken) {
var params = {
client_secret: clientSecret,
country: phoneCountry,
phone_number: phoneNumber,
send_attempt: sendAttempt === null || sendAttempt === void 0 ? void 0 : sendAttempt.toString()
};
if (nextLink) params.next_link = nextLink;
return this.http.idServerRequest(Method.Post, "/validate/msisdn/requestToken", params, IdentityPrefix.V2, identityAccessToken);
}
/**
* Submits a MSISDN token to the identity server
*
* This is used when submitting the code sent by SMS to a phone number.
* The identity server has an equivalent API for email but the js-sdk does
* not expose this, since email is normally validated by the user clicking
* a link rather than entering a code.
*
* @param sid - The sid given in the response to requestToken
* @param clientSecret - A secret binary string generated by the client.
* This must be the same value submitted in the requestToken call.
* @param msisdnToken - The MSISDN token, as entered by the user.
* @param identityAccessToken - The `access_token` field of the Identity
* Server `/account/register` response (see {@link registerWithIdentityServer}).
* Some legacy identity servers had no authentication here.
*
* @returns Promise which resolves: Object, containing success boolean.
* @returns Rejects: with an error response.
* @throws Error if No identity server is set
*/
submitMsisdnToken(sid, clientSecret, msisdnToken, identityAccessToken) {
var params = {
sid,
client_secret: clientSecret,
token: msisdnToken
};
return this.http.idServerRequest(Method.Post, "/validate/msisdn/submitToken", params, IdentityPrefix.V2, identityAccessToken !== null && identityAccessToken !== void 0 ? identityAccessToken : void 0);
}
/**
* Submits a MSISDN token to an arbitrary URL.
*
* This is used when submitting the code sent by SMS to a phone number in the
* newer 3PID flow where the homeserver validates 3PID ownership (as part of
* `requestAdd3pidMsisdnToken`). The homeserver response may include a
* `submit_url` to specify where the token should be sent, and this helper can
* be used to pass the token to this URL.
*
* @param url - The URL to submit the token to
* @param sid - The sid given in the response to requestToken
* @param clientSecret - A secret binary string generated by the client.
* This must be the same value submitted in the requestToken call.
* @param msisdnToken - The MSISDN token, as entered by the user.
*
* @returns Promise which resolves: Object, containing success boolean.
* @returns Rejects: with an error response.
*/
submitMsisdnTokenOtherUrl(url, sid, clientSecret, msisdnToken) {
var params = {
sid,
client_secret: clientSecret,
token: msisdnToken
};
return this.http.requestOtherUrl(Method.Post, url, params);
}
/**
* Gets the V2 hashing information from the identity server. Primarily useful for
* lookups.
* @param identityAccessToken - The access token for the identity server.
* @returns The hashing information for the identity server.
*/
getIdentityHashDetails(identityAccessToken) {
return this.http.idServerRequest(Method.Get, "/hash_details", void 0, IdentityPrefix.V2, identityAccessToken);
}
/**
* Performs a hashed lookup of addresses against the identity server. This is
* only supported on identity servers which have at least the version 2 API.
* @param addressPairs - An array of 2 element arrays.
* The first element of each pair is the address, the second is the 3PID medium.
* Eg: `["email@example.org", "email"]`
* @param identityAccessToken - The access token for the identity server.
* @returns A collection of address mappings to
* found MXIDs. Results where no user could be found will not be listed.
*/
identityHashedLookup(addressPairs, identityAccessToken) {
var _this74 = this;
return (0, import_asyncToGenerator.default)(function* () {
var params = {};
var hashes = yield _this74.getIdentityHashDetails(identityAccessToken);
if (!hashes || !hashes["lookup_pepper"] || !hashes["algorithms"]) throw new Error("Unsupported identity server: bad response");
params["pepper"] = hashes["lookup_pepper"];
var localMapping = {};
if (hashes["algorithms"].includes("sha256")) {
params["addresses"] = yield Promise.all(addressPairs.map(/* @__PURE__ */ function() {
var _ref10 = (0, import_asyncToGenerator.default)(function* (p) {
var addr = p[0].toLowerCase();
var med = p[1].toLowerCase();
var hashed = encodeUnpaddedBase64Url(yield sha256("".concat(addr, " ").concat(med, " ").concat(params["pepper"])));
localMapping[hashed] = p[0];
return hashed;
});
return function(_x4) {
return _ref10.apply(this, arguments);
};
}()));
params["algorithm"] = "sha256";
} else if (hashes["algorithms"].includes("none")) {
params["addresses"] = addressPairs.map((p) => {
var addr = p[0].toLowerCase();
var med = p[1].toLowerCase();
var unhashed = "".concat(addr, " ").concat(med);
localMapping[unhashed] = p[0];
return unhashed;
});
params["algorithm"] = "none";
} else throw new Error("Unsupported identity server: unknown hash algorithm");
var response = yield _this74.http.idServerRequest(Method.Post, "/lookup", params, IdentityPrefix.V2, identityAccessToken);
if (!(response !== null && response !== void 0 && response["mappings"])) return [];
var foundAddresses = [];
for (var hashed of Object.keys(response["mappings"])) {
var mxid = response["mappings"][hashed];
var plainAddress = localMapping[hashed];
if (!plainAddress) throw new Error("Identity server returned more results than expected");
foundAddresses.push({
address: plainAddress,
mxid
});
}
return foundAddresses;
})();
}
/**
* Looks up the public Matrix ID mapping for a given 3rd party
* identifier from the identity server
*
* @param medium - The medium of the threepid, eg. 'email'
* @param address - The textual address of the threepid
* @param identityAccessToken - The `access_token` field of the Identity
* Server `/account/register` response (see {@link registerWithIdentityServer}).
*
* @returns Promise which resolves: A threepid mapping
* object or the empty object if no mapping
* exists
* @returns Rejects: with an error response.
*/
lookupThreePid(medium, address, identityAccessToken) {
var _this75 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = (yield _this75.identityHashedLookup([[address, medium]], identityAccessToken)).find((p) => p.address === address);
if (!result) return {};
return {
address,
medium,
mxid: result.mxid
};
})();
}
/**
* Looks up the public Matrix ID mappings for multiple 3PIDs.
*
* @param query - Array of arrays containing
* [medium, address]
* @param identityAccessToken - The `access_token` field of the Identity
* Server `/account/register` response (see {@link registerWithIdentityServer}).
*
* @returns Promise which resolves: Lookup results from IS.
* @returns Rejects: with an error response.
*/
bulkLookupThreePids(query, identityAccessToken) {
var _this76 = this;
return (0, import_asyncToGenerator.default)(function* () {
var response = yield _this76.identityHashedLookup(query.map((p) => [p[1], p[0]]), identityAccessToken);
var v1results = [];
var _loop2 = function* _loop2(mapping) {
var originalQuery = query.find((p) => p[1] === mapping.address);
if (!originalQuery) throw new Error("Identity sever returned unexpected results");
v1results.push([
originalQuery[0],
mapping.address,
mapping.mxid
]);
};
for (var mapping of response) yield* _loop2(mapping);
return { threepids: v1results };
})();
}
/**
* Get account info from the identity server. This is useful as a neutral check
* to verify that other APIs are likely to approve access by testing that the
* token is valid, terms have been agreed, etc.
*
* @param identityAccessToken - The `access_token` field of the Identity
* Server `/account/register` response (see {@link registerWithIdentityServer}).
*
* @returns Promise which resolves: an object with account info.
* @returns Rejects: with an error response.
*/
getIdentityAccount(identityAccessToken) {
return this.http.idServerRequest(Method.Get, "/account", void 0, IdentityPrefix.V2, identityAccessToken);
}
/**
* Send an event to a specific list of devices.
* This is a low-level API that simply wraps the HTTP API
* call to send to-device messages. We recommend using
* queueToDevice() which is a higher level API.
*
* @param eventType - type of event to send
* content to send. Map from user_id to device_id to content object.
* @param txnId - transaction id. One will be made up if not
* supplied.
* @returns Promise which resolves: to an empty object `{}`
*/
sendToDevice(eventType, contentMap, txnId) {
var path = encodeUri("/sendToDevice/$eventType/$txnId", {
$eventType: eventType,
$txnId: txnId ? txnId : this.makeTxnId()
});
var body = { messages: recursiveMapToObject(contentMap) };
var targets = /* @__PURE__ */ new Map();
for (var [userId, deviceMessages] of contentMap) targets.set(userId, Array.from(deviceMessages.keys()));
this.logger.debug("PUT ".concat(path), targets);
return this.http.authedRequest(Method.Put, path, void 0, body);
}
/**
* This will encrypt the payload for all devices in the list and will queue it.
* The type of the sent to-device message will be `m.room.encrypted`.
* @param eventType - The type of event to send
* @param devices - The list of devices to send the event to.
* @param payload - The payload to send. This will be encrypted.
* @returns Promise which resolves once queued there is no error feedback when sending fails.
*/
encryptAndSendToDevice(eventType, devices, payload) {
var _this77 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!_this77.cryptoBackend) throw new Error("Cannot encrypt to device event, your client does not support encryption.");
var batch = yield _this77.cryptoBackend.encryptToDeviceMessages(eventType, devices, payload);
yield _this77.queueToDevice(batch);
})();
}
/**
* Sends events directly to specific devices using Matrix's to-device
* messaging system. The batch will be split up into appropriately sized
* batches for sending and stored in the store so they can be retried
* later if they fail to send. Retries will happen automatically.
* @param batch - The to-device messages to send
*/
queueToDevice(batch) {
return this.toDeviceMessageQueue.queueBatch(batch);
}
/**
* Get the third party protocols that can be reached using
* this HS
* @returns Promise which resolves to the result object
*/
getThirdpartyProtocols() {
return this.http.authedRequest(Method.Get, "/thirdparty/protocols").then((response) => {
if (!response || typeof response !== "object") throw new Error("/thirdparty/protocols did not return an object: ".concat(response));
return response;
});
}
/**
* Get information on how a specific place on a third party protocol
* may be reached.
* @param protocol - The protocol given in getThirdpartyProtocols()
* @param params - Protocol-specific parameters, as given in the
* response to getThirdpartyProtocols()
* @returns Promise which resolves to the result object
*/
getThirdpartyLocation(protocol, params) {
var path = encodeUri("/thirdparty/location/$protocol", { $protocol: protocol });
return this.http.authedRequest(Method.Get, path, params);
}
/**
* Get information on how a specific user on a third party protocol
* may be reached.
* @param protocol - The protocol given in getThirdpartyProtocols()
* @param params - Protocol-specific parameters, as given in the
* response to getThirdpartyProtocols()
* @returns Promise which resolves to the result object
*/
getThirdpartyUser(protocol, params) {
var path = encodeUri("/thirdparty/user/$protocol", { $protocol: protocol });
return this.http.authedRequest(Method.Get, path, params);
}
getTerms(serviceType, baseUrl) {
var url = this.termsUrlForService(serviceType, baseUrl);
return this.http.requestOtherUrl(Method.Get, url);
}
agreeToTerms(serviceType, baseUrl, accessToken, termsUrls) {
var url = this.termsUrlForService(serviceType, baseUrl);
var headers = { Authorization: "Bearer " + accessToken };
return this.http.requestOtherUrl(Method.Post, url, { user_accepts: termsUrls }, { headers });
}
/**
* Reports an event as inappropriate to the server, which may then notify the appropriate people.
* @param roomId - The room in which the event being reported is located.
* @param eventId - The event to report.
* @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.
* @param reason - The reason the content is being reported. May be blank.
* @returns Promise which resolves to an empty object if successful
*/
reportEvent(roomId, eventId, score, reason) {
var path = encodeUri("/rooms/$roomId/report/$eventId", {
$roomId: roomId,
$eventId: eventId
});
return this.http.authedRequest(Method.Post, path, void 0, {
score,
reason
});
}
/**
* Reports a room as inappropriate to the server, which may then notify the appropriate people.
*
* This API was introduced in Matrix v1.13.
*
* @param roomId - The room being reported.
* @param reason - The reason the room is being reported. May be blank.
* @returns Promise which resolves to an empty object if successful
*/
reportRoom(roomId, reason) {
var path = encodeUri("/rooms/$roomId/report", { $roomId: roomId });
return this.http.authedRequest(Method.Post, path, void 0, { reason });
}
/**
* Fetches or paginates a room hierarchy asmatrix-js-sdk/spec/unit/matrix-client.spec.ts defined by MSC2946.
* Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.
* @param roomId - The ID of the space-room to use as the root of the summary.
* @param limit - The maximum number of rooms to return per page.
* @param maxDepth - The maximum depth in the tree from the root room to return.
* @param suggestedOnly - Whether to only return rooms with suggested=true.
* @param fromToken - The opaque token to paginate a previous request.
* @returns the response, with next_batch & rooms fields.
*/
getRoomHierarchy(roomId, limit, maxDepth) {
var suggestedOnly = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
var fromToken = arguments.length > 4 ? arguments[4] : void 0;
var path = encodeUri("/rooms/$roomId/hierarchy", { $roomId: roomId });
var queryParams = {
suggested_only: String(suggestedOnly),
max_depth: maxDepth === null || maxDepth === void 0 ? void 0 : maxDepth.toString(),
from: fromToken,
limit: limit === null || limit === void 0 ? void 0 : limit.toString()
};
return this.http.authedRequest(Method.Get, path, queryParams, void 0, { prefix: ClientPrefix.V1 }).catch((e) => {
if (e.errcode === "M_UNRECOGNIZED") return this.http.authedRequest(Method.Get, path, queryParams, void 0, { prefix: "/_matrix/client/unstable/org.matrix.msc2946" });
throw e;
});
}
/**
* Creates a new file tree space with the given name. The client will pick
* defaults for how it expects to be able to support the remaining API offered
* by the returned class.
*
* Note that this is UNSTABLE and may have breaking changes without notice.
* @param name - The name of the tree space.
* @returns Promise which resolves to the created space.
*/
unstableCreateFileTree(name) {
var _this78 = this;
return (0, import_asyncToGenerator.default)(function* () {
var { room_id: roomId } = yield _this78.createRoom({
name,
preset: Preset.PrivateChat,
power_level_content_override: _objectSpread$1(_objectSpread$1({}, DEFAULT_TREE_POWER_LEVELS_TEMPLATE), {}, { users: { [_this78.getUserId()]: 100 } }),
creation_content: { [RoomCreateTypeField]: RoomType.Space },
initial_state: [{
type: UNSTABLE_MSC3088_PURPOSE.name,
state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,
content: { [UNSTABLE_MSC3088_ENABLED.name]: true }
}, {
type: EventType.RoomEncryption,
state_key: "",
content: { algorithm: "m.megolm.v1.aes-sha2" }
}]
});
return new MSC3089TreeSpace(_this78, roomId);
})();
}
/**
* Gets a reference to a tree space, if the room ID given is a tree space. If the room
* does not appear to be a tree space then null is returned.
*
* Note that this is UNSTABLE and may have breaking changes without notice.
* @param roomId - The room ID to get a tree space reference for.
* @returns The tree space, or null if not a tree space.
*/
unstableGetFileTreeSpace(roomId) {
var _purposeEvent$getCont, _createEvent$getConte;
var room = this.getRoom(roomId);
if ((room === null || room === void 0 ? void 0 : room.getMyMembership()) !== KnownMembership.Join) return null;
var createEvent = room.currentState.getStateEvents(EventType.RoomCreate, "");
var purposeEvent = room.currentState.getStateEvents(UNSTABLE_MSC3088_PURPOSE.name, UNSTABLE_MSC3089_TREE_SUBTYPE.name);
if (!createEvent) throw new Error("Expected single room create event");
if (!(purposeEvent !== null && purposeEvent !== void 0 && (_purposeEvent$getCont = purposeEvent.getContent()) !== null && _purposeEvent$getCont !== void 0 && _purposeEvent$getCont[UNSTABLE_MSC3088_ENABLED.name])) return null;
if (((_createEvent$getConte = createEvent.getContent()) === null || _createEvent$getConte === void 0 ? void 0 : _createEvent$getConte["type"]) !== RoomType.Space) return null;
return new MSC3089TreeSpace(this, roomId);
}
/**
* Perform a single MSC3575 sliding sync request.
* @param req - The request to make.
* @param proxyBaseUrl - The base URL for the sliding sync proxy.
* @param abortSignal - Optional signal to abort request mid-flight.
* @returns The sliding sync response, or a standard error.
* @throws on non 2xx status codes with an object with a field "httpStatus":number.
*/
slidingSync(req, proxyBaseUrl, abortSignal) {
var qps = {};
if (req.pos) {
qps.pos = req.pos;
delete req.pos;
}
if (req.timeout) {
qps.timeout = req.timeout;
delete req.timeout;
}
var clientTimeout = req.clientTimeout;
delete req.clientTimeout;
return this.http.authedRequest(Method.Post, "/sync", qps, req, {
prefix: "/_matrix/client/unstable/org.matrix.simplified_msc3575",
baseUrl: proxyBaseUrl,
localTimeoutMs: clientTimeout,
abortSignal
});
}
/**
* A helper to determine thread support
* @returns a boolean to determine if threads are enabled
*/
supportsThreads() {
var _this$clientOpts4;
return ((_this$clientOpts4 = this.clientOpts) === null || _this$clientOpts4 === void 0 ? void 0 : _this$clientOpts4.threadSupport) || false;
}
/**
* A helper to determine intentional mentions support
* @returns a boolean to determine if intentional mentions are enabled on the server
* @experimental
*/
supportsIntentionalMentions() {
return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;
}
/**
* Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse
* Proposed at https://github.com/matrix-org/matrix-doc/pull/3266
* @param roomIdOrAlias - The ID or alias of the room to get the summary of.
* @param via - The list of servers which know about the room if only an ID was provided.
*/
getRoomSummary(roomIdOrAlias, via) {
var _this79 = this;
return (0, import_asyncToGenerator.default)(function* () {
var paramOpts = { prefix: "/_matrix/client/unstable/im.nheko.summary" };
try {
var path = encodeUri("/summary/$roomid", { $roomid: roomIdOrAlias });
return yield _this79.http.authedRequest(Method.Get, path, { via }, void 0, paramOpts);
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_UNRECOGNIZED") {
var _path = encodeUri("/rooms/$roomid/summary", { $roomid: roomIdOrAlias });
return yield _this79.http.authedRequest(Method.Get, _path, { via }, void 0, paramOpts);
} else throw e;
}
})();
}
/**
* Processes a list of threaded events and adds them to their respective timelines
* @param room - the room the adds the threaded events
* @param threadedEvents - an array of the threaded events
* @param toStartOfTimeline - the direction in which we want to add the events
*/
processThreadEvents(room, threadedEvents, toStartOfTimeline) {
room.processThreadedEvents(threadedEvents, toStartOfTimeline);
}
/**
* Processes a list of thread roots and creates a thread model
* @param room - the room to create the threads in
* @param threadedEvents - an array of thread roots
* @param toStartOfTimeline - the direction
*/
processThreadRoots(room, threadedEvents, toStartOfTimeline) {
if (!this.supportsThreads()) return;
room.processThreadRoots(threadedEvents, toStartOfTimeline);
}
processBeaconEvents(room, events) {
this.processAggregatedTimelineEvents(room, events);
}
/**
* Calls aggregation functions for event types that are aggregated
* Polls and location beacons
* @param room - room the events belong to
* @param events - timeline events to be processed
* @returns
*/
processAggregatedTimelineEvents(room, events) {
if (!(events !== null && events !== void 0 && events.length)) return;
if (!room) return;
room.currentState.processBeaconEvents(events, this);
room.processPollEvents(events);
}
/**
* Fetches information about the user for the configured access token.
*/
whoami() {
var _this80 = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this80.http.authedRequest(Method.Get, "/account/whoami");
})();
}
/**
* Find the event_id closest to the given timestamp in the given direction.
* @returns Resolves: A promise of an object containing the event_id and
* origin_server_ts of the closest event to the timestamp in the given direction
* @returns Rejects: when the request fails (module:http-api.MatrixError)
*/
timestampToEvent(roomId, timestamp, dir) {
var _this81 = this;
return (0, import_asyncToGenerator.default)(function* () {
var path = encodeUri("/rooms/$roomId/timestamp_to_event", { $roomId: roomId });
var queryParams = {
ts: timestamp.toString(),
dir
};
try {
return yield _this81.http.authedRequest(Method.Get, path, queryParams, void 0, { prefix: ClientPrefix.V1 });
} catch (err) {
if (err.errcode === "M_UNRECOGNIZED" && (err.httpStatus === 400 || err.httpStatus === 404 || err.httpStatus === 405)) return yield _this81.http.authedRequest(Method.Get, path, queryParams, void 0, { prefix: "/_matrix/client/unstable/org.matrix.msc3030" });
throw err;
}
})();
}
/**
* Discover and validate the auth metadata for the OAuth 2.0 API.
*
* Fetches /auth_metadata falling back to legacy implementation using /auth_issuer followed by
* https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.
* When successful, validated metadata is returned.
*
* @returns validated authentication metadata and optionally signing keys
* @throws when delegated auth config is invalid or unreachable
*/
getAuthMetadata() {
var _this82 = this;
return (0, import_asyncToGenerator.default)(function* () {
var authMetadata;
try {
var useStable = yield _this82.isVersionSupported("v1.15");
authMetadata = yield _this82.http.request(Method.Get, "/auth_metadata", void 0, void 0, { prefix: useStable ? ClientPrefix.V1 : ClientPrefix.Unstable + "/org.matrix.msc2965" });
} catch (e) {
if (e instanceof MatrixError && e.errcode === "M_UNRECOGNIZED") {
var { issuer } = yield _this82.http.request(Method.Get, "/auth_issuer", void 0, void 0, { prefix: ClientPrefix.Unstable + "/org.matrix.msc2965" });
return discoverAndValidateOIDCIssuerWellKnown(issuer);
}
throw e;
}
return validateAuthMetadataAndKeys(authMetadata);
})();
}
};
(0, import_defineProperty.default)(MatrixClient, "RESTORE_BACKUP_ERROR_BAD_KEY", "RESTORE_BACKUP_ERROR_BAD_KEY");
function getUnstableDelayQueryOpts(delayOpts) {
return Object.fromEntries(Object.entries(delayOpts).map((_ref11) => {
var [k, v] = _ref11;
return ["".concat(UNSTABLE_MSC4140_DELAYED_EVENTS, ".").concat(k), v];
}));
}
/**
* recalculates an accurate notifications count on event decryption.
* Servers do not have enough knowledge about encrypted events to calculate an
* accurate notification_count
*/
function fixNotificationCountOnDecryption(cli, event) {
var _actions$tweaks;
var ourUserId = cli.getUserId();
var eventId = event.getId();
var room = cli.getRoom(event.getRoomId());
if (!room || !ourUserId || !eventId) return;
if (!room.findEventById(eventId)) {
logger$2.info("Decrypted event ".concat(event.getId(), " is not in room ").concat(room.roomId, ": ignoring"));
return;
}
var isThreadEvent = !!event.threadRootId && !event.isThreadRoot;
var hasReadEvent;
if (isThreadEvent) {
var thread = room.getThread(event.threadRootId);
hasReadEvent = thread ? thread.hasUserReadEvent(ourUserId, eventId) : true;
} else hasReadEvent = room.hasUserReadEvent(ourUserId, eventId);
if (hasReadEvent) return;
var actions = cli.getPushActionsForEvent(event, true);
if (!!(actions !== null && actions !== void 0 && (_actions$tweaks = actions.tweaks) !== null && _actions$tweaks !== void 0 && _actions$tweaks.highlight)) {
var newCount = room.getUnreadCountForEventContext(NotificationCountType.Highlight, event) + 1;
if (isThreadEvent) room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Highlight, newCount);
else room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);
}
if (!!(actions !== null && actions !== void 0 && actions.notify)) {
var _newCount = room.getUnreadCountForEventContext(NotificationCountType.Total, event) + 1;
if (isThreadEvent) room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Total, _newCount);
else room.setUnreadNotificationCount(NotificationCountType.Total, _newCount);
}
}
/**
* Given an event, figure out the thread ID we should use for it in a receipt.
*
* This will either be "main", or event.threadRootId. For the thread root, or
* e.g. reactions to the thread root, this will be main. For events inside the
* thread, or e.g. reactions to them, this will be event.threadRootId.
*
* (Exported for test.)
*/
function threadIdForReceipt(event) {
return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId;
}
/**
* a) True for non-threaded messages, thread roots and non-thread relations to thread roots.
* b) False for messages with thread relations to the thread root.
* c) False for messages with any kind of relation to a message from case b.
*
* Note: true for redactions of messages that are in threads. Redacted messages
* are not really in threads (because their relations are gone), so if they look
* like they are in threads, that is a sign of a bug elsewhere. (At time of
* writing, this bug definitely exists - messages are not moved to another
* thread when they are redacted.)
*
* @returns true if this event is considered to be in the main timeline as far
* as receipts are concerned.
*/
function inMainTimelineForReceipt(event) {
if (!event.threadRootId) return true;
if (event.isThreadRoot) return true;
if (!event.isRelation()) {
logger$2.warn("Event is not a relation or a thread root, but still has a threadRootId! id=".concat(event.getId()));
return true;
}
if (event.isRelation(THREAD_RELATION_TYPE.name)) return false;
return event.relationEventId === event.threadRootId;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/thread.js
function 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;
}
function _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) {
(0, import_defineProperty.default)(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;
}
var ThreadEvent = /* @__PURE__ */ function(ThreadEvent) {
ThreadEvent["New"] = "Thread.new";
ThreadEvent["Update"] = "Thread.update";
ThreadEvent["NewReply"] = "Thread.newReply";
ThreadEvent["ViewThread"] = "Thread.viewThread";
ThreadEvent["Delete"] = "Thread.delete";
return ThreadEvent;
}({});
var FeatureSupport = /* @__PURE__ */ function(FeatureSupport) {
FeatureSupport[FeatureSupport["None"] = 0] = "None";
FeatureSupport[FeatureSupport["Experimental"] = 1] = "Experimental";
FeatureSupport[FeatureSupport["Stable"] = 2] = "Stable";
return FeatureSupport;
}({});
function determineFeatureSupport(stable, unstable) {
if (stable) return FeatureSupport.Stable;
else if (unstable) return FeatureSupport.Experimental;
else return FeatureSupport.None;
}
var Thread = class Thread extends ReadReceipt {
constructor(id, rootEvent, opts) {
var _this, _opts$pendingEventOrd;
super();
_this = this;
this.id = id;
this.rootEvent = rootEvent;
/**
* A reference to all the events ID at the bottom of the threads
*/
(0, import_defineProperty.default)(this, "timelineSet", void 0);
(0, import_defineProperty.default)(this, "_currentUserParticipated", false);
(0, import_defineProperty.default)(this, "reEmitter", void 0);
/**
* The last event in this thread, if we don't yet have this in the timeline.
*
* When we run {@link processRootEvent} (which I think happens during the
* setting-up of the thread), we set this to the event pointed to by the
* server in `latest_event` [1] that came through with the thread root.
*
* [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships
*
* Later, when we have populated the timeline, this is set to undefined, so
* that methods like {@link replyToEvent} fall through to use lastReply,
* which looks in the timeline for the latest event that is a "thread reply"
* i.e. directly refers to the thread root with an m.thread relation.
*
* So it looks like this is only really relevant when initialEventsFetched
* is false, because as soon as the initial events have been fetched, we
* should have a proper chunk of timeline from the pagination fetch.
*
* If all replies in this thread are redacted, this is set to the root
* event. I'm not clear what the meaning of this is, since usually after the
* initial events have been fetched, lastEvent should be undefined.
* In fact, the whole usage inside onRedaction looks suspect - it may be
* that we were thinking lastEvent always refers to the actual last event,
* but it only does so before initialEventsFetched becomes true.
*
* The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd
* think we probably mean {@link replyToEvent} there - we are trying not to
* echo a duplicate event, and we probably want that behaviour even after
* initialEventsFetched has become true.
*
* -- andyb
*/
(0, import_defineProperty.default)(this, "lastEvent", void 0);
(0, import_defineProperty.default)(this, "replyCount", 0);
(0, import_defineProperty.default)(this, "lastPendingEvent", void 0);
(0, import_defineProperty.default)(this, "pendingReplyCount", 0);
(0, import_defineProperty.default)(this, "room", void 0);
(0, import_defineProperty.default)(this, "client", void 0);
(0, import_defineProperty.default)(this, "pendingEventOrdering", void 0);
(0, import_defineProperty.default)(this, "processRootEventPromise", void 0);
/**
* Whether or not we need to fetch the initial set of events for the thread. We can
* only do this if the server has support for it, so if it doesn't we just pretend
* that we've already fetched them.
*/
(0, import_defineProperty.default)(this, "initialEventsFetched", !Thread.hasServerSideSupport);
(0, import_defineProperty.default)(this, "initalEventFetchProm", void 0);
/**
* An array of events to add to the timeline once the thread has been initialised
* with server suppport.
*/
(0, import_defineProperty.default)(this, "replayEvents", []);
(0, import_defineProperty.default)(this, "onTimelineReset", /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
yield _this.processRootEventPromise;
_this.processRootEventPromise = void 0;
}));
(0, import_defineProperty.default)(this, "onBeforeRedaction", (event, redaction) => {
if (event !== null && event !== void 0 && event.isRelation(THREAD_RELATION_TYPE.name) && this.room.eventShouldLiveIn(event).threadId === this.id && event.getId() !== this.id && !redaction.status) {
this.replyCount--;
this.updatePendingReplyCount();
this.emit(ThreadEvent.Update, this);
}
});
(0, import_defineProperty.default)(this, "onRedaction", /* @__PURE__ */ function() {
var _ref2 = (0, import_asyncToGenerator.default)(function* (event, room, threadRootId) {
if (threadRootId !== _this.id) return;
if (_this.replyCount <= 0) {
for (var threadEvent of _this.timeline) _this.clearEventMetadata(threadEvent);
_this.lastEvent = _this.rootEvent;
_this._currentUserParticipated = false;
_this.emit(ThreadEvent.Delete, _this);
} else {
var _this$lastEvent;
if (((_this$lastEvent = _this.lastEvent) === null || _this$lastEvent === void 0 ? void 0 : _this$lastEvent.getId()) === event.getAssociatedId()) {
yield _this.processRootEventPromise;
_this.processRootEventPromise = void 0;
}
yield _this.updateThreadMetadata();
}
});
return function(_x, _x2, _x3) {
return _ref2.apply(this, arguments);
};
}());
(0, import_defineProperty.default)(this, "onTimelineEvent", (event, room, toStartOfTimeline) => {
if (!toStartOfTimeline) {
var sender = event.getSender();
if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) room.addLocalEchoReceipt(sender, event, ReceiptType.Read);
if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) this.replyCount++;
}
this.onEcho(event, toStartOfTimeline !== null && toStartOfTimeline !== void 0 ? toStartOfTimeline : false);
});
(0, import_defineProperty.default)(this, "onLocalEcho", (event) => {
this.onEcho(event, false);
});
(0, import_defineProperty.default)(this, "onEcho", /* @__PURE__ */ function() {
var _ref3 = (0, import_asyncToGenerator.default)(function* (event, toStartOfTimeline) {
if (event.threadRootId !== _this.id) return;
if (_this.lastEvent === event) return;
yield _this.updateThreadMetadata();
if (!event.isRelation(THREAD_RELATION_TYPE.name)) return;
if (toStartOfTimeline) return;
_this.lastEvent = void 0;
_this.emit(ThreadEvent.NewReply, _this, event);
});
return function(_x4, _x5) {
return _ref3.apply(this, arguments);
};
}());
this.setMaxListeners(1e3);
if (!(opts !== null && opts !== void 0 && opts.room)) throw new Error("element-web#22141: A thread requires a room in order to function");
this.room = opts.room;
this.client = opts.client;
this.pendingEventOrdering = (_opts$pendingEventOrd = opts.pendingEventOrdering) !== null && _opts$pendingEventOrd !== void 0 ? _opts$pendingEventOrd : PendingEventOrdering.Chronological;
this.timelineSet = new EventTimelineSet(this.room, {
timelineSupport: true,
pendingEvents: true
}, this.client, this);
this.reEmitter = new TypedReEmitter(this);
this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);
this.room.on(RoomEvent.Redaction, this.onRedaction);
this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);
this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);
this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);
this.processReceipts(opts.receipts);
this.updateThreadMetadata();
this.setEventMetadata(this.rootEvent);
}
fetchRootEvent() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
try {
var eventData = yield _this2.client.fetchRoomEvent(_this2.roomId, _this2.id);
_this2.rootEvent = _this2.client.getEventMapper()(eventData);
} catch (e) {
logger$2.error("Failed to fetch thread root to construct thread with", e);
}
yield _this2.processEvent(_this2.rootEvent);
})();
}
static setServerSideSupport(status) {
Thread.hasServerSideSupport = status;
if (status !== FeatureSupport.Stable) {
FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);
FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);
THREAD_RELATION_TYPE.setPreferUnstable(true);
}
}
static setServerSideListSupport(status) {
Thread.hasServerSideListSupport = status;
}
static setServerSideFwdPaginationSupport(status) {
Thread.hasServerSideFwdPaginationSupport = status;
}
shouldSendLocalEchoReceipt(sender, event) {
var _this$client$canSuppo;
if (((_this$client$canSuppo = this.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this$client$canSuppo !== void 0 ? _this$client$canSuppo : ServerSupport.Unsupported) === ServerSupport.Unsupported) {
var _this$getReadReceiptF;
var oldReceiptEventId = (_this$getReadReceiptF = this.getReadReceiptForUserId(sender)) === null || _this$getReadReceiptF === void 0 ? void 0 : _this$getReadReceiptF.eventId;
if (oldReceiptEventId) {
var receiptEvent = this.findEventById(oldReceiptEventId);
if (receiptEvent && receiptEvent.getTs() > event.getTs()) return false;
}
}
return true;
}
get roomState() {
return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS);
}
addEventToTimeline(event, toStartOfTimeline) {
if (!this.findEventById(event.getId())) this.timelineSet.addEventToTimeline(event, this.liveTimeline, {
toStartOfTimeline,
fromCache: false,
roomState: this.roomState,
addToState: false
});
}
/**
* TEMPORARY. Only call this when MSC3981 is not available, and we have some
* late-arriving events to insert, because we recursively found them as part
* of populating a thread. When we have MSC3981 we won't need it, because
* they will all be supplied by the homeserver in one request, and they will
* already be in the right order in that response.
* This is a copy of addEventToTimeline above, modified to call
* insertEventIntoTimeline so this event is inserted into our best guess of
* the right place based on timestamp. (We should be using Sync Order but we
* don't have it.)
*
* @internal
*/
insertEventIntoTimeline(event) {
var eventId = event.getId();
if (!eventId) return;
if (this.findEventById(eventId)) return;
this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);
}
addEvents(events, toStartOfTimeline) {
events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));
this.updateThreadMetadata();
}
/**
* Add an event to the thread and updates
* the tail/root references if needed
* Will fire "Thread.update"
* @param event - The event to add
* @param toStartOfTimeline - whether the event is being added
* to the start (and not the end) of the timeline.
* @param emit - whether to emit the Update event if the thread was updated or not.
*/
addEvent(event, toStartOfTimeline) {
var emit = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
this.setEventMetadata(event);
var lastReply = this.lastReply();
var isNewestReply = !lastReply || event.localTimestamp >= lastReply.localTimestamp;
if (!Thread.hasServerSideSupport) {
this.addEventToTimeline(event, toStartOfTimeline);
this.client.decryptEventIfNeeded(event);
} else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {
this.addRelatedThreadEvent(event, toStartOfTimeline);
return;
} else if (!toStartOfTimeline && isNewestReply) {
this.addEventToTimeline(event, false);
this.fetchEditsWhereNeeded(event);
} else if (toStartOfTimeline) this.addEventToTimeline(event, toStartOfTimeline);
else this.insertEventIntoTimeline(event);
if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name) && !toStartOfTimeline && isNewestReply) this.lastEvent = void 0;
if (emit) {
this.emit(ThreadEvent.NewReply, this, event);
this.updateThreadMetadata();
}
}
addRelatedThreadEvent(event, toStartOfTimeline) {
if (!this.initialEventsFetched) {
var _this$replayEvents;
/**
* A thread can be fully discovered via a single sync response
* And when that's the case we still ask the server to do an initialisation
* as it's the safest to ensure we have everything.
* However when we are in that scenario we might loose annotation or edits
*
* This fix keeps a reference to those events and replay them once the thread
* has been initialised properly.
*/
(_this$replayEvents = this.replayEvents) === null || _this$replayEvents === void 0 || _this$replayEvents.push(event);
if (event.isRelation(RelationType.Annotation)) {
var _this$timelineSet$rel;
(_this$timelineSet$rel = this.timelineSet.relations) === null || _this$timelineSet$rel === void 0 || _this$timelineSet$rel.aggregateChildEvent(event, this.timelineSet);
}
} else {
var _this$client$canSuppo2;
if (((_this$client$canSuppo2 = this.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this$client$canSuppo2 !== void 0 ? _this$client$canSuppo2 : ServerSupport.Unsupported) === ServerSupport.Unsupported) this.insertEventIntoTimeline(event);
else this.addEventToTimeline(event, toStartOfTimeline);
}
}
processEvent(event) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (event) {
_this3.setEventMetadata(event);
yield _this3.fetchEditsWhereNeeded(event);
}
})();
}
/**
* Processes the receipts that were caught during initial sync
* When clients become aware of a thread, they try to retrieve those read receipts
* and apply them to the current thread
* @param receipts - A collection of the receipts cached from initial sync
*/
processReceipts() {
for (var { eventId, receiptType, userId, receipt, synthetic } of arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : []) this.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);
}
getRootEventBundledRelationship() {
var rootEvent = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.rootEvent;
return rootEvent === null || rootEvent === void 0 ? void 0 : rootEvent.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);
}
processRootEvent() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var bundledRelationship = _this4.getRootEventBundledRelationship();
if (Thread.hasServerSideSupport && bundledRelationship) {
_this4.replyCount = bundledRelationship.count;
_this4._currentUserParticipated = !!bundledRelationship.current_user_participated;
_this4.lastEvent = _this4.client.getEventMapper()(_objectSpread(_objectSpread({}, bundledRelationship.latest_event), {}, { room_id: _this4.roomId }));
_this4.updatePendingReplyCount();
yield _this4.processEvent(_this4.lastEvent);
}
})();
}
updatePendingReplyCount() {
var pendingEvents = (this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events).filter((ev) => {
var _this$lastEvent2;
return ev.threadRootId === this.id && ev.isRelation(THREAD_RELATION_TYPE.name) && ev.status !== null && ev.getId() !== ((_this$lastEvent2 = this.lastEvent) === null || _this$lastEvent2 === void 0 ? void 0 : _this$lastEvent2.getId());
});
this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : void 0;
this.pendingReplyCount = pendingEvents.length;
}
/**
* Reset the live timeline of all timelineSets, and start new ones.
*
* <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages
* /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore
* and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to
* set new pagination tokens on the old and the new timeline.
*
* @param backPaginationToken - token for back-paginating the new timeline
* @param forwardPaginationToken - token for forward-paginating the old live timeline,
* if absent or null, all timelines are reset, removing old ones (including the previous live
* timeline which would otherwise be unable to paginate forwards without this token).
* Removing just the old live timeline whilst preserving previous ones is not supported.
*/
resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
var oldLive = _this5.liveTimeline;
_this5.timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : void 0, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : void 0);
var newLive = _this5.liveTimeline;
var newBackward;
var oldForward;
if (backPaginationToken) newBackward = (yield _this5.client.createMessagesRequest(_this5.roomId, backPaginationToken, 1, Direction.Forward)).end;
if (forwardPaginationToken) oldForward = (yield _this5.client.createMessagesRequest(_this5.roomId, forwardPaginationToken, 1, Direction.Backward)).start;
if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) oldLive.setPaginationToken(oldForward !== null && oldForward !== void 0 ? oldForward : null, Direction.Forward);
if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) newLive.setPaginationToken(newBackward !== null && newBackward !== void 0 ? newBackward : null, Direction.Backward);
})();
}
updateThreadFromRootEvent() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (Thread.hasServerSideSupport) {
if (!_this6.initialEventsFetched && !_this6.lastEvent) yield _this6.processRootEvent();
yield _this6.fetchRootEvent();
}
yield _this6.processRootEvent();
})();
}
updateThreadMetadata() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
_this7.updatePendingReplyCount();
if (!_this7.processRootEventPromise) _this7.processRootEventPromise = _this7.updateThreadFromRootEvent();
yield _this7.processRootEventPromise;
if (!_this7.initialEventsFetched) if (_this7.initalEventFetchProm) yield _this7.initalEventFetchProm;
else try {
_this7.timelineSet.resetLiveTimeline();
if (_this7.replyCount === 0 && _this7.rootEvent) {
_this7.timelineSet.addEventsToTimeline([_this7.rootEvent], true, false, _this7.liveTimeline, null);
_this7.liveTimeline.setPaginationToken(null, Direction.Backward);
} else {
_this7.initalEventFetchProm = _this7.client.paginateEventTimeline(_this7.liveTimeline, { backwards: true });
yield _this7.initalEventFetchProm;
}
_this7.initialEventsFetched = true;
for (var event of _this7.replayEvents) _this7.addEvent(event, false);
_this7.replayEvents = null;
_this7.emit(RoomEvent.TimelineReset, _this7.room, _this7.timelineSet, true);
} catch (e) {
logger$2.error("Failed to load start of newly created thread: ", e);
_this7.initialEventsFetched = false;
}
_this7.emit(ThreadEvent.Update, _this7);
})();
}
fetchEditsWhereNeeded() {
var _arguments = arguments, _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _this8$client$canSupp;
if (((_this8$client$canSupp = _this8.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this8$client$canSupp !== void 0 ? _this8$client$canSupp : ServerSupport.Unsupported) === ServerSupport.Unsupported) {
for (var _len = _arguments.length, events = new Array(_len), _key = 0; _key < _len; _key++) events[_key] = _arguments[_key];
return Promise.all(events.filter(isAnEncryptedThreadMessage).map(/* @__PURE__ */ function() {
var _ref4 = (0, import_asyncToGenerator.default)(function* (event) {
try {
var relations = yield _this8.client.relations(_this8.roomId, event.getId(), RelationType.Replace, event.getType(), { limit: 1 });
if (relations.events.length) {
var editEvent = relations.events[0];
event.makeReplaced(editEvent);
_this8.insertEventIntoTimeline(editEvent);
}
} catch (e) {
logger$2.error("Failed to load edits for encrypted thread event", e);
}
});
return function(_x6) {
return _ref4.apply(this, arguments);
};
}()));
}
})();
}
setEventMetadata(event) {
if (event) {
EventTimeline.setEventMetadata(event, this.roomState, false);
event.setThread(this);
}
}
clearEventMetadata(event) {
if (event) {
var _event$event;
event.setThread(void 0);
(_event$event = event.event) === null || _event$event === void 0 || (_event$event = _event$event.unsigned) === null || _event$event === void 0 || (_event$event = _event$event["m.relations"]) === null || _event$event === void 0 || delete _event$event[THREAD_RELATION_TYPE.name];
}
}
/**
* Finds an event by ID in the current thread
*/
findEventById(eventId) {
return this.timelineSet.findEventById(eventId);
}
/**
* Return last reply to the thread, if known.
*/
lastReply() {
var matches = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : (ev) => ev.isRelation(THREAD_RELATION_TYPE.name);
for (var i = this.timeline.length - 1; i >= 0; i--) {
var event = this.timeline[i];
if (matches(event)) return event;
}
return null;
}
get roomId() {
return this.room.roomId;
}
/**
* The number of messages in the thread
* Only count rel_type=m.thread as we want to
* exclude annotations from that number
*/
get length() {
return this.replyCount + this.pendingReplyCount;
}
/**
* A getter for the last event of the thread.
* This might be a synthesized event, if so, it will not emit any events to listeners.
*/
get replyToEvent() {
var _ref5, _this$lastPendingEven;
return (_ref5 = (_this$lastPendingEven = this.lastPendingEvent) !== null && _this$lastPendingEven !== void 0 ? _this$lastPendingEven : this.lastEvent) !== null && _ref5 !== void 0 ? _ref5 : this.lastReply();
}
/**
* The live event timeline for this thread.
* @deprecated Present for backwards compatibility.
* Use this.events instead
* @returns The live event timeline for this thread.
*/
get timeline() {
return this.events;
}
get events() {
return this.liveTimeline.getEvents();
}
has(eventId) {
return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;
}
get hasCurrentUserParticipated() {
return this._currentUserParticipated;
}
get liveTimeline() {
return this.timelineSet.getLiveTimeline();
}
getUnfilteredTimelineSet() {
return this.timelineSet;
}
addReceipt(event, synthetic) {
throw new Error("Unsupported function on the thread model");
}
/**
* Get the ID of the event that a given user has read up to within this thread,
* or null if we have received no read receipt (at all) from them.
* @param userId - The user ID to get read receipt event ID for
* @param ignoreSynthesized - If true, return only receipts that have been
* sent by the server, not implicit ones generated
* by the JS SDK.
* @returns ID of the latest event that the given user has read, or null.
*/
getEventReadUpTo(userId, ignoreSynthesized) {
var isCurrentUser = userId === this.client.getUserId();
var lastReply = this.timeline[this.timeline.length - 1];
if (isCurrentUser && lastReply) {
var beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();
var lastReplyId = lastReply.getId();
if (beforeFirstThreadedReceipt && lastReplyId) return lastReplyId;
}
var readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);
if (lastReply) {
var unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);
if (!unthreadedReceipt) return readUpToId;
for (var i = ((_this$timeline = this.timeline) === null || _this$timeline === void 0 ? void 0 : _this$timeline.length) - 1; i >= 0; --i) {
var _this$timeline, _ev$getId;
var ev = this.timeline[i];
if (ev.getId() === readUpToId) return readUpToId;
if (ev.getTs() < unthreadedReceipt.ts) return (_ev$getId = ev.getId()) !== null && _ev$getId !== void 0 ? _ev$getId : readUpToId;
}
}
return readUpToId;
}
/**
* Determine if the given user has read a particular event.
*
* It is invalid to call this method with an event that is not part of this thread.
*
* This is not a definitive check as it only checks the events that have been
* loaded client-side at the time of execution.
* @param userId - The user ID to check the read state of.
* @param eventId - The event ID to check if the user read.
* @returns True if the user has read the event, false otherwise.
*/
hasUserReadEvent(userId, eventId) {
if (userId === this.client.getUserId()) {
var _this$lastReply$getTs, _this$lastReply, _this$room$getLastUnt, _this$room$getLastUnt2, _this$lastReply$getTs2, _this$lastReply2;
var beforeFirstThreadedReceipt = ((_this$lastReply$getTs = (_this$lastReply = this.lastReply()) === null || _this$lastReply === void 0 ? void 0 : _this$lastReply.getTs()) !== null && _this$lastReply$getTs !== void 0 ? _this$lastReply$getTs : 0) < this.room.getOldestThreadedReceiptTs();
var unthreadedReceiptTs = (_this$room$getLastUnt = (_this$room$getLastUnt2 = this.room.getLastUnthreadedReceiptFor(userId)) === null || _this$room$getLastUnt2 === void 0 ? void 0 : _this$room$getLastUnt2.ts) !== null && _this$room$getLastUnt !== void 0 ? _this$room$getLastUnt : 0;
var beforeLastUnthreadedReceipt = ((_this$lastReply$getTs2 = this === null || this === void 0 || (_this$lastReply2 = this.lastReply()) === null || _this$lastReply2 === void 0 ? void 0 : _this$lastReply2.getTs()) !== null && _this$lastReply$getTs2 !== void 0 ? _this$lastReply$getTs2 : 0) < unthreadedReceiptTs;
if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) return true;
}
return this.room.hasUserReadEvent(userId, eventId);
}
setUnread(type, count) {
return this.room.setThreadUnreadNotificationCount(this.id, type, count);
}
/**
* Returns the most recent unthreaded receipt for a given user
* @param userId - the MxID of the User
* @returns an unthreaded Receipt. Can be undefined if receipts have been disabled
* or a user chooses to use private read receipts (or we have simply not received
* a receipt from this user yet).
*/
getLastUnthreadedReceiptFor(userId) {
return this.room.getLastUnthreadedReceiptFor(userId);
}
};
/**
* Decide whether an event deserves to have its potential edits fetched.
*
* @returns true if this event is encrypted and is a message that is part of a
* thread - either inside it, or a root.
*/
(0, import_defineProperty.default)(Thread, "hasServerSideSupport", FeatureSupport.None);
(0, import_defineProperty.default)(Thread, "hasServerSideListSupport", FeatureSupport.None);
(0, import_defineProperty.default)(Thread, "hasServerSideFwdPaginationSupport", FeatureSupport.None);
function isAnEncryptedThreadMessage(event) {
return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);
}
var FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue("related_by_senders", "io.element.relation_senders");
var FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue("related_by_rel_types", "io.element.relation_types");
var THREAD_RELATION_TYPE = new ServerControlledNamespacedValue("m.thread", "io.element.thread");
var ThreadFilterType = /* @__PURE__ */ function(ThreadFilterType) {
ThreadFilterType[ThreadFilterType["My"] = 0] = "My";
ThreadFilterType[ThreadFilterType["All"] = 1] = "All";
return ThreadFilterType;
}({});
function threadFilterTypeToFilter(type) {
switch (type) {
case ThreadFilterType.My: return "participated";
default: return "all";
}
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/common-crypto/CryptoBackend.js
/**
* Common interface for the crypto implementations
*
* @internal
*/
/** The methods which crypto implementations should expose to the Sync api
*
* @internal
*/
/**
* @internal
*/
/**
* The result of a (successful) call to {@link CryptoBackend.decryptEvent}
*/
/**
* Responsible for decrypting megolm session data retrieved from a remote backup.
* The result of {@link CryptoBackend#getBackupDecryptor}.
*/
/**
* Exception thrown when decryption fails
*
* @param code - Reason code for the failure.
*
* @param msg - user-visible message describing the problem
*
* @param details - key/value pairs reported in the logs but not shown
* to the user.
*/
var DecryptionError = class extends Error {
constructor(code, msg, details) {
super(msg);
this.code = code;
(0, import_defineProperty.default)(this, "detailedString", void 0);
this.name = "DecryptionError";
this.detailedString = detailedStringForDecryptionError(this, details);
}
};
function detailedStringForDecryptionError(err, details) {
var result = err.name + "[msg: " + err.message;
if (details) result += ", " + Object.keys(details).map((k) => k + ": " + details[k]).join(", ");
result += "]";
return result;
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/event.js
/**
* This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for
* the public classes.
*/
/**
* When an event is a visibility change event, as per MSC3531,
* the visibility change implied by the event.
*/
/**
* Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531.
*/
/**
* Variant of `MessageVisibility` for the case in which the message should be displayed.
*/
/**
* Variant of `MessageVisibility` for the case in which the message should be hidden.
*/
var MESSAGE_VISIBLE = Object.freeze({ visible: true });
var MAX_STICKY_DURATION_MS = 36e5;
var MatrixEventEvent = /* @__PURE__ */ function(MatrixEventEvent) {
/**
* An event has been decrypted, or we have failed to decrypt it.
*
* The payload consists of:
*
* * `event` - The {@link MatrixEvent} which we attempted to decrypt.
*
* * `err` - The error that occurred during decryption, or `undefined` if no error occurred.
* Avoid use of this: {@link MatrixEvent.decryptionFailureReason} is more useful.
*/
MatrixEventEvent["Decrypted"] = "Event.decrypted";
MatrixEventEvent["BeforeRedaction"] = "Event.beforeRedaction";
MatrixEventEvent["VisibilityChange"] = "Event.visibilityChange";
MatrixEventEvent["LocalEventIdReplaced"] = "Event.localEventIdReplaced";
MatrixEventEvent["Status"] = "Event.status";
MatrixEventEvent["Replaced"] = "Event.replaced";
MatrixEventEvent["RelationsCreated"] = "Event.relationsCreated";
MatrixEventEvent["SentinelUpdated"] = "Event.sentinelUpdated";
return MatrixEventEvent;
}({});
var MatrixEvent = class MatrixEvent extends TypedEventEmitter {
/**
* Update the sentinels and forwardLooking flag for this event.
* @param stateContext - the room state to be queried
* @param toStartOfTimeline - if true the event's forwardLooking flag is set false
* @internal
*/
setMetadata(stateContext, toStartOfTimeline) {
var _this$sender, _this$target;
var affectsSelf = this.isState() && this.getType() === EventType.RoomMember && this.getSender() === this.getStateKey();
var changed = false;
if (affectsSelf || !((_this$sender = this.sender) !== null && _this$sender !== void 0 && (_this$sender = _this$sender.events) !== null && _this$sender !== void 0 && _this$sender.member)) {
var newSender = stateContext.getSentinelMember(this.getSender());
if (newSender !== this.sender) changed = true;
this.sender = newSender;
}
if (affectsSelf || !((_this$target = this.target) !== null && _this$target !== void 0 && (_this$target = _this$target.events) !== null && _this$target !== void 0 && _this$target.member) && this.getType() === EventType.RoomMember) {
var newTarget = stateContext.getSentinelMember(this.getStateKey());
if (newTarget !== this.target) changed = true;
this.target = newTarget;
}
if (this.isState()) {
if (toStartOfTimeline) this.forwardLooking = false;
}
if (changed) this.emit(MatrixEventEvent.SentinelUpdated);
}
/**
* The sending status of the event.
* @privateRemarks
* Should be read-only
*/
/**
* Construct a Matrix Event object
*
* @param event - The raw (possibly encrypted) event. <b>Do not access
* this property</b> directly unless you absolutely have to. Prefer the getter
* methods defined on this class. Using the getter methods shields your app
* from changes to event JSON between Matrix versions.
*/
constructor() {
var _this$getTs;
var event = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
super();
this.event = event;
(0, import_defineProperty.default)(this, "pushDetails", {});
(0, import_defineProperty.default)(this, "_replacingEvent", null);
(0, import_defineProperty.default)(this, "_localRedactionEvent", null);
(0, import_defineProperty.default)(this, "_isCancelled", false);
(0, import_defineProperty.default)(this, "clearEvent", void 0);
(0, import_defineProperty.default)(this, "visibility", MESSAGE_VISIBLE);
(0, import_defineProperty.default)(this, "_hasCachedExtEv", false);
(0, import_defineProperty.default)(this, "_cachedExtEv", void 0);
/** If we failed to decrypt this event, the reason for the failure. Otherwise, `null`. */
(0, import_defineProperty.default)(this, "_decryptionFailureReason", null);
(0, import_defineProperty.default)(this, "senderCurve25519Key", null);
(0, import_defineProperty.default)(this, "claimedEd25519Key", null);
/**
* If another user forwarded the key to this message
* (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),
* the ID of that user.
*/
(0, import_defineProperty.default)(this, "keyForwardedBy", void 0);
(0, import_defineProperty.default)(this, "decryptionPromise", null);
(0, import_defineProperty.default)(this, "retryDecryption", false);
(0, import_defineProperty.default)(this, "txnId", void 0);
/**
* A reference to the thread this event belongs to
*/
(0, import_defineProperty.default)(this, "thread", void 0);
(0, import_defineProperty.default)(this, "threadId", void 0);
(0, import_defineProperty.default)(this, "localTimestamp", void 0);
/**
* The room member who sent this event, or null e.g.
* this is a presence event. This is only guaranteed to be set for events that
* appear in a timeline, ie. do not guarantee that it will be set on state
* events.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "sender", null);
/**
* The room member who is the target of this event, e.g.
* the invitee, the person being banned, etc.
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "target", null);
(0, import_defineProperty.default)(this, "status", null);
/**
* most recent error associated with sending the event, if any
* @privateRemarks
* Should be read-only. May not be a MatrixError.
*/
(0, import_defineProperty.default)(this, "error", null);
/**
* True if this event is 'forward looking', meaning
* that getDirectionalContent() will return event.content and not event.prev_content.
* Only state events may be backwards looking
* Default: true. <strong>This property is experimental and may change.</strong>
* @privateRemarks
* Should be read-only
*/
(0, import_defineProperty.default)(this, "forwardLooking", true);
(0, import_defineProperty.default)(this, "reEmitter", void 0);
/**
* The timestamp for when this event should expire, in milliseconds.
* Prefers using the server-provided value, but will fall back to local calculation.
*
* This value is **safe** to use, as malicious start time and duration are appropriately capped.
*
* If the event is not a sticky event (or not supported by the server),
* then this returns `undefined`.
*/
(0, import_defineProperty.default)(this, "unstableStickyExpiresAt", void 0);
[
"state_key",
"type",
"sender",
"room_id",
"membership"
].forEach((prop) => {
if (typeof event[prop] !== "string") return;
event[prop] = internaliseString(event[prop]);
});
[
"membership",
"avatar_url",
"displayname"
].forEach((prop) => {
var _event$content;
if (typeof ((_event$content = event.content) === null || _event$content === void 0 ? void 0 : _event$content[prop]) !== "string") return;
event.content[prop] = internaliseString(event.content[prop]);
});
["rel_type"].forEach((prop) => {
var _event$content2;
if (typeof ((_event$content2 = event.content) === null || _event$content2 === void 0 || (_event$content2 = _event$content2["m.relates_to"]) === null || _event$content2 === void 0 ? void 0 : _event$content2[prop]) !== "string") return;
event.content["m.relates_to"][prop] = internaliseString(event.content["m.relates_to"][prop]);
});
this.txnId = event.txn_id;
var age = this.getAge();
var now = Date.now();
this.localTimestamp = age !== void 0 ? now - age : (_this$getTs = this.getTs()) !== null && _this$getTs !== void 0 ? _this$getTs : now;
this.reEmitter = new TypedReEmitter(this);
if (this.unstableStickyInfo) if (this.unstableStickyInfo.duration_ttl_ms) this.unstableStickyExpiresAt = now + this.unstableStickyInfo.duration_ttl_ms;
else this.unstableStickyExpiresAt = Math.min(now, this.getTs()) + this.unstableStickyInfo.duration_ms;
}
/**
* Unstable getter to try and get an extensible event. Note that this might
* return a falsy value if the event could not be parsed as an extensible
* event.
*
* @deprecated Use stable functions where possible.
*/
get unstableExtensibleEvent() {
if (!this._hasCachedExtEv) {
var _ExtensibleEvents$par;
this._cachedExtEv = (_ExtensibleEvents$par = import_lib$1.ExtensibleEvents.parse(this.getEffectiveEvent())) !== null && _ExtensibleEvents$par !== void 0 ? _ExtensibleEvents$par : void 0;
}
return this._cachedExtEv;
}
invalidateExtensibleEvent() {
this._hasCachedExtEv = false;
}
/**
* Gets the event as it would appear if it had been sent unencrypted.
*
* If the event is encrypted, we attempt to mock up an event as it would have looked had the sender not encrypted it.
* If the event is not encrypted, a copy of it is simply returned as-is.
*
* @returns A shallow copy of the event, in wire format, as it would have been had it not been encrypted.
*/
getEffectiveEvent() {
var content = Object.assign({}, this.getContent());
if (this.getWireType() === EventType.RoomMessageEncrypted) for (var [_key, value] of Object.entries(this.getWireContent())) {
if ([
"algorithm",
"ciphertext",
"device_id",
"sender_key",
"session_id"
].includes(_key)) continue;
if (content[_key] === void 0) content[_key] = value;
}
return Object.assign({}, this.event, this.clearEvent, { content });
}
/**
* Get the event_id for this event.
* @returns The event ID, e.g. <code>$143350589368169JsLZx:localhost
* </code>
*/
getId() {
return this.event.event_id;
}
/**
* Get the user_id for this event.
* @returns The user ID, e.g. `@alice:matrix.org`
*/
getSender() {
return this.event.sender;
}
/**
* Get the (decrypted, if necessary) type of event.
*
* @returns The event type, e.g. `m.room.message`
*/
getType() {
if (this.clearEvent) return this.clearEvent.type;
return this.event.type;
}
/**
* Get the (possibly encrypted) type of the event that will be sent to the
* homeserver.
*
* @returns The event type.
*/
getWireType() {
return this.event.type;
}
/**
* Get the room_id for this event. This will return `undefined`
* for `m.presence` events.
* @returns The room ID, e.g. <code>!cURbafjkfsMDVwdRDQ:matrix.org
* </code>
*/
getRoomId() {
return this.event.room_id;
}
/**
* Get the timestamp of this event.
* @returns The event timestamp, e.g. `1433502692297`
*/
getTs() {
return this.event.origin_server_ts;
}
/**
* Get the timestamp of this event, as a Date object.
* @returns The event date, e.g. `new Date(1433502692297)`
*/
getDate() {
return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;
}
/**
* Get a string containing details of this event
*
* This is intended for logging, to help trace errors. Example output:
*
* @example
* ```
* id=$HjnOHV646n0SjLDAqFrgIjim7RCpB7cdMXFrekWYAn type=m.room.encrypted
* sender=@user:example.com room=!room:example.com ts=2022-10-25T17:30:28.404Z
* ```
*/
getDetails() {
var room = this.getRoomId();
if (room) {
var _this$getDate;
return "id=".concat(this.getId(), " type=").concat(this.getWireType(), " sender=").concat(this.getSender(), " room=").concat(room, " ts=").concat((_this$getDate = this.getDate()) === null || _this$getDate === void 0 ? void 0 : _this$getDate.toISOString());
} else {
var msgid = this.getContent()[ToDeviceMessageId];
return "msgid=".concat(msgid, " type=").concat(this.getWireType(), " sender=").concat(this.getSender());
}
}
/**
* Get the (decrypted, if necessary) event content JSON, even if the event
* was replaced by another event.
*
* @returns The event content JSON, or an empty object.
*/
getOriginalContent() {
var _this$event$content;
if (this._localRedactionEvent) return {};
if (this.clearEvent) {
var _this$clearEvent$cont;
return (_this$clearEvent$cont = this.clearEvent.content) !== null && _this$clearEvent$cont !== void 0 ? _this$clearEvent$cont : {};
}
return (_this$event$content = this.event.content) !== null && _this$event$content !== void 0 ? _this$event$content : {};
}
/**
* Get the (decrypted, if necessary) event content JSON,
* or the content from the replacing event, if any.
* See `makeReplaced`.
*
* @returns The event content JSON, or an empty object.
*/
getContent() {
if (this._localRedactionEvent) return {};
else if (this._replacingEvent) {
var _this$_replacingEvent;
return (_this$_replacingEvent = this._replacingEvent.getContent()["m.new_content"]) !== null && _this$_replacingEvent !== void 0 ? _this$_replacingEvent : {};
} else return this.getOriginalContent();
}
/**
* Get the (possibly encrypted) event content JSON that will be sent to the
* homeserver.
*
* @returns The event content JSON, or an empty object.
*/
getWireContent() {
return this.event.content || {};
}
/**
* Get the event ID of the thread head
*/
get threadRootId() {
var _this$getWireContent;
if (this.isState()) return;
var relatesTo = (_this$getWireContent = this.getWireContent()) === null || _this$getWireContent === void 0 ? void 0 : _this$getWireContent["m.relates_to"];
if ((relatesTo === null || relatesTo === void 0 ? void 0 : relatesTo.rel_type) === THREAD_RELATION_TYPE.name) return relatesTo.event_id;
if (this.thread) return this.thread.id;
if (this.threadId !== void 0) return this.threadId;
var unsigned = this.getUnsigned();
if (typeof unsigned[UNSIGNED_THREAD_ID_FIELD.name] === "string") return unsigned[UNSIGNED_THREAD_ID_FIELD.name];
}
/**
* A helper to check if an event is a thread's head or not
*/
get isThreadRoot() {
if (this.isState()) return false;
return !!this.getServerAggregatedRelation(THREAD_RELATION_TYPE.name) || this.threadRootId === this.getId();
}
get replyEventId() {
var _this$getWireContent$;
return (_this$getWireContent$ = this.getWireContent()["m.relates_to"]) === null || _this$getWireContent$ === void 0 || (_this$getWireContent$ = _this$getWireContent$["m.in_reply_to"]) === null || _this$getWireContent$ === void 0 ? void 0 : _this$getWireContent$.event_id;
}
get relationEventId() {
var _this$getWireContent2;
return (_this$getWireContent2 = this.getWireContent()) === null || _this$getWireContent2 === void 0 || (_this$getWireContent2 = _this$getWireContent2["m.relates_to"]) === null || _this$getWireContent2 === void 0 ? void 0 : _this$getWireContent2.event_id;
}
/**
* Get the previous event content JSON. This will only return something for
* state events which exist in the timeline.
* @returns The previous event content JSON, or an empty object.
*/
getPrevContent() {
return this.getUnsigned().prev_content || {};
}
/**
* Get either 'content' or 'prev_content' depending on if this event is
* 'forward-looking' or not. This can be modified via event.forwardLooking.
* In practice, this means we get the chronologically earlier content value
* for this event (this method should surely be called getEarlierContent)
* <strong>This method is experimental and may change.</strong>
* @returns event.content if this event is forward-looking, else
* event.prev_content.
*/
getDirectionalContent() {
return this.forwardLooking ? this.getContent() : this.getPrevContent();
}
/**
* Get the age of this event. This represents the age of the event when the
* event arrived at the device, and not the age of the event when this
* function was called.
* Can only be returned once the server has echo'ed back
* @returns The age of this event in milliseconds.
*/
getAge() {
return this.getUnsigned().age;
}
/**
* Get the age of the event when this function was called.
* This is the 'age' field adjusted according to how long this client has
* had the event.
* @returns The age of this event in milliseconds.
*/
getLocalAge() {
return Date.now() - this.localTimestamp;
}
/**
* Get the event state_key if it has one. If necessary, this will perform
* string-unpacking on the state key, as per MSC4362. This will return
* <code>undefined</code> for message events.
* @returns The event's `state_key`.
*/
getStateKey() {
if (this.clearEvent) return this.clearEvent.state_key;
return this.event.state_key;
}
/**
* Get the raw event state_key if it has one. This may be string-packed as per
* MSC4362 if the state event is encrypted. This will return <code>undefined
* </code> for message events.
* @returns The event's `state_key`.
*/
getWireStateKey() {
return this.event.state_key;
}
/**
* Check if this event is a state event.
* @returns True if this is a state event.
*/
isState() {
return this.event.state_key !== void 0;
}
/**
* Get the user's room membership at the time the event was sent, as reported
* by the server. This uses MSC4115.
*
* @returns The user's room membership, or `undefined` if the server does
* not report it.
*/
getMembershipAtEvent() {
var unsigned = this.getUnsigned();
return UNSIGNED_MEMBERSHIP_FIELD.findIn(unsigned);
}
/**
* Replace the content of this event with encrypted versions.
* (This is used when sending an event; it should not be used by applications).
*
* @internal
*
* @param cryptoType - type of the encrypted event - typically
* <tt>"m.room.encrypted"</tt>
*
* @param cryptoContent - raw 'content' for the encrypted event.
*
* @param senderCurve25519Key - curve25519 key to record for the
* sender of this event.
* See {@link MatrixEvent#getSenderKey}.
*
* @param claimedEd25519Key - claimed ed25519 key to record for the
* sender if this event.
* See {@link MatrixEvent#getClaimedEd25519Key}
*/
makeEncrypted(cryptoType, cryptoContent, senderCurve25519Key, claimedEd25519Key) {
this.clearEvent = {
type: this.event.type,
content: this.event.content,
state_key: this.event.state_key
};
this.event.type = cryptoType;
this.event.content = cryptoContent;
this.senderCurve25519Key = senderCurve25519Key;
this.claimedEd25519Key = claimedEd25519Key;
if (this.isState()) this.event.state_key = "".concat(this.clearEvent.type, ":").concat(this.clearEvent.state_key);
}
/**
* Check if this event is currently being decrypted.
*
* @returns True if this event is currently being decrypted, else false.
*/
isBeingDecrypted() {
return this.decryptionPromise != null;
}
getDecryptionPromise() {
return this.decryptionPromise;
}
/**
* Check if this event is an encrypted event which we failed to decrypt
*
* (This implies that we might retry decryption at some point in the future)
*
* @returns True if this event is an encrypted event which we
* couldn't decrypt.
*/
isDecryptionFailure() {
return this._decryptionFailureReason !== null;
}
/** If we failed to decrypt this event, the reason for the failure. Otherwise, `null`. */
get decryptionFailureReason() {
return this._decryptionFailureReason;
}
shouldAttemptDecryption() {
if (this.isRedacted()) return false;
if (this.isBeingDecrypted()) return false;
if (this.clearEvent) return false;
if (!this.isEncrypted()) return false;
return true;
}
/**
* Start the process of trying to decrypt this event.
*
* (This is used within the SDK: it isn't intended for use by applications)
*
* @internal
*
* @param crypto - crypto module
*
* @returns promise which resolves (to undefined) when the decryption
* attempt is completed.
*/
attemptDecryption(crypto) {
var _arguments = arguments, _this = this;
return (0, import_asyncToGenerator.default)(function* () {
var options = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : {};
if (!_this.isEncrypted()) throw new Error("Attempt to decrypt event which isn't encrypted");
if (_this.clearEvent && !_this.isDecryptionFailure()) throw new Error("Attempt to decrypt event which has already been decrypted");
if (_this.decryptionPromise) {
logger$2.log("Event ".concat(_this.getId(), " already being decrypted; queueing a retry"));
_this.retryDecryption = true;
return _this.decryptionPromise;
}
_this.decryptionPromise = _this.decryptionLoop(crypto, options);
return _this.decryptionPromise;
})();
}
/**
* Calculate the recipients for keyshare requests.
*
* @param userId - the user who received this event.
*
* @returns array of recipients
*/
getKeyRequestRecipients(userId) {
return [{
userId,
deviceId: "*"
}];
}
decryptionLoop(crypto) {
var _arguments2 = arguments, _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var options = _arguments2.length > 1 && _arguments2[1] !== void 0 ? _arguments2[1] : {};
yield Promise.resolve();
while (true) {
_this2.retryDecryption = false;
var err = void 0;
try {
var res = yield crypto.decryptEvent(_this2);
if (options.isRetry === true) logger$2.info("Decrypted event on retry (".concat(_this2.getDetails(), ")"));
_this2.setClearData(res);
_this2._decryptionFailureReason = null;
} catch (e) {
var detailedError = e instanceof DecryptionError ? e.detailedString : String(e);
err = e;
if (_this2.retryDecryption) {
logger$2.log("Error decrypting event (".concat(_this2.getDetails(), "), but retrying: ").concat(detailedError));
continue;
}
logger$2.warn("Error decrypting event (".concat(_this2.getDetails(), "): ").concat(detailedError));
_this2.setClearDataForDecryptionFailure(String(e));
_this2._decryptionFailureReason = e instanceof DecryptionError ? e.code : DecryptionFailureCode.UNKNOWN_ERROR;
}
_this2.decryptionPromise = null;
_this2.retryDecryption = false;
_this2.setPushDetails();
if (options.emit !== false) _this2.emit(MatrixEventEvent.Decrypted, _this2, err);
return;
}
})();
}
/**
* Update the cleartext data on this event.
*
* (This is used after decrypting an event; it should not be used by applications).
*
* @internal
*
* @param decryptionResult - the decryption result, including the plaintext and some key info
*/
setClearData(decryptionResult) {
var _decryptionResult$sen, _decryptionResult$cla;
this.clearEvent = decryptionResult.clearEvent;
this.senderCurve25519Key = (_decryptionResult$sen = decryptionResult.senderCurve25519Key) !== null && _decryptionResult$sen !== void 0 ? _decryptionResult$sen : null;
this.claimedEd25519Key = (_decryptionResult$cla = decryptionResult.claimedEd25519Key) !== null && _decryptionResult$cla !== void 0 ? _decryptionResult$cla : null;
this.keyForwardedBy = decryptionResult.keyForwardedBy;
this.invalidateExtensibleEvent();
}
/**
* Update the cleartext data on this event after a decryption failure.
*
* @param reason - the textual reason for the failure
*/
setClearDataForDecryptionFailure(reason) {
this.clearEvent = {
type: EventType.RoomMessage,
content: {
msgtype: "m.bad.encrypted",
body: "** Unable to decrypt: ".concat(reason, " **")
}
};
this.senderCurve25519Key = null;
this.claimedEd25519Key = null;
this.invalidateExtensibleEvent();
}
/**
* Gets the cleartext content for this event. If the event is not encrypted,
* or encryption has not been completed, this will return null.
*
* @returns The cleartext (decrypted) content for the event
*/
getClearContent() {
return this.clearEvent ? this.clearEvent.content : null;
}
/**
* Check if the event is encrypted.
* @returns True if this event is encrypted.
*/
isEncrypted() {
return this.event.type === EventType.RoomMessageEncrypted;
}
/**
* The curve25519 key for the device that we think sent this event
*
* For an Olm-encrypted event, this is inferred directly from the DH
* exchange at the start of the session: the curve25519 key is involved in
* the DH exchange, so only a device which holds the private part of that
* key can establish such a session.
*
* For a megolm-encrypted event, it is inferred from the Olm message which
* established the megolm session
*/
getSenderKey() {
return this.senderCurve25519Key;
}
/**
* The additional keys the sender of this encrypted event claims to possess.
*
* Just a wrapper for #getClaimedEd25519Key (q.v.)
*/
getKeysClaimed() {
if (!this.claimedEd25519Key) return {};
return { ed25519: this.claimedEd25519Key };
}
/**
* Get the ed25519 the sender of this event claims to own.
*
* For Olm messages, this claim is encoded directly in the plaintext of the
* event itself. For megolm messages, it is implied by the m.room_key event
* which established the megolm session.
*
* Until we download the device list of the sender, it's just a claim: the
* device list gives a proof that the owner of the curve25519 key used for
* this event (and returned by #getSenderKey) also owns the ed25519 key by
* signing the public curve25519 key with the ed25519 key.
*
* In general, applications should not use this method directly, but should
* instead use {@link crypto-api!CryptoApi#getEncryptionInfoForEvent}.
*/
getClaimedEd25519Key() {
return this.claimedEd25519Key;
}
/**
* Returns an empty array.
*
* Previously, this returned the chain of Curve25519 keys through which
* this session was forwarded, via `m.forwarded_room_key` events.
* However, that is not cryptographically reliable, and clients should not
* be using it.
*
* @see https://github.com/matrix-org/matrix-spec/issues/1089
* @deprecated
*/
getForwardingCurve25519KeyChain() {
return [];
}
/**
* @deprecated always returns false
*/
isKeySourceUntrusted() {
return false;
}
/**
* If another user forwarded the key to this message
* (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),
* get the ID of that user.
*/
getKeyForwardingUser() {
return this.keyForwardedBy;
}
getUnsigned() {
return this.event.unsigned || {};
}
setUnsigned(unsigned) {
this.event.unsigned = unsigned;
}
unmarkLocallyRedacted() {
var value = this._localRedactionEvent;
this._localRedactionEvent = null;
if (this.event.unsigned) this.event.unsigned.redacted_because = void 0;
return !!value;
}
markLocallyRedacted(redactionEvent) {
if (this._localRedactionEvent) return;
this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);
this._localRedactionEvent = redactionEvent;
if (!this.event.unsigned) this.event.unsigned = {};
this.event.unsigned.redacted_because = redactionEvent.event;
}
/**
* Change the visibility of an event, as per https://github.com/matrix-org/matrix-doc/pull/3531 .
*
* @param visibilityChange - event holding a hide/unhide payload, or nothing
* if the event is being reset to its original visibility (presumably
* by a visibility event being redacted).
*
* @remarks
* Fires {@link MatrixEventEvent.VisibilityChange} if `visibilityEvent`
* caused a change in the actual visibility of this event, either by making it
* visible (if it was hidden), by making it hidden (if it was visible) or by
* changing the reason (if it was hidden).
*/
applyVisibilityEvent(visibilityChange) {
var _visibilityChange$vis, _visibilityChange$rea;
var visible = (_visibilityChange$vis = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.visible) !== null && _visibilityChange$vis !== void 0 ? _visibilityChange$vis : true;
var reason = (_visibilityChange$rea = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.reason) !== null && _visibilityChange$rea !== void 0 ? _visibilityChange$rea : null;
var change = false;
if (this.visibility.visible !== visible) change = true;
else if (!this.visibility.visible && this.visibility["reason"] !== reason) change = true;
if (change) {
if (visible) this.visibility = MESSAGE_VISIBLE;
else this.visibility = Object.freeze({
visible: false,
reason
});
this.emit(MatrixEventEvent.VisibilityChange, this, visible);
}
}
/**
* Return instructions to display or hide the message.
*
* @returns Instructions determining whether the message
* should be displayed.
*/
messageVisibility() {
return this.visibility;
}
/**
* Update the content of an event in the same way it would be by the server
* if it were redacted before it was sent to us
*
* @param redactionEvent - event causing the redaction
* @param room - the room in which the event exists
*/
makeRedacted(redactionEvent, room) {
if (!redactionEvent.event) throw new Error("invalid redactionEvent in makeRedacted");
this._localRedactionEvent = null;
this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);
this._replacingEvent = null;
if (!this.event.unsigned) this.event.unsigned = {};
this.event.unsigned.redacted_because = redactionEvent.event;
for (var _key2 in this.event) if (this.event.hasOwnProperty(_key2) && !REDACT_KEEP_KEYS.has(_key2)) delete this.event[_key2];
if (this.isEncrypted()) this.clearEvent = void 0;
var keeps = this.getType() in REDACT_KEEP_CONTENT_MAP ? REDACT_KEEP_CONTENT_MAP[this.getType()] : {};
var content = this.getContent();
for (var _key3 in content) if (content.hasOwnProperty(_key3) && !keeps[_key3]) delete content[_key3];
if (!this.isThreadRoot && this.threadRootId && this.threadRootId !== this.getId()) {
this.moveAllRelatedToMainTimeline(room);
redactionEvent.moveToMainTimeline(room);
}
this.invalidateExtensibleEvent();
}
moveAllRelatedToMainTimeline(room) {
var thread = this.thread;
this.moveToMainTimeline(room);
if (thread) for (var _event of thread.events) {
var _event$getRelation;
if (((_event$getRelation = _event.getRelation()) === null || _event$getRelation === void 0 ? void 0 : _event$getRelation.event_id) === this.getId()) _event.moveAllRelatedToMainTimeline(room);
}
}
moveToMainTimeline(room) {
var _this$thread;
(_this$thread = this.thread) === null || _this$thread === void 0 || _this$thread.timelineSet.removeEvent(this.getId());
this.setThread(void 0);
var timeline = room.getLiveTimeline();
timeline.getTimelineSet().insertEventIntoTimeline(this, timeline, timeline.getState(EventTimeline.FORWARDS), false);
}
/**
* Check if this event has been redacted
*
* @returns True if this event has been redacted
*/
isRedacted() {
return Boolean(this.getUnsigned().redacted_because);
}
/**
* Check if this event is a redaction of another event
*
* @returns True if this event is a redaction
*/
isRedaction() {
return this.getType() === EventType.RoomRedaction;
}
/**
* Return the visibility change caused by this event,
* as per https://github.com/matrix-org/matrix-doc/pull/3531.
*
* @returns If the event is a well-formed visibility change event,
* an instance of `IVisibilityChange`, otherwise `null`.
*/
asVisibilityChange() {
if (!EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())) return null;
var relation = this.getRelation();
if (!relation || relation.rel_type != "m.reference") return null;
var eventId = relation.event_id;
if (!eventId) return null;
var content = this.getWireContent();
var visible = !!content.visible;
var reason = content.reason;
if (reason && typeof reason != "string") return null;
return {
visible,
reason,
eventId
};
}
/**
* Check if this event alters the visibility of another event,
* as per https://github.com/matrix-org/matrix-doc/pull/3531.
*
* @returns True if this event alters the visibility
* of another event.
*/
isVisibilityEvent() {
return EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType());
}
/**
* Get the (decrypted, if necessary) redaction event JSON
* if event was redacted
*
* @returns The redaction event JSON, or an empty object
*/
getRedactionEvent() {
var _this$clearEvent, _this$event$unsigned;
if (!this.isRedacted()) return null;
if ((_this$clearEvent = this.clearEvent) !== null && _this$clearEvent !== void 0 && _this$clearEvent.unsigned) {
var _this$clearEvent$unsi, _this$clearEvent2;
return (_this$clearEvent$unsi = (_this$clearEvent2 = this.clearEvent) === null || _this$clearEvent2 === void 0 ? void 0 : _this$clearEvent2.unsigned.redacted_because) !== null && _this$clearEvent$unsi !== void 0 ? _this$clearEvent$unsi : null;
} else if ((_this$event$unsigned = this.event.unsigned) !== null && _this$event$unsigned !== void 0 && _this$event$unsigned.redacted_because) return this.event.unsigned.redacted_because;
else return {};
}
/**
* Get the push actions, if known, for this event
*
* @returns push actions
*/
getPushActions() {
return this.pushDetails.actions || null;
}
/**
* Get the push details, if known, for this event
*
* @returns push actions
*/
getPushDetails() {
return this.pushDetails;
}
/**
* Set the push details for this event.
*
* @param pushActions - push actions
* @param rule - the executed push rule
*/
setPushDetails(pushActions, rule) {
this.pushDetails = {
actions: pushActions,
rule
};
}
/**
* Replace the `event` property and recalculate any properties based on it.
* @param event - the object to assign to the `event` property
*/
handleRemoteEcho(event) {
var _this$getAge;
var oldUnsigned = this.getUnsigned();
var oldId = this.getId();
this.event = event;
if (oldUnsigned.redacted_because) {
if (!this.event.unsigned) this.event.unsigned = {};
this.event.unsigned.redacted_because = oldUnsigned.redacted_because;
}
this.setStatus(null);
if (this.getId() !== oldId) this.emit(MatrixEventEvent.LocalEventIdReplaced, this);
this.localTimestamp = Date.now() - ((_this$getAge = this.getAge()) !== null && _this$getAge !== void 0 ? _this$getAge : 0);
}
/**
* Whether the event is in any phase of sending, send failure, waiting for
* remote echo, etc.
*/
isSending() {
return !!this.status;
}
/**
* Update the event's sending status and emit an event as well.
*
* @param status - The new status
*/
setStatus(status) {
this.status = status;
this.emit(MatrixEventEvent.Status, this, status);
}
replaceLocalEventId(eventId) {
this.event.event_id = eventId;
this.emit(MatrixEventEvent.LocalEventIdReplaced, this);
}
/**
* Get whether the event is a relation event, and of a given type if
* `relType` is passed in. State events cannot be relation events
*
* @param relType - if given, checks that the relation is of the
* given type
*/
isRelation(relType) {
var _this$getWireContent3;
var relation = (_this$getWireContent3 = this.getWireContent()) === null || _this$getWireContent3 === void 0 ? void 0 : _this$getWireContent3["m.relates_to"];
if (this.isState() && !!(relation !== null && relation !== void 0 && relation.rel_type) && [RelationType.Replace, RelationType.Thread].includes(relation.rel_type)) return false;
return !!(relation !== null && relation !== void 0 && relation.rel_type && relation.event_id && (relType ? relation.rel_type === relType : true));
}
/**
* Get relation info for the event, if any.
*/
getRelation() {
var _this$getWireContent$2;
if (!this.isRelation()) return null;
return (_this$getWireContent$2 = this.getWireContent()["m.relates_to"]) !== null && _this$getWireContent$2 !== void 0 ? _this$getWireContent$2 : null;
}
/**
* Set an event that replaces the content of this event, through an m.replace relation.
*
* @param newEvent - the event with the replacing content, if any.
*
* @remarks
* Fires {@link MatrixEventEvent.Replaced}
*/
makeReplaced(newEvent) {
if (this.isRedacted() && newEvent) return;
if (this.isState()) return;
if (this._replacingEvent !== newEvent) {
this._replacingEvent = newEvent !== null && newEvent !== void 0 ? newEvent : null;
this.emit(MatrixEventEvent.Replaced, this);
this.invalidateExtensibleEvent();
}
}
/**
* Returns the status of any associated edit or redaction
* (not for reactions/annotations as their local echo doesn't affect the original event),
* or else the status of the event.
*/
getAssociatedStatus() {
if (this._replacingEvent) return this._replacingEvent.status;
else if (this._localRedactionEvent) return this._localRedactionEvent.status;
return this.status;
}
getServerAggregatedRelation(relType) {
var _this$getUnsigned$mR;
return (_this$getUnsigned$mR = this.getUnsigned()["m.relations"]) === null || _this$getUnsigned$mR === void 0 ? void 0 : _this$getUnsigned$mR[relType];
}
/**
* Returns the event ID of the event replacing the content of this event, if any.
*/
replacingEventId() {
var replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);
if (replaceRelation) return replaceRelation.event_id;
else if (this._replacingEvent) return this._replacingEvent.getId();
}
/**
* Returns the event replacing the content of this event, if any.
* Replacements are aggregated on the server, so this would only
* return an event in case it came down the sync, or for local echo of edits.
*/
replacingEvent() {
return this._replacingEvent;
}
/**
* Returns the origin_server_ts of the event replacing the content of this event, if any.
*/
replacingEventDate() {
var replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);
if (replaceRelation) {
var ts = replaceRelation.origin_server_ts;
if (Number.isFinite(ts)) return new Date(ts);
} else if (this._replacingEvent) {
var _this$_replacingEvent2;
return (_this$_replacingEvent2 = this._replacingEvent.getDate()) !== null && _this$_replacingEvent2 !== void 0 ? _this$_replacingEvent2 : void 0;
}
}
/**
* Returns the event that wants to redact this event, but hasn't been sent yet.
* @returns the event
*/
localRedactionEvent() {
return this._localRedactionEvent;
}
/**
* For relations and redactions, returns the event_id this event is referring to.
*/
getAssociatedId() {
var relation = this.getRelation();
if (this.replyEventId) return this.replyEventId;
else if (relation) return relation.event_id;
else if (this.isRedaction()) return this.event.redacts;
}
/**
* Checks if this event is associated with another event. See `getAssociatedId`.
*/
hasAssociation() {
return !!this.getAssociatedId();
}
/**
* Update the related id with a new one.
*
* Used to replace a local id with remote one before sending
* an event with a related id.
*
* @param eventId - the new event id
*/
updateAssociatedId(eventId) {
var relation = this.getRelation();
if (relation) relation.event_id = eventId;
else if (this.isRedaction()) this.event.redacts = eventId;
}
/**
* Flags an event as cancelled due to future conditions. For example, a verification
* request event in the same sync transaction may be flagged as cancelled to warn
* listeners that a cancellation event is coming down the same pipe shortly.
* @param cancelled - Whether the event is to be cancelled or not.
*/
flagCancelled() {
this._isCancelled = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
}
/**
* Gets whether or not the event is flagged as cancelled. See flagCancelled() for
* more information.
* @returns True if the event is cancelled, false otherwise.
*/
isCancelled() {
return this._isCancelled;
}
/**
* Get a copy/snapshot of this event. The returned copy will be loosely linked
* back to this instance, though will have "frozen" event information. Other
* properties of this MatrixEvent instance will be copied verbatim, which can
* mean they are in reference to this instance despite being on the copy too.
* The reference the snapshot uses does not change, however members aside from
* the underlying event will not be deeply cloned, thus may be mutated internally.
* For example, the sender profile will be copied over at snapshot time, and
* the sender profile internally may mutate without notice to the consumer.
*
* This is meant to be used to snapshot the event details themselves, not the
* features (such as sender) surrounding the event.
* @returns A snapshot of this event.
*/
toSnapshot() {
var ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event)));
for (var [p, v] of Object.entries(this)) if (p !== "event") ev[p] = v;
return ev;
}
/**
* Determines if this event is equivalent to the given event. This only checks
* the event object itself, not the other properties of the event. Intended for
* use with toSnapshot() to identify events changing.
* @param otherEvent - The other event to check against.
* @returns True if the events are the same, false otherwise.
*/
isEquivalentTo(otherEvent) {
if (!otherEvent) return false;
if (otherEvent === this) return true;
var myProps = deepSortedObjectEntries(this.event);
var theirProps = deepSortedObjectEntries(otherEvent.event);
return JSON.stringify(myProps) === JSON.stringify(theirProps);
}
/**
* Summarise the event as JSON.
*
* If encrypted, include both the decrypted and encrypted view of the event.
*
* This is named `toJSON` for use with `JSON.stringify` which checks objects
* for functions named `toJSON` and will call them to customise the output
* if they are defined.
*
* **WARNING** Do not log the result of this method; otherwise, it will end up
* in rageshakes, leading to a privacy violation.
*
* @deprecated Prefer to use {@link MatrixEvent#getEffectiveEvent} or similar.
* This method will be removed soon; it is too easy to use it accidentally
* and cause a privacy violation (cf https://github.com/vector-im/element-web/issues/26380).
* In any case, the value it returns is not a faithful serialization of the object.
*/
toJSON() {
var event = this.getEffectiveEvent();
if (!this.isEncrypted()) return event;
return {
decrypted: event,
encrypted: this.event
};
}
setTxnId(txnId) {
this.txnId = txnId;
}
getTxnId() {
return this.txnId;
}
/**
* Set the instance of a thread associated with the current event
* @param thread - the thread
*/
setThread(thread) {
if (this.isState()) return;
if (this.thread) this.reEmitter.stopReEmitting(this.thread, [ThreadEvent.Update]);
this.thread = thread;
this.setThreadId(thread === null || thread === void 0 ? void 0 : thread.id);
if (thread) this.reEmitter.reEmit(thread, [ThreadEvent.Update]);
}
/**
* Get the instance of the thread associated with the current event
*/
getThread() {
return this.thread;
}
setThreadId(threadId) {
this.threadId = threadId;
}
/**
* Unstable getter to try and get the sticky information for the event.
* If the event is not a sticky event (or not supported by the server),
* then this returns `undefined`.
*
* `duration_ms` is safely bounded to a hour.
*/
get unstableStickyInfo() {
var _this$event$msc4354_s, _this$event$unsigned2;
if (!((_this$event$msc4354_s = this.event.msc4354_sticky) !== null && _this$event$msc4354_s !== void 0 && _this$event$msc4354_s.duration_ms)) return;
return {
duration_ms: Math.min(MAX_STICKY_DURATION_MS, this.event.msc4354_sticky.duration_ms),
duration_ttl_ms: (_this$event$unsigned2 = this.event.unsigned) === null || _this$event$unsigned2 === void 0 ? void 0 : _this$event$unsigned2.msc4354_sticky_duration_ttl_ms
};
}
};
var REDACT_KEEP_KEYS = new Set([
"event_id",
"type",
"room_id",
"user_id",
"sender",
"state_key",
"prev_state",
"content",
"unsigned",
"origin_server_ts"
]);
var REDACT_KEEP_CONTENT_MAP = {
[EventType.RoomMember]: { membership: 1 },
[EventType.RoomJoinRules]: { join_rule: 1 },
[EventType.RoomPowerLevels]: {
ban: 1,
events: 1,
events_default: 1,
kick: 1,
redact: 1,
state_default: 1,
users: 1,
users_default: 1
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/utils/roomVersion.js
/**
* Room versions strings that we know about and do not use hydra semantics.
*/
var PRE_HYDRA_ROOM_VERSIONS = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11"
];
/**
* Checks if the given room version is one where new "hydra" power level
* semantics (ie. room version 12 or later) should be used
* (see https://github.com/matrix-org/matrix-spec-proposals/pull/4289).
* This will return `false` for versions that are known to the js-sdk and
* do not use hydra: any room versions unknown to the js-sdk (experimental or
* otherwise) will cause the function to return true.
*
* @param roomVersion - The version of the room to check.
* @returns `true` if hydra semantics should be used for the room version, `false` otherwise.
*/
function shouldUseHydraForRoomVersion(roomVersion) {
return !PRE_HYDRA_ROOM_VERSIONS.includes(roomVersion);
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/room-state.js
var OobStatus = /* @__PURE__ */ function(OobStatus) {
OobStatus[OobStatus["NotStarted"] = 0] = "NotStarted";
OobStatus[OobStatus["InProgress"] = 1] = "InProgress";
OobStatus[OobStatus["Finished"] = 2] = "Finished";
return OobStatus;
}(OobStatus || {});
var RoomStateEvent = /* @__PURE__ */ function(RoomStateEvent) {
RoomStateEvent["Events"] = "RoomState.events";
RoomStateEvent["Members"] = "RoomState.members";
RoomStateEvent["NewMember"] = "RoomState.newMember";
RoomStateEvent["Update"] = "RoomState.update";
RoomStateEvent["BeaconLiveness"] = "RoomState.BeaconLiveness";
RoomStateEvent["Marker"] = "RoomState.Marker";
return RoomStateEvent;
}({});
var RoomState = class RoomState extends TypedEventEmitter {
/**
* Construct room state.
*
* Room State represents the state of the room at a given point.
* It can be mutated by adding state events to it.
* There are two types of room member associated with a state event:
* normal member objects (accessed via getMember/getMembers) which mutate
* with the state to represent the current state of that room/user, e.g.
* the object returned by `getMember('@bob:example.com')` will mutate to
* get a different display name if Bob later changes his display name
* in the room.
* There are also 'sentinel' members (accessed via getSentinelMember).
* These also represent the state of room members at the point in time
* represented by the RoomState object, but unlike objects from getMember,
* sentinel objects will always represent the room state as at the time
* getSentinelMember was called, so if Bob subsequently changes his display
* name, a room member object previously acquired with getSentinelMember
* will still have his old display name. Calling getSentinelMember again
* after the display name change will return a new RoomMember object
* with Bob's new display name.
*
* @param roomId - Optional. The ID of the room which has this state.
* If none is specified it just tracks paginationTokens, useful for notifTimelineSet
* @param oobMemberFlags - Optional. The state of loading out of bound members.
* As the timeline might get reset while they are loading, this state needs to be inherited
* and shared when the room state is cloned for the new timeline.
* This should only be passed from clone.
*/
constructor(roomId) {
var oobMemberFlags = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { status: OobStatus.NotStarted };
super();
this.roomId = roomId;
this.oobMemberFlags = oobMemberFlags;
(0, import_defineProperty.default)(this, "reEmitter", new TypedReEmitter(this));
(0, import_defineProperty.default)(this, "sentinels", {});
(0, import_defineProperty.default)(this, "displayNameToUserIds", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "userIdsToDisplayNames", {});
(0, import_defineProperty.default)(this, "tokenToInvite", {});
(0, import_defineProperty.default)(this, "joinedMemberCount", null);
(0, import_defineProperty.default)(this, "summaryJoinedMemberCount", null);
(0, import_defineProperty.default)(this, "invitedMemberCount", null);
(0, import_defineProperty.default)(this, "summaryInvitedMemberCount", null);
(0, import_defineProperty.default)(this, "modified", -1);
(0, import_defineProperty.default)(this, "members", {});
(0, import_defineProperty.default)(this, "events", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "paginationToken", null);
(0, import_defineProperty.default)(this, "beacons", /* @__PURE__ */ new Map());
(0, import_defineProperty.default)(this, "_liveBeaconIds", []);
(0, import_defineProperty.default)(this, "getVersionWarning", false);
this.updateModifiedTime();
}
/**
* Gets the version of the room
* @returns The version of the room
*/
getRoomVersion() {
var _createEvent$getConte;
var createEvent = this.getStateEvents(EventType.RoomCreate, "");
if (!createEvent) {
if (!this.getVersionWarning) {
logger$2.warn("[getVersion] Room " + this.roomId + " does not have an m.room.create event");
this.getVersionWarning = true;
}
return "1";
}
return (_createEvent$getConte = createEvent.getContent()["room_version"]) !== null && _createEvent$getConte !== void 0 ? _createEvent$getConte : "1";
}
/**
* Returns the number of joined members in this room
* This method caches the result.
* @returns The number of members in this room whose membership is 'join'
*/
getJoinedMemberCount() {
if (this.summaryJoinedMemberCount !== null) return this.summaryJoinedMemberCount;
if (this.joinedMemberCount === null) this.joinedMemberCount = this.getMembers().reduce((count, m) => {
return m.membership === KnownMembership.Join ? count + 1 : count;
}, 0);
return this.joinedMemberCount;
}
/**
* Set the joined member count explicitly (like from summary part of the sync response)
* @param count - the amount of joined members
*/
setJoinedMemberCount(count) {
this.summaryJoinedMemberCount = count;
}
/**
* Returns the number of invited members in this room
* @returns The number of members in this room whose membership is 'invite'
*/
getInvitedMemberCount() {
if (this.summaryInvitedMemberCount !== null) return this.summaryInvitedMemberCount;
if (this.invitedMemberCount === null) this.invitedMemberCount = this.getMembers().reduce((count, m) => {
return m.membership === KnownMembership.Invite ? count + 1 : count;
}, 0);
return this.invitedMemberCount;
}
/**
* Set the amount of invited members in this room
* @param count - the amount of invited members
*/
setInvitedMemberCount(count) {
this.summaryInvitedMemberCount = count;
}
/**
* Get all RoomMembers in this room.
* @returns A list of RoomMembers.
*/
getMembers() {
return Object.values(this.members);
}
/**
* Get all RoomMembers in this room, excluding the user IDs provided.
* @param excludedIds - The user IDs to exclude.
* @returns A list of RoomMembers.
*/
getMembersExcept(excludedIds) {
return this.getMembers().filter((m) => !excludedIds.includes(m.userId));
}
/**
* Get a room member by their user ID.
* @param userId - The room member's user ID.
* @returns The member or null if they do not exist.
*/
getMember(userId) {
return this.members[userId] || null;
}
/**
* Get a room member whose properties will not change with this room state. You
* typically want this if you want to attach a RoomMember to a MatrixEvent which
* may no longer be represented correctly by Room.currentState or Room.oldState.
* The term 'sentinel' refers to the fact that this RoomMember is an unchanging
* guardian for state at this particular point in time.
* @param userId - The room member's user ID.
* @returns The member or null if they do not exist.
*/
getSentinelMember(userId) {
if (!userId) return null;
var sentinel = this.sentinels[userId];
if (sentinel === void 0) {
sentinel = new RoomMember(this.roomId, userId);
var member = this.members[userId];
if (member !== null && member !== void 0 && member.events.member) sentinel.setMembershipEvent(member.events.member, this);
this.sentinels[userId] = sentinel;
}
return sentinel;
}
/**
* Get state events from the state of the room.
* @param eventType - The event type of the state event.
* @returns A list of events
*/
/**
* Get state events from the state of the room.
* @param eventType - The event type of the state event.
* @param stateKey - The state_key of the state event.
* @returns A single event (or null if no match found).
*/
getStateEvents(eventType, stateKey) {
if (!this.events.has(eventType)) return stateKey === void 0 ? [] : null;
if (stateKey === void 0) return Array.from(this.events.get(eventType).values());
var event = this.events.get(eventType).get(stateKey);
return event ? event : null;
}
get hasLiveBeacons() {
var _this$liveBeaconIds;
return !!((_this$liveBeaconIds = this.liveBeaconIds) !== null && _this$liveBeaconIds !== void 0 && _this$liveBeaconIds.length);
}
get liveBeaconIds() {
return this._liveBeaconIds;
}
/**
* Creates a copy of this room state so that mutations to either won't affect the other.
* @returns the copy of the room state
*/
clone() {
var copy = new RoomState(this.roomId, this.oobMemberFlags);
var status = this.oobMemberFlags.status;
this.oobMemberFlags.status = OobStatus.NotStarted;
Array.from(this.events.values()).forEach((eventsByStateKey) => {
copy.setStateEvents(Array.from(eventsByStateKey.values()));
});
this.oobMemberFlags.status = status;
if (this.summaryInvitedMemberCount !== null) copy.setInvitedMemberCount(this.getInvitedMemberCount());
if (this.summaryJoinedMemberCount !== null) copy.setJoinedMemberCount(this.getJoinedMemberCount());
if (this.oobMemberFlags.status == OobStatus.Finished) this.getMembers().forEach((member) => {
if (member.isOutOfBand()) {
var _copy$getMember;
(_copy$getMember = copy.getMember(member.userId)) === null || _copy$getMember === void 0 || _copy$getMember.markOutOfBand();
}
});
return copy;
}
/**
* Add previously unknown state events.
* When lazy loading members while back-paginating,
* the relevant room state for the timeline chunk at the end
* of the chunk can be set with this method.
* @param events - state events to prepend
*/
setUnknownStateEvents(events) {
var unknownStateEvents = events.filter((event) => {
return !this.events.has(event.getType()) || !this.events.get(event.getType()).has(event.getStateKey());
});
this.setStateEvents(unknownStateEvents);
}
/**
* Add an array of one or more state MatrixEvents, overwriting any existing
* state with the same `{type, stateKey}` tuple. Will fire "RoomState.events"
* for every event added. May fire "RoomState.members" if there are
* `m.room.member` events. May fire "RoomStateEvent.Marker" if there are
* `UNSTABLE_MSC2716_MARKER` events.
* @param stateEvents - a list of state events for this room.
*
* @remarks
* Fires {@link RoomStateEvent.Members}
* Fires {@link RoomStateEvent.NewMember}
* Fires {@link RoomStateEvent.Events}
* Fires {@link RoomStateEvent.Marker}
*/
setStateEvents(stateEvents, markerFoundOptions) {
this.updateModifiedTime();
var affectedDisplayNames = /* @__PURE__ */ new Set();
var processedMemberUserIds = /* @__PURE__ */ new Set();
stateEvents.forEach((event) => {
if (event.getRoomId() !== this.roomId || !event.isState()) return;
if (M_BEACON_INFO.matches(event.getType())) this.setBeacon(event);
var lastStateEvent = this.getStateEventMatching(event);
this.setStateEvent(event);
if (event.getType() === EventType.RoomMember) {
var _event$getContent$dis;
var userId = event.getStateKey();
processedMemberUserIds.add(userId);
var newDisplayName = (_event$getContent$dis = event.getContent().displayname) !== null && _event$getContent$dis !== void 0 ? _event$getContent$dis : "";
var oldDisplayName = this.userIdsToDisplayNames[userId];
if (oldDisplayName) {
var strippedOld = removeHiddenChars(oldDisplayName);
if (strippedOld) affectedDisplayNames.add(strippedOld);
}
if (newDisplayName) {
var strippedNew = removeHiddenChars(newDisplayName);
if (strippedNew) affectedDisplayNames.add(strippedNew);
}
this.updateDisplayNameCache(userId, newDisplayName);
this.updateThirdPartyTokenCache(event);
}
this.emit(RoomStateEvent.Events, event, this, lastStateEvent);
});
this.onBeaconLivenessChange();
stateEvents.forEach((event) => {
if (event.getRoomId() !== this.roomId || !event.isState()) return;
if (event.getType() === EventType.RoomMember) {
var userId = event.getStateKey();
if (event.getContent().membership === KnownMembership.Leave || event.getContent().membership === KnownMembership.Ban) {
event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url;
event.getContent().displayname = event.getContent().displayname || event.getPrevContent().displayname;
}
var member = this.getOrCreateMember(userId, event);
member.setMembershipEvent(event, this);
this.updateMember(member);
this.emit(RoomStateEvent.Members, event, this, member);
} else if (event.getType() === EventType.RoomPowerLevels) {
if (event.getStateKey() !== "") return;
var members = Object.values(this.members);
var createEvent = this.getStateEvents(EventType.RoomCreate, "");
var creators = getCreators(this.getRoomVersion(), createEvent);
members.forEach((member) => {
var oldLastModified = member.getLastModifiedTime();
if (createEvent) {
var pl = powerLevelForUserId(member.userId, event, creators);
member.setPowerLevel(pl, event);
}
if (oldLastModified !== member.getLastModifiedTime()) this.emit(RoomStateEvent.Members, event, this, member);
});
this.sentinels = {};
} else if (UNSTABLE_MSC2716_MARKER.matches(event.getType())) this.emit(RoomStateEvent.Marker, event, markerFoundOptions);
});
if (affectedDisplayNames.size > 0) {
var affectedUserIds = /* @__PURE__ */ new Set();
for (var displayName of affectedDisplayNames) {
var _this$displayNameToUs;
((_this$displayNameToUs = this.displayNameToUserIds.get(displayName)) !== null && _this$displayNameToUs !== void 0 ? _this$displayNameToUs : []).forEach((id) => affectedUserIds.add(id));
}
for (var userId of affectedUserIds) {
if (processedMemberUserIds.has(userId)) continue;
var member = this.members[userId];
if (member !== null && member !== void 0 && member.events.member) {
if (member.recalculateDisambiguatedName(this)) this.emit(RoomStateEvent.Members, member.events.member, this, member);
}
}
}
this.emit(RoomStateEvent.Update, this);
}
processBeaconEvents(events, matrixClient) {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!events.length || !_this.beacons.size) return;
var beaconByEventIdDict = [..._this.beacons.values()].reduce((dict, beacon) => {
dict[beacon.beaconInfoId] = beacon;
return dict;
}, {});
var processBeaconRelation = (beaconInfoEventId, event) => {
if (!M_BEACON.matches(event.getType())) return;
var beacon = beaconByEventIdDict[beaconInfoEventId];
if (beacon) beacon.addLocations([event]);
};
var _loop = function* _loop(event) {
var _event$getRelation;
var relatedToEventId = (_event$getRelation = event.getRelation()) === null || _event$getRelation === void 0 ? void 0 : _event$getRelation.event_id;
if (!relatedToEventId || !beaconByEventIdDict[relatedToEventId]) return { v: void 0 };
if (!M_BEACON.matches(event.getType()) && !event.isEncrypted()) return { v: void 0 };
try {
yield matrixClient.decryptEventIfNeeded(event);
processBeaconRelation(relatedToEventId, event);
} catch (_unused) {
if (event.isDecryptionFailure()) event.once(MatrixEventEvent.Decrypted, /* @__PURE__ */ (0, import_asyncToGenerator.default)(function* () {
processBeaconRelation(relatedToEventId, event);
}));
}
}, _ret;
for (var event of events) {
_ret = yield* _loop(event);
if (_ret) return _ret.v;
}
})();
}
/**
* Looks up a member by the given userId, and if it doesn't exist,
* create it and emit the `RoomState.newMember` event.
* This method makes sure the member is added to the members dictionary
* before emitting, as this is done from setStateEvents and setOutOfBandMember.
* @param userId - the id of the user to look up
* @param event - the membership event for the (new) member. Used to emit.
* @returns the member, existing or newly created.
*
* @remarks
* Fires {@link RoomStateEvent.NewMember}
*/
getOrCreateMember(userId, event) {
var member = this.members[userId];
if (!member) {
member = new RoomMember(this.roomId, userId);
this.members[userId] = member;
this.emit(RoomStateEvent.NewMember, event, this, member);
}
return member;
}
setStateEvent(event) {
if (!this.events.has(event.getType())) this.events.set(event.getType(), /* @__PURE__ */ new Map());
this.events.get(event.getType()).set(event.getStateKey(), event);
}
/**
* @experimental
*/
setBeacon(event) {
var beaconIdentifier = getBeaconInfoIdentifier(event);
if (this.beacons.has(beaconIdentifier)) {
var _beacon = this.beacons.get(beaconIdentifier);
if (event.isRedacted()) {
var _event$getRedactionEv;
if (_beacon.beaconInfoId === ((_event$getRedactionEv = event.getRedactionEvent()) === null || _event$getRedactionEv === void 0 ? void 0 : _event$getRedactionEv.redacts)) {
_beacon.destroy();
this.beacons.delete(beaconIdentifier);
}
return;
}
return _beacon.update(event);
}
if (event.isRedacted()) return;
var beacon = new Beacon(event);
this.reEmitter.reEmit(beacon, [
BeaconEvent.New,
BeaconEvent.Update,
BeaconEvent.Destroy,
BeaconEvent.LivenessChange
]);
this.emit(BeaconEvent.New, event, beacon);
beacon.on(BeaconEvent.LivenessChange, this.onBeaconLivenessChange.bind(this));
beacon.on(BeaconEvent.Destroy, this.onBeaconLivenessChange.bind(this));
this.beacons.set(beacon.identifier, beacon);
}
/**
* @experimental
* Check liveness of room beacons
* emit RoomStateEvent.BeaconLiveness event
*/
onBeaconLivenessChange() {
this._liveBeaconIds = Array.from(this.beacons.values()).filter((beacon) => beacon.isLive).map((beacon) => beacon.identifier);
this.emit(RoomStateEvent.BeaconLiveness, this, this.hasLiveBeacons);
}
getStateEventMatching(event) {
var _this$events$get$get, _this$events$get;
return (_this$events$get$get = (_this$events$get = this.events.get(event.getType())) === null || _this$events$get === void 0 ? void 0 : _this$events$get.get(event.getStateKey())) !== null && _this$events$get$get !== void 0 ? _this$events$get$get : null;
}
updateMember(member) {
var createEvent = this.getStateEvents(EventType.RoomCreate, "");
var pwrLvlEvent = this.getStateEvents(EventType.RoomPowerLevels, "");
if (pwrLvlEvent && createEvent) {
var powerLevel = powerLevelForUserId(member.userId, pwrLvlEvent, getCreators(this.getRoomVersion(), createEvent));
member.setPowerLevel(powerLevel, pwrLvlEvent);
}
delete this.sentinels[member.userId];
this.members[member.userId] = member;
this.joinedMemberCount = null;
this.invitedMemberCount = null;
}
/**
* Get the out-of-band members loading state, whether loading is needed or not.
* Note that loading might be in progress and hence isn't needed.
* @returns whether or not the members of this room need to be loaded
*/
needsOutOfBandMembers() {
return this.oobMemberFlags.status === OobStatus.NotStarted;
}
/**
* Check if loading of out-of-band-members has completed
*
* @returns true if the full membership list of this room has been loaded. False if it is not started or is in
* progress.
*/
outOfBandMembersReady() {
return this.oobMemberFlags.status === OobStatus.Finished;
}
/**
* Mark this room state as waiting for out-of-band members,
* ensuring it doesn't ask for them to be requested again
* through needsOutOfBandMembers
*/
markOutOfBandMembersStarted() {
if (this.oobMemberFlags.status !== OobStatus.NotStarted) return;
this.oobMemberFlags.status = OobStatus.InProgress;
}
/**
* Mark this room state as having failed to fetch out-of-band members
*/
markOutOfBandMembersFailed() {
if (this.oobMemberFlags.status !== OobStatus.InProgress) return;
this.oobMemberFlags.status = OobStatus.NotStarted;
}
/**
* Clears the loaded out-of-band members
*/
clearOutOfBandMembers() {
var count = 0;
Object.keys(this.members).forEach((userId) => {
if (this.members[userId].isOutOfBand()) {
++count;
delete this.members[userId];
}
});
logger$2.log("LL: RoomState removed ".concat(count, " members..."));
this.oobMemberFlags.status = OobStatus.NotStarted;
}
/**
* Sets the loaded out-of-band members.
* @param stateEvents - array of membership state events
*/
setOutOfBandMembers(stateEvents) {
logger$2.log("LL: RoomState about to set ".concat(stateEvents.length, " OOB members ..."));
if (this.oobMemberFlags.status !== OobStatus.InProgress) return;
logger$2.log("LL: RoomState put in finished state ...");
this.oobMemberFlags.status = OobStatus.Finished;
stateEvents.forEach((e) => this.setOutOfBandMember(e));
this.emit(RoomStateEvent.Update, this);
}
/**
* Sets a single out of band member, used by both setOutOfBandMembers and clone
* @param stateEvent - membership state event
*/
setOutOfBandMember(stateEvent) {
if (stateEvent.getType() !== EventType.RoomMember) return;
var userId = stateEvent.getStateKey();
var existingMember = this.getMember(userId);
if (existingMember && !existingMember.isOutOfBand()) return;
var member = this.getOrCreateMember(userId, stateEvent);
member.setMembershipEvent(stateEvent, this);
member.markOutOfBand();
this.updateDisplayNameCache(member.userId, member.name);
this.setStateEvent(stateEvent);
this.updateMember(member);
this.emit(RoomStateEvent.Members, stateEvent, this, member);
}
/**
* Set the current typing event for this room.
* @param event - The typing event
*/
setTypingEvent(event) {
Object.values(this.members).forEach(function(member) {
member.setTypingEvent(event);
});
}
/**
* Get the m.room.member event which has the given third party invite token.
*
* @param token - The token
* @returns The m.room.member event or null
*/
getInviteForThreePidToken(token) {
return this.tokenToInvite[token] || null;
}
/**
* Update the last modified time to the current time.
*/
updateModifiedTime() {
this.modified = Date.now();
}
/**
* Get the timestamp when this room state was last updated. This timestamp is
* updated when this object has received new state events.
* @returns The timestamp
*/
getLastModifiedTime() {
return this.modified;
}
/**
* Get user IDs with the specified or similar display names.
* @param displayName - The display name to get user IDs from.
* @returns An array of user IDs or an empty array.
*/
getUserIdsWithDisplayName(displayName) {
var _this$displayNameToUs2;
return (_this$displayNameToUs2 = this.displayNameToUserIds.get(removeHiddenChars(displayName))) !== null && _this$displayNameToUs2 !== void 0 ? _this$displayNameToUs2 : [];
}
/**
* Returns true if userId is in room, event is not redacted and either sender of
* mxEvent or has power level sufficient to redact events other than their own.
* @param mxEvent - The event to test permission for
* @param userId - The user ID of the user to test permission for
* @returns true if the given used ID can redact given event
*/
maySendRedactionForEvent(mxEvent, userId) {
var member = this.getMember(userId);
if (!member || member.membership === KnownMembership.Leave) return false;
if (mxEvent.status || mxEvent.isRedacted()) return false;
if (!this.maySendEvent(EventType.RoomRedaction, userId)) return false;
if (mxEvent.getSender() === userId) return true;
return this.hasSufficientPowerLevelFor("redact", member.powerLevel);
}
/**
* Returns true if the given power level is sufficient for action
* @param action - The type of power level to check
* @param powerLevel - The power level of the member
* @returns true if the given power level is sufficient
*/
hasSufficientPowerLevelFor(action, powerLevel) {
var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, "");
var powerLevels = {};
if (powerLevelsEvent) powerLevels = powerLevelsEvent.getContent();
var requiredLevel = 50;
if (isNumber(powerLevels[action])) requiredLevel = powerLevels[action];
return powerLevel >= requiredLevel;
}
/**
* Short-form for maySendEvent('m.room.message', userId)
* @param userId - The user ID of the user to test permission for
* @returns true if the given user ID should be permitted to send
* message events into the given room.
*/
maySendMessage(userId) {
return this.maySendEventOfType(EventType.RoomMessage, userId, false);
}
/**
* Returns true if the given user ID has permission to send a normal
* event of type `eventType` into this room.
* @param eventType - The type of event to test
* @param userId - The user ID of the user to test permission for
* @returns true if the given user ID should be permitted to send
* the given type of event into this room,
* according to the room's state.
*/
maySendEvent(eventType, userId) {
return this.maySendEventOfType(eventType, userId, false);
}
/**
* Returns true if the given MatrixClient has permission to send a state
* event of type `stateEventType` into this room.
* @param stateEventType - The type of state events to test
* @param cli - The client to test permission for
* @returns true if the given client should be permitted to send
* the given type of state event into this room,
* according to the room's state.
*/
mayClientSendStateEvent(stateEventType, cli) {
if (cli.isGuest() || !cli.credentials.userId) return false;
return this.maySendStateEvent(stateEventType, cli.credentials.userId);
}
/**
* Returns true if the given user ID has permission to send a state
* event of type `stateEventType` into this room.
* @param stateEventType - The type of state events to test
* @param userId - The user ID of the user to test permission for
* @returns true if the given user ID should be permitted to send
* the given type of state event into this room,
* according to the room's state.
*/
maySendStateEvent(stateEventType, userId) {
return this.maySendEventOfType(stateEventType, userId, true);
}
/**
* Returns true if the given user ID has permission to send a normal or state
* event of type `eventType` into this room.
* @param eventType - The type of event to test
* @param userId - The user ID of the user to test permission for
* @param state - If true, tests if the user may send a state
event of this type. Otherwise tests whether
they may send a regular event.
* @returns true if the given user ID should be permitted to send
* the given type of event into this room,
* according to the room's state.
*/
maySendEventOfType(eventType, userId, state) {
var _roomMember$powerLeve;
var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, "");
var powerLevels;
var eventsLevels = {};
var stateDefault = 0;
var eventsDefault = 0;
if (powerLevelsEvent) {
powerLevels = powerLevelsEvent.getContent();
eventsLevels = powerLevels.events || {};
if (Number.isSafeInteger(powerLevels.state_default)) stateDefault = powerLevels.state_default;
else stateDefault = 50;
if (Number.isSafeInteger(powerLevels.events_default)) eventsDefault = powerLevels.events_default;
}
var requiredLevel = state ? stateDefault : eventsDefault;
if (Number.isSafeInteger(eventsLevels[eventType])) requiredLevel = eventsLevels[eventType];
var roomMember = this.getMember(userId);
return ((_roomMember$powerLeve = roomMember === null || roomMember === void 0 ? void 0 : roomMember.powerLevel) !== null && _roomMember$powerLeve !== void 0 ? _roomMember$powerLeve : 0) >= requiredLevel;
}
/**
* Returns true if the given user ID has permission to trigger notification
* of type `notifLevelKey`
* @param notifLevelKey - The level of notification to test (eg. 'room')
* @param userId - The user ID of the user to test permission for
* @returns true if the given user ID has permission to trigger a
* notification of this type.
*/
mayTriggerNotifOfType(notifLevelKey, userId) {
var member = this.getMember(userId);
if (!member) return false;
var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, "");
var notifLevel = 50;
if (powerLevelsEvent && powerLevelsEvent.getContent() && powerLevelsEvent.getContent().notifications && isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])) notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];
return member.powerLevel >= notifLevel;
}
/**
* Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
* @returns the join_rule applied to this room
*/
getJoinRule() {
var _joinRuleEvent$getCon;
var joinRuleEvent = this.getStateEvents(EventType.RoomJoinRules, "");
return ((_joinRuleEvent$getCon = joinRuleEvent === null || joinRuleEvent === void 0 ? void 0 : joinRuleEvent.getContent()) !== null && _joinRuleEvent$getCon !== void 0 ? _joinRuleEvent$getCon : {})["join_rule"] || JoinRule.Invite;
}
/**
* Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
* @returns the history_visibility applied to this room
*/
getHistoryVisibility() {
var _historyVisibilityEve;
var historyVisibilityEvent = this.getStateEvents(EventType.RoomHistoryVisibility, "");
return ((_historyVisibilityEve = historyVisibilityEvent === null || historyVisibilityEvent === void 0 ? void 0 : historyVisibilityEvent.getContent()) !== null && _historyVisibilityEve !== void 0 ? _historyVisibilityEve : {})["history_visibility"] || HistoryVisibility.Shared;
}
/**
* Returns the guest access based on the m.room.guest_access state event, defaulting to `shared`.
* @returns the guest_access applied to this room
*/
getGuestAccess() {
var _guestAccessEvent$get;
var guestAccessEvent = this.getStateEvents(EventType.RoomGuestAccess, "");
return ((_guestAccessEvent$get = guestAccessEvent === null || guestAccessEvent === void 0 ? void 0 : guestAccessEvent.getContent()) !== null && _guestAccessEvent$get !== void 0 ? _guestAccessEvent$get : {})["guest_access"] || GuestAccess.Forbidden;
}
/**
* Find the predecessor room based on this room state.
*
* @param msc3946ProcessDynamicPredecessor - if true, look for an
* m.room.predecessor state event and use it if found (MSC3946).
* @returns null if this room has no predecessor. Otherwise, returns
* the roomId, last eventId and viaServers of the predecessor room.
*
* If msc3946ProcessDynamicPredecessor is true, use m.predecessor events
* as well as m.room.create events to find predecessors.
*
* Note: if an m.predecessor event is used, eventId may be undefined
* since last_known_event_id is optional.
*
* Note: viaServers may be undefined, and will definitely be undefined if
* this predecessor comes from a RoomCreate event (rather than a
* RoomPredecessor, which has the optional via_servers property).
*/
findPredecessor() {
if (arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false) {
var predecessorEvent = this.getStateEvents(EventType.RoomPredecessor, "");
if (predecessorEvent) {
var content = predecessorEvent.getContent();
var _roomId = content.predecessor_room_id;
var eventId = content.last_known_event_id;
if (typeof eventId !== "string") eventId = void 0;
var viaServers = content.via_servers;
if (!Array.isArray(viaServers)) viaServers = void 0;
if (typeof _roomId === "string") return {
roomId: _roomId,
eventId,
viaServers
};
}
}
var createEvent = this.getStateEvents(EventType.RoomCreate, "");
if (createEvent) {
var predecessor = createEvent.getContent()["predecessor"];
if (predecessor) {
var _roomId2 = predecessor["room_id"];
if (typeof _roomId2 === "string") {
var _eventId = predecessor["event_id"];
if (typeof _eventId !== "string" || _eventId === "") _eventId = void 0;
return {
roomId: _roomId2,
eventId: _eventId
};
}
}
}
return null;
}
updateThirdPartyTokenCache(memberEvent) {
if (!memberEvent.getContent().third_party_invite) return;
var token = (memberEvent.getContent().third_party_invite.signed || {}).token;
if (!token) return;
if (!this.getStateEvents(EventType.RoomThirdPartyInvite, token)) return;
this.tokenToInvite[token] = memberEvent;
}
updateDisplayNameCache(userId, displayName) {
var oldName = this.userIdsToDisplayNames[userId];
delete this.userIdsToDisplayNames[userId];
if (oldName) {
var strippedOldName = removeHiddenChars(oldName);
var existingUserIds = this.displayNameToUserIds.get(strippedOldName);
if (existingUserIds) {
var filteredUserIDs = existingUserIds.filter((id) => id !== userId);
this.displayNameToUserIds.set(strippedOldName, filteredUserIDs);
}
}
this.userIdsToDisplayNames[userId] = displayName;
var strippedDisplayname = displayName && removeHiddenChars(displayName);
if (strippedDisplayname) {
var _this$displayNameToUs3;
var arr = (_this$displayNameToUs3 = this.displayNameToUserIds.get(strippedDisplayname)) !== null && _this$displayNameToUs3 !== void 0 ? _this$displayNameToUs3 : [];
arr.push(userId);
this.displayNameToUserIds.set(strippedDisplayname, arr);
}
}
};
/**
* Get the set of creator user IDs for a room: empty if the room is not a 'hydra' room, otherwise
* computed from the sender of the m.room.create event plus the additional_creators field.
* @param roomVersion The version of the room
* @param roomCreateEvent The m.room.create event for the room
* @returns A set of user IDs of the creators of the room.
*/
function getCreators(roomVersion, roomCreateEvent) {
var creators = /* @__PURE__ */ new Set();
if (shouldUseHydraForRoomVersion(roomVersion) && roomCreateEvent) {
var roomCreateSender = roomCreateEvent.getSender();
if (roomCreateSender) creators.add(roomCreateSender);
var additionalCreators = roomCreateEvent.getDirectionalContent().additional_creators;
if (Array.isArray(additionalCreators)) additionalCreators.forEach((c) => creators.add(c));
}
return creators;
}
/**
*
* @param userId The user ID to compute the power level for
* @param powerLevelEvents The power level event for the room
* @param creators The set of creator user IDs for the room if the room is a 'hydra' room, otherwise the empty set.
*/
function powerLevelForUserId(userId, powerLevelEvent, creators) {
if (creators.has(userId)) return Infinity;
else {
var evContent = powerLevelEvent.getDirectionalContent();
var users = evContent.users || {};
if (users[userId] !== void 0 && Number.isInteger(users[userId])) return users[userId];
else if (evContent.users_default !== void 0) return evContent.users_default;
else return 0;
}
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/models/device.js
/** State of the verification of the device. */
var DeviceVerification = /* @__PURE__ */ function(DeviceVerification) {
DeviceVerification[DeviceVerification["Blocked"] = -1] = "Blocked";
DeviceVerification[DeviceVerification["Unverified"] = 0] = "Unverified";
DeviceVerification[DeviceVerification["Verified"] = 1] = "Verified";
return DeviceVerification;
}({});
/** A map from user ID to device ID to Device */
/**
* Information on a user's device, as returned by {@link crypto-api!CryptoApi.getUserDeviceInfo}.
*/
var Device = class {
constructor(opts) {
/** id of the device */
(0, import_defineProperty.default)(this, "deviceId", void 0);
/** id of the user that owns the device */
(0, import_defineProperty.default)(this, "userId", void 0);
/** list of algorithms supported by this device */
(0, import_defineProperty.default)(this, "algorithms", void 0);
/** a map from `<key type>:<id> -> <base64-encoded key>` */
(0, import_defineProperty.default)(this, "keys", void 0);
/** whether the device has been verified/blocked by the user */
(0, import_defineProperty.default)(this, "verified", void 0);
/** a map `<userId, map<algorithm:device_id, signature>>` */
(0, import_defineProperty.default)(this, "signatures", void 0);
/** display name of the device */
(0, import_defineProperty.default)(this, "displayName", void 0);
/** whether the device is a dehydrated device */
(0, import_defineProperty.default)(this, "dehydrated", false);
this.deviceId = opts.deviceId;
this.userId = opts.userId;
this.algorithms = opts.algorithms;
this.keys = opts.keys;
this.verified = opts.verified || DeviceVerification.Unverified;
this.signatures = opts.signatures || /* @__PURE__ */ new Map();
this.displayName = opts.displayName;
this.dehydrated = !!opts.dehydrated;
}
/**
* Get the fingerprint for this device (ie, the Ed25519 key)
*
* @returns base64-encoded fingerprint of this device
*/
getFingerprint() {
return this.keys.get("ed25519:".concat(this.deviceId));
}
/**
* Get the identity key for this device (ie, the Curve25519 key)
*
* @returns base64-encoded identity key of this device
*/
getIdentityKey() {
return this.keys.get("curve25519:".concat(this.deviceId));
}
};
//#endregion
//#region node_modules/matrix-js-sdk/lib/indexeddb-helpers.js
/**
* Check if an IndexedDB database exists. The only way to do so is to try opening it, so
* we do that and then delete it did not exist before.
*
* @param indexedDB - The `indexedDB` interface
* @param dbName - The database name to test for
* @returns Whether the database exists
*/
function exists(indexedDB, dbName) {
return new Promise((resolve, reject) => {
var exists = true;
var req = indexedDB.open(dbName);
req.onupgradeneeded = () => {
exists = false;
};
req.onblocked = () => reject(req.error);
req.onsuccess = () => {
req.result.close();
if (!exists) indexedDB.deleteDatabase(dbName);
resolve(exists);
};
req.onerror = () => reject(req.error);
});
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto/store/localStorage-crypto-store.js
/**
* Internal module. Partial localStorage backed storage for e2e.
* This is not a full crypto store, just the in-memory store with
* some things backed by localStorage. It exists because indexedDB
* is broken in Firefox private mode or set to, "will not remember
* history".
*/
var E2E_PREFIX = "crypto.";
var KEY_END_TO_END_MIGRATION_STATE = E2E_PREFIX + "migration";
var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
var KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + "cross_signing_keys";
var KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + "inboundgroupsessions/";
var KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + "inboundgroupsessions.withheld/";
var KEY_ROOMS_PREFIX = E2E_PREFIX + "rooms/";
var KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + "sessionsneedingbackup";
function keyEndToEndSessions(deviceKey) {
return E2E_PREFIX + "sessions/" + deviceKey;
}
function keyEndToEndInboundGroupSession(senderKey, sessionId) {
return KEY_INBOUND_SESSION_PREFIX + senderKey + "/" + sessionId;
}
function keyEndToEndInboundGroupSessionWithheld(senderKey, sessionId) {
return KEY_INBOUND_SESSION_WITHHELD_PREFIX + senderKey + "/" + sessionId;
}
function keyEndToEndRoomsPrefix(roomId) {
return KEY_ROOMS_PREFIX + roomId;
}
var LocalStorageCryptoStore = class LocalStorageCryptoStore extends MemoryCryptoStore {
static exists(store) {
var length = store.length;
for (var i = 0; i < length; i++) {
var _store$key;
if ((_store$key = store.key(i)) !== null && _store$key !== void 0 && _store$key.startsWith(E2E_PREFIX)) return true;
}
return false;
}
constructor(store) {
super();
this.store = store;
}
/**
* Returns true if this CryptoStore has ever been initialised (ie, it might contain data).
*
* Implementation of {@link CryptoStore.containsData}.
*
* @internal
*/
containsData() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
return LocalStorageCryptoStore.exists(_this.store);
})();
}
/**
* Get data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.getMigrationState}.
*
* @internal
*/
getMigrationState() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var _getJsonItem;
return (_getJsonItem = getJsonItem(_this2.store, KEY_END_TO_END_MIGRATION_STATE)) !== null && _getJsonItem !== void 0 ? _getJsonItem : MigrationState.NOT_STARTED;
})();
}
/**
* Set data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.setMigrationState}.
*
* @internal
*/
setMigrationState(migrationState) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
setJsonItem(_this3.store, KEY_END_TO_END_MIGRATION_STATE, migrationState);
})();
}
countEndToEndSessions(txn, func) {
var count = 0;
for (var i = 0; i < this.store.length; ++i) {
var key = this.store.key(i);
if (key !== null && key !== void 0 && key.startsWith(keyEndToEndSessions(""))) {
var sessions = getJsonItem(this.store, key);
count += Object.keys(sessions !== null && sessions !== void 0 ? sessions : {}).length;
}
}
func(count);
}
_getEndToEndSessions(deviceKey) {
var sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey));
var fixedSessions = {};
for (var [sid, val] of Object.entries(sessions || {})) if (typeof val === "string") fixedSessions[sid] = { session: val };
else fixedSessions[sid] = val;
return fixedSessions;
}
getEndToEndSession(deviceKey, sessionId, txn, func) {
var _sessions$sessionId;
func((_sessions$sessionId = this._getEndToEndSessions(deviceKey)[sessionId]) !== null && _sessions$sessionId !== void 0 ? _sessions$sessionId : {});
}
getEndToEndSessions(deviceKey, txn, func) {
var _this$_getEndToEndSes;
func((_this$_getEndToEndSes = this._getEndToEndSessions(deviceKey)) !== null && _this$_getEndToEndSes !== void 0 ? _this$_getEndToEndSes : {});
}
storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
var sessions = this._getEndToEndSessions(deviceKey) || {};
sessions[sessionId] = sessionInfo;
setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions);
}
/**
* Fetch a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.
*
* @internal
*/
getEndToEndSessionsBatch() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = [];
for (var i = 0; i < _this4.store.length; ++i) {
var _this4$store$key;
if ((_this4$store$key = _this4.store.key(i)) !== null && _this4$store$key !== void 0 && _this4$store$key.startsWith(keyEndToEndSessions(""))) {
var deviceKey = _this4.store.key(i).split("/")[1];
for (var session of Object.values(_this4._getEndToEndSessions(deviceKey))) {
result.push(session);
if (result.length >= 50) return result;
}
}
}
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.
*
* @internal
*/
deleteEndToEndSessionsBatch(sessions) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var { deviceKey, sessionId } of sessions) {
var deviceSessions = _this5._getEndToEndSessions(deviceKey) || {};
delete deviceSessions[sessionId];
if (Object.keys(deviceSessions).length === 0) _this5.store.removeItem(keyEndToEndSessions(deviceKey));
else setJsonItem(_this5.store, keyEndToEndSessions(deviceKey), deviceSessions);
}
})();
}
getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
func(getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)), getJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId)));
}
storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData);
}
/**
* Count the number of Megolm sessions in the database.
*
* Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.
*
* @internal
*/
countEndToEndInboundGroupSessions() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var count = 0;
for (var i = 0; i < _this6.store.length; ++i) {
var key = _this6.store.key(i);
if (key !== null && key !== void 0 && key.startsWith(KEY_INBOUND_SESSION_PREFIX)) count += 1;
}
return count;
})();
}
/**
* Fetch a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
getEndToEndInboundGroupSessionsBatch() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var sessionsNeedingBackup = getJsonItem(_this7.store, KEY_SESSIONS_NEEDING_BACKUP) || {};
var result = [];
for (var i = 0; i < _this7.store.length; ++i) {
var key = _this7.store.key(i);
if (key !== null && key !== void 0 && key.startsWith(KEY_INBOUND_SESSION_PREFIX)) {
var key2 = key.slice(KEY_INBOUND_SESSION_PREFIX.length);
result.push({
senderKey: key2.slice(0, 43),
sessionId: key2.slice(44),
sessionData: getJsonItem(_this7.store, key),
needsBackup: key2 in sessionsNeedingBackup
});
if (result.length >= 50) return result;
}
}
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
deleteEndToEndInboundGroupSessionsBatch(sessions) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
for (var { senderKey, sessionId } of sessions) {
var k = keyEndToEndInboundGroupSession(senderKey, sessionId);
_this8.store.removeItem(k);
}
})();
}
getEndToEndRooms(txn, func) {
var result = {};
var prefix = keyEndToEndRoomsPrefix("");
for (var i = 0; i < this.store.length; ++i) {
var key = this.store.key(i);
if (key !== null && key !== void 0 && key.startsWith(prefix)) {
var roomId = key.slice(prefix.length);
result[roomId] = getJsonItem(this.store, key);
}
}
func(result);
}
markSessionsNeedingBackup(sessions) {
var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};
for (var session of sessions) sessionsNeedingBackup[session.senderKey + "/" + session.sessionId] = true;
setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup);
return Promise.resolve();
}
/**
* Delete all data from this store.
*
* @returns Promise which resolves when the store has been cleared.
*/
deleteAllData() {
this.store.removeItem(KEY_END_TO_END_ACCOUNT);
return Promise.resolve();
}
getAccount(txn, func) {
func(getJsonItem(this.store, KEY_END_TO_END_ACCOUNT));
}
storeAccount(txn, accountPickle) {
setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, accountPickle);
}
getCrossSigningKeys(txn, func) {
func(getJsonItem(this.store, KEY_CROSS_SIGNING_KEYS));
}
getSecretStorePrivateKey(txn, func, type) {
func(getJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type)));
}
storeSecretStorePrivateKey(txn, type, key) {
setJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type), key);
}
doTxn(mode, stores, func) {
return Promise.resolve(func(null));
}
};
function getJsonItem(store, key) {
try {
return JSON.parse(store.getItem(key));
} catch (e) {
logger$2.log("Error: Failed to get key %s: %s", key, e.message);
logger$2.log(e.stack);
}
return null;
}
function setJsonItem(store, key, val) {
store.setItem(key, JSON.stringify(val));
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto/store/indexeddb-crypto-store-backend.js
var PROFILE_TRANSACTIONS = false;
/**
* Implementation of a CryptoStore which is backed by an existing
* IndexedDB connection. Generally you want IndexedDBCryptoStore
* which connects to the database and defers to one of these.
*
* @internal
*/
var Backend = class {
/**
*/
constructor(db) {
this.db = db;
(0, import_defineProperty.default)(this, "nextTxnId", 0);
db.onversionchange = () => {
logger$2.log("versionchange for indexeddb ".concat(this.db.name, ": closing"));
db.close();
};
}
containsData() {
return (0, import_asyncToGenerator.default)(function* () {
throw Error("Not implemented for Backend");
})();
}
startup() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
return _this;
})();
}
deleteAllData() {
return (0, import_asyncToGenerator.default)(function* () {
throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.");
})();
}
/**
* Get data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.getMigrationState}.
*/
getMigrationState() {
var _this2 = this;
return (0, import_asyncToGenerator.default)(function* () {
var migrationState = MigrationState.NOT_STARTED;
yield _this2.doTxn("readonly", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
var getReq = txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT).get(ACCOUNT_OBJECT_KEY_MIGRATION_STATE);
getReq.onsuccess = () => {
var _getReq$result;
migrationState = (_getReq$result = getReq.result) !== null && _getReq$result !== void 0 ? _getReq$result : MigrationState.NOT_STARTED;
};
});
return migrationState;
})();
}
/**
* Set data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.setMigrationState}.
*/
setMigrationState(migrationState) {
var _this3 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this3.doTxn("readwrite", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {
txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT).put(migrationState, ACCOUNT_OBJECT_KEY_MIGRATION_STATE);
});
})();
}
getAccount(txn, func) {
var getReq = txn.objectStore("account").get("-");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
storeAccount(txn, accountPickle) {
txn.objectStore("account").put(accountPickle, "-");
}
getCrossSigningKeys(txn, func) {
var getReq = txn.objectStore("account").get("crossSigningKeys");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
getSecretStorePrivateKey(txn, func, type) {
var getReq = txn.objectStore("account").get("ssss_cache:".concat(type));
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
storeSecretStorePrivateKey(txn, type, key) {
txn.objectStore("account").put(key, "ssss_cache:".concat(type));
}
countEndToEndSessions(txn, func) {
var countReq = txn.objectStore("sessions").count();
countReq.onsuccess = function() {
try {
func(countReq.result);
} catch (e) {
abortWithException(txn, e);
}
};
}
getEndToEndSessions(deviceKey, txn, func) {
var getReq = txn.objectStore("sessions").index("deviceKey").openCursor(deviceKey);
var results = {};
getReq.onsuccess = function() {
var cursor = getReq.result;
if (cursor) {
results[cursor.value.sessionId] = {
session: cursor.value.session,
lastReceivedMessageTs: cursor.value.lastReceivedMessageTs
};
cursor.continue();
} else try {
func(results);
} catch (e) {
abortWithException(txn, e);
}
};
}
getEndToEndSession(deviceKey, sessionId, txn, func) {
var getReq = txn.objectStore("sessions").get([deviceKey, sessionId]);
getReq.onsuccess = function() {
try {
if (getReq.result) func({
session: getReq.result.session,
lastReceivedMessageTs: getReq.result.lastReceivedMessageTs
});
else func(null);
} catch (e) {
abortWithException(txn, e);
}
};
}
storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
txn.objectStore("sessions").put({
deviceKey,
sessionId,
session: sessionInfo.session,
lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs
});
}
/**
* Fetch a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.
*/
getEndToEndSessionsBatch() {
var _this4 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = [];
yield _this4.doTxn("readonly", [IndexedDBCryptoStore.STORE_SESSIONS], (txn) => {
var getReq = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS).openCursor();
getReq.onsuccess = function() {
try {
var cursor = getReq.result;
if (cursor) {
result.push(cursor.value);
if (result.length < 50) cursor.continue();
}
} catch (e) {
abortWithException(txn, e);
}
};
});
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.
*
* @internal
*/
deleteEndToEndSessionsBatch(sessions) {
var _this5 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this5.doTxn("readwrite", [IndexedDBCryptoStore.STORE_SESSIONS], /* @__PURE__ */ function() {
var _ref = (0, import_asyncToGenerator.default)(function* (txn) {
try {
var objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);
var _loop = function* _loop() {
var req = objectStore.delete([deviceKey, sessionId]);
yield new Promise((resolve) => {
req.onsuccess = resolve;
});
};
for (var { deviceKey, sessionId } of sessions) yield* _loop();
} catch (e) {
abortWithException(txn, e);
}
});
return function(_x) {
return _ref.apply(this, arguments);
};
}());
})();
}
getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
var session = false;
var withheld = false;
var getReq = txn.objectStore("inbound_group_sessions").get([senderCurve25519Key, sessionId]);
getReq.onsuccess = function() {
try {
if (getReq.result) session = getReq.result.session;
else session = null;
if (withheld !== false) func(session, withheld);
} catch (e) {
abortWithException(txn, e);
}
};
var withheldGetReq = txn.objectStore("inbound_group_sessions_withheld").get([senderCurve25519Key, sessionId]);
withheldGetReq.onsuccess = function() {
try {
if (withheldGetReq.result) withheld = withheldGetReq.result.session;
else withheld = null;
if (session !== false) func(session, withheld);
} catch (e) {
abortWithException(txn, e);
}
};
}
storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
txn.objectStore("inbound_group_sessions").put({
senderCurve25519Key,
sessionId,
session: sessionData
});
}
/**
* Count the number of Megolm sessions in the database.
*
* Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.
*
* @internal
*/
countEndToEndInboundGroupSessions() {
var _this6 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = 0;
yield _this6.doTxn("readonly", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {
var countReq = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS).count();
countReq.onsuccess = () => {
result = countReq.result;
};
});
return result;
})();
}
/**
* Fetch a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.
*/
getEndToEndInboundGroupSessionsBatch() {
var _this7 = this;
return (0, import_asyncToGenerator.default)(function* () {
var result = [];
yield _this7.doTxn("readonly", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_BACKUP], (txn) => {
var sessionStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);
var backupStore = txn.objectStore(IndexedDBCryptoStore.STORE_BACKUP);
var getReq = sessionStore.openCursor();
getReq.onsuccess = function() {
try {
var cursor = getReq.result;
if (cursor) {
var backupGetReq = backupStore.get(cursor.key);
backupGetReq.onsuccess = () => {
result.push({
senderKey: cursor.value.senderCurve25519Key,
sessionId: cursor.value.sessionId,
sessionData: cursor.value.session,
needsBackup: backupGetReq.result !== void 0
});
if (result.length < 50) cursor.continue();
};
}
} catch (e) {
abortWithException(txn, e);
}
};
});
if (result.length === 0) return null;
return result;
})();
}
/**
* Delete a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
deleteEndToEndInboundGroupSessionsBatch(sessions) {
var _this8 = this;
return (0, import_asyncToGenerator.default)(function* () {
yield _this8.doTxn("readwrite", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], /* @__PURE__ */ function() {
var _ref2 = (0, import_asyncToGenerator.default)(function* (txn) {
try {
var objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);
var _loop2 = function* _loop2() {
var req = objectStore.delete([senderKey, sessionId]);
yield new Promise((resolve) => {
req.onsuccess = resolve;
});
};
for (var { senderKey, sessionId } of sessions) yield* _loop2();
} catch (e) {
abortWithException(txn, e);
}
});
return function(_x2) {
return _ref2.apply(this, arguments);
};
}());
})();
}
getEndToEndDeviceData(txn, func) {
var getReq = txn.objectStore("device_data").get("-");
getReq.onsuccess = function() {
try {
func(getReq.result || null);
} catch (e) {
abortWithException(txn, e);
}
};
}
getEndToEndRooms(txn, func) {
var rooms = {};
var getReq = txn.objectStore("rooms").openCursor();
getReq.onsuccess = function() {
var cursor = getReq.result;
if (cursor) {
rooms[cursor.key] = cursor.value;
cursor.continue();
} else try {
func(rooms);
} catch (e) {
abortWithException(txn, e);
}
};
}
markSessionsNeedingBackup(sessions, txn) {
var _this9 = this;
return (0, import_asyncToGenerator.default)(function* () {
if (!txn) txn = _this9.db.transaction("sessions_needing_backup", "readwrite");
var objectStore = txn.objectStore("sessions_needing_backup");
yield Promise.all(sessions.map((session) => {
return new Promise((resolve, reject) => {
var req = objectStore.put({
senderCurve25519Key: session.senderKey,
sessionId: session.sessionId
});
req.onsuccess = resolve;
req.onerror = reject;
});
}));
})();
}
doTxn(mode, stores, func) {
var log = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : logger$2;
var startTime;
var description;
if (PROFILE_TRANSACTIONS) {
var txnId = this.nextTxnId++;
startTime = Date.now();
description = "".concat(mode, " crypto store transaction ").concat(txnId, " in ").concat(stores);
log.debug("Starting ".concat(description));
}
var txn = this.db.transaction(stores, mode);
var promise = promiseifyTxn(txn);
var result = func(txn);
if (PROFILE_TRANSACTIONS) promise.then(() => {
var elapsedTime = Date.now() - startTime;
log.debug("Finished ".concat(description, ", took ").concat(elapsedTime, " ms"));
}, () => {
var elapsedTime = Date.now() - startTime;
log.error("Failed ".concat(description, ", took ").concat(elapsedTime, " ms"));
});
return promise.then(() => {
return result;
});
}
};
var DB_MIGRATIONS = [
(db) => {
createDatabase(db);
},
(db) => {
db.createObjectStore("account");
},
(db) => {
db.createObjectStore("sessions", { keyPath: ["deviceKey", "sessionId"] }).createIndex("deviceKey", "deviceKey");
},
(db) => {
db.createObjectStore("inbound_group_sessions", { keyPath: ["senderCurve25519Key", "sessionId"] });
},
(db) => {
db.createObjectStore("device_data");
},
(db) => {
db.createObjectStore("rooms");
},
(db) => {
db.createObjectStore("sessions_needing_backup", { keyPath: ["senderCurve25519Key", "sessionId"] });
},
(db) => {
db.createObjectStore("inbound_group_sessions_withheld", { keyPath: ["senderCurve25519Key", "sessionId"] });
},
(db) => {
db.createObjectStore("session_problems", { keyPath: ["deviceKey", "time"] }).createIndex("deviceKey", "deviceKey");
db.createObjectStore("notified_error_devices", { keyPath: ["userId", "deviceId"] });
},
(db) => {
db.createObjectStore("shared_history_inbound_group_sessions", { keyPath: ["roomId"] });
},
(db) => {
db.createObjectStore("parked_shared_history", { keyPath: ["roomId"] });
}
];
var VERSION = DB_MIGRATIONS.length;
function upgradeDatabase(db, oldVersion) {
logger$2.log("Upgrading IndexedDBCryptoStore from version ".concat(oldVersion) + " to ".concat(VERSION));
DB_MIGRATIONS.forEach((migration, index) => {
if (oldVersion <= index) migration(db);
});
}
function createDatabase(db) {
var outgoingRoomKeyRequestsStore = db.createObjectStore("outgoingRoomKeyRequests", { keyPath: "requestId" });
outgoingRoomKeyRequestsStore.createIndex("session", ["requestBody.room_id", "requestBody.session_id"]);
outgoingRoomKeyRequestsStore.createIndex("state", "state");
}
function abortWithException(txn, e) {
txn._mx_abortexception = e;
try {
txn.abort();
} catch (_unused) {}
}
function promiseifyTxn(txn) {
return new Promise((resolve, reject) => {
txn.oncomplete = () => {
if (txn._mx_abortexception !== void 0) reject(txn._mx_abortexception);
resolve(null);
};
txn.onerror = (event) => {
if (txn._mx_abortexception !== void 0) reject(txn._mx_abortexception);
else {
logger$2.log("Error performing indexeddb txn", event);
reject(txn.error);
}
};
txn.onabort = (event) => {
if (txn._mx_abortexception !== void 0) reject(txn._mx_abortexception);
else {
logger$2.log("Error performing indexeddb txn", event);
reject(txn.error);
}
};
});
}
//#endregion
//#region node_modules/matrix-js-sdk/lib/crypto/store/indexeddb-crypto-store.js
/**
* An implementation of CryptoStore, which is normally backed by an indexeddb,
* but with fallback to MemoryCryptoStore.
*/
var IndexedDBCryptoStore = class IndexedDBCryptoStore {
static exists(indexedDB, dbName) {
return exists(indexedDB, dbName);
}
/**
* Utility to check if a legacy crypto store exists and has not been migrated.
* Returns true if the store exists and has not been migrated, false otherwise.
*/
static existsAndIsNotMigrated(indexedDb, dbName) {
return new Promise((resolve, reject) => {
var exists = true;
var openDBRequest = indexedDb.open(dbName);
openDBRequest.onupgradeneeded = () => {
exists = false;
};
openDBRequest.onblocked = () => reject(openDBRequest.error);
openDBRequest.onsuccess = () => {
var db = openDBRequest.result;
if (!exists) {
db.close();
indexedDb.deleteDatabase(dbName);
resolve(false);
} else {
var getReq = db.transaction([IndexedDBCryptoStore.STORE_ACCOUNT], "readonly").objectStore(IndexedDBCryptoStore.STORE_ACCOUNT).get(ACCOUNT_OBJECT_KEY_MIGRATION_STATE);
getReq.onsuccess = () => {
var _getReq$result;
resolve(((_getReq$result = getReq.result) !== null && _getReq$result !== void 0 ? _getReq$result : MigrationState.NOT_STARTED) === MigrationState.NOT_STARTED);
};
getReq.onerror = () => {
reject(getReq.error);
};
db.close();
}
};
openDBRequest.onerror = () => reject(openDBRequest.error);
});
}
/**
* Create a new IndexedDBCryptoStore
*
* @param indexedDB - global indexedDB instance
* @param dbName - name of db to connect to
*/
constructor(indexedDB, dbName) {
this.indexedDB = indexedDB;
this.dbName = dbName;
(0, import_defineProperty.default)(this, "backendPromise", void 0);
(0, import_defineProperty.default)(this, "backend", void 0);
}
/**
* Returns true if this CryptoStore has ever been initialised (ie, it might contain data).
*
* Implementation of {@link CryptoStore.containsData}.
*
* @internal
*/
containsData() {
var _this = this;
return (0, import_asyncToGenerator.default)(function* () {
return IndexedDBCryptoStore.exists(_this.indexedDB, _this.dbName);
})();
}
/**
* Ensure the database exists and is up-to-date, or fall back to
* a local storage or in-memory store.
*
* This must be called before the store can be used.
*
* @returns resolves to either an IndexedDBCryptoStoreBackend.Backend,
* or a MemoryCryptoStore
*/
startup() {
if (this.backendPromise) return this.backendPromise;
this.backendPromise = new Promise((resolve, reject) => {
if (!this.indexedDB) {
reject(/* @__PURE__ */ new Error("no indexeddb support available"));
return;
}
logger$2.log("connecting to indexeddb ".concat(this.dbName));
var req = this.indexedDB.open(this.dbName, VERSION);
req.onupgradeneeded = (ev) => {
var db = req.result;
var oldVersion = ev.oldVersion;
upgradeDatabase(db, oldVersion);
};
req.onblocked = () => {
logger$2.log("can't yet open IndexedDBCryptoStore because it is open elsewhere");
};
req.onerror = (ev) => {
logger$2.log("Error connecting to indexeddb", ev);
reject(req.error);
};
req.onsuccess = () => {
var db = req.result;
logger$2.log("connected to indexeddb ".concat(this.dbName));
resolve(new Backend(db));
};
}).then((backend) => {
return backend.doTxn("readonly", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], (txn) => {
backend.getEndToEndInboundGroupSession("", "", txn, () => {});
}).then(() => backend);
}).catch((e) => {
if (e.name === "VersionError") {
logger$2.warn("Crypto DB is too new for us to use!", e);
throw new InvalidCryptoStoreError(InvalidCryptoStoreState.TooNew);
}
logger$2.warn("unable to connect to indexeddb ".concat(this.dbName) + ": falling back to localStorage store: ".concat(e));
try {
if (!(globalThis.localStorage instanceof Storage)) throw new Error("localStorage is not available");
return new LocalStorageCryptoStore(globalThis.localStorage);
} catch (e) {
logger$2.warn("Unable to open localStorage: falling back to in-memory store: ".concat(e));
return new MemoryCryptoStore();
}
}).then((backend) => {
this.backend = backend;
return backend;
});
return this.backendPromise;
}
/**
* Delete all data from this store.
*
* @returns resolves when the store has been cleared.
*/
deleteAllData() {
return new Promise((resolve, reject) => {
if (!this.indexedDB) {
reject(/* @__PURE__ */ new Error("no indexeddb support available"));
return;
}
logger$2.log("Removing indexeddb instance: ".concat(this.dbName));
var req = this.indexedDB.deleteDatabase(this.dbName);
req.onblocked = () => {
logger$2.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere");
};
req.onerror = (ev) => {
logger$2.log("Error deleting data from indexeddb", ev);
reject(req.error);
};
req.onsuccess = () => {
logger$2.log("Removed indexeddb instance: ".concat(this.dbName));
resolve();
};
}).catch((e) => {
logger$2.warn("unable to delete IndexedDBCryptoStore: ".concat(e));
});
}
/**
* Get data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.getMigrationState}.
*
* @internal
*/
getMigrationState() {
return this.backend.getMigrationState();
}
/**
* Set data on how much of the libolm to Rust Crypto migration has been done.
*
* Implementation of {@link CryptoStore.setMigrationState}.
*
* @internal
*/
setMigrationState(migrationState) {
return this.backend.setMigrationState(migrationState);
}
getAccount(txn, func) {
this.backend.getAccount(txn, func);
}
/**
* Write the account pickle to the store.
* This requires an active transaction. See doTxn().
*
* @param txn - An active transaction. See doTxn().
* @param accountPickle - The new account pickle to store.
*/
storeAccount(txn, accountPickle) {
this.backend.storeAccount(txn, accountPickle);
}
/**
* Get the public part of the cross-signing keys (eg. self-signing key,
* user signing key).
*
* @param txn - An active transaction. See doTxn().
* @param func - Called with the account keys object:
* `{ key_type: base64 encoded seed }` where key type = user_signing_key_seed or self_signing_key_seed
*/
getCrossSigningKeys(txn, func) {
this.backend.getCrossSigningKeys(txn, func);
}
/**
* @param txn - An active transaction. See doTxn().
* @param func - Called with the private key
* @param type - A key type
*/
getSecretStorePrivateKey(txn, func, type) {
this.backend.getSecretStorePrivateKey(txn, func, type);
}
/**
* Write the cross-signing private keys back to the store
*
* @param txn - An active transaction. See doTxn().
* @param type - The type of cross-signing private key to store
* @param key - keys object as getCrossSigningKeys()
*/
storeSecretStorePrivateKey(txn, type, key) {
this.backend.storeSecretStorePrivateKey(txn, type, key);
}
/**
* Returns the number of end-to-end sessions in the store
* @param txn - An active transaction. See doTxn().
* @param func - Called with the count of sessions
*/
countEndToEndSessions(txn, func) {
this.backend.countEndToEndSessions(txn, func);
}
/**
* Retrieve a specific end-to-end session between the logged-in user
* and another device.
* @param deviceKey - The public key of the other device.
* @param sessionId - The ID of the session to retrieve
* @param txn - An active transaction. See doTxn().
* @param func - Called with A map from sessionId
* to session information object with 'session' key being the
* Base64 end-to-end session and lastReceivedMessageTs being the
* timestamp in milliseconds at which the session last received
* a message.
*/
getEndToEndSession(deviceKey, sessionId, txn, func) {
this.backend.getEndToEndSession(deviceKey, sessionId, txn, func);
}
/**
* Retrieve the end-to-end sessions between the logged-in user and another
* device.
* @param deviceKey - The public key of the other device.
* @param txn - An active transaction. See doTxn().
* @param func - Called with A map from sessionId
* to session information object with 'session' key being the
* Base64 end-to-end session and lastReceivedMessageTs being the
* timestamp in milliseconds at which the session last received
* a message.
*/
getEndToEndSessions(deviceKey, txn, func) {
this.backend.getEndToEndSessions(deviceKey, txn, func);
}
/**
* Store a session between the logged-in user and another device
* @param deviceKey - The public key of the other device.
* @param sessionId - The ID for this end-to-end session.
* @param sessionInfo - Session information object
* @param txn - An active transaction. See doTxn().
*/
storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {
this.backend.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn);
}
/**
* Count the number of Megolm sessions in the database.
*
* Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.
*
* @internal
*/
countEndToEndInboundGroupSessions() {
return this.backend.countEndToEndInboundGroupSessions();
}
/**
* Fetch a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.
*
* @internal
*/
getEndToEndSessionsBatch() {
return this.backend.getEndToEndSessionsBatch();
}
/**
* Delete a batch of Olm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.
*
* @internal
*/
deleteEndToEndSessionsBatch(sessions) {
return this.backend.deleteEndToEndSessionsBatch(sessions);
}
/**
* Retrieve the end-to-end inbound group session for a given
* server key and session ID
* @param senderCurve25519Key - The sender's curve 25519 key
* @param sessionId - The ID of the session
* @param txn - An active transaction. See doTxn().
* @param func - Called with A map from sessionId
* to Base64 end-to-end session.
*/
getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {
this.backend.getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func);
}
/**
* Writes an end-to-end inbound group session to the store.
* If there already exists an inbound group session with the same
* senderCurve25519Key and sessionID, it will be overwritten.
* @param senderCurve25519Key - The sender's curve 25519 key
* @param sessionId - The ID of the session
* @param sessionData - The session data structure
* @param txn - An active transaction. See doTxn().
*/
storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {
this.backend.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
}
/**
* Fetch a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
getEndToEndInboundGroupSessionsBatch() {
return this.backend.getEndToEndInboundGroupSessionsBatch();
}
/**
* Delete a batch of Megolm sessions from the database.
*
* Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.
*
* @internal
*/
deleteEndToEndInboundGroupSessionsBatch(sessions) {
return this.backend.deleteEndToEndInboundGroupSessionsBatch(sessions);
}
/**
* Get an object of `roomId->roomInfo` for all e2e rooms in the store
* @param txn - An active transaction. See doTxn().
* @param func - Function called with the end-to-end encrypted rooms
*/
getEndToEndRooms(txn, func) {
this.backend.getEndToEndRooms(txn, func);
}
/**
* Mark sessions as needing to be backed up.
* @param sessions - The sessions that need to be backed up.
* @param txn - An active transaction. See doTxn(). (optional)
* @returns resolves when the sessions are marked
*/
markSessionsNeedingBackup(sessions, txn) {
return this.backend.markSessionsNeedingBackup(sessions, txn);
}
/**
* Perform a transaction on the crypto store. Any store methods
* that require a transaction (txn) object to be passed in may
* only be called within a callback of either this function or
* one of the store functions operating on the same transaction.
*
* @param mode - 'readwrite' if you need to call setter
* functions with this transaction. Otherwise, 'readonly'.
* @param stores - List IndexedDBCryptoStore.STORE_*
* options representing all types of object that will be
* accessed or written to with this transaction.
* @param func - Function called with the
* transaction object: an opaque object that should be passed
* to store functions.
* @param log - A possibly customised log
* @returns Promise that resolves with the result of the `func`
* when the transaction is complete. If the backend is
* async (ie. the indexeddb backend) any of the callback
* functions throwing an exception will cause this promise to
* reject with that exception. On synchronous backends, the
* exception will propagate to the caller of the getFoo method.
*/
doTxn(mode, stores, func, log) {
return this.backend.doTxn(mode, stores, func, log);
}
};
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_ACCOUNT", "account");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_SESSIONS", "sessions");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_INBOUND_GROUP_SESSIONS", "inbound_group_sessions");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_INBOUND_GROUP_SESSIONS_WITHHELD", "inbound_group_sessions_withheld");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS", "shared_history_inbound_group_sessions");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_PARKED_SHARED_HISTORY", "parked_shared_history");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_DEVICE_DATA", "device_data");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_ROOMS", "rooms");
(0, import_defineProperty.default)(IndexedDBCryptoStore, "STORE_BACKUP", "sessions_needing_backup");
//#endregion
//#region node_modules/matrix-js-sdk/lib/types.js
/** The different methods for device and user verification */
var VerificationMethod = /* @__PURE__ */ function(VerificationMethod) {
/** Short authentication string (emoji or decimals).
*
* @see https://spec.matrix.org/v1.9/client-server-api/#short-authentication-string-sas-verification
*/
VerificationMethod["Sas"] = "m.sas.v1";
/**
* Verification by showing a QR code which is scanned by the other device.
*
* @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes
*/
VerificationMethod["ShowQrCode"] = "m.qr_code.show.v1";
/**
* Verification by scanning a QR code that is shown by the other device.
*
* @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes
*/
VerificationMethod["ScanQrCode"] = "m.qr_code.scan.v1";
/**
* Verification by confirming that we have scanned a QR code.
*
* @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes
*/
VerificationMethod["Reciprocate"] = "m.reciprocate.v1";
return VerificationMethod;
}({});
//#endregion
export { MapWithDefault as $, VerifierEvent as A, Method as B, UserVerificationStatus as C, encodeRecoveryKey as D, decodeRecoveryKey as E, decodeBase64 as F, MsgType as G, TypedReEmitter as H, encodeBase64 as I, LogSpan as J, ToDeviceMessageId as K, ClientPrefix as L, HistoryVisibility as M, Preset as N, VerificationPhase as O, secureRandomString as P, MigrationState as Q, calculateRetryBackoff as R, ImportRoomKeyStage as S, deriveRecoveryKeyFromPassphrase as T, KnownMembership as U, UNREAD_THREAD_NOTIFICATIONS as V, EventType as W, getHttpUriForMxc as X, logger$2 as Y, MemoryCryptoStore as Z, DecryptionKeyDoesNotMatchError as _, RoomStateEvent as a, sleep as at, EventShieldColour as b, DecryptionError as c, require_asyncToGenerator as ct, ClientStoppedError as d, deepCopy as et, SECRET_STORAGE_ALGORITHM_V1_AES as f, DecryptionFailureCode as g, CrossSigningKey as h, DeviceVerification as i, recursiveMapToObject as it, MatrixScheduler as j, VerificationRequestEvent as k, ClientEvent as l, AllDevicesIsolationMode as m, IndexedDBCryptoStore as n, isSupportedReceiptType as nt, MAX_STICKY_DURATION_MS as o, UnstableValue$3 as ot, decryptAESSecretStorageItem as p, TypedEventEmitter as q, Device as r, logDuration as rt, MatrixEventEvent as s, require_defineProperty as st, VerificationMethod as t, encodeUri as tt, MatrixClient as u, DeviceIsolationModeKind as v, CryptoEvent as w, EventShieldReason as x, DeviceVerificationStatus as y, MatrixError as z };